acadrust 0.6.5

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
//! DWG Object / Entity Writer (Sprint 4)
//!
//! Writes all DWG object records — table controls, table entries,
//! block headers, entities in each block, and non-graphical objects
//! (dictionaries, layouts, etc.).
//!
//! Ported from the reference `DwgObjectWriter` (partial class across
//! `DwgObjectWriter.cs`, `…Common.cs`, `…Entities.cs`, `…Objects.cs`).
//!
//! ## Record format
//!
//! Each object record in the output stream is:
//! ```text
//! [ModularShort(len)] [merged-stream bytes] [CRC16]
//! ```
//! The merged-stream bytes contain main + text + handle sub-streams
//! interleaved per the DWG spec.

pub mod associative;
pub mod class_object;
pub mod common;
pub mod data_objects;
pub mod dynamic_block;
pub mod entities;
pub mod field;
pub mod objects;

use std::collections::{HashMap, HashSet, VecDeque};

use crate::document::CadDocument;
use crate::entities::{EntityCommon, EntityType};
use crate::io::dwg::dwg_reference_type::DwgReferenceType;
use crate::io::dwg::dwg_stream_writers::DwgMergedWriter;
use crate::io::dwg::dwg_version::DwgVersion;
use crate::objects::{ClassObject, ClassObjectData, ObjectType};
use crate::tables::{BlockRecord, TableEntry};
use crate::types::{BoundingBox3D, DxfVersion, Handle};

// ── Helpers ─────────────────────────────────────────────────────────

/// Convert a deduplicated block name back to the DWG binary name.
///
/// In DWG format, all paper-space blocks are stored as `*Paper_Space`
/// and anonymous blocks share names like `*U`, `*D`, etc. (no numeric
/// suffixes).  Our reader adds suffixes (`*Paper_Space0`, `*U1`, …)
/// for deduplication.  This function strips them back for writing.
fn dwg_block_name(name: &str) -> &str {
    // Known multi-word prefixes first
    for prefix in &["*Model_Space", "*Paper_Space"] {
        if name
            .get(..prefix.len())
            .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
        {
            let rest = &name[prefix.len()..];
            if rest.is_empty() || rest.chars().all(|c| c.is_ascii_digit()) {
                return &name[..prefix.len()];
            }
        }
    }
    // Generic anonymous: *<alpha><digits> → *<alpha>
    if name.starts_with('*') && name.len() >= 2 {
        let alpha_end = name[1..]
            .find(|c: char| !c.is_ascii_alphabetic())
            .map(|p| 1 + p)
            .unwrap_or(name.len());
        let rest = &name[alpha_end..];
        if !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()) {
            return &name[..alpha_end];
        }
    }
    name
}

// ── Public struct ───────────────────────────────────────────────────

/// Writes all DWG object records (entities + table entries + objects)
/// into a contiguous byte stream, tracking handle→offset pairs for
/// the handle section.
pub struct DwgObjectWriter<'a> {
    /// Target DWG version (controls which fields are emitted)
    pub(super) version: DwgVersion,
    /// DXF version (for R2013/R2018 flag checks)
    pub(super) dxf_version: DxfVersion,
    /// Reference to the CAD document being written
    pub(super) document: &'a CadDocument,
    /// Per-object scratch writer (main + text + handle streams)
    pub(super) writer: DwgMergedWriter,
    /// Accumulated output bytes (all object records)
    pub(super) output: Vec<u8>,
    /// Handle → byte-offset map (for handle section)
    pub(super) handle_map: Vec<(u64, u32)>,
    /// Queue of non-graphical objects still to be written
    pub(super) object_queue: VecDeque<Handle>,
    /// Previous entity handle for pre-R2004 entity chain
    pub(super) prev_handle: Option<Handle>,
    /// Next entity handle for pre-R2004 entity chain
    pub(super) next_handle: Option<Handle>,
    /// Next handle value for allocating sub-entity handles (vertices, seqend)
    pub(super) next_alloc_handle: u64,
    /// Computed model space extents for VPort view adjustment and header EXTMIN/EXTMAX
    pub(crate) model_space_extents: Option<BoundingBox3D>,
    /// SAB data entries collected during entity writing (AC1027+).
    /// Each entry is (entity_handle, sab_binary_data).
    pub(super) sab_entries: Vec<(Handle, Vec<u8>)>,
    /// Set by a modeler-entity writer immediately before it emits the common
    /// entity data, so the R2013+ `has_ds_data` bit is written `true` for a
    /// 3DSOLID/REGION/BODY/SURFACE that contributes a SAB blob to the AcDs
    /// section. `write_common_entity_data` consumes and clears it, so every
    /// other entity writes `false`.
    pub(super) pending_has_ds_data: bool,
    /// Tracks which object handles have already been written to prevent duplicates.
    pub(super) visited_objects: HashSet<Handle>,
    /// Number of emitted records for every class-based type code.
    pub(super) class_instance_counts: HashMap<i16, i32>,
    /// Type code belonging to the record currently being assembled.
    pub(super) pending_type_code: Option<i16>,
    /// False when an opaque record prevents an exact class census.
    pub(super) class_counts_complete: bool,
    /// Every handle actually emitted to the object map. Central guard against
    /// writing the same handle twice (e.g. an xdictionary XRECORD reachable
    /// from more than one path): a duplicate handle is a hard DWG integrity
    /// error that strict audits reject, so register_* skips repeats.
    pub(super) registered_handles: HashSet<u64>,
    /// Records selected for serialization by the raw-all exclusion filter.
    /// Shared with parallel entity writers so their passthrough decisions agree.
    pub(super) raw_excluded_handles: std::sync::Arc<HashSet<u64>>,
    /// Owner handle overrides for extension dictionaries whose parent entity
    /// was re-allocated (e.g. ATTRIB children of INSERT).
    pub(super) owner_overrides: std::collections::HashMap<Handle, Handle>,
    /// Pre-allocated handles for table entries that have Handle::NULL in the
    /// document (e.g. user-created linetypes). Keyed by linetype name (uppercase).
    /// Populated before writing any table controls so controls and records agree.
    #[allow(dead_code)]
    pub(super) linetype_handles: std::collections::HashMap<String, Handle>,
    /// Cached fallback for owners without a direct extension-dictionary handle.
    pub(super) xdic_owner_index: std::sync::Arc<std::collections::HashMap<Handle, Handle>>,
    pub(super) block_users: std::sync::Arc<std::collections::HashMap<Handle, Vec<Handle>>>,
}

struct ParallelEntityBatch {
    output: Vec<u8>,
    handle_map: Vec<(u64, u32)>,
    object_queue: VecDeque<Handle>,
    registered_handles: HashSet<u64>,
    class_instance_counts: HashMap<i16, i32>,
    class_counts_complete: bool,
}

impl<'a> DwgObjectWriter<'a> {
    // ── Constructor ─────────────────────────────────────────────────

    /// Create a new object writer for the given document and version.
    pub fn new(document: &'a CadDocument) -> crate::error::Result<Self> {
        let version = DwgVersion::from_dxf_version(document.version)?;
        let dxf_version = document.version;
        let encoding = crate::io::dxf::code_page::encoding_from_dwg_code_page(
            crate::io::dxf::code_page::dwg_code_page_index(&document.header.code_page),
        );
        let writer = DwgMergedWriter::with_encoding(version, dxf_version, encoding);

        // Compute safe starting handle for allocation.
        // document.header.handle_seed may be stale (e.g. DWG roundtrip
        // without resolve_references), so scan all handles and use whichever
        // value is higher.
        let mut max_h = document.header.handle_seed;
        for entity in document.entities() {
            let h = entity.common().handle.value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for (handle, object) in &document.objects {
            if let ObjectType::ClassObject(ClassObject {
                data: ClassObjectData::DataTable(table),
                ..
            }) = object
            {
                table.validate()?;
            }
            let h = handle.value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for br in document.block_records.iter() {
            let h = br.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
            // Also scan block entity and endblk entity handles:
            // these are written verbatim by write_block_begin/write_block_end
            // but are NOT part of document.entities(), so they would otherwise
            // be missed and cause alloc_handle() to re-issue their handle values.
            let h2 = br.block_entity_handle.value() + 1;
            if h2 > max_h {
                max_h = h2;
            }
            let h3 = br.block_end_handle.value() + 1;
            if h3 > max_h {
                max_h = h3;
            }
        }
        for ly in document.layers.iter() {
            let h = ly.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for lt in document.line_types.iter() {
            let h = lt.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for ts in document.text_styles.iter() {
            let h = ts.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        // Also scan the remaining table entries that were previously missed:
        // app_ids, dim_styles, views, vports, ucss
        for a in document.app_ids.iter() {
            let h = a.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for ds in document.dim_styles.iter() {
            let h = ds.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for v in document.views.iter() {
            let h = v.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for vp in document.vports.iter() {
            let h = vp.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }
        for u in document.ucss.iter() {
            let h = u.handle().value() + 1;
            if h > max_h {
                max_h = h;
            }
        }

        Ok(Self {
            version,
            dxf_version,
            document,
            writer,
            output: Vec::with_capacity(64 * 1024),
            handle_map: Vec::with_capacity(1024),
            object_queue: VecDeque::new(),
            registered_handles: HashSet::new(),
            raw_excluded_handles: std::sync::Arc::new(HashSet::new()),
            prev_handle: None,
            next_handle: None,
            next_alloc_handle: max_h,
            model_space_extents: None,
            sab_entries: Vec::new(),
            pending_has_ds_data: false,
            visited_objects: HashSet::new(),
            class_instance_counts: HashMap::new(),
            pending_type_code: None,
            class_counts_complete: true,
            owner_overrides: std::collections::HashMap::new(),
            linetype_handles: std::collections::HashMap::new(),
            xdic_owner_index: std::sync::Arc::new(Self::build_xdic_owner_index(document)),
            block_users: std::sync::Arc::new(Self::build_block_users(document)),
        })
    }

    fn build_block_users(document: &CadDocument) -> std::collections::HashMap<Handle, Vec<Handle>> {
        let mut users: std::collections::HashMap<Handle, Vec<Handle>> = std::collections::HashMap::new();
        for entity in document.entities() {
            let record = match entity {
                EntityType::Insert(insert) => document.block_records.get(&insert.block_name).map(|r| r.handle),
                EntityType::Table(table) => table
                    .block_record_handle
                    .or_else(|| document.block_records.get(&table.block_name).map(|r| r.handle)),
                _ => None,
            };
            if let Some(record) = record.filter(|h| !h.is_null()) {
                users.entry(record).or_default().push(entity.common().handle);
            }
        }
        for list in users.values_mut() {
            list.sort();
        }
        users
    }

    fn block_insert_handles(&self, record: &BlockRecord) -> Vec<Handle> {
        let mut out: Vec<Handle> = record
            .insert_handles
            .iter()
            .copied()
            .filter(|h| self.document.get_entity(*h).is_some())
            .collect();
        for h in self.block_users.get(&record.handle).into_iter().flatten() {
            if !out.contains(h) {
                out.push(*h);
            }
        }
        out
    }

    /// Index the fallback ownership lookup used by `extension_dictionary_handle`.
    fn build_xdic_owner_index(document: &CadDocument) -> std::collections::HashMap<Handle, Handle> {
        let mut index = std::collections::HashMap::new();
        for (handle, object) in &document.objects {
            if let crate::objects::ObjectType::Dictionary(dictionary) = object {
                if handle.is_null() || dictionary.owner.is_null() {
                    continue;
                }
                if matches!(
                    document.objects.get(&dictionary.owner),
                    Some(crate::objects::ObjectType::Dictionary(_))
                ) {
                    continue;
                }
                index.entry(dictionary.owner).or_insert(*handle);
            }
        }
        index
    }

    /// Resolve an extension dictionary without scanning every object per call.
    pub(super) fn extension_dictionary_handle(&self, owner: Handle) -> Option<Handle> {
        use crate::objects::ObjectType;
        let document = self.document;
        if let Some(entity) = document.get_entity(owner) {
            if let Some(handle) = entity.common().xdictionary_handle {
                return (!handle.is_null()).then_some(handle);
            }
        }
        if let Some(handle) = document.xdic_by_handle.get(&owner).copied() {
            return (!handle.is_null()).then_some(handle);
        }
        if let Some(handle) = match document.objects.get(&owner) {
            Some(ObjectType::Dictionary(value)) => value.xdictionary_handle,
            Some(ObjectType::Layout(value)) => value.xdictionary_handle,
            Some(ObjectType::XRecord(value)) => value.xdictionary_handle,
            Some(ObjectType::PlotSettings(value)) => value.xdictionary_handle,
            Some(ObjectType::VisualStyle(value)) => value.xdictionary_handle,
            Some(ObjectType::Material(value)) => value.xdictionary_handle,
            Some(ObjectType::ProxyObject(value)) => value.xdictionary_handle,
            _ => None,
        } {
            if !handle.is_null() {
                return Some(handle);
            }
        }
        if matches!(
            document.objects.get(&owner),
            Some(ObjectType::Dictionary(_))
        ) {
            return None;
        }
        self.xdic_owner_index.get(&owner).copied()
    }

    // ── Main entry point ────────────────────────────────────────────

    pub fn write(
        self,
    ) -> (
        Vec<u8>,
        Vec<(u64, u32)>,
        Option<BoundingBox3D>,
        Vec<(Handle, Vec<u8>)>,
    ) {
        let (output, handles, extents, sab_entries, _, _) = self.write_with_class_metadata();
        (output, handles, extents, sab_entries)
    }

    /// Write all objects and return the encoded records and their derived metadata.
    ///
    /// For AC1027+, ACIS entities (3DSOLID, REGION, BODY) are written with
    /// `acis_empty=true` in the entity stream; their SAB binary data is
    /// collected into `sab_entries` for writing into the `AcDb:AcDsPrototype_1b`
    /// section.
    pub(crate) fn write_with_class_metadata(
        mut self,
    ) -> (
        Vec<u8>,
        Vec<(u64, u32)>,
        Option<BoundingBox3D>,
        Vec<(Handle, Vec<u8>)>,
        HashMap<i16, i32>,
        bool,
    ) {
        // Compute model space extents for VPort view adjustment
        self.model_space_extents = self.compute_model_space_extents();


        // R2004+: 0x0DCA marker at the start
        if self.version.r2004_plus() {
            self.output.extend_from_slice(&0x0DCAi32.to_le_bytes());
        }

        // Debug bisection aid (ACADRUST_RAW_ALL): re-emit source records verbatim.
        self.preregister_raw_records();

        // Enqueue root dictionary for later.
        // If the header handle is NULL (e.g., after a DWG read where the
        // header reader failed to parse handles), scan document.objects to
        // find the root dictionary (a Dictionary with owner == NULL).
        let mut root_dict_handle = self.document.header.named_objects_dict_handle;
        if root_dict_handle.is_null() {
            root_dict_handle = self.find_root_dict_handle();
        }
        if !root_dict_handle.is_null() {
            self.object_queue.push_back(root_dict_handle);
        }

        // ── Table controls ──────────────────────────────────────
        self.write_block_control();
        self.write_table_control(
            self.document.layers.handle(),
            common::OBJ_LAYER_CONTROL,
            &self
                .document
                .layers
                .iter()
                .map(|l| l.handle)
                .collect::<Vec<_>>(),
        );
        self.write_text_style_control();
        self.write_ltype_control();
        self.write_table_control(
            self.document.views.handle(),
            common::OBJ_VIEW_CONTROL,
            &self
                .document
                .views
                .iter()
                .map(|v| v.handle)
                .collect::<Vec<_>>(),
        );
        self.write_table_control(
            self.document.ucss.handle(),
            common::OBJ_UCS_CONTROL,
            &self
                .document
                .ucss
                .iter()
                .map(|u| u.handle)
                .collect::<Vec<_>>(),
        );
        self.write_table_control(
            self.document.vports.handle(),
            common::OBJ_VPORT_CONTROL,
            &self
                .document
                .vports
                .iter()
                .map(|v| v.handle)
                .collect::<Vec<_>>(),
        );
        let mut appid_handles: Vec<_> = self
            .document
            .app_ids
            .iter()
            .map(|a| (a.name.eq_ignore_ascii_case("ACAD"), a.handle))
            .collect();
        appid_handles.sort_by_key(|(is_acad, _)| !*is_acad);
        self.write_table_control(
            self.document.app_ids.handle(),
            common::OBJ_APPID_CONTROL,
            &appid_handles
                .into_iter()
                .map(|(_, handle)| handle)
                .collect::<Vec<_>>(),
        );
        self.write_dimstyle_control();

        // R13-R2000 only: VPEntHdr control (viewport entity header table)
        if self.version.r13_15_only() {
            self.write_vpent_hdr_control();
        }

        // ── Table entries ───────────────────────────────────────
        self.write_layer_entries();
        self.write_text_style_entries();
        self.write_ltype_entries();
        self.write_view_entries();
        self.write_ucs_entries();
        self.write_vport_entries();
        self.write_appid_entries();
        self.write_dimstyle_entries();
        if self.version.r13_15_only() {
            self.write_vx_entries();
        }

        // ── Block entities ──────────────────────────────────────
        self.write_block_entities();

        // ── Drain object queue ──────────────────────────────────
        self.write_objects();

        (
            self.output,
            self.handle_map,
            self.model_space_extents,
            self.sab_entries,
            self.class_instance_counts,
            self.class_counts_complete,
        )
    }

    /// Whether this version stores ACIS data externally (AcDsPrototype_1b section)
    /// rather than inline in the entity stream.
    /// Currently disabled: always write inline because the DWG reader doesn't yet
    /// parse the AcDsPrototype_1b section, which causes ACIS data loss on read-back.
    fn needs_acds_section(&self) -> bool {
        // R2013+ stores ACIS (3DSOLID/REGION/BODY/SURFACE) geometry in the
        // AcDsPrototype_1b section rather than inline in the entity stream.
        self.version.r2013_plus(self.dxf_version)
    }

    /// Find the root dictionary handle by scanning document.objects.
    ///
    /// The root dictionary is a Dictionary with `owner == Handle::NULL`.
    /// If multiple candidates exist, prefer the one with the most entries.
    fn find_root_dict_handle(&self) -> Handle {
        let mut best_handle = Handle::NULL;
        let mut best_entry_count = 0usize;

        for (handle, obj) in &self.document.objects {
            if let crate::objects::ObjectType::Dictionary(dict) = obj {
                if dict.owner.is_null() {
                    if dict.entries.len() > best_entry_count
                        || (dict.entries.len() == best_entry_count
                            && handle.value() > best_handle.value())
                    {
                        best_handle = *handle;
                        best_entry_count = dict.entries.len();
                    }
                }
            }
        }

        best_handle
    }

    /// Compute the bounding box of all entities in the *Model_Space block.
    fn compute_model_space_extents(&self) -> Option<BoundingBox3D> {
        let ms_block = self.document.block_records.get("*Model_Space")?;
        let mut extents: Option<BoundingBox3D> = None;
        for eh in &ms_block.entity_handles {
            if let Some(&idx) = self.document.entity_index.get(eh) {
                let bbox = self.document.entities[idx].as_entity().bounding_box();
                extents = Some(match extents {
                    Some(existing) => existing.merge(&bbox),
                    None => bbox,
                });
            }
        }
        extents
    }

    // ── Table control writers ───────────────────────────────────────

    /// Generic table control object: type code, count, soft-owner handles.
    fn write_table_control(
        &mut self,
        table_handle: Handle,
        type_code: i16,
        entry_handles: &[Handle],
    ) {
        // Owner is always 0 for table controls (owned by header)
        self.write_common_non_entity_data(type_code, table_handle, Handle::NULL, &[], &None);

        // Entry count
        self.writer.write_bit_long(entry_handles.len() as i32);

        // Entry handles (soft ownership)
        for h in entry_handles {
            self.writer
                .write_handle(DwgReferenceType::SoftOwnership, h.value());
        }

        self.register_object(table_handle);
    }

    /// BLOCK_CONTROL — special: excludes *Model_Space and *Paper_Space
    /// from the count, writes them as hard-owner references at the end.
    fn write_block_control(&mut self) {
        let table_handle = self.document.block_records.handle();

        self.write_common_non_entity_data(
            common::OBJ_BLOCK_CONTROL,
            table_handle,
            Handle::NULL,
            &[],
            &None,
        );

        // Gather handles
        let mut regular: Vec<Handle> = Vec::new();
        let mut ms_handle = Handle::NULL;
        let mut ps_handle = Handle::NULL;

        for br in self.document.block_records.iter() {
            if br.name.eq_ignore_ascii_case("*Model_Space") {
                ms_handle = br.handle;
            } else if br.name.eq_ignore_ascii_case("*Paper_Space") {
                ps_handle = br.handle;
            } else {
                regular.push(br.handle);
            }
        }

        // Count excludes model/paper space
        self.writer.write_bit_long(regular.len() as i32);

        for h in &regular {
            self.writer
                .write_handle(DwgReferenceType::SoftOwnership, h.value());
        }

        // *Model_Space, *Paper_Space (hard owner)
        self.writer
            .write_handle(DwgReferenceType::HardOwnership, ms_handle.value());
        self.writer
            .write_handle(DwgReferenceType::HardOwnership, ps_handle.value());

        self.register_object(table_handle);
    }

    /// STYLE_CONTROL
    fn write_text_style_control(&mut self) {
        let handles: Vec<Handle> = self.document.text_styles.iter().map(|s| s.handle).collect();
        self.write_table_control(
            self.document.text_styles.handle(),
            common::OBJ_STYLE_CONTROL,
            &handles,
        );
    }

    /// LTYPE_CONTROL — special: excludes ByLayer/ByBlock from count.
    fn write_ltype_control(&mut self) {
        let table_handle = self.document.line_types.handle();
        self.write_common_non_entity_data(
            common::OBJ_LTYPE_CONTROL,
            table_handle,
            Handle::NULL,
            &[],
            &None,
        );

        let mut regular = Vec::new();
        let mut byblock_handle = Handle::NULL;
        let mut bylayer_handle = Handle::NULL;

        for lt in self.document.line_types.iter() {
            if lt.name.eq_ignore_ascii_case("ByBlock") {
                byblock_handle = lt.handle;
            } else if lt.name.eq_ignore_ascii_case("ByLayer") {
                bylayer_handle = lt.handle;
            } else {
                regular.push(lt.handle);
            }
        }

        self.writer.write_bit_long(regular.len() as i32);
        for h in &regular {
            self.writer
                .write_handle(DwgReferenceType::SoftOwnership, h.value());
        }
        // ByBlock, ByLayer (hard owner)
        self.writer
            .write_handle(DwgReferenceType::HardOwnership, byblock_handle.value());
        self.writer
            .write_handle(DwgReferenceType::HardOwnership, bylayer_handle.value());

        self.register_object(table_handle);
    }

    /// DIMSTYLE_CONTROL — special: has an extra undocumented byte in R2000+.
    fn write_dimstyle_control(&mut self) {
        let table_handle = self.document.dim_styles.handle();
        let handles: Vec<Handle> = self.document.dim_styles.iter().map(|d| d.handle).collect();

        self.write_common_non_entity_data(
            common::OBJ_DIMSTYLE_CONTROL,
            table_handle,
            Handle::NULL,
            &[],
            &None,
        );

        self.writer.write_bit_long(handles.len() as i32);

        // Undocumented byte in R2000+
        if self.version.r2000_plus() {
            self.writer.write_byte(0);
        }

        for h in &handles {
            self.writer
                .write_handle(DwgReferenceType::SoftOwnership, h.value());
        }

        self.register_object(table_handle);
    }

    /// VPENT_HDR_CONTROL — R13-R2000 only.
    /// Viewport entity header table control.
    /// The header section references this via hard-ownership handle.
    fn write_vpent_hdr_control(&mut self) {
        let table_handle = self.document.vx_table.handle();
        if table_handle.is_null() {
            return;
        }

        let mut handles = self.document.vx_control_entries.clone();
        for record in self.document.vx_table.iter() {
            if !handles.contains(&record.handle) {
                handles.push(record.handle);
            }
        }

        self.write_common_non_entity_data(
            common::OBJ_VPENT_HDR_CONTROL,
            table_handle,
            Handle::NULL,
            &[],
            &None,
        );
        self.writer.write_bit_short(handles.len() as i16);
        for handle in &handles {
            self.writer
                .write_handle(DwgReferenceType::SoftOwnership, handle.value());
        }
        self.register_object(table_handle);
    }

    // ── Table entry writers ─────────────────────────────────────────

    fn write_vx_entries(&mut self) {
        let entries: Vec<_> = self.document.vx_table.iter().cloned().collect();
        for entry in &entries {
            self.write_vx_entry(entry);
        }
    }

    fn write_vx_entry(&mut self, entry: &crate::tables::VxTableRecord) {
        self.write_common_non_entity_data(
            common::OBJ_VPENT_HDR,
            entry.handle,
            self.document.vx_table.handle(),
            &[],
            &None,
        );

        self.writer.write_variable_text(&entry.name);
        self.writer.write_bit(entry.is_xref_reference);
        self.writer
            .write_bit_short(if entry.is_xref_resolved { 256 } else { 0 });
        self.writer.write_bit(entry.is_xref_dependent);
        self.writer.write_bit(entry.is_on);
        self.writer
            .write_handle(DwgReferenceType::HardPointer, entry.xref_handle.value());
        self.writer
            .write_handle(DwgReferenceType::SoftPointer, entry.viewport.value());
        self.writer
            .write_handle(DwgReferenceType::HardPointer, entry.previous_entry.value());
        self.register_object(entry.handle);
    }

    fn write_layer_entries(&mut self) {
        let entries: Vec<_> = self.document.layers.iter().map(|l| l.clone()).collect();
        for layer in &entries {
            self.write_layer(layer);
        }
    }

    fn write_layer(&mut self, layer: &crate::tables::Layer) {
        let transparency_app = self.document.app_ids.get("AcCmTransparency");
        let had_transparency_eed = self
            .existing_xdata_values(layer.handle, "AcCmTransparency")
            .is_some_and(|values| {
                values.iter().any(|value| {
                    matches!(value, crate::xdata::XDataValue::Integer32(_))
                })
            });
        let transparency_eed = transparency_app.and_then(|app| {
            (!layer.transparency.is_opaque() || had_transparency_eed).then(|| {
                let mut bytes = vec![71];
                bytes.extend_from_slice(&layer.transparency.to_dxf_value().to_le_bytes());
                (app.handle.value(), bytes)
            })
        });
        // A description is stored the same way, under its own application,
        // as two strings of which the second is the text. Encoded through the
        // EED codec rather than by hand: a DWG string carries a length and a
        // code page, and from R2007 it is UTF-16.
        let description_eed = self
            .document
            .app_ids
            .get(crate::tables::layer::LAYER_DESCRIPTION_APP)
            .and_then(|app| {
                let had_description = self
                    .existing_xdata_values(layer.handle, crate::tables::layer::LAYER_DESCRIPTION_APP)
                    .is_some_and(|values| {
                        values.iter().filter(|value| {
                            matches!(value, crate::xdata::XDataValue::String(_))
                        }).count() >= 2
                    });
                (!layer.description.is_empty() || had_description).then(|| {
                    let code_page = crate::io::dxf::code_page::dwg_code_page_index(
                        &self.document.header.code_page,
                    );
                    let encoding =
                        crate::io::dxf::code_page::encoding_from_dwg_code_page(code_page);
                    let values = [
                        crate::xdata::XDataValue::String(String::new()),
                        crate::xdata::XDataValue::String(layer.description.clone()),
                    ];
                    let bytes = crate::io::dwg::eed_codec::encode_values_with_encoding(
                        self.version.r2007_plus(),
                        &values,
                        encoding,
                        code_page,
                        |_| 0,
                    );
                    (app.handle.value(), bytes)
                })
            });

        let extra_eed: Vec<_> = transparency_eed
            .into_iter()
            .chain(description_eed)
            .collect();
        self.write_common_non_entity_data_eed(
            common::OBJ_LAYER,
            layer.handle,
            self.document.layers.handle(),
            &[],
            &None,
            extra_eed,
        );

        // Entry name
        self.writer.write_variable_text(&layer.name);

        // Xref-dependant bit
        self.write_xref_dependant_bit_value(layer.flags.xref_dependent);

        if self.version.r2000_plus() {
            let lw_index = layer.line_weight.to_dwg_index() as i16;
            let mut values: i16 = (lw_index & 0x1F) << 5; // lineweight in bits 5..9

            if layer.flags.frozen {
                values |= 0b0001;
            }
            // "off" flag goes in bit 1 (inverted: on → bit clear)
            if layer.flags.off {
                values |= 0b0010;
            }
            if layer.flags.frozen_in_new_viewport {
                values |= 0b0100;
            }
            if layer.flags.locked {
                values |= 0b1000;
            }
            if layer.is_plottable {
                values |= 0b10000;
            }
            self.writer.write_bit_short(values);
        } else {
            self.writer.write_bit(layer.flags.frozen);
            self.writer.write_bit(layer.flags.off); // off flag (0=on, 1=off, same as R2000+)
            self.writer.write_bit(layer.flags.frozen_in_new_viewport);
            self.writer.write_bit(layer.flags.locked);
        }

        // Color (CMC)
        self.writer.write_cm_color_with_names(
            &layer.color,
            layer.color_name.as_deref(),
            layer.book_name.as_deref(),
        );

        // External reference block handle
        self.writer.write_handle(
            DwgReferenceType::HardPointer,
            layer.xref_block_record_handle.value(),
        );

        if self.version.r2000_plus() {
            // Plotstyle handle
            self.writer.write_handle(
                DwgReferenceType::HardPointer,
                layer.plotstyle_handle.value(),
            );
        }

        if self.version.r2007_plus() {
            // Material handle
            let material = if self.is_writable_object(&layer.material) {
                layer.material
            } else {
                Handle::NULL
            };
            self.writer
                .write_handle(DwgReferenceType::HardPointer, material.value());
        }

        // Linetype handle — look up by name
        let lt_handle = self
            .document
            .line_types
            .get(&layer.line_type)
            .map(|lt| lt.handle)
            .unwrap_or(Handle::NULL);
        self.writer
            .write_handle(DwgReferenceType::HardPointer, lt_handle.value());

        if self.version.r2013_plus(self.dxf_version) {
            self.writer.write_handle(DwgReferenceType::HardPointer, 0);
        }

        self.register_object(layer.handle);
    }

    fn write_text_style_entries(&mut self) {
        let entries: Vec<_> = self
            .document
            .text_styles
            .iter()
            .map(|s| s.clone())
            .collect();
        for style in &entries {
            self.write_text_style(style);
        }
    }

    fn write_text_style(&mut self, style: &crate::tables::TextStyle) {
        let mut eed: Vec<(u64, Vec<u8>)> =
            self.annotative_eed_block_for_handle(style.handle, style.annotative).into_iter().collect();
        // The TrueType typeface goes in `ACAD` EED; the record has no field.
        if !style.true_type_font.trim().is_empty() {
            if let Some(app) = self.document.app_ids.get("ACAD") {
                eed.push((
                    app.handle.value(),
                    crate::io::dwg::typeface_eed::encode(
                        self.version.r2007_plus(),
                        style.true_type_font.trim(),
                        style.true_type_font_flags,
                    ),
                ));
            }
        }
        self.write_common_non_entity_data_eed(
            common::OBJ_STYLE,
            style.handle,
            self.document.text_styles.handle(),
            &[],
            &None,
            eed,
        );

        // Entry name
        self.writer.write_variable_text(&style.name);

        // Xref-dependent flag
        self.write_xref_dependant_bit_value(style.xref_dependent);

        // Shape file flag
        self.writer.write_bit(style.is_shape_file);
        // Vertical flag
        self.writer.write_bit(style.is_vertical);

        // Fixed height
        self.writer.write_bit_double(style.height);
        // Width factor
        self.writer.write_bit_double(style.width_factor);
        // Oblique angle
        self.writer.write_bit_double(style.oblique_angle);
        // Generation (mirror flags: 2 = backward, 4 = upside down)
        let generation = (if style.flags.backward { 2u8 } else { 0 }) | (if style.flags.upside_down { 4u8 } else { 0 });
        self.writer.write_byte(generation);
        // Last height (must be > 0; use effective_last_height)
        self.writer.write_bit_double(style.effective_last_height());
        // Font name
        self.writer.write_variable_text(&style.font_file);
        // Big font name
        self.writer.write_variable_text(&style.big_font_file);

        // External reference block handle (hard pointer)
        self.writer.write_handle(
            DwgReferenceType::HardPointer,
            style.xref_block_record_handle.value(),
        );

        self.register_object(style.handle);
    }

    fn write_ltype_entries(&mut self) {
        let entries: Vec<_> = self
            .document
            .line_types
            .iter()
            .map(|lt| lt.clone())
            .collect();
        for lt in &entries {
            self.write_line_type(lt);
        }
    }

    fn write_line_type(&mut self, ltype: &crate::tables::LineType) {
        self.write_common_non_entity_data(
            common::OBJ_LTYPE,
            ltype.handle,
            self.document.line_types.handle(),
            &[],
            &None,
        );

        // Entry name
        self.writer.write_variable_text(&ltype.name);
        // Xref-dependent flag (linetypes that came in through an xref keep it,
        // otherwise AUDIT renames every "xref|name" record).
        self.write_xref_dependant_bit_value(ltype.xref_dependent);
        // Description
        self.writer.write_variable_text(&ltype.description);
        // Pattern length
        self.writer.write_bit_double(ltype.pattern_length);
        // Alignment
        self.writer.write_byte(b'A');
        // Num dashes
        self.writer.write_byte(ltype.elements.len() as u8);

        let unicode_text = self.version.r2007_plus();
        let mut text_area = if unicode_text {
            ltype
                .elements
                .iter()
                .any(|seg| seg.complex.as_ref().is_some_and(|cx| cx.is_text()))
                .then(|| vec![0u8; 512])
        } else {
            Some(vec![0u8; 256])
        };
        let mut text_cursor = if self.dxf_version <= DxfVersion::AC1014 {
            1usize
        } else {
            0usize
        };
        let mut shape_numbers = Vec::with_capacity(ltype.elements.len());
        let mut shape_flags = Vec::with_capacity(ltype.elements.len());

        for seg in &ltype.elements {
            let c = seg.complex.as_ref();
            let flags = if let Some(ref cx) = c {
                let mut f: i16 = cx.source_flags as i16;
                f &= !(0x01 | 0x02 | 0x04);
                if cx.is_absolute_rotation() {
                    f |= 0x01;
                }
                if cx.is_text() {
                    f |= 0x02;
                }
                if cx.is_shape() {
                    f |= 0x04;
                }
                f
            } else {
                0
            };
            shape_flags.push(flags);

            let mut shape_number = c.and_then(|cx| cx.shape_number()).unwrap_or(0);
            if let (Some(cx), Some(area)) = (c, text_area.as_mut()) {
                if let Some(text) = cx.text().filter(|text| !text.is_empty()) {
                    let bytes = if unicode_text {
                        text.encode_utf16()
                            .flat_map(u16::to_le_bytes)
                            .collect::<Vec<_>>()
                    } else {
                        self.writer.encode_legacy_text(text)
                    };
                    let terminator_len = if unicode_text { 2 } else { 1 };
                    if text_cursor + bytes.len() + terminator_len <= area.len() {
                        shape_number = text_cursor as i16;
                        area[text_cursor..text_cursor + bytes.len()].copy_from_slice(&bytes);
                        text_cursor += bytes.len() + terminator_len;
                    } else {
                        shape_number = 0;
                    }
                }
            }
            shape_numbers.push(shape_number);
        }

        for ((seg, shape_number), flags) in
            ltype.elements.iter().zip(shape_numbers).zip(shape_flags)
        {
            let c = seg.complex.as_ref();
            self.writer.write_bit_double(seg.length);
            self.writer.write_bit_short(shape_number);
            self.writer
                .write_raw_double(c.map_or(0.0, |cx| cx.offset[0]));
            self.writer
                .write_raw_double(c.map_or(0.0, |cx| cx.offset[1]));
            self.writer.write_bit_double(c.map_or(1.0, |cx| cx.scale));
            self.writer
                .write_bit_double(c.map_or(0.0, |cx| cx.rotation));
            self.writer.write_bit_short(flags);
        }

        // R2004- always carries 256 encoded bytes. R2007+ carries 512
        // UTF-16LE bytes only when at least one text segment exists.
        if let Some(area) = text_area {
            for byte in area {
                self.writer.write_byte(byte);
            }
        }

        // External reference block handle
        self.writer.write_handle(
            DwgReferenceType::HardPointer,
            ltype.xref_block_record_handle.value(),
        );

        // Shape file handles for each segment
        for seg in &ltype.elements {
            let sh = seg.complex.as_ref().map_or(0, |cx| cx.style_handle.value());
            self.writer.write_handle(DwgReferenceType::HardPointer, sh);
        }

        self.register_object(ltype.handle);
    }

    fn write_view_entries(&mut self) {
        let entries: Vec<_> = self.document.views.iter().map(|v| v.clone()).collect();
        for view in &entries {
            self.write_view(view);
        }
    }

    fn write_view(&mut self, view: &crate::tables::View) {
        self.write_common_non_entity_data(
            common::OBJ_VIEW,
            view.handle,
            self.document.views.handle(),
            &[],
            &None,
        );

        self.writer.write_variable_text(&view.name);
        self.write_xref_table_flags(view.xref_reference, view.xref_resolved, view.xref_dependent);

        self.writer.write_bit_double(view.height);
        self.writer.write_bit_double(view.width);
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: view.center.x,
            y: view.center.y,
        });
        self.writer.write_3bit_double(view.target);
        self.writer.write_3bit_double(view.direction);
        self.writer.write_bit_double(view.twist_angle);
        self.writer.write_bit_double(view.lens_length);
        self.writer.write_bit_double(view.front_clip);
        self.writer.write_bit_double(view.back_clip);

        // View mode (4 bits)
        self.writer.write_bit(view.perspective);
        self.writer.write_bit(view.front_clipping);
        self.writer.write_bit(view.back_clipping);
        self.writer.write_bit(view.front_clip_at_eye);

        if self.version.r2000_plus() {
            self.writer.write_byte(view.render_mode.to_value() as u8);
        }

        if self.version.r2007_plus() {
            self.writer.write_bit(view.use_default_lights);
            self.writer.write_byte(view.default_lighting_type as u8);
            self.writer.write_bit_double(view.brightness);
            self.writer.write_bit_double(view.contrast);
            self.writer.write_cm_color(&view.ambient_color);
        }

        self.writer.write_bit(view.paper_space);

        if self.version.r2000_plus() {
            self.writer.write_bit(view.ucs_associated);
            if view.ucs_associated {
                self.writer.write_3bit_double(view.ucs_origin);
                self.writer.write_3bit_double(view.ucs_x_axis);
                self.writer.write_3bit_double(view.ucs_y_axis);
                self.writer.write_bit_double(view.ucs_elevation);
                self.writer.write_bit_short(view.ucs_ortho_type);
            }
        }

        if self.version.r2007_plus() {
            self.writer.write_bit(view.camera_plottable);
        }

        self.writer
            .write_handle(DwgReferenceType::HardPointer, view.xref_handle.value());

        if self.version.r2007_plus() {
            self.writer.write_handle(
                DwgReferenceType::SoftPointer,
                view.background_handle.value(),
            );
            self.writer.write_handle(
                DwgReferenceType::HardPointer,
                view.visual_style_handle.value(),
            );
            self.writer
                .write_handle(DwgReferenceType::HardOwnership, view.sun_handle.value());
        }

        if self.version.r2000_plus() && view.ucs_associated {
            self.writer
                .write_handle(DwgReferenceType::HardPointer, view.base_ucs_handle.value());
            self.writer
                .write_handle(DwgReferenceType::HardPointer, view.named_ucs_handle.value());
        }

        if self.version.r2007_plus() {
            self.writer.write_handle(
                DwgReferenceType::SoftPointer,
                view.live_section_handle.value(),
            );
        }

        self.register_object(view.handle);
    }

    fn write_ucs_entries(&mut self) {
        let entries: Vec<_> = self.document.ucss.iter().map(|u| u.clone()).collect();
        for ucs in &entries {
            self.write_ucs(ucs);
        }
    }

    fn write_ucs(&mut self, ucs: &crate::tables::Ucs) {
        self.write_common_non_entity_data(
            common::OBJ_UCS,
            ucs.handle,
            self.document.ucss.handle(),
            &[],
            &None,
        );

        self.writer.write_variable_text(&ucs.name);
        self.write_xref_table_flags(ucs.xref_reference, ucs.xref_resolved, ucs.xref_dependent);

        self.writer.write_3bit_double(ucs.origin);
        self.writer.write_3bit_double(ucs.x_axis);
        self.writer.write_3bit_double(ucs.y_axis);

        if self.version.r2000_plus() {
            self.writer.write_bit_double(ucs.elevation);
            self.writer.write_bit_short(ucs.ortho_view_type);
            self.writer.write_bit_short(ucs.ortho_type);
        }

        self.writer
            .write_handle(DwgReferenceType::HardPointer, ucs.xref_handle.value());

        if self.version.r2000_plus() {
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ucs.base_ucs_handle.value());
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ucs.named_ucs_handle.value());
        }

        self.register_object(ucs.handle);
    }

    fn write_vport_entries(&mut self) {
        let entries: Vec<_> = self.document.vports.iter().cloned().collect();
        for vp in &entries {
            self.write_vport(vp);
        }
    }

    fn write_vport(&mut self, vport: &crate::tables::VPort) {
        self.write_common_non_entity_data(
            common::OBJ_VPORT,
            vport.handle,
            self.document.vports.handle(),
            &[],
            &None,
        );

        // Common: Entry name TV 2
        self.writer.write_variable_text(&vport.name);
        self.write_xref_table_flags(
            vport.xref_reference,
            vport.xref_resolved,
            vport.xref_dependent,
        );

        // View height BD 40
        self.writer.write_bit_double(vport.view_height);
        // Aspect ratio BD 41 — DWG stores aspect_ratio * view_height
        // (R13 quirk; reader divides by view_height to get actual ratio)
        self.writer
            .write_bit_double(vport.aspect_ratio * vport.view_height);
        // View Center 2RD 12
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.view_center.x,
            y: vport.view_center.y,
        });
        // View target 3BD 17
        self.writer.write_3bit_double(vport.view_target);
        // View dir 3BD 16
        self.writer.write_3bit_double(vport.view_direction);
        // View twist BD 51
        self.writer.write_bit_double(vport.view_twist);
        // Lens length BD 42
        self.writer.write_bit_double(vport.lens_length);
        // Front clip BD 43
        self.writer.write_bit_double(vport.front_clip);
        // Back clip BD 44
        self.writer.write_bit_double(vport.back_clip);

        // View mode X 71 — 4 bits: 0123
        self.writer.write_bit(vport.perspective);
        self.writer.write_bit(vport.front_clipping);
        self.writer.write_bit(vport.back_clipping);
        self.writer.write_bit(vport.front_clip_at_eye);

        // R2000+: Render Mode RC 281
        if self.version.r2000_plus() {
            self.writer.write_byte(vport.render_mode.to_value() as u8);
        }

        // R2007+: lighting
        if self.version.r2007_plus() {
            // Use default lights B 292
            self.writer.write_bit(vport.use_default_lights);
            // Default lighting type RC 282
            self.writer.write_byte(vport.default_lighting_type as u8);
            // Brightness BD 141
            self.writer.write_bit_double(vport.brightness);
            // Contrast BD 142
            self.writer.write_bit_double(vport.contrast);
            // Ambient Color CMC 63
            self.writer.write_cm_color(&vport.ambient_color);
        }

        // Common: Lower left 2RD 10
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.lower_left.x,
            y: vport.lower_left.y,
        });
        // Common: Upper right 2RD 11
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.upper_right.x,
            y: vport.upper_right.y,
        });

        // UCSFOLLOW B 71
        self.writer.write_bit(vport.ucsfollow);
        // Circle zoom BS 72
        self.writer.write_bit_short(vport.circle_zoom);
        // Fast zoom B 73
        self.writer.write_bit(vport.fast_zoom);
        // UCSICON X 74 — 2 individual bits
        self.writer.write_bit(vport.ucsicon_lower);
        self.writer.write_bit(vport.ucsicon_origin);
        // Grid on/off B 76
        self.writer.write_bit(vport.grid_on);
        // Grid spacing 2RD 15
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.grid_spacing.x,
            y: vport.grid_spacing.y,
        });
        // Snap on/off B 75
        self.writer.write_bit(vport.snap_on);
        // Snap style B 77
        self.writer.write_bit(vport.snap_style);
        // Snap isopair BS 78
        self.writer.write_bit_short(vport.snap_isopair);
        // Snap rot BD 50
        self.writer.write_bit_double(vport.snap_rotation);
        // Snap base 2RD 13
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.snap_base.x,
            y: vport.snap_base.y,
        });
        // Snap spacing 2RD 14
        self.writer.write_2raw_double(crate::types::Vector2 {
            x: vport.snap_spacing.x,
            y: vport.snap_spacing.y,
        });

        // R2000+
        if self.version.r2000_plus() {
            self.writer.write_bit(vport.ucs_at_origin);
            self.writer.write_bit(vport.ucs_per_viewport);
            self.writer.write_3bit_double(vport.ucs_origin);
            self.writer.write_3bit_double(vport.ucs_x_axis);
            self.writer.write_3bit_double(vport.ucs_y_axis);
            self.writer.write_bit_double(vport.ucs_elevation);
            self.writer.write_bit_short(vport.ucs_ortho_type);
        }

        // R2007+
        if self.version.r2007_plus() {
            // Grid flags BS 60 — adaptive grid enabled
            self.writer.write_bit_short(vport.grid_flags.to_bits());
            // Grid major BS 61
            self.writer.write_bit_short(vport.grid_major);
        }

        // Common: External reference block handle (hard pointer)
        self.writer
            .write_handle(DwgReferenceType::HardPointer, vport.xref_handle.value());

        // R2007+
        if self.version.r2007_plus() {
            // Background handle H 332 soft pointer (code 4)
            self.writer.write_handle(
                DwgReferenceType::SoftPointer,
                vport.background_handle.value(),
            );
            // Visual Style handle H 348 hard pointer (code 5)
            self.writer.write_handle(
                DwgReferenceType::HardPointer,
                vport.visual_style_handle.value(),
            );
            // Sun handle H 361 hard owner (code 3)
            self.writer
                .write_handle(DwgReferenceType::HardOwnership, vport.sun_handle.value());
        }

        // R2000+
        if self.version.r2000_plus() {
            // Named UCS Handle H 345 hard pointer
            self.writer.write_handle(
                DwgReferenceType::HardPointer,
                vport.named_ucs_handle.value(),
            );
            // Base UCS Handle H 346 hard pointer
            self.writer
                .write_handle(DwgReferenceType::HardPointer, vport.base_ucs_handle.value());
        }

        self.register_object(vport.handle);
    }

    fn write_appid_entries(&mut self) {
        let mut entries: Vec<_> = self.document.app_ids.iter().map(|a| a.clone()).collect();
        entries.sort_by_key(|app| !app.name.eq_ignore_ascii_case("ACAD"));
        for app in &entries {
            self.write_appid(app);
        }
    }

    fn write_appid(&mut self, app: &crate::tables::AppId) {
        self.write_common_non_entity_data(
            common::OBJ_APPID,
            app.handle,
            self.document.app_ids.handle(),
            &[],
            &None,
        );

        // Sanitize name: strip control chars and forbidden symbol table characters
        let name: String = app
            .name
            .chars()
            .filter(|c| {
                !c.is_control()
                    && !matches!(
                        c,
                        '<' | '>'
                            | '/'
                            | '\\'
                            | '"'
                            | ':'
                            | ';'
                            | '?'
                            | '*'
                            | '|'
                            | ','
                            | '='
                            | '`'
                    )
            })
            .collect();
        self.writer.write_variable_text(&name);
        self.write_xref_dependant_bit();

        // Unknown byte (group 71)
        self.writer.write_byte(0);

        // External reference block handle
        self.writer.write_handle(DwgReferenceType::HardPointer, 0);

        self.register_object(app.handle);
    }

    fn write_dimstyle_entries(&mut self) {
        let entries: Vec<_> = self.document.dim_styles.iter().map(|d| d.clone()).collect();
        for ds in &entries {
            self.write_dimstyle(ds);
        }
    }

    fn write_dimstyle(&mut self, ds: &crate::tables::DimStyle) {
        let dimclrd_color = ds
            .dimclrd_true_color
            .unwrap_or_else(|| crate::types::Color::from_index(ds.dimclrd));
        let dimclre_color = ds
            .dimclre_true_color
            .unwrap_or_else(|| crate::types::Color::from_index(ds.dimclre));
        let dimclrt_color = ds
            .dimclrt_true_color
            .unwrap_or_else(|| crate::types::Color::from_index(ds.dimclrt));
        let dimtfillclr_color = ds
            .dimtfillclr_true_color
            .unwrap_or_else(|| crate::types::Color::from_index(ds.dimtfillclr));
        let anno = self.annotative_eed_block_for_handle(ds.handle, ds.annotative);
        self.write_common_non_entity_data_eed(
            common::OBJ_DIMSTYLE,
            ds.handle,
            self.document.dim_styles.handle(),
            &[],
            &None,
            anno.into_iter().collect(),
        );

        // Common: Entry name TV 2
        self.writer.write_variable_text(&ds.name);
        self.write_xref_table_flags(ds.xref_reference, ds.xref_resolved, ds.xref_dependent);

        // ── R13/R14 Only: DimStyle fields ───────────────────────────
        // These fields are ONLY written for R13/R14 (not R2000+).
        // Field order matches the reference writeDimensionStyle() R13_14Only block.
        if self.version.r13_14_only() {
            // DIMTOL B 71
            self.writer.write_bit(ds.dimtol);
            // DIMLIM B 72
            self.writer.write_bit(ds.dimlim);
            // DIMTIH B 73
            self.writer.write_bit(ds.dimtih);
            // DIMTOH B 74
            self.writer.write_bit(ds.dimtoh);
            // DIMSE1 B 75
            self.writer.write_bit(ds.dimse1);
            // DIMSE2 B 76
            self.writer.write_bit(ds.dimse2);
            // DIMALT B 170
            self.writer.write_bit(ds.dimalt);
            // DIMTOFL B 172
            self.writer.write_bit(ds.dimtofl);
            // DIMSAH B 173
            self.writer.write_bit(ds.dimsah);
            // DIMTIX B 174
            self.writer.write_bit(ds.dimtix);
            // DIMSOXD B 175
            self.writer.write_bit(ds.dimsoxd);
            // DIMALTD RC 171
            self.writer.write_byte(ds.dimaltd as u8);
            // DIMZIN RC 78
            self.writer.write_byte(ds.dimzin as u8);
            // DIMSD1 B 281
            self.writer.write_bit(ds.dimsd1);
            // DIMSD2 B 282
            self.writer.write_bit(ds.dimsd2);
            // DIMTOLJ RC 283
            self.writer.write_byte(ds.dimtolj as u8);
            // DIMJUST RC 280
            self.writer.write_byte(ds.dimjust as u8);
            // DIMFIT RC 287
            self.writer.write_byte(ds.dimfit as u8);
            // DIMUPT B 288
            self.writer.write_bit(ds.dimupt);
            // DIMTZIN RC 284
            self.writer.write_byte(ds.dimtzin as u8);
            // DIMALTZ RC 285
            self.writer.write_byte(ds.dimaltz as u8);
            // DIMALTTZ RC 286
            self.writer.write_byte(ds.dimalttz as u8);
            // DIMTAD RC 77
            self.writer.write_byte(ds.dimtad as u8);
            // DIMUNIT BS 270
            self.writer.write_bit_short(ds.dimunit);
            // DIMAUNIT BS 275
            self.writer.write_bit_short(ds.dimaunit);
            // DIMDEC BS 271
            self.writer.write_bit_short(ds.dimdec);
            // DIMTDEC BS 272
            self.writer.write_bit_short(ds.dimtdec);
            // DIMALTU BS 273
            self.writer.write_bit_short(ds.dimaltu);
            // DIMALTTD BS 274
            self.writer.write_bit_short(ds.dimalttd);
            // DIMSCALE BD 40
            self.writer.write_bit_double(ds.dimscale);
            // DIMASZ BD 41
            self.writer.write_bit_double(ds.dimasz);
            // DIMEXO BD 42
            self.writer.write_bit_double(ds.dimexo);
            // DIMDLI BD 43
            self.writer.write_bit_double(ds.dimdli);
            // DIMEXE BD 44
            self.writer.write_bit_double(ds.dimexe);
            // DIMRND BD 45
            self.writer.write_bit_double(ds.dimrnd);
            // DIMDLE BD 46
            self.writer.write_bit_double(ds.dimdle);
            // DIMTP BD 47
            self.writer.write_bit_double(ds.dimtp);
            // DIMTM BD 48
            self.writer.write_bit_double(ds.dimtm);
            // DIMTXT BD 140
            self.writer.write_bit_double(ds.dimtxt);
            // DIMCEN BD 141
            self.writer.write_bit_double(ds.dimcen);
            // DIMTSZ BD 142
            self.writer.write_bit_double(ds.dimtsz);
            // DIMALTF BD 143
            self.writer.write_bit_double(ds.dimaltf);
            // DIMLFAC BD 144
            self.writer.write_bit_double(ds.dimlfac);
            // DIMTVP BD 145
            self.writer.write_bit_double(ds.dimtvp);
            // DIMTFAC BD 146
            self.writer.write_bit_double(ds.dimtfac);
            // DIMGAP BD 147
            self.writer.write_bit_double(ds.dimgap);
            // DIMPOST T 3
            self.writer.write_variable_text(&ds.dimpost);
            // DIMAPOST T 4
            self.writer.write_variable_text(&ds.dimapost);
            // DIMBLK T 5
            self.writer.write_variable_text(&ds.dimblk_name);
            // DIMBLK1 T 6
            self.writer.write_variable_text(&ds.dimblk1_name);
            // DIMBLK2 T 7
            self.writer.write_variable_text(&ds.dimblk2_name);
            // DIMCLRD BS 176
            self.writer.write_cm_color(&dimclrd_color);
            // DIMCLRE BS 177
            self.writer.write_cm_color(&dimclre_color);
            // DIMCLRT BS 178
            self.writer.write_cm_color(&dimclrt_color);
        }

        // ── R2000+ DimStyle fields ──────────────────────────────────
        // Field order, data types, and version guards match the reference implementation
        // DwgObjectWriter.writeDimensionStyle() exactly.
        if self.version.r2000_plus() {
            // DIMPOST TV 3
            self.writer.write_variable_text(&ds.dimpost);
            // DIMAPOST TV 4
            self.writer.write_variable_text(&ds.dimapost);
            // DIMSCALE BD 40
            self.writer.write_bit_double(ds.dimscale);
            // DIMASZ BD 41
            self.writer.write_bit_double(ds.dimasz);
            // DIMEXO BD 42
            self.writer.write_bit_double(ds.dimexo);
            // DIMDLI BD 43
            self.writer.write_bit_double(ds.dimdli);
            // DIMEXE BD 44
            self.writer.write_bit_double(ds.dimexe);
            // DIMRND BD 45
            self.writer.write_bit_double(ds.dimrnd);
            // DIMDLE BD 46
            self.writer.write_bit_double(ds.dimdle);
            // DIMTP BD 47
            self.writer.write_bit_double(ds.dimtp);
            // DIMTM BD 48
            self.writer.write_bit_double(ds.dimtm);
        }

        // R2007+
        if self.version.r2007_plus() {
            // DIMFXL BD 49
            self.writer.write_bit_double(ds.dimfxl);
            // DIMJOGANG BD 50 — clamp to valid range [5°..90°]
            self.writer
                .write_bit_double(ds.dimjogang.clamp(0.0873, 1.5708));
            // DIMTFILL BS 69
            self.writer.write_bit_short(ds.dimtfill);
            // DIMTFILLCLR CMC 70
            self.writer.write_cm_color(&dimtfillclr_color);
        }

        // R2000+
        if self.version.r2000_plus() {
            // DIMTOL B 71
            self.writer.write_bit(ds.dimtol);
            // DIMLIM B 72
            self.writer.write_bit(ds.dimlim);
            // DIMTIH B 73
            self.writer.write_bit(ds.dimtih);
            // DIMTOH B 74
            self.writer.write_bit(ds.dimtoh);
            // DIMSE1 B 75
            self.writer.write_bit(ds.dimse1);
            // DIMSE2 B 76
            self.writer.write_bit(ds.dimse2);
            // DIMTAD BS 77
            self.writer.write_bit_short(ds.dimtad);
            // DIMZIN BS 78
            self.writer.write_bit_short(ds.dimzin);
            // DIMAZIN BS 79
            self.writer.write_bit_short(ds.dimazin);
        }

        // R2007+
        if self.version.r2007_plus() {
            // DIMARCSYM BS 90
            self.writer.write_bit_short(ds.dimarcsym);
        }

        // R2000+
        if self.version.r2000_plus() {
            // DIMTXT BD 140
            self.writer.write_bit_double(ds.dimtxt);
            // DIMCEN BD 141
            self.writer.write_bit_double(ds.dimcen);
            // DIMTSZ BD 142
            self.writer.write_bit_double(ds.dimtsz);
            // DIMALTF BD 143
            self.writer.write_bit_double(ds.dimaltf);
            // DIMLFAC BD 144
            self.writer.write_bit_double(ds.dimlfac);
            // DIMTVP BD 145
            self.writer.write_bit_double(ds.dimtvp);
            // DIMTFAC BD 146
            self.writer.write_bit_double(ds.dimtfac);
            // DIMGAP BD 147
            self.writer.write_bit_double(ds.dimgap);
            // DIMALTRND BD 148
            self.writer.write_bit_double(ds.dimaltrnd);
            // DIMALT B 170
            self.writer.write_bit(ds.dimalt);
            // DIMALTD BS 171
            self.writer.write_bit_short(ds.dimaltd);
            // DIMTOFL B 172
            self.writer.write_bit(ds.dimtofl);
            // DIMSAH B 173
            self.writer.write_bit(ds.dimsah);
            // DIMTIX B 174
            self.writer.write_bit(ds.dimtix);
            // DIMSOXD B 175
            self.writer.write_bit(ds.dimsoxd);
            // DIMCLRD BS 176
            self.writer.write_cm_color(&dimclrd_color);
            // DIMCLRE BS 177
            self.writer.write_cm_color(&dimclre_color);
            // DIMCLRT BS 178
            self.writer.write_cm_color(&dimclrt_color);
            // DIMADEC BS 179
            self.writer.write_bit_short(ds.dimadec);
            // DIMDEC BS 271
            self.writer.write_bit_short(ds.dimdec);
            // DIMTDEC BS 272
            self.writer.write_bit_short(ds.dimtdec);
            // DIMALTU BS 273
            self.writer.write_bit_short(ds.dimaltu);
            // DIMALTTD BS 274
            self.writer.write_bit_short(ds.dimalttd);
            // DIMAUNIT BS 275
            self.writer.write_bit_short(ds.dimaunit);
            // DIMFRAC BS 276
            self.writer.write_bit_short(ds.dimfrac);
            // DIMLUNIT BS 277
            self.writer.write_bit_short(ds.dimlunit);
            // DIMDSEP BS 278
            self.writer.write_bit_short(ds.dimdsep);
            // DIMTMOVE BS 279
            self.writer.write_bit_short(ds.dimtmove);
            // DIMJUST BS 280
            self.writer.write_bit_short(ds.dimjust);
            // DIMSD1 B 281
            self.writer.write_bit(ds.dimsd1);
            // DIMSD2 B 282
            self.writer.write_bit(ds.dimsd2);
            // DIMTOLJ BS 283
            self.writer.write_bit_short(ds.dimtolj);
            // DIMTZIN BS 284
            self.writer.write_bit_short(ds.dimtzin);
            // DIMALTZ BS 285
            self.writer.write_bit_short(ds.dimaltz);
            // DIMALTTZ BS 286
            self.writer.write_bit_short(ds.dimalttz);
            // DIMUPT B 288
            self.writer.write_bit(ds.dimupt);
            // DIMATFIT BS 289
            self.writer.write_bit_short(ds.dimatfit);
        }

        // R2007+
        if self.version.r2007_plus() {
            // DIMFXLON B 290
            self.writer.write_bit(ds.dimfxlon);
        }

        // R2010+
        if self.version.r2010_plus() {
            // DIMTXTDIRECTION B 295
            self.writer.write_bit(ds.dimtxtdirection);
            // DIMALTMZF BD
            self.writer.write_bit_double(ds.dimaltmzf);
            // DIMALTMZS T
            self.writer.write_variable_text(&ds.dimaltmzs);
            // DIMMZF BD
            self.writer.write_bit_double(ds.dimmzf);
            // DIMMZS T
            self.writer.write_variable_text(&ds.dimmzs);
        }

        // R2000+
        if self.version.r2000_plus() {
            // DIMLWD BS 371
            self.writer.write_bit_short(ds.dimlwd);
            // DIMLWE BS 372
            self.writer.write_bit_short(ds.dimlwe);
        }

        // Common: Unknown B 70
        self.writer.write_bit(false);

        // ── Handle references ───────────────────────────────────────

        // External reference block handle (hard pointer)
        self.writer
            .write_handle(DwgReferenceType::HardPointer, ds.xref_handle.value());

        // 340 DIMTXSTY (hard pointer)
        self.writer
            .write_handle(DwgReferenceType::HardPointer, ds.dimtxsty_handle.value());

        // R2000+
        if self.version.r2000_plus() {
            // 341 DIMLDRBLK (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimldrblk.value());
            // 342 DIMBLK (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimblk.value());
            // 343 DIMBLK1 (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimblk1.value());
            // 344 DIMBLK2 (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimblk2.value());
        }

        // R2007+
        if self.version.r2007_plus() {
            // 345 dimltype (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimltex_handle.value());
            // 346 dimltex1 (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimltex1_handle.value());
            // 347 dimltex2 (hard pointer)
            self.writer
                .write_handle(DwgReferenceType::HardPointer, ds.dimltex2_handle.value());
        }

        self.register_object(ds.handle);
    }

    // ── Block entity writing ────────────────────────────────────────

    /// Write block begin/entities/end for every block record.
    fn write_block_entities(&mut self) {
        use crate::io::dwg::parallel::{map_chunks, worker_count};

        let block_records: Vec<BlockRecord> = self
            .document
            .block_records
            .iter()
            .map(|br| br.clone())
            .collect();

        for br in &block_records {
            // An xref block record references an external drawing: its contents
            // live in that file, not here. Some hosts merge the resolved xref
            // geometry into the block record for display; serializing those as
            // owned entities would bind/explode the xref into the host file on
            // the next open. Write the header with an empty owned list and skip
            // the entity loop entirely, leaving only the BLOCK/ENDBLK markers.
            // This matches the reader, which writes/reads no owned-object count
            // for an xref block (see the `is_xref` guards in the header).
            let is_xref = br.flags.is_xref || br.flags.is_xref_overlay;

            // Keep only live entities directly owned by the block header.
            let live_handles: Vec<Handle> = br
                .entity_handles
                .iter()
                .copied()
                .filter(|h| self.document.entity_index.contains_key(h))
                .collect();
            let entity_handles_for_header = if is_xref {
                Vec::new()
            } else {
                // Preserve the original order when it still matches the live set.
                match self.document.block_entity_handles.get(&br.handle) {
                    Some(orig) => {
                        use std::collections::HashSet;
                        let valid: HashSet<u64> = live_handles.iter().map(|h| h.value()).collect();
                        let filtered: Vec<Handle> = orig
                            .iter()
                            .copied()
                            .filter(|h| valid.contains(&h.value()))
                            .collect();
                        if filtered.len() == live_handles.len() {
                            filtered
                        } else {
                            live_handles.clone()
                        }
                    }
                    None => live_handles.clone(),
                }
            };
            self.write_block_header_with_handles(br, &entity_handles_for_header);
            self.write_block_begin(br);

            if !is_xref {
                // Look up entities by handle from the document. Iterate the
                // dangling-filtered list so the pre-R2004 prev/next links
                // never point at a handle that is not in the stream.
                let handles = &live_handles;
                let len = handles.len();
                let parallel = self.version.r2004_plus() && handles.len() >= 1_024;
                let mut i = 0usize;
                while i < len {
                    if parallel
                        && self
                            .document
                            .entity_index
                            .get(&handles[i])
                            .is_some_and(|idx| {
                                Self::parallel_entity_safe(self.document.entities[*idx].as_ref())
                            })
                    {
                        let start = i;
                        i += 1;
                        while i < len
                            && self
                                .document
                                .entity_index
                                .get(&handles[i])
                                .is_some_and(|idx| {
                                    Self::parallel_entity_safe(
                                        self.document.entities[*idx].as_ref(),
                                    )
                                })
                        {
                            i += 1;
                        }
                        let run = &handles[start..i];
                        let mut unique = foldhash::HashSet::default();
                        let safe_to_batch = run.len() >= 1_024
                            && run.iter().all(|handle| {
                                !self.registered_handles.contains(&handle.value())
                                    && unique.insert(handle.value())
                            });
                        if safe_to_batch {
                            let worker_count = worker_count();
                            let chunk_size =
                                ((run.len() + worker_count * 4 - 1) / (worker_count * 4)).max(512);
                            let batches: Vec<ParallelEntityBatch> =
                                map_chunks(run, chunk_size, |chunk| {
                                    self.serialize_parallel_entity_batch(chunk)
                                });
                            for batch in batches {
                                self.append_parallel_entity_batch(batch);
                            }
                            continue;
                        }
                        for (offset, eh) in run.iter().enumerate() {
                            if let Some(&idx) = self.document.entity_index.get(eh) {
                                self.prev_handle =
                                    (start + offset > 0).then(|| handles[start + offset - 1]);
                                self.next_handle =
                                    (start + offset + 1 < len).then(|| handles[start + offset + 1]);
                                self.write_entity(&self.document.entities[idx]);
                            }
                        }
                        continue;
                    }

                    let eh = &handles[i];
                    if let Some(&idx) = self.document.entity_index.get(eh) {
                        let entity = &self.document.entities[idx];
                        // Set prev/next for entity linking (pre-R2004)
                        self.prev_handle = if i > 0 { Some(handles[i - 1]) } else { None };
                        self.next_handle = if i + 1 < len {
                            Some(handles[i + 1])
                        } else {
                            None
                        };

                        self.write_entity(entity);
                    }
                    i += 1;
                }
            }

            self.prev_handle = None;
            self.next_handle = None;

            self.write_block_end(br);
        }
    }

    fn parallel_entity_safe(entity: &EntityType) -> bool {
        !matches!(
            entity,
            EntityType::Insert(_)
                | EntityType::Polyline2D(_)
                | EntityType::Polyline3D(_)
                | EntityType::PolyfaceMesh(_)
                | EntityType::PolygonMesh(_)
                | EntityType::Polyline(_)
                | EntityType::Solid3D(_)
                | EntityType::Region(_)
                | EntityType::Body(_)
                | EntityType::Surface(_)
                | EntityType::Block(_)
                | EntityType::BlockEnd(_)
        )
    }

    fn serialize_parallel_entity_batch(&self, handles: &[Handle]) -> ParallelEntityBatch {
        let encoding = crate::io::dxf::code_page::encoding_from_dwg_code_page(
            crate::io::dxf::code_page::dwg_code_page_index(&self.document.header.code_page),
        );
        let mut worker = Self {
            version: self.version,
            dxf_version: self.dxf_version,
            document: self.document,
            writer: DwgMergedWriter::with_encoding(self.version, self.dxf_version, encoding),
            output: Vec::with_capacity(handles.len().saturating_mul(64)),
            handle_map: Vec::with_capacity(handles.len()),
            object_queue: VecDeque::new(),
            prev_handle: None,
            next_handle: None,
            next_alloc_handle: self.next_alloc_handle,
            model_space_extents: None,
            sab_entries: Vec::new(),
            pending_has_ds_data: false,
            visited_objects: HashSet::new(),
            class_instance_counts: HashMap::new(),
            pending_type_code: None,
            class_counts_complete: true,
            registered_handles: HashSet::with_capacity(handles.len()),
            raw_excluded_handles: self.raw_excluded_handles.clone(),
            xdic_owner_index: self.xdic_owner_index.clone(),
            block_users: self.block_users.clone(),
            owner_overrides: std::collections::HashMap::new(),
            linetype_handles: std::collections::HashMap::new(),
        };
        for handle in handles {
            if let Some(&idx) = worker.document.entity_index.get(handle) {
                worker.write_entity(&worker.document.entities[idx]);
            }
        }
        ParallelEntityBatch {
            output: worker.output,
            handle_map: worker.handle_map,
            object_queue: worker.object_queue,
            registered_handles: worker.registered_handles,
            class_instance_counts: worker.class_instance_counts,
            class_counts_complete: worker.class_counts_complete,
        }
    }

    fn append_parallel_entity_batch(&mut self, batch: ParallelEntityBatch) {
        debug_assert!(
            batch
                .registered_handles
                .iter()
                .all(|handle| !self.registered_handles.contains(handle)),
            "parallel entity batch emitted a duplicate handle"
        );
        let base = self.output.len() as u32;
        self.output.extend_from_slice(&batch.output);
        self.handle_map.extend(
            batch
                .handle_map
                .into_iter()
                .map(|(handle, offset)| (handle, base + offset)),
        );
        self.object_queue.extend(batch.object_queue);
        self.registered_handles.extend(batch.registered_handles);
        for (class_number, count) in batch.class_instance_counts {
            *self.class_instance_counts.entry(class_number).or_default() += count;
        }
        self.class_counts_complete &= batch.class_counts_complete;
    }

    /// Write a BLOCK_HEADER (block record) object with explicit entity handles.
    fn write_block_header_with_handles(&mut self, record: &BlockRecord, entity_handles: &[Handle]) {
        // Before R2007 the block record has no insertion-units field; the
        // units travel in the ACAD `DesignCenter Data` EED (version 1).
        let had_units = self
            .existing_xdata_values(record.handle, "ACAD")
            .is_some_and(|values| {
                values.iter().any(|value| {
                    matches!(value, crate::xdata::XDataValue::String(label) if label == "DesignCenter Data")
                })
            });
        let extra = if self.version.r2007_plus() || (record.units == 0 && !had_units) {
            Vec::new()
        } else {
            let mut units = crate::xdata::ExtendedDataRecord::new("ACAD");
            units.values = crate::tables::block_record::design_center_units_values(record.units);
            self.encode_xdata_record(&units).into_iter().collect()
        };
        self.write_common_non_entity_data_eed(
            common::OBJ_BLOCK_HEADER,
            record.handle,
            self.document.block_records.handle(),
            &[],
            &None,
            extra,
        );

        // Entry name (DWG uses bare names without numeric suffixes)
        let dwg_name = dwg_block_name(&record.name);
        self.writer.write_variable_text(dwg_name);
        // Xref dependant
        self.write_xref_dependant_bit();

        // Anonymous flag
        self.writer.write_bit(record.flags.anonymous);
        // Has attributes
        let has_attributes = record.entity_handles.iter().any(|handle| {
            matches!(
                self.document.get_entity(*handle),
                Some(EntityType::AttributeDefinition(_))
            )
        });
        self.writer.write_bit(record.flags.has_attributes || has_attributes);
        // Is xref
        self.writer.write_bit(record.flags.is_xref);
        // Is xref overlay
        self.writer.write_bit(record.flags.is_xref_overlay);

        // R2000+: "loaded" bit, 1 = xref currently unloaded (0 = loaded)
        if self.version.r2000_plus() {
            self.writer.write_bit(record.flags.is_xref_unloaded);
        }

        // R2004+: owned object count (non-xref)
        if self.version.r2004_plus() && !record.flags.is_xref && !record.flags.is_xref_overlay {
            self.writer.write_bit_long(entity_handles.len() as i32);
        }

        // Base point (from Block entity if found)
        let base_pt = record
            .entity_handles
            .iter()
            .find_map(|eh| {
                if let Some(EntityType::Block(b)) = self
                    .document
                    .entity_index
                    .get(eh)
                    .map(|&idx| self.document.entities[idx].as_ref())
                {
                    Some(b.base_point)
                } else {
                    None
                }
            })
            .unwrap_or(record.base_point);
        self.writer.write_3bit_double(base_pt);

        // Xref path
        self.writer.write_variable_text(&record.xref_path);

        // R2000+: insert count bytes + block description + preview data
        if self.version.r2000_plus() {
            // Insert count bytes: one non-zero byte per insert handle written
            // below, then a zero terminator.
            for (i, _) in self.block_insert_handles(record).iter().enumerate() {
                let b = record.insert_count_bytes.get(i).copied().filter(|b| *b != 0).unwrap_or(1);
                self.writer.write_byte(b);
            }
            self.writer.write_byte(0);

            // Block description
            self.writer.write_variable_text(&record.description);

            // Preview data
            self.writer.write_bit_long(record.preview_data.len() as i32);
            for &b in &record.preview_data {
                self.writer.write_byte(b);
            }
        }

        // R2007+: units, explodable, scaling
        if self.version.r2007_plus() {
            self.writer.write_bit_short(record.units);
            self.writer.write_bit(record.explodable);
            self.writer
                .write_byte(if record.scale_uniformly { 1 } else { 0 });
        }

        // NULL handle (hard pointer)
        self.writer.write_handle(DwgReferenceType::HardPointer, 0);

        // BLOCK entity handle (hard owner)
        self.writer.write_handle(
            DwgReferenceType::HardOwnership,
            record.block_entity_handle.value(),
        );

        // R13-R2000: first/last entity handles
        if self.version.r13_15_only() && !record.flags.is_xref && !record.flags.is_xref_overlay {
            let first = entity_handles.first().copied().unwrap_or(Handle::NULL);
            let last = entity_handles.last().copied().unwrap_or(Handle::NULL);
            self.writer
                .write_handle(DwgReferenceType::SoftPointer, first.value());
            self.writer
                .write_handle(DwgReferenceType::SoftPointer, last.value());
        }

        // R2004+: entity handles (hard owner). Xref blocks own no entities in
        // the format — the owned-object count is skipped above, so the reader
        // reads zero handles here. Writing any would desync the handle stream
        // and corrupt the block record on read, matching the R13-R2000 guard.
        if self.version.r2004_plus() && !record.flags.is_xref && !record.flags.is_xref_overlay {
            for h in entity_handles {
                self.writer
                    .write_handle(DwgReferenceType::HardOwnership, h.value());
            }
        }

        // ENDBLK handle (hard owner)
        self.writer.write_handle(
            DwgReferenceType::HardOwnership,
            record.block_end_handle.value(),
        );

        // R2000+: insert handles come BEFORE the layout handle (ODA spec
        // order: endblk, inserts[num_inserts], layout). Writing layout first
        // desyncs the handle stream for any block that is referenced by an
        // insert, making AutoCAD discard the block record (eWrongObjectType).
        if self.version.r2000_plus() {
            for ih in self.block_insert_handles(record) {
                self.writer
                    .write_handle(DwgReferenceType::SoftPointer, ih.value());
            }
        }

        // R2000+: layout handle
        if self.version.r2000_plus() {
            self.writer
                .write_handle(DwgReferenceType::HardPointer, record.layout.value());
        }

        self.register_object(record.handle);
    }

    /// Write BLOCK entity (block begin).
    fn write_block_begin(&mut self, record: &BlockRecord) {
        // New documents reserve marker handles in BlockRecord without storing
        // BLOCK entities. Synthesize those markers; imported ones retain metadata.
        let block = if !record.block_entity_handle.is_null() {
            self.document
                .entity_index
                .get(&record.block_entity_handle)
                .and_then(|&idx| {
                    if let EntityType::Block(b) = self.document.entities[idx].as_ref() {
                        Some(b.clone())
                    } else {
                        None
                    }
                })
        } else {
            None
        };

        let (handle, name, use_raw_name) = if let Some(ref b) = block {
            (b.common.handle, b.name.as_str(), true)
        } else {
            (record.block_entity_handle, record.name.as_str(), false)
        };

        let mut common = block
            .as_ref()
            .map(|b| &b.common)
            .cloned()
            .unwrap_or_else(|| EntityCommon {
                handle,
                owner_handle: record.handle,
                ..Default::default()
            });
        // The block record is the structural owner even when a damaged or
        // loosely decoded BLOCK marker carried a different common owner.
        common.owner_handle = record.handle;

        self.write_common_entity_data(
            common::OBJ_BLOCK,
            common.handle,
            common.owner_handle,
            &common.layer,
            &common.color,
            &common.line_weight,
            &common.transparency,
            common.invisible,
            common.linetype_scale,
            &common.linetype,
            &common.linetype_handle,
            &common.extended_data,
            &common.reactors,
            &common.xdictionary_handle,
            common.graphic_data.as_deref(),
            common.entity_mode,
            common.material_flags,
            &common.material_handle,
            common.shadow_flags,
            common.plotstyle_flags,
            &common.plotstyle_handle,
            &common.color_book_handle,
            &common.full_visual_style_handle,
            &common.face_visual_style_handle,
            &common.edge_visual_style_handle,
        );

        // Use the original name as-is when we have the Block entity from binary;
        // only apply dwg_block_name() for programmatically-created blocks.
        if use_raw_name {
            self.writer.write_variable_text(name);
        } else {
            self.writer.write_variable_text(dwg_block_name(name));
        }

        self.register_object(common.handle);
    }

    /// Write ENDBLK entity (block end).
    fn write_block_end(&mut self, record: &BlockRecord) {
        let block_end = if !record.block_end_handle.is_null() {
            self.document
                .entity_index
                .get(&record.block_end_handle)
                .and_then(|&idx| {
                    if let EntityType::BlockEnd(be) = self.document.entities[idx].as_ref() {
                        Some(be.clone())
                    } else {
                        None
                    }
                })
        } else {
            None
        };

        let mut common = block_end
            .map(|be| be.common)
            .unwrap_or_else(|| EntityCommon {
                handle: record.block_end_handle,
                owner_handle: record.handle,
                ..Default::default()
            });
        common.owner_handle = record.handle;

        self.write_common_entity_data(
            common::OBJ_ENDBLK,
            common.handle,
            common.owner_handle,
            &common.layer,
            &common.color,
            &common.line_weight,
            &common.transparency,
            common.invisible,
            common.linetype_scale,
            &common.linetype,
            &common.linetype_handle,
            &common.extended_data,
            &common.reactors,
            &common.xdictionary_handle,
            common.graphic_data.as_deref(),
            common.entity_mode,
            common.material_flags,
            &common.material_handle,
            common.shadow_flags,
            common.plotstyle_flags,
            &common.plotstyle_handle,
            &common.color_book_handle,
            &common.full_visual_style_handle,
            &common.face_visual_style_handle,
            &common.edge_visual_style_handle,
        );

        self.register_object(common.handle);
    }

    // ── Object queue draining ───────────────────────────────────────

    /// Debug bisection aid. When `ACADRUST_RAW_ALL` is set, every record the
    /// reader captured from the source file (see `CadDocument::raw_records`)
    /// is registered verbatim up front, so the normal serialisers are only
    /// used for record types listed in `ACADRUST_RAW_EXCLUDE` (comma-separated
    /// numeric DWG type codes or class DXF names, case-insensitive). The
    /// duplicate-handle guards in `register_object` / `register_raw_object`
    /// and the early return in `write_entity` keep the normal path from
    /// emitting a second copy. Compound parents and children are excluded
    /// together because their serializers also write their child records.
    /// Only meaningful for an unmodified document written back to its own version.
    fn preregister_raw_records(&mut self) {
        if std::env::var_os("ACADRUST_RAW_ALL").is_none() || self.document.raw_records.is_empty() {
            return;
        }
        let exclude: Vec<String> = std::env::var("ACADRUST_RAW_EXCLUDE")
            .unwrap_or_default()
            .split(',')
            .map(|s| s.trim().to_ascii_uppercase())
            .filter(|s| !s.is_empty())
            .collect();
        let mut handles: Vec<u64> = self.document.raw_records.keys().copied().collect();
        handles.sort_unstable();
        let mut excluded_handles = HashSet::new();
        for &h in &handles {
            let (type_code, raw) = &self.document.raw_records[&h];
            if raw.version != self.dxf_version {
                continue;
            }
            let class_name = if *type_code >= 500 {
                self.document
                    .classes
                    .iter()
                    .find(|c| c.class_number == *type_code)
                    .map(|c| c.dxf_name.to_ascii_uppercase())
                    .unwrap_or_default()
            } else {
                String::new()
            };
            let code_str = type_code.to_string();
            // Category tokens: TABLES (symbol tables + controls + block headers),
            // ENTITIES, OBJECTS (everything else).
            let is_table =
                crate::io::dwg::dwg_stream_readers::object_reader::common::is_table_type(*type_code);
            let is_entity = if *type_code >= 500 {
                self.document
                    .classes
                    .iter()
                    .find(|c| c.class_number == *type_code)
                    .map(|c| c.is_an_entity)
                    .unwrap_or(false)
            } else {
                crate::io::dwg::dwg_stream_readers::object_reader::common::is_entity_type(*type_code)
            };
            let category = if is_table {
                "TABLES"
            } else if is_entity {
                "ENTITIES"
            } else {
                "OBJECTS"
            };
            if exclude.iter().any(|e| {
                *e == code_str || *e == category || (!class_name.is_empty() && *e == class_name)
            }) {
                excluded_handles.insert(h);
            }
        }

        // Child records are folded into their parent on read. Selecting any
        // member must run the parent writer and replace the whole child set.
        for (&child, &owner) in &self.document.raw_record_owners {
            if excluded_handles.contains(&child) {
                excluded_handles.insert(owner);
            }
        }
        for (&child, &owner) in &self.document.raw_record_owners {
            if excluded_handles.contains(&owner) {
                excluded_handles.insert(child);
            }
        }
        self.raw_excluded_handles = std::sync::Arc::new(excluded_handles);

        let (mut registered, mut excluded, mut skipped) = (0usize, 0usize, 0usize);
        for h in handles {
            let (_, raw) = &self.document.raw_records[&h];
            if raw.version != self.dxf_version {
                skipped += 1;
                continue;
            }
            if self.raw_excluded_handles.contains(&h) {
                excluded += 1;
                continue;
            }
            self.register_raw_object(Handle::from(h), &raw.data, raw.handle_bits);
            if let Some(entity) = self.document.get_entity(Handle::from(h)) {
                self.queue_raw_entity_sab(entity);
            }
            registered += 1;
        }
        eprintln!(
            "[acadrust raw-all] registered={registered} excluded={excluded} version-skipped={skipped} exclude={exclude:?}"
        );
    }

    /// Drain the object queue, writing each non-graphical object.
    fn write_objects(&mut self) {
        // Phase 1: drain the queue (root dict entries + xdict handles)
        while let Some(handle) = self.object_queue.pop_front() {
            if self.visited_objects.contains(&handle) {
                continue;
            }
            if let Some(obj) = self.document.objects.get(&handle) {
                self.visited_objects.insert(handle);
                let obj = obj.clone();
                self.write_object(&obj);
            }
        }

        // Phase 2: write any remaining objects not yet visited.
        // Extension dictionaries on table entries (layers, block records,
        // etc.) may not be reachable from the root dictionary chain because
        // the table entry structs don't store xdictionary handles.  This
        // loop catches all orphaned dictionaries, XRecords, etc.
        //
        // First, seed visited_objects with ALL handles already written
        // (table controls, table entries, block entities, Phase 1 objects)
        // to prevent Phase 2 from creating duplicate handle→offset entries
        // that would corrupt the Object Map.
        for &(handle_val, _) in &self.handle_map {
            self.visited_objects.insert(Handle::from(handle_val));
        }

        let mut remaining: Vec<(Handle, crate::objects::ObjectType)> = self
            .document
            .objects
            .iter()
            .filter(|(h, _)| !self.visited_objects.contains(h))
            .map(|(h, o)| (*h, o.clone()))
            .collect();
        // `objects` is a HashMap: iterate in handle order so the same
        // document writes the same bytes on every call.
        remaining.sort_by_key(|(h, _)| h.value());

        for (handle, obj) in remaining {
            self.visited_objects.insert(handle);
            self.write_object(&obj);
            // Drain any newly enqueued objects (children of orphan dicts)
            while let Some(child) = self.object_queue.pop_front() {
                if self.visited_objects.contains(&child) {
                    continue;
                }
                if let Some(child_obj) = self.document.objects.get(&child) {
                    self.visited_objects.insert(child);
                    let child_obj = child_obj.clone();
                    self.write_object(&child_obj);
                }
            }
        }
    }

    // ── Access helpers ──────────────────────────────────────────────

    /// Get the output bytes.
    pub fn output(&self) -> &[u8] {
        &self.output
    }

    /// Get the handle map.
    pub fn handle_map(&self) -> &[(u64, u32)] {
        &self.handle_map
    }
}

// ── Tests ──────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
    use super::*;
    use crate::entities::Line;
    use crate::objects::{Dictionary, ObjectType};

    #[test]
    fn object_writer_creates_for_default_document() {
        let doc = CadDocument::new();
        let writer = DwgObjectWriter::new(&doc);
        assert!(writer.is_ok());
    }

    #[test]
    fn object_writer_writes_basic_document() {
        let doc = CadDocument::new();
        let writer = DwgObjectWriter::new(&doc).unwrap();
        let (output, handle_map, _, _) = writer.write();
        // Should have produced some output (at least the 0x0DCA marker)
        assert!(!output.is_empty());
        // Should have recorded some handles (table controls + entries)
        assert!(!handle_map.is_empty());
    }

    #[test]
    fn object_writer_encodes_dca_marker() {
        let doc = CadDocument::new();
        let writer = DwgObjectWriter::new(&doc).unwrap();
        let (output, _, _, _) = writer.write();
        // First 4 bytes should be 0x0DCA as little-endian i32
        if output.len() >= 4 {
            let marker = i32::from_le_bytes([output[0], output[1], output[2], output[3]]);
            assert_eq!(marker, 0x0DCA);
        }
    }

    #[test]
    fn extension_dictionary_index_matches_document_fallback() {
        let mut document = CadDocument::new();
        let owner = document
            .add_entity(EntityType::Line(Line::from_coords(
                0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
            )))
            .expect("line");
        let dictionary_handle = document.allocate_handle();
        let dictionary = Dictionary {
            handle: dictionary_handle,
            owner,
            ..Dictionary::new()
        };
        document
            .objects
            .insert(dictionary_handle, ObjectType::Dictionary(dictionary));

        let expected = document.extension_dictionary_handle(owner);
        let writer = DwgObjectWriter::new(&document).expect("writer");
        assert_eq!(writer.extension_dictionary_handle(owner), expected);
    }
}