summaryrefslogtreecommitdiff
path: root/pcbnew/specctra.h
blob: 540fcf9b133c79f8d7e89c953fc67b0e6911f6ce (plain)
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
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2007-2013 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2007-2015 KiCad Developers, see change_log.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#ifndef SPECCTRA_H_
#define SPECCTRA_H_


//  see http://www.boost.org/libs/ptr_container/doc/ptr_sequence_adapter.html
#include <boost/ptr_container/ptr_vector.hpp>

//  see http://www.boost.org/libs/ptr_container/doc/ptr_set.html
#include <boost/ptr_container/ptr_set.hpp>
#include <boost/shared_ptr.hpp>

#include <fctsys.h>
#include <specctra_lexer.h>
#include <pcbnew.h>

// all outside the DSN namespace:
class BOARD;
class TRACK;
class VIA;
class NETCLASS;
class MODULE;
class SHAPE_POLY_SET;

typedef DSN::T  DSN_T;


/**
    This source file implements export and import capabilities to the
    specctra dsn file format.  The grammar for that file format is documented
    fairly well.  There are classes for each major type of descriptor in the
    spec.

    Since there are so many classes in here, it may be helpful to generate
    the Doxygen directory:

    $ cd &ltkicadSourceRoot&gt
    $ doxygen

    Then you can view the html documentation in the &ltkicadSourceRoot&gt/doxygen
    directory.  The main class in this file is SPECCTRA_DB and its main
    functions are LoadPCB(), LoadSESSION(), and ExportPCB().

    Wide use is made of boost::ptr_vector&lt&gt and std::vector&lt&gt template classes.
    If the contained object is small, then std::vector tends to be used.
    If the contained object is large, variable size, or would require writing
    an assignment operator() or copy constructore, then boost::ptr_vector
    cannot be beat.
*/
namespace DSN {


class SPECCTRA_DB;


/**
 * Function GetTokenText
 * is in the DSN namespace and returns the C string representing a
 * SPECCTRA_DB::keyword.  We needed a non-instanance function to get at
 * the SPECCTRA_DB::keyword[] and class SPECCTRA_DB is not defined yet.
 */
const char* GetTokenText( T aTok );


/**
 * Struct POINT
 * is a holder for a point in the SPECCTRA DSN coordinate system.  It can also
 * be used to hold a distance (vector really) from some origin.
 */
struct POINT
{
    double  x;
    double  y;

    POINT() { x=0.0; y=0.0; }

    POINT( double aX, double aY ) :
        x(aX), y(aY)
    {
    }

    bool operator==( const POINT& other ) const
    {
        return x==other.x && y==other.y;
    }

    bool operator!=( const POINT& other ) const
    {
        return !( *this == other );
    }

    POINT& operator+=( const POINT& other )
    {
        x += other.x;
        y += other.y;
        return *this;
    }

    POINT& operator=( const POINT& other )
    {
        x = other.x;
        y = other.y;
        return *this;
    }

    /**
     * Function FixNegativeZero
     * will change negative zero to positive zero in the IEEE floating point
     * storage format.  Basically turns off the sign bit if the mantissa and
     * exponent say the value is otherwise zero.
     */
    void FixNegativeZero()
    {
        if( x == -0.0 )
            x = 0.0;
        if( y == -0.0 )
            y = 0.0;
    }

    /**
     * Function Format
     * writes this object as ASCII out to an OUTPUTFORMATTER according to the
     * SPECCTRA DSN format.
     * @param out The formatter to write to.
     * @param nestLevel A multiple of the number of spaces to preceed the output with.
     * @throw IO_ERROR if a system error writing the output, such as a full disk.
     */
    void Format( OUTPUTFORMATTER* out, int nestLevel ) const throw( IO_ERROR )
    {
        out->Print( nestLevel, " %.6g %.6g", x, y );
    }
};

typedef std::vector<std::string>    STRINGS;
typedef std::vector<POINT>          POINTS;

struct PROPERTY
{
    std::string name;
    std::string value;

    /**
     * Function Format
     * writes this object as ASCII out to an OUTPUTFORMATTER according to the
     * SPECCTRA DSN format.
     * @param out The formatter to write to.
     * @param nestLevel A multiple of the number of spaces to preceed the output with.
     * @throw IO_ERROR if a system error writing the output, such as a full disk.
     */
    void Format( OUTPUTFORMATTER* out, int nestLevel ) const throw( IO_ERROR )
    {
        const char* quoteName  = out->GetQuoteChar( name.c_str() );
        const char* quoteValue = out->GetQuoteChar( value.c_str() );

        out->Print( nestLevel, "(%s%s%s %s%s%s)\n",
                   quoteName,  name.c_str(), quoteName,
                   quoteValue, value.c_str(), quoteValue );
    }
};
typedef std::vector<PROPERTY>       PROPERTIES;


class UNIT_RES;

/**
 * Class ELEM
 * is a base class for any DSN element class.
 * See class ELEM_HOLDER also.
 */
class ELEM
{
    friend class SPECCTRA_DB;

protected:
    DSN_T           type;
    ELEM*           parent;


    /**
     * Function makeHash
     * returns a string which uniquely represents this ELEM amoung other
     * ELEMs of the same derived class as "this" one.
     * It is not useable for all derived classes, only those which plan for
     * it by implementing a FormatContents() function that captures all info
     * which will be used in the subsequent string compare.  THIS SHOULD
     * NORMALLY EXCLUDE THE TYPENAME, AND INSTANCE NAME OR ID AS WELL.
     */
    std::string makeHash()
    {
        sf.Clear();
        FormatContents( &sf, 0 );
        sf.StripUseless();

        return sf.GetString();
    }

    // avoid creating this for every compare, make static.
    static STRING_FORMATTER  sf;


public:

    ELEM( DSN_T aType, ELEM* aParent = 0 );

    virtual ~ELEM();

    DSN_T   Type() const { return type; }

    const char* Name() const;


    /**
     * Function GetUnits
     * returns the units for this section.  Derived classes may override this
     * to check for section specific overrides.
     * @return UNIT_RES* - from a local or parent scope
     */
    virtual UNIT_RES* GetUnits() const;

    /**
     * Function Format
     * writes this object as ASCII out to an OUTPUTFORMATTER according to the
     * SPECCTRA DSN format.
     * @param out The formatter to write to.
     * @param nestLevel A multiple of the number of spaces to preceed the output with.
     * @throw IO_ERROR if a system error writing the output, such as a full disk.
     */
    virtual void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR );


    /**
     * Function FormatContents
     * writes the contents as ASCII out to an OUTPUTFORMATTER according to the
     * SPECCTRA DSN format.  This is the same as Format() except that the outer
     * wrapper is not included.
     * @param out The formatter to write to.
     * @param nestLevel A multiple of the number of spaces to preceed the output with.
     * @throw IO_ERROR if a system error writing the output, such as a full disk.
     */
    virtual void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        // overridden in ELEM_HOLDER
    }

    void SetParent( ELEM* aParent )
    {
        parent = aParent;
    }
};


/**
 * Class ELEM_HOLDER
 * is a holder for any DSN class.  It can contain other
 * class instances, including classes derived from this class.
 */
class ELEM_HOLDER : public ELEM
{
    friend class SPECCTRA_DB;

    typedef boost::ptr_vector<ELEM> ELEM_ARRAY;

    ELEM_ARRAY      kids;      ///< ELEM pointers

public:

    ELEM_HOLDER( DSN_T aType, ELEM* aParent = 0 ) :
        ELEM( aType, aParent )
    {
    }

    virtual void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR );


    //-----< list operations >--------------------------------------------

    /**
     * Function FindElem
     * finds a particular instance number of a given type of ELEM.
     * @param aType The type of ELEM to find
     * @param instanceNum The instance number of to find: 0 for first, 1 for second, etc.
     * @return int - The index into the kids array or -1 if not found.
     */
    int FindElem( DSN_T aType, int instanceNum = 0 );


    /**
     * Function Length
     * returns the number of ELEMs in this ELEM.
     * @return int - the count of children
     */
    int     Length() const
    {
        return kids.size();
    }

    void    Append( ELEM* aElem )
    {
        kids.push_back( aElem );
    }

    ELEM*   Replace( int aIndex, ELEM* aElem )
    {
        ELEM_ARRAY::auto_type ret = kids.replace( aIndex, aElem );
        return ret.release();
    }

    ELEM*   Remove( int aIndex )
    {
        ELEM_ARRAY::auto_type ret = kids.release( kids.begin()+aIndex );
        return ret.release();
    }

    void    Insert( int aIndex, ELEM* aElem )
    {
        kids.insert( kids.begin()+aIndex, aElem );
    }

    ELEM*   At( int aIndex ) const
    {
        // we have varying sized objects and are using polymorphism, so we
        // must return a pointer not a reference.
        return (ELEM*) &kids[aIndex];
    }

    ELEM* operator[]( int aIndex ) const
    {
        return At( aIndex );
    }

    void    Delete( int aIndex )
    {
        kids.erase( kids.begin()+aIndex );
    }
};


/**
 * Class PARSER
 * is simply a configuration record per the SPECCTRA DSN file spec.
 * It is not actually a parser, but rather corresponds to &lt;parser_descriptor&gt;
 */
class PARSER : public ELEM
{
    friend class SPECCTRA_DB;

    char        string_quote;
    bool        space_in_quoted_tokens;
    bool        case_sensitive;
    bool        wires_include_testpoint;
    bool        routes_include_testpoint;
    bool        routes_include_guides;
    bool        routes_include_image_conductor;
    bool        via_rotate_first;
    bool        generated_by_freeroute;

    /// This holds pairs of strings, one pair for each constant definition
    STRINGS     constants;

    std::string host_cad;
    std::string host_version;


public:

    PARSER( ELEM* aParent );

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR );
};


/**
 * Class UNIT_RES
 * is a holder for either a T_unit or T_resolution object which are usually
 * mutually exclusive in the dsn grammar, except within the T_pcb level.
 */
class UNIT_RES : public ELEM
{
    friend class SPECCTRA_DB;

    DSN_T       units;
    int         value;

public:

    /**
     * A static instance which holds the default units of T_inch and 2540000.
     * See page 108 of the specctra spec, May 2000.
     */
    static UNIT_RES Default;

    UNIT_RES( ELEM* aParent, DSN_T aType ) :
        ELEM( aType, aParent )
    {
        units = T_inch;
        value = 2540000;
    }

    DSN_T   GetEngUnits() const  { return units; }
    int     GetValue() const  { return value; }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( type == T_unit )
            out->Print( nestLevel, "(%s %s)\n", Name(),
                       GetTokenText(units) );

        else    // T_resolution
            out->Print( nestLevel, "(%s %s %d)\n", Name(),
                       GetTokenText(units), value );
    }
};


class RECTANGLE : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     layer_id;

    POINT           point0;         ///< one of two opposite corners
    POINT           point1;

public:

    RECTANGLE( ELEM* aParent ) :
        ELEM( T_rect, aParent )
    {
    }

    void SetLayerId( const char* aLayerId )
    {
        layer_id = aLayerId;
    }

    void SetCorners( const POINT& aPoint0, const POINT& aPoint1 )
    {
        point0 = aPoint0;
        point0.FixNegativeZero();

        point1 = aPoint1;
        point1.FixNegativeZero();
    }

    POINT GetOrigin() { return point0; }
    POINT GetEnd() { return point1; }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* newline = nestLevel ? "\n" : "";

        const char* quote = out->GetQuoteChar( layer_id.c_str() );

        out->Print( nestLevel, "(%s %s%s%s %.6g %.6g %.6g %.6g)%s",
                   Name(),
                   quote, layer_id.c_str(), quote,
                   point0.x, point0.y,
                   point1.x, point1.y,
                   newline );
    }
};


/**
 * Class RULE
 * corresponds to the &lt;rule_descriptor&gt; in the specctra dsn spec.
 */
class RULE : public ELEM
{
    friend class SPECCTRA_DB;

    STRINGS     rules;      ///< rules are saved in std::string form.

public:

    RULE( ELEM* aParent, DSN_T aType ) :
        ELEM( aType, aParent )
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s", Name() );

        bool singleLine;

        if( rules.size() == 1 )
        {
            singleLine = true;
            out->Print( 0, " %s)", rules.begin()->c_str() );
        }

        else
        {
            out->Print( 0, "\n" );
            singleLine = false;
            for( STRINGS::const_iterator i = rules.begin();  i!=rules.end(); ++i )
                out->Print( nestLevel+1, "%s\n", i->c_str() );
            out->Print( nestLevel, ")" );
        }

        if( nestLevel || !singleLine )
            out->Print( 0, "\n" );
    }
};


class LAYER_RULE : public ELEM
{
    friend class SPECCTRA_DB;

    STRINGS         layer_ids;
    RULE*           rule;

public:

    LAYER_RULE( ELEM* aParent ) :
        ELEM( T_layer_rule, aParent )
    {
        rule = 0;
    }
    ~LAYER_RULE()
    {
        delete rule;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s", Name() );

        for( STRINGS::const_iterator i=layer_ids.begin();  i!=layer_ids.end();  ++i )
        {
            const char* quote = out->GetQuoteChar( i->c_str() );
            out->Print( 0, " %s%s%s", quote, i->c_str(), quote );
        }
        out->Print( 0 , "\n" );

        if( rule )
            rule->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }
};
typedef boost::ptr_vector<LAYER_RULE>   LAYER_RULES;


/**
 * Class PATH
 * supports both the &lt;path_descriptor&gt; and the &lt;polygon_descriptor&gt; per
 * the specctra dsn spec.
 */
class PATH : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     layer_id;
    double          aperture_width;

    POINTS          points;
    DSN_T           aperture_type;

public:

    PATH( ELEM* aParent, DSN_T aType = T_path ) :
        ELEM( aType, aParent )
    {
        aperture_width = 0.0;
        aperture_type  = T_round;
    }

    void AppendPoint( const POINT& aPoint )
    {
        points.push_back( aPoint );
    }

    POINTS& GetPoints() {return points; }

    void SetLayerId( const char* aLayerId )
    {
        layer_id = aLayerId;
    }

    void SetAperture( double aWidth )
    {
        aperture_width = aWidth;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* newline = nestLevel ? "\n" : "";

        const char* quote = out->GetQuoteChar( layer_id.c_str() );

        const int RIGHTMARGIN = 70;
        int perLine = out->Print( nestLevel, "(%s %s%s%s %.6g",
                               Name(),
                               quote, layer_id.c_str(), quote,
                               aperture_width );

        int wrapNest = std::max( nestLevel+1, 6 );
        for( unsigned i=0;  i<points.size();  ++i )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( wrapNest, "%s", "" );
            }
            else
                perLine += out->Print( 0, "  " );

            perLine += out->Print( 0, "%.6g %.6g", points[i].x, points[i].y );
        }

        if( aperture_type == T_square )
        {
            out->Print( 0, "(aperture_type square)" );
        }

        out->Print( 0, ")%s", newline );
    }
};
typedef boost::ptr_vector<PATH> PATHS;


class BOUNDARY : public ELEM
{
    friend class SPECCTRA_DB;

    // only one or the other of these two is used, not both
    PATHS           paths;
    RECTANGLE*      rectangle;


public:

    BOUNDARY( ELEM* aParent, DSN_T aType = T_boundary ) :
        ELEM( aType, aParent )
    {
        rectangle = 0;
    }

    ~BOUNDARY()
    {
        delete rectangle;
    }

    /**
     * GetCorners fills aBuffer with a list of coordinates (x,y) of corners
     */
    void GetCorners( std::vector<double>& aBuffer )
    {
        if( rectangle )
        {
            aBuffer.push_back( rectangle->GetOrigin().x );
            aBuffer.push_back( rectangle->GetOrigin().y );

            aBuffer.push_back( rectangle->GetOrigin().x );
            aBuffer.push_back( rectangle->GetEnd().y );

            aBuffer.push_back( rectangle->GetEnd().x );
            aBuffer.push_back( rectangle->GetEnd().y );

            aBuffer.push_back( rectangle->GetEnd().x );
            aBuffer.push_back( rectangle->GetOrigin().y );
        }
        else
        {
            for( PATHS::iterator i=paths.begin();  i!=paths.end();  ++i )
            {
                POINTS& plist = i->GetPoints();
                for( unsigned jj = 0; jj < plist.size(); jj++ )
                {
                    aBuffer.push_back( plist[jj].x );
                    aBuffer.push_back( plist[jj].y );
                }
            }
        }
    }


    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s\n", Name() );

        if( rectangle )
            rectangle->Format( out, nestLevel+1 );
        else
        {
            for( PATHS::iterator i=paths.begin();  i!=paths.end();  ++i )
                i->Format( out, nestLevel+1 );
        }

        out->Print( nestLevel, ")\n" );
    }
};


class CIRCLE : public ELEM
{
    friend class SPECCTRA_DB;

    std::string layer_id;

    double      diameter;
    POINT       vertex;     // POINT's constructor sets to (0,0)

public:
    CIRCLE( ELEM* aParent ) :
        ELEM( T_circle, aParent )
    {
        diameter = 0.0;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* newline = nestLevel ? "\n" : "";

        const char* quote = out->GetQuoteChar( layer_id.c_str() );
        out->Print( nestLevel, "(%s %s%s%s %.6g", Name(),
                                quote, layer_id.c_str(), quote,
                                diameter );

        if( vertex.x!=0.0 || vertex.y!=0.0 )
            out->Print( 0, " %.6g %.6g)%s", vertex.x, vertex.y, newline );
        else
            out->Print( 0, ")%s", newline );
    }

    void SetLayerId( const char* aLayerId )
    {
        layer_id = aLayerId;
    }

    void SetDiameter( double aDiameter )
    {
        diameter = aDiameter;
    }

    void SetVertex( const POINT& aVertex )
    {
        vertex = aVertex;
    }
};


class QARC : public ELEM
{
    friend class SPECCTRA_DB;

    std::string layer_id;
    double      aperture_width;
    POINT       vertex[3];

public:
    QARC( ELEM* aParent ) :
        ELEM( T_qarc, aParent )
    {
        aperture_width = 0.0;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* newline = nestLevel ? "\n" : "";

        const char* quote = out->GetQuoteChar( layer_id.c_str() );
        out->Print( nestLevel, "(%s %s%s%s %.6g", Name() ,
                                 quote, layer_id.c_str(), quote,
                                 aperture_width);

        for( int i=0;  i<3;  ++i )
            out->Print( 0, "  %.6g %.6g",  vertex[i].x, vertex[i].y );

        out->Print( 0, ")%s", newline );
    }

    void SetLayerId( const char* aLayerId )
    {
        layer_id = aLayerId;
    }
    void SetStart( const POINT& aStart )
    {
        vertex[0] = aStart;
        // no -0.0 on the printouts!
        vertex[0].FixNegativeZero();
    }
    void SetEnd( const POINT& aEnd )
    {
        vertex[1] = aEnd;
        // no -0.0 on the printouts!
        vertex[1].FixNegativeZero();
    }
    void SetCenter( const POINT& aCenter )
    {
        vertex[2] = aCenter;
        // no -0.0 on the printouts!
        vertex[2].FixNegativeZero();
    }
};


class WINDOW : public ELEM
{
    friend class SPECCTRA_DB;

protected:
    /*  <shape_descriptor >::=
        [<rectangle_descriptor> |
        <circle_descriptor> |
        <polygon_descriptor> |
        <path_descriptor> |
        <qarc_descriptor> ]
    */
    ELEM*       shape;

public:

    WINDOW( ELEM* aParent, DSN_T aType = T_window ) :
        ELEM( aType, aParent )
    {
        shape = 0;
    }

    ~WINDOW()
    {
        delete shape;
    }

    void SetShape( ELEM* aShape )
    {
        delete shape;
        shape = aShape;

        if( aShape )
        {
            wxASSERT(aShape->Type()==T_rect || aShape->Type()==T_circle
                     || aShape->Type()==T_qarc || aShape->Type()==T_path
                     || aShape->Type()==T_polygon);

            aShape->SetParent( this );
        }
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s ", Name() );

        if( shape )
            shape->Format( out, 0 );

        out->Print( 0, ")\n" );
    }
};
typedef boost::ptr_vector<WINDOW>   WINDOWS;


/**
 * Class KEEPOUT
 * is used for &lt;keepout_descriptor&gt; and &lt;plane_descriptor&gt;.
 */
class KEEPOUT : public ELEM
{
    friend class SPECCTRA_DB;

protected:
    std::string     name;
    int             sequence_number;
    RULE*           rules;
    RULE*           place_rules;

    WINDOWS         windows;

    /*  <shape_descriptor >::=
        [<rectangle_descriptor> |
        <circle_descriptor> |
        <polygon_descriptor> |
        <path_descriptor> |
        <qarc_descriptor> ]
    */
    ELEM*           shape;

public:

    /**
     * Constructor KEEPOUT
     * requires a DSN_T because this class is used for T_place_keepout, T_via_keepout,
     * T_wire_keepout, T_bend_keepout, and T_elongate_keepout as well as T_keepout.
     */
    KEEPOUT( ELEM* aParent, DSN_T aType ) :
        ELEM( aType, aParent )
    {
        rules = 0;
        place_rules = 0;
        shape = 0;

        sequence_number = -1;
    }

    ~KEEPOUT()
    {
        delete rules;
        delete place_rules;
        delete shape;
    }

    void SetShape( ELEM* aShape )
    {
        delete shape;
        shape = aShape;

        if( aShape )
        {
            wxASSERT(aShape->Type()==T_rect || aShape->Type()==T_circle
                     || aShape->Type()==T_qarc || aShape->Type()==T_path
                     || aShape->Type()==T_polygon);

            aShape->SetParent( this );
        }
    }

    void AddWindow( WINDOW* aWindow )
    {
        aWindow->SetParent( this );
        windows.push_back( aWindow );
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* newline = "\n";

        out->Print( nestLevel, "(%s", Name() );

        if( name.size() )
        {
            const char* quote = out->GetQuoteChar( name.c_str() );
            out->Print( 0, " %s%s%s", quote, name.c_str(), quote );
        }
        else
            out->Print( 0, " \"\"" );   // the zone with no name or net_code == 0

        if( sequence_number != -1 )
            out->Print( 0, " (sequence_number %d)", sequence_number );

        if( shape )
        {
            out->Print( 0, " " );
            shape->Format( out, 0 );
        }

        if( rules )
        {
            out->Print( 0, "%s", newline );
            newline = "";
            rules->Format( out, nestLevel+1 );
        }

        if( place_rules )
        {
            out->Print( 0, "%s", newline );
            newline = "";
            place_rules->Format( out, nestLevel+1 );
        }

        if( windows.size() )
        {
            out->Print( 0, "%s", newline );
            newline = "";

            for( WINDOWS::iterator i=windows.begin();  i!=windows.end();  ++i )
                i->Format( out, nestLevel+1 );

            out->Print( nestLevel, ")\n" );
        }
        else
            out->Print( 0, ")\n" );
    }
};
typedef boost::ptr_vector<KEEPOUT>  KEEPOUTS;


/**
 * Class VIA
 * corresponds to the &lt;via_descriptor&gt; in the specctra dsn spec.
 */
class VIA : public ELEM
{
    friend class SPECCTRA_DB;

    STRINGS     padstacks;
    STRINGS     spares;

public:

    VIA( ELEM* aParent ) :
        ELEM( T_via, aParent )
    {
    }

    void AppendVia( const char* aViaName )
    {
        padstacks.push_back( aViaName );
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const int RIGHTMARGIN = 80;
        int perLine = out->Print( nestLevel, "(%s", Name() );

        for( STRINGS::iterator i=padstacks.begin();  i!=padstacks.end();  ++i )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "");
            }

            const char* quote = out->GetQuoteChar( i->c_str() );
            perLine += out->Print( 0, " %s%s%s", quote, i->c_str(), quote );
        }

        if( spares.size() )
        {
            out->Print( 0, "\n" );

            perLine = out->Print( nestLevel+1, "(spare" );

            for( STRINGS::iterator i=spares.begin();  i!=spares.end();  ++i )
            {
                if( perLine > RIGHTMARGIN )
                {
                    out->Print( 0, "\n" );
                    perLine = out->Print( nestLevel+2, "%s", "");
                }
                const char* quote = out->GetQuoteChar( i->c_str() );
                perLine += out->Print( 0, " %s%s%s", quote, i->c_str(), quote );
            }

            out->Print( 0, ")" );
        }

        out->Print( 0, ")\n" );
    }
};


class CLASSES : public ELEM
{
    friend class SPECCTRA_DB;

    STRINGS         class_ids;

public:
    CLASSES( ELEM* aParent ) :
        ELEM( T_classes, aParent )
    {
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( STRINGS::iterator i=class_ids.begin();  i!=class_ids.end();  ++i )
        {
            const char* quote = out->GetQuoteChar( i->c_str() );
            out->Print( nestLevel, "%s%s%s\n", quote, i->c_str(), quote );
        }
    }
};


class CLASS_CLASS : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;

    CLASSES*        classes;

    /*  rule | layer_rule are put into the kids container.
    */


public:

    /**
     * Constructor CLASS_CLASS
     * @param aParent - Parent element of the object.
     * @param aType May be either T_class_class or T_region_class_class
     */
    CLASS_CLASS( ELEM* aParent, DSN_T aType ) :
        ELEM_HOLDER( aType, aParent )
    {
        classes = 0;
    }

    ~CLASS_CLASS()
    {
        delete classes;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( classes )
            classes->Format( out, nestLevel );

        // format the kids
        ELEM_HOLDER::FormatContents( out, nestLevel );
    }
};


class CONTROL : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;

    bool    via_at_smd;
    bool    via_at_smd_grid_on;

public:
    CONTROL( ELEM* aParent ) :
        ELEM_HOLDER( T_control, aParent )
    {
        via_at_smd = false;
        via_at_smd_grid_on = false;
    }

    ~CONTROL()
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s\n", Name() );

        //if( via_at_smd )
        {
            out->Print( nestLevel+1, "(via_at_smd %s", via_at_smd ? "on" : "off" );
            if( via_at_smd_grid_on )
                out->Print( 0, " grid %s", via_at_smd_grid_on ? "on" : "off" );

            out->Print( 0, ")\n" );
        }

        for( int i=0;  i<Length();  ++i )
        {
            At(i)->Format( out, nestLevel+1 );
        }

        out->Print( nestLevel, ")\n" );
    }
};


class LAYER : public ELEM
{
    friend class SPECCTRA_DB;

    std::string name;
    DSN_T       layer_type; ///< one of: T_signal, T_power, T_mixed, T_jumper
    int         direction;
    int         cost;       ///< [forbidden | high | medium | low | free | \<positive_integer\> | -1]
    int         cost_type;  ///< T_length | T_way
    RULE*       rules;
    STRINGS     use_net;

    PROPERTIES  properties;

public:

    LAYER( ELEM* aParent ) :
        ELEM( T_layer, aParent )
    {
        layer_type = T_signal;
        direction  = -1;
        cost       = -1;
        cost_type  = -1;

        rules = 0;
    }

    ~LAYER()
    {
        delete rules;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( name.c_str() );

        out->Print( nestLevel, "(%s %s%s%s\n", Name(),
                       quote, name.c_str(), quote );

        out->Print( nestLevel+1, "(type %s)\n", GetTokenText( layer_type ) );

        if( properties.size() )
        {
            out->Print( nestLevel+1, "(property\n" );

            for( PROPERTIES::iterator i = properties.begin();  i != properties.end();  ++i )
            {
                i->Format( out, nestLevel+2 );
            }
            out->Print( nestLevel+1, ")\n" );
        }

        if( direction != -1 )
            out->Print( nestLevel+1, "(direction %s)\n",
                       GetTokenText( (DSN_T)direction ) );

        if( rules )
            rules->Format( out, nestLevel+1 );

        if( cost != -1 )
        {
            if( cost < 0 )
                out->Print( nestLevel+1, "(cost %d", -cost );   // positive integer, stored as negative
            else
                out->Print( nestLevel+1, "(cost %s", GetTokenText( (DSN_T)cost ) );

            if( cost_type != -1 )
                out->Print( 0, " (type %s)", GetTokenText( (DSN_T)cost_type ) );

            out->Print( 0, ")\n" );
        }

        if( use_net.size() )
        {
            out->Print( nestLevel+1, "(use_net" );
            for( STRINGS::const_iterator i = use_net.begin();  i!=use_net.end(); ++i )
            {
                const char* quote = out->GetQuoteChar( i->c_str() );
                out->Print( 0, " %s%s%s",  quote, i->c_str(), quote );
            }
            out->Print( 0, ")\n" );
        }

        out->Print( nestLevel, ")\n" );
    }
};

typedef boost::ptr_vector<LAYER>    LAYERS;


class LAYER_PAIR : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     layer_id0;
    std::string     layer_id1;

    double          layer_weight;

public:
    LAYER_PAIR( ELEM* aParent ) :
        ELEM( T_layer_pair, aParent )
    {
        layer_weight = 0.0;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote0 = out->GetQuoteChar( layer_id0.c_str() );
        const char* quote1 = out->GetQuoteChar( layer_id1.c_str() );

        out->Print( nestLevel, "(%s %s%s%s %s%s%s %.6g)\n", Name(),
               quote0, layer_id0.c_str(), quote0,
               quote1, layer_id1.c_str(), quote1,
               layer_weight );
    }
};
typedef boost::ptr_vector<LAYER_PAIR>  LAYER_PAIRS;


class LAYER_NOISE_WEIGHT : public ELEM
{
    friend class SPECCTRA_DB;

    LAYER_PAIRS     layer_pairs;

public:

    LAYER_NOISE_WEIGHT( ELEM* aParent ) :
        ELEM( T_layer_noise_weight, aParent )
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s\n", Name() );

        for( LAYER_PAIRS::iterator i=layer_pairs.begin(); i!=layer_pairs.end();  ++i )
            i->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }
};


/**
 * Class COPPER_PLANE
 * corresponds to a &lt;plane_descriptor&gt; in the specctra dsn spec.
 */
class COPPER_PLANE : public KEEPOUT
{
    friend class SPECCTRA_DB;

public:
    COPPER_PLANE( ELEM* aParent ) :
        KEEPOUT( aParent, T_plane )
    {}
};
typedef boost::ptr_vector<COPPER_PLANE>    COPPER_PLANES;


/**
 * Class TOKPROP
 * is a container for a single property whose value is another DSN_T token.
 * The name of the property is obtained from the DSN_T Type().
 */
class TOKPROP : public ELEM
{
    friend class SPECCTRA_DB;

    DSN_T       value;

public:

    TOKPROP( ELEM* aParent, DSN_T aType ) :
        ELEM( aType, aParent )
    {
        // Do not leave uninitialized members
        value = T_NONE;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s %s)\n", Name(),
                   GetTokenText( value ) );
    }
};


/**
 * Class STRINGPROP
 * is a container for a single property whose value is a string.
 * The name of the property is obtained from the DSN_T.
 */
class STRINGPROP : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     value;

public:

    STRINGPROP( ELEM* aParent, DSN_T aType ) :
        ELEM( aType, aParent )
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( value.c_str() );

        out->Print( nestLevel, "(%s %s%s%s)\n", Name(),
                                quote, value.c_str(), quote );
    }
};


class REGION : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;

    std::string     region_id;

    //-----<mutually exclusive>--------------------------------------
    RECTANGLE*      rectangle;
    PATH*           polygon;
    //-----</mutually exclusive>-------------------------------------

    /* region_net | region_class | region_class_class are all mutually
       exclusive and are put into the kids container.
    */

    RULE*           rules;

public:
    REGION( ELEM* aParent ) :
        ELEM_HOLDER( T_region, aParent )
    {
        rectangle = 0;
        polygon = 0;
        rules = 0;
    }

    ~REGION()
    {
        delete rectangle;
        delete polygon;
        delete rules;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( region_id.size() )
        {
            const char* quote = out->GetQuoteChar( region_id.c_str() );
            out->Print( nestLevel, "%s%s%s\n", quote, region_id.c_str(), quote );
        }

        if( rectangle )
            rectangle->Format( out, nestLevel );

        if( polygon )
            polygon->Format( out, nestLevel );

        ELEM_HOLDER::FormatContents( out, nestLevel );

        if( rules )
            rules->Format( out, nestLevel );
    }
};


class GRID : public ELEM
{
    friend class SPECCTRA_DB;

    DSN_T       grid_type;      ///< T_via | T_wire | T_via_keepout | T_place | T_snap
    double      dimension;
    DSN_T       direction;      ///< T_x | T_y | -1 for both
    double      offset;
    DSN_T       image_type;

public:

    GRID( ELEM* aParent ) :
        ELEM( T_grid, aParent )
    {
        grid_type = T_via;
        direction = T_NONE;
        dimension = 0.0;
        offset    = 0.0;
        image_type= T_NONE;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s %s %.6g",
                   Name(),
                   GetTokenText( grid_type ), dimension );

        if( grid_type == T_place )
        {
            if( image_type==T_smd || image_type==T_pin )
                out->Print( 0, " (image_type %s)", GetTokenText( image_type ) );
        }
        else
        {
            if( direction==T_x || direction==T_y )
                out->Print( 0, " (direction %s)", GetTokenText( direction ) );
        }

        if( offset != 0.0 )
            out->Print( 0, " (offset %.6g)", offset );

        out->Print( 0, ")\n");
    }
};


class STRUCTURE_OUT : public ELEM
{
    friend class SPECCTRA_DB;

    LAYERS      layers;
    RULE*       rules;

public:
    STRUCTURE_OUT( ELEM* aParent ) :
        ELEM( T_structure_out, aParent )
    {
        rules = 0;
    }

    ~STRUCTURE_OUT()
    {
        delete rules;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( LAYERS::iterator i=layers.begin();  i!=layers.end();  ++i )
            i->Format( out, nestLevel );

        if( rules )
            rules->Format( out, nestLevel );
    }
};


class STRUCTURE : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;

    UNIT_RES*   unit;

    LAYERS      layers;

    LAYER_NOISE_WEIGHT*  layer_noise_weight;

    BOUNDARY*   boundary;
    BOUNDARY*   place_boundary;
    VIA*        via;
    CONTROL*    control;
    RULE*       rules;

    KEEPOUTS    keepouts;

    COPPER_PLANES      planes;

    typedef boost::ptr_vector<REGION>   REGIONS;
    REGIONS     regions;

    RULE*       place_rules;

    typedef boost::ptr_vector<GRID>     GRIDS;
    GRIDS       grids;

public:

    STRUCTURE( ELEM* aParent ) :
        ELEM_HOLDER( T_structure, aParent )
    {
        unit = 0;
        layer_noise_weight = 0;
        boundary = 0;
        place_boundary = 0;
        via = 0;
        control = 0;
        rules = 0;
        place_rules = 0;
    }

    ~STRUCTURE()
    {
        delete unit;
        delete layer_noise_weight;
        delete boundary;
        delete place_boundary;
        delete via;
        delete control;
        delete rules;
        delete place_rules;
    }

    void SetBOUNDARY( BOUNDARY *aBoundary )
    {
        delete boundary;
        boundary = aBoundary;
        if( boundary )
        {
            boundary->SetParent( this );
        }
    }

    void SetPlaceBOUNDARY( BOUNDARY *aBoundary )
    {
        delete place_boundary;
        place_boundary = aBoundary;
        if( place_boundary )
            place_boundary->SetParent( this );
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( unit )
            unit->Format( out, nestLevel );

        for( LAYERS::iterator i=layers.begin();  i!=layers.end();  ++i )
            i->Format( out, nestLevel );

        if( layer_noise_weight )
            layer_noise_weight->Format( out, nestLevel );

        if( boundary )
            boundary->Format( out, nestLevel );

        if( place_boundary )
            place_boundary->Format( out, nestLevel );

        for( COPPER_PLANES::iterator i=planes.begin();  i!=planes.end();  ++i )
            i->Format( out, nestLevel );

        for( REGIONS::iterator i=regions.begin();  i!=regions.end();  ++i )
            i->Format( out, nestLevel );

        for( KEEPOUTS::iterator i=keepouts.begin();  i!=keepouts.end();  ++i )
            i->Format( out, nestLevel );

        if( via )
            via->Format( out, nestLevel );

        if( control )
            control->Format( out, nestLevel );

        for( int i=0; i<Length();  ++i )
        {
            At(i)->Format( out, nestLevel );
        }

        if( rules )
            rules->Format( out, nestLevel );

        if( place_rules )
            place_rules->Format( out, nestLevel );

        for( GRIDS::iterator i=grids.begin();  i!=grids.end();  ++i )
            i->Format( out, nestLevel );
    }

    UNIT_RES* GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};


/**
 * Class PLACE
 * implements the &lt;placement_reference&gt; in the specctra dsn spec.
 */
class PLACE : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     component_id;       ///< reference designator

    DSN_T           side;

    double          rotation;

    bool            hasVertex;
    POINT           vertex;

    DSN_T           mirror;
    DSN_T           status;

    std::string     logical_part;

    RULE*           place_rules;

    PROPERTIES      properties;

    DSN_T           lock_type;

    //-----<mutually exclusive>--------------
    RULE*           rules;
    REGION*         region;
    //-----</mutually exclusive>-------------

    std::string     part_number;

public:

    PLACE( ELEM* aParent ) :
        ELEM( T_place, aParent )
    {
        side = T_front;

        rotation = 0.0;

        hasVertex = false;

        mirror = T_NONE;
        status = T_NONE;

        place_rules = 0;

        lock_type = T_NONE;
        rules = 0;
        region = 0;
    }

    ~PLACE()
    {
        delete place_rules;
        delete rules;
        delete region;
    }

    void SetVertex( const POINT& aVertex )
    {
        vertex = aVertex;
        vertex.FixNegativeZero();
        hasVertex = true;
    }

    void SetRotation( double aRotation )
    {
        rotation = aRotation;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR );
};
typedef boost::ptr_vector<PLACE>    PLACES;


/**
 * Class COMPONENT
 * implements the &lt;component_descriptor&gt; in the specctra dsn spec.
 */
class COMPONENT : public ELEM
{
    friend class SPECCTRA_DB;

//    std::string     hash;       ///< a hash string used by Compare(), not Format()ed/exported.

    std::string     image_id;
    PLACES          places;

public:
    COMPONENT( ELEM* aParent ) :
        ELEM( T_component, aParent )
    {
    }

    const std::string& GetImageId() const  { return image_id; }
    void SetImageId( const std::string& aImageId )
    {
        image_id = aImageId;
    }


    /**
     * Function Compare
     * compares two objects of this type and returns <0, 0, or >0.
     */
//    static int Compare( IMAGE* lhs, IMAGE* rhs );

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( image_id.c_str() );
        out->Print( nestLevel, "(%s %s%s%s\n", Name(),
                                quote, image_id.c_str(), quote );

        FormatContents( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( PLACES::iterator i=places.begin();  i!=places.end();  ++i )
            i->Format( out, nestLevel );
    }
};
typedef boost::ptr_vector<COMPONENT> COMPONENTS;


class PLACEMENT : public ELEM
{
    friend class SPECCTRA_DB;

    UNIT_RES*   unit;

    DSN_T       flip_style;

    COMPONENTS  components;

public:
    PLACEMENT( ELEM* aParent ) :
        ELEM( T_placement, aParent )
    {
        unit = 0;
        flip_style = DSN_T( T_NONE );
    }

    ~PLACEMENT()
    {
        delete unit;
    }

    /**
     * Function LookupCOMPONENT
     * looks up a COMPONENT by name.  If the name is not found, a new
     * COMPONENT is added to the components container.  At any time the
     * names in the component container should remain unique.
     * @return COMPONENT* - an existing or new
     */
    COMPONENT* LookupCOMPONENT( const std::string& imageName )
    {
        for( unsigned i=0; i<components.size();  ++i )
        {
            if( 0 == components[i].GetImageId().compare( imageName ) )
                return &components[i];
        }

        COMPONENT* added = new COMPONENT(this);
        components.push_back( added );
        added->SetImageId( imageName );
        return added;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( unit )
            unit->Format( out, nestLevel );

        if( flip_style != DSN_T( T_NONE ) )
        {
            out->Print( nestLevel, "(place_control (flip_style %s))\n",
                       GetTokenText( flip_style ) );
        }

        for( COMPONENTS::iterator i=components.begin();  i!=components.end();  ++i )
            i->Format( out, nestLevel );
    }

    UNIT_RES* GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};


/**
 * Class SHAPE
 * corresponds to the "(shape ..)" element in the specctra dsn spec.
 * It is not a &lt;shape_descriptor&gt;, which is one of things that this
 * elements contains, i.e. in its "shape" field.  This class also implements
 * the "(outline ...)" element as a dual personality.
 */
class SHAPE : public WINDOW
{
    friend class SPECCTRA_DB;

    DSN_T           connect;

    /*  <shape_descriptor >::=
        [<rectangle_descriptor> |
        <circle_descriptor> |
        <polygon_descriptor> |
        <path_descriptor> |
        <qarc_descriptor> ]
    ELEM*           shape;      // inherited from WINDOW
    */

    WINDOWS         windows;

public:

    /**
     * Constructor SHAPE
     * alternatively takes a DSN_T aType of T_outline
     */
    SHAPE( ELEM* aParent, DSN_T aType = T_shape ) :
        WINDOW( aParent, aType )
    {
        connect = T_on;
    }

    void SetConnect( DSN_T aConnect )
    {
        connect = aConnect;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s ", Name() );

        if( shape )
            shape->Format( out, 0 );

        if( connect == T_off )
            out->Print( 0, "(connect %s)", GetTokenText( connect ) );

        if( windows.size() )
        {
            out->Print( 0, "\n" );

            for( WINDOWS::iterator i=windows.begin();  i!=windows.end();  ++i )
                i->Format( out, nestLevel+1 );

            out->Print( nestLevel, ")\n" );
        }
        else
            out->Print( 0, ")\n" );
    }
};


class PIN : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     padstack_id;
    double          rotation;
    bool            isRotated;
    std::string     pin_id;
    POINT           vertex;

    int             kiNetCode;      ///< KiCad netcode


public:
    PIN( ELEM* aParent ) :
        ELEM( T_pin, aParent )
    {
        rotation = 0.0;
        isRotated = false;
        kiNetCode = 0;
    }

    void SetRotation( double aRotation )
    {
        rotation = aRotation;
        isRotated = (aRotation != 0.0);
    }

    void SetVertex( const POINT& aPoint )
    {
        vertex = aPoint;
        vertex.FixNegativeZero();
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( padstack_id.c_str() );
        if( isRotated )
            out->Print( nestLevel, "(pin %s%s%s (rotate %.6g)",
                                     quote, padstack_id.c_str(), quote,
                                     rotation
                                     );
        else
            out->Print( nestLevel, "(pin %s%s%s", quote, padstack_id.c_str(), quote );

        quote = out->GetQuoteChar( pin_id.c_str() );
        out->Print( 0, " %s%s%s %.6g %.6g)\n", quote, pin_id.c_str(), quote,
                   vertex.x, vertex.y );
    }
};
typedef boost::ptr_vector<PIN>  PINS;


class LIBRARY;
class IMAGE : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;
    friend class LIBRARY;

    std::string     hash;       ///< a hash string used by Compare(), not Format()ed/exported.

    std::string     image_id;
    DSN_T           side;
    UNIT_RES*       unit;

    /*  The grammar spec says only one outline is supported, but I am seeing
        *.dsn examples with multiple outlines.  So the outlines will go into
        the kids list.
    */

    PINS            pins;

    RULE*           rules;
    RULE*           place_rules;

    KEEPOUTS        keepouts;

    int             duplicated;     ///< no. times this image_id is duplicated

public:

    IMAGE( ELEM* aParent ) :
        ELEM_HOLDER( T_image, aParent )
    {
        side = T_both;
        unit = 0;
        rules = 0;
        place_rules = 0;
        duplicated = 0;
    }
    ~IMAGE()
    {
        delete unit;
        delete rules;
        delete place_rules;
    }

    /**
     * Function Compare
     * compares two objects of this type and returns <0, 0, or >0.
     */
    static int Compare( IMAGE* lhs, IMAGE* rhs );

    std::string GetImageId()
    {
        if( duplicated )
        {
            char    buf[32];

            std::string ret = image_id;
            ret += "::";
            sprintf( buf, "%d", duplicated );
            ret += buf;
            return ret;
        }

        return image_id;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        std::string imageId = GetImageId();

        const char* quote = out->GetQuoteChar( imageId.c_str() );

        out->Print( nestLevel, "(%s %s%s%s", Name(),
                                quote, imageId.c_str(), quote );

        FormatContents( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }

    // this is here for makeHash()
    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( side != T_both )
            out->Print( 0, " (side %s)", GetTokenText( side ) );

        out->Print( 0, "\n");

        if( unit )
            unit->Format( out, nestLevel );

        // format the kids, which in this class are the shapes
        ELEM_HOLDER::FormatContents( out, nestLevel );

        for( PINS::iterator i=pins.begin();  i!=pins.end();  ++i )
            i->Format( out, nestLevel );

        if( rules )
            rules->Format( out, nestLevel );

        if( place_rules )
            place_rules->Format( out, nestLevel );

        for( KEEPOUTS::iterator i=keepouts.begin();  i!=keepouts.end();  ++i )
            i->Format( out, nestLevel );
    }


    UNIT_RES* GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};
typedef boost::ptr_vector<IMAGE>    IMAGES;


/**
 * Class PADSTACK
 * holds either a via or a pad definition.
 */
class PADSTACK : public ELEM_HOLDER
{
    friend class SPECCTRA_DB;

    std::string     hash;       ///< a hash string used by Compare(), not Format()ed/exported.

    std::string     padstack_id;
    UNIT_RES*       unit;

    /* The shapes are stored in the kids list */

    DSN_T           rotate;
    DSN_T           absolute;
    DSN_T           attach;
    std::string     via_id;

    RULE*           rules;

public:

    /**
     * Constructor PADSTACK()
     * cannot take ELEM* aParent because PADSTACKSET confuses this with a
     * copy constructor and causes havoc.  Instead set parent with
     * LIBRARY::AddPadstack()
     */
    PADSTACK() :
        ELEM_HOLDER( T_padstack, NULL )
    {
        unit = 0;
        rotate = T_on;
        absolute = T_off;
        rules = 0;
        attach = T_off;
    }
    ~PADSTACK()
    {
        delete unit;
        delete rules;
    }

    const std::string& GetPadstackId()
    {
        return padstack_id;
    }

    /**
     * Function Compare
     * compares two objects of this type and returns <0, 0, or >0.
     */
    static int Compare( PADSTACK* lhs, PADSTACK* rhs );


    void SetPadstackId( const char* aPadstackId )
    {
        padstack_id = aPadstackId;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( padstack_id.c_str() );

        out->Print( nestLevel, "(%s %s%s%s\n", Name(),
                                quote, padstack_id.c_str(), quote );

        FormatContents( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }


    // this factored out for use by Compare()
    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( unit )
            unit->Format( out, nestLevel );

        // format the kids, which in this class are the shapes
        ELEM_HOLDER::FormatContents( out, nestLevel );

        out->Print( nestLevel, "%s", "" );

        // spec for <attach_descriptor> says default is on, so
        // print the off condition to override this.
        if( attach == T_off )
            out->Print( 0, "(attach off)" );
        else if( attach == T_on )
        {
            const char* quote = out->GetQuoteChar( via_id.c_str() );
            out->Print( 0, "(attach on (use_via %s%s%s))",
                       quote, via_id.c_str(), quote );
        }

        if( rotate == T_off )   // print the non-default
            out->Print( 0, "(rotate %s)", GetTokenText( rotate ) );

        if( absolute == T_on )  // print the non-default
            out->Print( 0, "(absolute %s)", GetTokenText( absolute ) );

        out->Print( 0, "\n" );

        if( rules )
            rules->Format( out, nestLevel );
    }


    UNIT_RES* GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};
typedef boost::ptr_vector<PADSTACK> PADSTACKS;


/**
 * Function operator<
 * is used by the PADSTACKSET boost::ptr_set below
 */
inline bool operator<( const PADSTACK& lhs, const PADSTACK& rhs )
{
    return PADSTACK::Compare( (PADSTACK*) &lhs, (PADSTACK*) &rhs ) < 0;
}


/**
 * Class LIBRARY
 * corresponds to the &lt;library_descriptor&gt; in the specctra dsn specification.
 * Only unit_descriptor, image_descriptors, and padstack_descriptors are
 * included as children at this time.
 */
class LIBRARY : public ELEM
{
    friend class SPECCTRA_DB;

    UNIT_RES*       unit;
    IMAGES          images;

    PADSTACKS       padstacks;      ///< all except vias, which are in 'vias'
    PADSTACKS       vias;

public:

    LIBRARY( ELEM* aParent, DSN_T aType = T_library ) :
        ELEM( aType, aParent )
    {
        unit = 0;
//        via_start_index = -1;       // 0 or greater means there is at least one via
    }
    ~LIBRARY()
    {
        delete unit;
    }

    void AddPadstack( PADSTACK* aPadstack )
    {
        aPadstack->SetParent( this );
        padstacks.push_back( aPadstack );
    }

/*
    void SetViaStartIndex( int aIndex )
    {
        via_start_index = aIndex;
    }
    int GetViaStartIndex()
    {
        return via_start_index;
    }
*/


    /**
     * Function FindIMAGE
     * searches this LIBRARY for an image which matches the argument.
     * @return int - if found the index into the images list, else -1.
     */
    int FindIMAGE( IMAGE* aImage )
    {
        unsigned i;
        for( i=0;  i<images.size();  ++i )
        {
            if( 0 == IMAGE::Compare( aImage, &images[i] ) )
                return (int) i;
        }

        // There is no match to the IMAGE contents, but now generate a unique
        // name for it.
        int dups = 1;
        for( i=0;  i<images.size();  ++i )
        {
            if( 0 == aImage->image_id.compare( images[i].image_id ) )
                aImage->duplicated = dups++;
        }

        return -1;
    }


    /**
     * Function AppendIMAGE
     * adds the image to the image list.
     */
    void AppendIMAGE( IMAGE* aImage )
    {
        aImage->SetParent( this );
        images.push_back( aImage );
    }

    /**
     * Function LookupIMAGE
     * will add the image only if one exactly like it does not already exist
     * in the image container.
     * @return IMAGE* - the IMAGE which is registered in the LIBRARY that
     *           matches the argument, and it will be either the argument or
     *           a previous image which is a duplicate.
     */
    IMAGE* LookupIMAGE( IMAGE* aImage )
    {
        int ndx = FindIMAGE( aImage );
        if( ndx == -1 )
        {
            AppendIMAGE( aImage );
            return aImage;
        }
        return &images[ndx];
    }

    /**
     * Function FindVia
     * searches this LIBRARY for a via which matches the argument.
     * @return int - if found the index into the padstack list, else -1.
     */
    int FindVia( PADSTACK* aVia )
    {
        for( unsigned i=0;  i<vias.size();  ++i )
        {
            if( 0 == PADSTACK::Compare( aVia, &vias[i] ) )
                return int( i );
        }
        return -1;
    }

    /**
     * Function AppendVia
     * adds \a aVia to the internal via container.
     */
    void AppendVia( PADSTACK* aVia )
    {
        aVia->SetParent( this );
        vias.push_back( aVia );
    }


    /**
     * Function AppendPADSTACK
     * adds the padstack to the padstack container.
     */
    void AppendPADSTACK( PADSTACK* aPadstack )
    {
        aPadstack->SetParent( this );
        padstacks.push_back( aPadstack );
    }

    /**
     * Function LookupVia
     * will add the via only if one exactly like it does not already exist
     * in the padstack container.
     * @return PADSTACK* - the PADSTACK which is registered in the LIBRARY that
     *           matches the argument, and it will be either the argument or
     *           a previous padstack which is a duplicate.
     */
    PADSTACK* LookupVia( PADSTACK* aVia )
    {
        int ndx = FindVia( aVia );
        if( ndx == -1 )
        {
            AppendVia( aVia );
            return aVia;
        }
        return &vias[ndx];
    }

    /**
     * Function FindPADSTACK
     * searches the padstack container by name.
     * @return PADSTACK* - The PADSTACK with a matching name if it exists, else NULL.
     */
    PADSTACK* FindPADSTACK( const std::string& aPadstackId )
    {
        for( unsigned i=0;  i<padstacks.size();  ++i )
        {
            PADSTACK* ps = &padstacks[i];
            if( 0 == ps->GetPadstackId().compare( aPadstackId ) )
                return ps;
        }
        return NULL;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( unit )
            unit->Format( out, nestLevel );

        for( IMAGES::iterator i=images.begin();  i!=images.end();  ++i )
            i->Format( out, nestLevel );

        for( PADSTACKS::iterator i=padstacks.begin();  i!=padstacks.end();  ++i )
            i->Format( out, nestLevel );

        for( PADSTACKS::iterator i=vias.begin();  i!=vias.end();  ++i )
            i->Format( out, nestLevel );
    }

    UNIT_RES* GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};


/**
 * Class PIN_REF
 * corresponds to the &lt;pin_reference&gt; definition in the specctra dsn spec.
 */
struct PIN_REF : public ELEM
{
    std::string     component_id;
    std::string     pin_id;

    PIN_REF( ELEM* aParent ) :
        ELEM( T_pin, aParent )
    {
    }


    /**
     * Function FormatIt
     * is like Format() but is not virual and returns the number of characters
     * that were output.
     */
    int FormatIt( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        // only print the newline if there is a nest level, and make
        // the quotes unconditional on this one.
        const char* newline = nestLevel ? "\n" : "";

        const char* cquote = out->GetQuoteChar( component_id.c_str() );
        const char* pquote = out->GetQuoteChar( pin_id.c_str() );

        return out->Print( nestLevel, "%s%s%s-%s%s%s%s",
                cquote, component_id.c_str(), cquote,
                pquote, pin_id.c_str(), pquote,
                newline );
    }
};
typedef std::vector<PIN_REF>   PIN_REFS;


class FROMTO : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     fromText;
    std::string     toText;

    DSN_T           fromto_type;
    std::string     net_id;
    RULE*           rules;
//    std::string     circuit;
    LAYER_RULES     layer_rules;


public:
    FROMTO( ELEM* aParent ) :
        ELEM( T_fromto, aParent )
    {
        rules = 0;
        fromto_type  = DSN_T( T_NONE );
    }
    ~FROMTO()
    {
        delete rules;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        // no quoting on these two, the lexer preserved the quotes on input
        out->Print( nestLevel, "(%s %s %s ",
                 Name(), fromText.c_str(), toText.c_str() );

        if( fromto_type != DSN_T( T_NONE ) )
            out->Print( 0, "(type %s)", GetTokenText( fromto_type ) );

        if( net_id.size() )
        {
            const char* quote = out->GetQuoteChar( net_id.c_str() );
            out->Print( 0, "(net %s%s%s)",  quote, net_id.c_str(), quote );
        }

        bool singleLine = true;

        if( rules || layer_rules.size() )
        {
            out->Print( 0, "\n" );
            singleLine = false;
        }

        if( rules )
            rules->Format( out, nestLevel+1 );

        /*
        if( circuit.size() )
            out->Print( nestLevel, "%s\n", circuit.c_str() );
        */

        for( LAYER_RULES::iterator i=layer_rules.begin();  i!=layer_rules.end();  ++i )
            i->Format( out, nestLevel+1 );

        out->Print( singleLine ? 0 : nestLevel, ")" );
        if( nestLevel || !singleLine )
            out->Print( 0, "\n" );
    }
};
typedef boost::ptr_vector<FROMTO>       FROMTOS;


/**
 * Class COMP_ORDER
 * corresponds to the &lt;component_order_descriptor&gt;
 */
class COMP_ORDER : public ELEM
{
    friend class SPECCTRA_DB;

    STRINGS         placement_ids;

public:
    COMP_ORDER( ELEM* aParent ) :
        ELEM( T_comp_order, aParent )
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s", Name() );

        for( STRINGS::iterator i=placement_ids.begin();  i!=placement_ids.end();  ++i )
        {
            const char* quote = out->GetQuoteChar( i->c_str() );
            out->Print( 0, " %s%s%s", quote, i->c_str(), quote );
        }

        out->Print( 0, ")" );
        if( nestLevel )
            out->Print( 0, "\n" );
    }
};
typedef boost::ptr_vector<COMP_ORDER>   COMP_ORDERS;

/**
 * Class NET
 * corresponds to a &lt;net_descriptor&gt;
 * in the DSN spec.
 */
class NET : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     net_id;
    bool            unassigned;
    int             net_number;

    DSN_T           pins_type;      ///< T_pins | T_order, type of field 'pins' below
    PIN_REFS        pins;

    PIN_REFS        expose;
    PIN_REFS        noexpose;
    PIN_REFS        source;
    PIN_REFS        load;
    PIN_REFS        terminator;

    DSN_T           type;           ///< T_fix | T_normal

    DSN_T           supply;         ///< T_power | T_ground

    RULE*           rules;

    LAYER_RULES     layer_rules;

    FROMTOS         fromtos;

    COMP_ORDER*     comp_order;

public:

    NET( ELEM* aParent ) :
        ELEM( T_net, aParent )
    {
        unassigned = false;
        net_number = T_NONE;
        pins_type = T_pins;

        type = T_NONE;
        supply = T_NONE;

        rules = 0;
        comp_order = 0;
    }

    ~NET()
    {
        delete rules;
        delete comp_order;
    }

    int FindPIN_REF( const std::string& aComponent )
    {
        for( unsigned i=0;  i<pins.size();  ++i )
        {
            if( 0 == aComponent.compare( pins[i].component_id ) )
                return int(i);
        }
        return -1;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( net_id.c_str() );
        const char* space = " ";

        out->Print( nestLevel, "(%s %s%s%s", Name(),
                   quote, net_id.c_str(), quote );

        if( unassigned )
        {
            out->Print( 0, "%s(unassigned)", space );
            space = "";         // only needed one space
        }

        if( net_number != T_NONE )
        {
            out->Print( 0, "%s(net_number %d)", space, net_number );
            // space = "";
        }

        out->Print( 0, "\n" );

        if( pins.size() )
        {
            const int RIGHTMARGIN = 80;
            int perLine = out->Print( nestLevel+1, "(%s", GetTokenText( pins_type ) );

            for( PIN_REFS::iterator i=pins.begin();  i!=pins.end();  ++i )
            {
                if( perLine > RIGHTMARGIN )
                {
                    out->Print( 0, "\n");
                    perLine = out->Print( nestLevel+2, "%s", "" );
                }
                else
                    perLine += out->Print( 0, " " );

                perLine += i->FormatIt( out, 0 );
            }
            out->Print( 0, ")\n" );
        }

        if( comp_order )
            comp_order->Format( out, nestLevel+1 );

        if( type != T_NONE )
            out->Print( nestLevel+1, "(type %s)\n", GetTokenText( type ) );

        if( rules )
            rules->Format( out, nestLevel+1 );

        for( LAYER_RULES::iterator i=layer_rules.begin();  i!=layer_rules.end();  ++i )
            i->Format( out, nestLevel+1 );

        for( FROMTOS::iterator i=fromtos.begin();  i!=fromtos.end();  ++i )
            i->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }
};
typedef boost::ptr_vector<NET>  NETS;


class TOPOLOGY : public ELEM
{
    friend class SPECCTRA_DB;

    FROMTOS         fromtos;

    COMP_ORDERS     comp_orders;

public:
    TOPOLOGY( ELEM* aParent ) :
        ELEM( T_topology, aParent )
    {
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( FROMTOS::iterator i=fromtos.begin();  i!=fromtos.end();  ++i )
            i->Format( out, nestLevel );

        for( COMP_ORDERS::iterator i=comp_orders.begin();  i!=comp_orders.end();  ++i )
            i->Format( out, nestLevel );
    }
};


/**
 * Class CLASS
 * corresponds to the &lt;class_descriptor&gt; in the specctra spec.
 */
class CLASS : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     class_id;

    STRINGS         net_ids;

    /// circuit descriptor list
    STRINGS         circuit;

    RULE*           rules;

    LAYER_RULES     layer_rules;

    TOPOLOGY*       topology;

public:

    CLASS( ELEM* aParent ) :
        ELEM( T_class, aParent )
    {
        rules = 0;
        topology = 0;
    }
    ~CLASS()
    {
        delete rules;
        delete topology;
    }


    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( class_id.c_str() );

        int perLine = out->Print( nestLevel, "(%s %s%s%s",
                              Name(),
                              quote, class_id.c_str(), quote );

        const int RIGHTMARGIN = 72;

        for( STRINGS::iterator i=net_ids.begin();  i!=net_ids.end();  ++i )
        {
            const char* space = " ";
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
                space = ""; // no space at first net_id of the line
            }

            quote = out->GetQuoteChar( i->c_str() );
            perLine += out->Print( 0, "%s%s%s%s", space, quote, i->c_str(), quote );
        }

        bool newLine = false;
        if( circuit.size() || rules || layer_rules.size() || topology )
        {
            out->Print( 0, "\n" );
            newLine = true;
        }

        if( circuit.size() )
        {
            out->Print( nestLevel+1, "(circuit\n" );
            for( STRINGS::iterator i=circuit.begin();  i!=circuit.end();  ++i )
                out->Print( nestLevel+2, "%s\n", i->c_str() );
            out->Print( nestLevel+1, ")\n" );
        }

        if( rules )
            rules->Format( out, nestLevel+1 );

        for( LAYER_RULES::iterator i=layer_rules.begin();  i!=layer_rules.end();  ++i )
            i->Format( out, nestLevel+1 );

        if( topology )
            topology->Format( out, nestLevel+1 );

        out->Print( newLine ? nestLevel : 0, ")\n" );
    }
};
typedef boost::ptr_vector<CLASS> CLASSLIST;


class NETWORK : public ELEM
{
    friend class SPECCTRA_DB;

    NETS        nets;
    CLASSLIST   classes;


public:

    NETWORK( ELEM* aParent ) :
        ELEM( T_network, aParent )
    {
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( NETS::iterator i=nets.begin();  i!=nets.end();  ++i )
            i->Format( out, nestLevel );

        for( CLASSLIST::iterator i=classes.begin();  i!=classes.end();  ++i )
            i->Format( out, nestLevel );
    }
};


class CONNECT : public ELEM
{
    // @todo not completed.

public:
    CONNECT( ELEM* parent ) :
        ELEM( T_connect, parent ) {}
};


/**
 * Class WIRE
 * corresponds to &lt;wire_shape_descriptor&gt; in the specctra dsn spec.
 */
class WIRE : public ELEM
{
    friend class SPECCTRA_DB;

    /*  <shape_descriptor >::=
        [<rectangle_descriptor> |
        <circle_descriptor> |
        <polygon_descriptor> |
        <path_descriptor> |
        <qarc_descriptor> ]
    */
    ELEM*           shape;

    std::string     net_id;
    int             turret;
    DSN_T           wire_type;
    DSN_T           attr;
    std::string     shield;
    WINDOWS         windows;
    CONNECT*        connect;
    bool            supply;

public:
    WIRE( ELEM* aParent ) :
        ELEM( T_wire, aParent )
    {
        shape = 0;
        connect = 0;

        turret = -1;
        wire_type = T_NONE;
        attr = T_NONE;
        supply = false;
    }

    ~WIRE()
    {
        delete shape;
        delete connect;
    }

    void SetShape( ELEM* aShape )
    {
        delete shape;
        shape = aShape;

        if( aShape )
        {
            wxASSERT(aShape->Type()==T_rect || aShape->Type()==T_circle
                     || aShape->Type()==T_qarc || aShape->Type()==T_path
                     || aShape->Type()==T_polygon);

            aShape->SetParent( this );
        }
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        out->Print( nestLevel, "(%s ", Name() );

        if( shape )
            shape->Format( out, 0 );

        if( net_id.size() )
        {
            const char* quote = out->GetQuoteChar( net_id.c_str() );
            out->Print( 0, "(net %s%s%s)",
                       quote, net_id.c_str(), quote );
        }

        if( turret >= 0 )
            out->Print( 0, "(turrent %d)", turret );

        if( wire_type != T_NONE )
            out->Print( 0, "(type %s)", GetTokenText( wire_type ) );

        if( attr != T_NONE )
            out->Print( 0, "(attr %s)", GetTokenText( attr ) );

        if( shield.size() )
        {
            const char* quote = out->GetQuoteChar( shield.c_str() );
            out->Print( 0, "(shield %s%s%s)",
                       quote, shield.c_str(), quote );
        }

        if( windows.size() )
        {
            out->Print( 0, "\n" );

            for( WINDOWS::iterator i=windows.begin();  i!=windows.end();  ++i )
                i->Format( out, nestLevel+1 );
        }

        if( connect )
            connect->Format( out, 0 );

        if( supply )
            out->Print( 0, "(supply)" );

        out->Print( 0, ")\n" );
    }
};
typedef boost::ptr_vector<WIRE>     WIRES;


/**
 * Class WIRE_VIA
 * corresponds to &lt;wire_via_descriptor&gt; in the specctra dsn spec.
 */
class WIRE_VIA : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     padstack_id;
    POINTS          vertexes;
    std::string     net_id;
    int             via_number;
    DSN_T           via_type;
    DSN_T           attr;
    std::string     virtual_pin_name;
    STRINGS         contact_layers;
    bool            supply;


public:
    WIRE_VIA( ELEM* aParent ) :
        ELEM( T_via, aParent )
    {
        via_number = -1;
        via_type = T_NONE;
        attr = T_NONE;
        supply = false;
    }

    const std::string& GetPadstackId()
    {
        return padstack_id;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( padstack_id.c_str() );

        const int RIGHTMARGIN = 80;
        int perLine = out->Print( nestLevel, "(%s %s%s%s",
                       Name(),
                       quote, padstack_id.c_str(), quote );

        for( POINTS::iterator i=vertexes.begin();  i!=vertexes.end();  ++i )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            else
                perLine += out->Print( 0, "  " );

            perLine += out->Print( 0, "%.6g %.6g", i->x, i->y );
        }

        if( net_id.size() || via_number!=-1 || via_type!=T_NONE || attr!=T_NONE || supply)
            out->Print( 0, " " );

        if( net_id.size() )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            const char* quote = out->GetQuoteChar( net_id.c_str() );
            perLine += out->Print( 0, "(net %s%s%s)", quote, net_id.c_str(), quote );
        }

        if( via_number != -1 )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            perLine += out->Print( 0, "(via_number %d)", via_number );
        }

        if( via_type != T_NONE )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            perLine += out->Print( 0, "(type %s)", GetTokenText( via_type ) );
        }

        if( attr != T_NONE )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            if( attr == T_virtual_pin )
            {
                const char* quote = out->GetQuoteChar( virtual_pin_name.c_str() );
                perLine += out->Print( 0, "(attr virtual_pin %s%s%s)",
                           quote, virtual_pin_name.c_str(), quote );
            }
            else
                perLine += out->Print( 0, "(attr %s)", GetTokenText( attr ) );
        }

        if( supply )
        {
            if( perLine > RIGHTMARGIN )
            {
                out->Print( 0, "\n" );
                perLine = out->Print( nestLevel+1, "%s", "" );
            }
            perLine += out->Print( 0, "(supply)" );
        }

        if( contact_layers.size() )
        {
            out->Print( 0, "\n" );
            out->Print( nestLevel+1, "(contact\n" );

            for( STRINGS::iterator i=contact_layers.begin();  i!=contact_layers.end();  ++i )
            {
                const char* quote = out->GetQuoteChar( i->c_str() );
                out->Print( nestLevel+2, "%s%s%s\n", quote, i->c_str(), quote );
            }
            out->Print( nestLevel+1, "))\n" );
        }
        else
            out->Print( 0, ")\n" );
    }
};
typedef boost::ptr_vector<WIRE_VIA>      WIRE_VIAS;


/**
 * Class WIRING
 * corresponds to &lt;wiring_descriptor&gt; in the specctra dsn spec.
 */
class WIRING : public ELEM
{
    friend class SPECCTRA_DB;

    UNIT_RES*   unit;
    WIRES       wires;
    WIRE_VIAS   wire_vias;

public:

    WIRING( ELEM* aParent ) :
        ELEM( T_wiring, aParent )
    {
        unit = 0;
    }
    ~WIRING()
    {
        delete unit;
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( unit )
            unit->Format( out, nestLevel );

        for( WIRES::iterator i=wires.begin();  i!=wires.end();  ++i )
            i->Format( out, nestLevel );

        for( WIRE_VIAS::iterator i=wire_vias.begin();  i!=wire_vias.end();  ++i )
            i->Format( out, nestLevel );
    }

    UNIT_RES*  GetUnits() const
    {
        if( unit )
            return unit;

        return ELEM::GetUnits();
    }
};


class PCB : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     pcbname;
    PARSER*         parser;
    UNIT_RES*       resolution;
    UNIT_RES*       unit;
    STRUCTURE*      structure;
    PLACEMENT*      placement;
    LIBRARY*        library;
    NETWORK*        network;
    WIRING*         wiring;

public:

    PCB( ELEM* aParent = 0 ) :
        ELEM( T_pcb, aParent )
    {
        parser = 0;
        resolution = 0;
        unit = 0;
        structure = 0;
        placement = 0;
        library = 0;
        network = 0;
        wiring = 0;
    }

    ~PCB()
    {
        delete parser;
        delete resolution;
        delete unit;
        delete structure;
        delete placement;
        delete library;
        delete network;
        delete wiring;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( pcbname.c_str() );

        out->Print( nestLevel, "(%s %s%s%s\n", Name(),
                                quote, pcbname.c_str(), quote );

        if( parser )
            parser->Format( out, nestLevel+1 );

        if( resolution )
            resolution->Format( out, nestLevel+1 );

        if( unit )
            unit->Format( out, nestLevel+1 );

        if( structure )
            structure->Format( out, nestLevel+1 );

        if( placement )
            placement->Format( out, nestLevel+1 );

        if( library )
            library->Format( out, nestLevel+1 );

        if( network )
            network->Format( out, nestLevel+1 );

        if( wiring )
            wiring->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }

    UNIT_RES*  GetUnits() const
    {
        if( unit )
            return unit;

        if( resolution )
            return resolution->GetUnits();

        return ELEM::GetUnits();
    }
};


class ANCESTOR : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     filename;
    std::string     comment;
    time_t          time_stamp;


public:
    ANCESTOR( ELEM* aParent ) :
        ELEM( T_ancestor, aParent )
    {
        time_stamp = time(NULL);
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        char    temp[80];
        struct  tm* tmp;

        tmp = localtime( &time_stamp );
        strftime( temp, sizeof(temp), "%b %d %H : %M : %S %Y", tmp );

        // format the time first to temp
        // filename may be empty, so quote it just in case.
        out->Print( nestLevel, "(%s \"%s\" (created_time %s)\n",
                     Name(),
                     filename.c_str(),
                     temp );

        if( comment.size() )
        {
            const char* quote = out->GetQuoteChar( comment.c_str() );
            out->Print( nestLevel+1, "(comment %s%s%s)\n",
                       quote, comment.c_str(), quote );
        }

        out->Print( nestLevel, ")\n" );
    }
};
typedef boost::ptr_vector<ANCESTOR>     ANCESTORS;


class HISTORY : public ELEM
{
    friend class SPECCTRA_DB;

    ANCESTORS       ancestors;
    time_t          time_stamp;
    STRINGS         comments;

public:

    HISTORY( ELEM* aParent ) :
        ELEM( T_history, aParent )
    {
        time_stamp = time(NULL);
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( ANCESTORS::iterator i=ancestors.begin();  i!=ancestors.end();  ++i )
            i->Format( out, nestLevel );

        char    temp[80];
        struct  tm* tmp;

        tmp = localtime( &time_stamp );
        strftime( temp, sizeof(temp), "%b %d %H : %M : %S %Y", tmp );

        // format the time first to temp
        out->Print( nestLevel, "(self (created_time %s)\n", temp );

        for( STRINGS::iterator i=comments.begin();  i!=comments.end();  ++i )
        {
            const char* quote = out->GetQuoteChar( i->c_str() );
            out->Print( nestLevel+1, "(comment %s%s%s)\n",
                       quote, i->c_str(), quote );
        }

        out->Print( nestLevel, ")\n" );
    }
};


/**
 * Class SUPPLY_PIN
 * corresponds to the &lt;supply_pin_descriptor&gt; in the specctra dsn spec.
*/
class SUPPLY_PIN : public ELEM
{
    friend class SPECCTRA_DB;

    PIN_REFS        pin_refs;
    std::string     net_id;

public:
    SUPPLY_PIN( ELEM* aParent ) :
        ELEM( T_supply_pin, aParent )
    {
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        bool singleLine = pin_refs.size() <= 1;
        out->Print( nestLevel, "(%s", Name() );

        if( singleLine )
        {
            out->Print( 0, "%s", " " );
            pin_refs.begin()->Format( out, 0 );
        }
        else
        {
            for( PIN_REFS::iterator i=pin_refs.begin();  i!=pin_refs.end();  ++i )
                i->FormatIt( out, nestLevel+1 );
        }

        if( net_id.size() )
        {
            const char* newline = singleLine ? "" : "\n";

            const char* quote = out->GetQuoteChar( net_id.c_str() );
            out->Print( singleLine ? 0 : nestLevel+1,
                       " (net %s%s%s)%s", quote, net_id.c_str(), quote, newline );
        }

        out->Print( singleLine ? 0 : nestLevel, ")\n");
    }
};
typedef boost::ptr_vector<SUPPLY_PIN>   SUPPLY_PINS;


/**
 * Class NET_OUT
 * corresponds to the &lt;net_out_descriptor&gt; of the specctra dsn spec.
 */
class NET_OUT : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     net_id;
    int             net_number;
    RULE*           rules;
    WIRES           wires;
    WIRE_VIAS       wire_vias;
    SUPPLY_PINS     supply_pins;


public:
    NET_OUT( ELEM* aParent ) :
        ELEM( T_net_out, aParent )
    {
        rules = 0;
        net_number = -1;
    }
    ~NET_OUT()
    {
        delete rules;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( net_id.c_str() );

        // cannot use Type() here, it is T_net_out and we need "(net "
        out->Print( nestLevel, "(net %s%s%s\n",
                   quote, net_id.c_str(), quote );

        if( net_number>= 0 )
            out->Print( nestLevel+1, "(net_number %d)\n", net_number );

        if( rules )
            rules->Format( out, nestLevel+1 );

        for( WIRES::iterator i=wires.begin();  i!=wires.end();  ++i )
            i->Format( out, nestLevel+1 );

        for( WIRE_VIAS::iterator i=wire_vias.begin();  i!=wire_vias.end();  ++i )
            i->Format( out, nestLevel+1 );

        for( SUPPLY_PINS::iterator i=supply_pins.begin();  i!=supply_pins.end();  ++i )
            i->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }
};
typedef boost::ptr_vector<NET_OUT>      NET_OUTS;


class ROUTE : public ELEM
{
    friend class SPECCTRA_DB;

    UNIT_RES*       resolution;
    PARSER*         parser;
    STRUCTURE_OUT*  structure_out;
    LIBRARY*        library;
    NET_OUTS        net_outs;
//    TEST_POINTS*    test_points;

public:

    ROUTE( ELEM* aParent ) :
        ELEM( T_route, aParent )
    {
        resolution = 0;
        parser = 0;
        structure_out = 0;
        library = 0;
    }
    ~ROUTE()
    {
        delete resolution;
        delete parser;
        delete structure_out;
        delete library;
//        delete test_points;
    }

    UNIT_RES*  GetUnits() const
    {
        if( resolution )
            return resolution;

        return ELEM::GetUnits();
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        if( resolution )
            resolution->Format( out, nestLevel );

        if( parser )
            parser->Format( out, nestLevel );

        if( structure_out )
            structure_out->Format( out, nestLevel );

        if( library )
            library->Format( out, nestLevel );

        if( net_outs.size() )
        {
            out->Print( nestLevel, "(network_out\n" );
            for( NET_OUTS::iterator i=net_outs.begin();  i!=net_outs.end();  ++i )
                i->Format( out, nestLevel+1 );
            out->Print( nestLevel, ")\n" );
        }

//        if( test_poinst )
//            test_points->Format( out, nestLevel );
    }
};


/**
 * Struct PIN_PAIR
 * is used within the WAS_IS class below to hold a pair of PIN_REFs and
 * corresponds to the (pins was is) construct within the specctra dsn spec.
 */
struct PIN_PAIR
{
    PIN_PAIR( ELEM* aParent = 0 ) :
        was( aParent ),
        is( aParent )
    {
    }

    PIN_REF     was;
    PIN_REF     is;
};
typedef std::vector<PIN_PAIR>   PIN_PAIRS;


/**
 * Class WAS_IS
 * corresponds to the &lt;was_is_descriptor&gt; in the specctra dsn spec.
 */
class WAS_IS : public ELEM
{
    friend class SPECCTRA_DB;

    PIN_PAIRS       pin_pairs;

public:
    WAS_IS( ELEM* aParent ) :
        ELEM( T_was_is, aParent )
    {
    }

    void FormatContents( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        for( PIN_PAIRS::iterator i=pin_pairs.begin();  i!=pin_pairs.end();  ++i )
        {
            out->Print( nestLevel, "(pins " );
            i->was.Format( out, 0 );
            out->Print( 0, " " );
            i->is.Format( out, 0 );
            out->Print( 0, ")\n" );
        }
    }
};


/**
 * Class SESSION
 * corresponds to the &lt;session_file_descriptor&gt; in the specctra dsn spec.
 */
class SESSION : public ELEM
{
    friend class SPECCTRA_DB;

    std::string     session_id;
    std::string     base_design;

    HISTORY*        history;
    STRUCTURE*      structure;
    PLACEMENT*      placement;
    WAS_IS*         was_is;
    ROUTE*          route;

/*  not supported:
    FLOOR_PLAN*         floor_plan;
    NET_PIN_CHANGES*    net_pin_changes;
    SWAP_HISTORY*       swap_history;
*/

public:

    SESSION( ELEM* aParent = 0 ) :
        ELEM( T_session, aParent )
    {
        history = 0;
        structure = 0;
        placement = 0;
        was_is = 0;
        route = 0;
    }
    ~SESSION()
    {
        delete history;
        delete structure;
        delete placement;
        delete was_is;
        delete route;
    }

    void Format( OUTPUTFORMATTER* out, int nestLevel ) throw( IO_ERROR )
    {
        const char* quote = out->GetQuoteChar( session_id.c_str() );
        out->Print( nestLevel, "(%s %s%s%s\n", Name(),
                                quote, session_id.c_str(), quote );

        out->Print( nestLevel+1, "(base_design \"%s\")\n", base_design.c_str() );

        if( history )
            history->Format( out, nestLevel+1 );

        if( structure )
            structure->Format( out, nestLevel+1 );

        if( placement )
            placement->Format( out, nestLevel+1 );

        if( was_is )
            was_is->Format( out, nestLevel+1 );

        if( route )
            route->Format( out, nestLevel+1 );

        out->Print( nestLevel, ")\n" );
    }
};

typedef boost::ptr_set<PADSTACK>    PADSTACKSET;


/**
 * Class SPECCTRA_DB
 * holds a DSN data tree, usually coming from a DSN file. Is essentially a
 * SPECCTRA_PARSER class.
 */
class SPECCTRA_DB : public SPECCTRA_LEXER
{
    /// specctra DSN keywords
    static const KEYWORD keywords[];
    static const unsigned keywordCount;

    PCB*            pcb;
    SESSION*        session;
    wxString        filename;
    std::string     quote_char;

    bool            modulesAreFlipped;

    STRING_FORMATTER sf;

    STRINGS         layerIds;       ///< indexed by PCB layer number

    /// maps BOARD layer number to PCB layer numbers
    std::vector<int> kicadLayer2pcb;

    /// maps PCB layer number to BOARD layer numbers
    std::vector<LAYER_ID>   pcbLayer2kicad;

    /// used during FromSESSION() only, memory for it is not owned here.
    UNIT_RES*       routeResolution;

    /// a copy to avoid passing as an argument, memory for it is not owned here.
    BOARD*          sessionBoard;

    static const KICAD_T scanPADs[];

    PADSTACKSET     padstackset;

    /// we don't want ownership here permanently, so we don't use boost::ptr_vector
    std::vector<NET*>   nets;

    /// specctra cu layers, 0 based index:
    int     m_top_via_layer;
    int     m_bot_via_layer;


    /**
     * Function buildLayerMaps
     * creates a few data translation structures for layer name and number
     * mapping between the DSN::PCB structure and the KiCad BOARD structure.
     * @param aBoard The BOARD to create the maps for.
     */
    void buildLayerMaps( BOARD* aBoard );

    /**
     * Function findLayerName
     * returns the PCB layer index for a given layer name, within the specctra session
     * file.
     *
     * @return int - the layer index within the specctra session file, or -1 if
     *  aLayerName is not found.
     */
    int findLayerName( const std::string& aLayerName ) const;

    /**
     * Function readCOMPnPIN
     * reads a &lt;pin_reference&gt; and splits it into the two parts which are
     * on either side of the hyphen.  This function is specialized because
     * pin_reference may or may not be using double quotes.  Both of these
     * are legal:  U2-14 or "U2"-"14".  The lexer treats the first one as a
     * single T_SYMBOL, so in that case we have to split it into two here.
     * <p>
     * The caller should have already read in the first token comprizing the
     * pin_reference and it will be tested through CurTok().
     *
     * @param component_id Where to put the text preceeding the '-' hyphen.
     * @param pid_id Where to put the text which trails the '-'.
     * @throw IO_ERROR, if the next token or two do no make up a pin_reference,
     * or there is an error reading from the input stream.
     */
    void readCOMPnPIN( std::string* component_id, std::string* pid_id ) throw( IO_ERROR );

    /**
     * Function readTIME
     * reads a &lt;time_stamp&gt; which consists of 8 lexer tokens:
     * "month date hour : minute : second year".
     * This function is specialized because time_stamps occur more than
     * once in a session file.
     * <p>
     * The caller should not have already read in the first token comprizing the
     * time stamp.
     *
     * @param time_stamp Where to put the parsed time value.
     * @throw IO_ERROR, if the next token or 8 do no make up a time stamp,
     * or there is an error reading from the input stream.
     */
    void readTIME( time_t* time_stamp ) throw( IO_ERROR );

    void doPCB( PCB* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doPARSER( PARSER* growth ) throw( IO_ERROR );
    void doRESOLUTION( UNIT_RES* growth ) throw( IO_ERROR );
    void doUNIT( UNIT_RES* growth ) throw( IO_ERROR );
    void doSTRUCTURE( STRUCTURE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doSTRUCTURE_OUT( STRUCTURE_OUT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doLAYER_NOISE_WEIGHT( LAYER_NOISE_WEIGHT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doLAYER_PAIR( LAYER_PAIR* growth ) throw( IO_ERROR );
    void doBOUNDARY( BOUNDARY* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doRECTANGLE( RECTANGLE* growth ) throw( IO_ERROR );
    void doPATH( PATH* growth ) throw( IO_ERROR );
    void doSTRINGPROP( STRINGPROP* growth ) throw( IO_ERROR );
    void doTOKPROP( TOKPROP* growth ) throw( IO_ERROR );
    void doVIA( VIA* growth ) throw( IO_ERROR );
    void doCONTROL( CONTROL* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doLAYER( LAYER* growth ) throw( IO_ERROR );
    void doRULE( RULE* growth ) throw( IO_ERROR );
    void doKEEPOUT( KEEPOUT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doCIRCLE( CIRCLE* growth ) throw( IO_ERROR );
    void doQARC( QARC* growth ) throw( IO_ERROR );
    void doWINDOW( WINDOW* growth ) throw( IO_ERROR );
    void doCONNECT( CONNECT* growth ) throw( IO_ERROR );
    void doREGION( REGION* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doCLASS_CLASS( CLASS_CLASS* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doLAYER_RULE( LAYER_RULE* growth ) throw( IO_ERROR );
    void doCLASSES( CLASSES* growth ) throw( IO_ERROR );
    void doGRID( GRID* growth ) throw( IO_ERROR );
    void doPLACE( PLACE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doCOMPONENT( COMPONENT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doPLACEMENT( PLACEMENT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doPROPERTIES( PROPERTIES* growth ) throw( IO_ERROR );
    void doPADSTACK( PADSTACK* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doSHAPE( SHAPE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doIMAGE( IMAGE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doLIBRARY( LIBRARY* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doPIN( PIN* growth ) throw( IO_ERROR );
    void doNET( NET* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doNETWORK( NETWORK* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doCLASS( CLASS* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doTOPOLOGY( TOPOLOGY* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doFROMTO( FROMTO* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doCOMP_ORDER( COMP_ORDER* growth ) throw( IO_ERROR );
    void doWIRE( WIRE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doWIRE_VIA( WIRE_VIA* growth ) throw( IO_ERROR );
    void doWIRING( WIRING* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doSESSION( SESSION* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doANCESTOR( ANCESTOR* growth ) throw( IO_ERROR );
    void doHISTORY( HISTORY* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doROUTE( ROUTE* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doWAS_IS( WAS_IS* growth ) throw( IO_ERROR );
    void doNET_OUT( NET_OUT* growth ) throw( IO_ERROR, boost::bad_pointer );
    void doSUPPLY_PIN( SUPPLY_PIN* growth ) throw( IO_ERROR );

    //-----<FromBOARD>-------------------------------------------------------

    /**
     * Function fillBOUNDARY
     * makes the board perimeter for the DSN file by filling the BOUNDARY element
     * in the specctra element tree.
     * @param aBoard The BOARD to get information from in order to make the BOUNDARY.
     * @param aBoundary The empty BOUNDARY to fill in.
     */
    void fillBOUNDARY( BOARD* aBoard, BOUNDARY* aBoundary ) throw( IO_ERROR, boost::bad_pointer );

    /**
     * Function makeIMAGE
     * allocates an IMAGE on the heap and creates all the PINs according
     * to the D_PADs in the MODULE.
     * @param aBoard The owner of the MODULE.
     * @param aModule The MODULE from which to build the IMAGE.
     * @return IMAGE* - not tested for duplication yet.
     */
    IMAGE* makeIMAGE( BOARD* aBoard, MODULE* aModule );

    /**
     * Function makePADSTACK
     * creates a PADSTACK which matches the given pad.  Only pads which do not
     * satisfy the function isKeepout() should be passed to this function.
     * @param aBoard The owner of the MODULE.
     * @param aPad The D_PAD which needs to be made into a PADSTACK.
     * @return PADSTACK* - The created padstack, including its padstack_id.
     */
    PADSTACK* makePADSTACK( BOARD* aBoard, D_PAD* aPad );

    /**
     * Function makeVia
     * makes a round through hole PADSTACK using the given KiCad diameter in deci-mils.
     * @param aCopperDiameter The diameter of the copper pad.
     * @param aDrillDiameter The drill diameter, used on re-import of the session file.
     * @param aTopLayer The DSN::PCB top most layer index.
     * @param aBotLayer The DSN::PCB bottom most layer index.
     * @return PADSTACK* - The padstack, which is on the heap only, user must save
     *  or delete it.
     */
    PADSTACK* makeVia( int aCopperDiameter, int aDrillDiameter,
                       int aTopLayer, int aBotLayer );

    /**
     * Function makeVia
     * makes any kind of PADSTACK using the given KiCad VIA.
     * @param aVia The VIA to build the padstack from.
     * @return PADSTACK* - The padstack, which is on the heap only, user must save
     *  or delete it.
     */
    PADSTACK* makeVia( const ::VIA* aVia );

    /**
     * Function deleteNETs
     * deletes all the NETs that may be in here.
     */
    void deleteNETs()
    {
        for( unsigned n=0;  n<nets.size();  ++n )
            delete nets[n];

        nets.clear();
    }

    /**
     * Function exportNETCLASS
     * exports \a aNetClass to the DSN file.
     */
    void exportNETCLASS( boost::shared_ptr<NETCLASS> aNetClass, BOARD* aBoard );

    //-----</FromBOARD>------------------------------------------------------

    //-----<FromSESSION>-----------------------------------------------------

    /**
     * Function makeTRACK
     * creates a TRACK form the PATH and BOARD info.
     */
    TRACK* makeTRACK( PATH* aPath, int aPointIndex, int aNetcode ) throw( IO_ERROR );

    /**
     * Function makeVIA
     * instantiates a KiCad VIA on the heap and initializes it with internal
     * values consistent with the given PADSTACK, POINT, and netcode.
     */
    ::VIA* makeVIA( PADSTACK* aPadstack, const POINT& aPoint, int aNetCode, int aViaDrillDefault )
        throw( IO_ERROR );

    //-----</FromSESSION>----------------------------------------------------

public:

    SPECCTRA_DB() :
        SPECCTRA_LEXER( 0 )         // LINE_READER* == NULL, no DSNLEXER::PushReader()
    {
        // The LINE_READER will be pushed from an automatic instantiation,
        // we don't own it:
        wxASSERT( !iOwnReaders );

        pcb   = 0;
        session = 0;
        quote_char += '"';
        modulesAreFlipped = false;

        SetSpecctraMode( true );

        // Avoid not initialized members:
        routeResolution = NULL;
        sessionBoard = NULL;
        m_top_via_layer = 0;
        m_bot_via_layer = 0;
    }

    virtual ~SPECCTRA_DB()
    {
        delete pcb;
        delete session;

        deleteNETs();
    }

    /**
     * Function MakePCB
     * makes a PCB with all the default ELEMs and parts on the heap.
     */
    static PCB* MakePCB();

    /**
     * Function SetPCB
     * deletes any existing PCB and replaces it with the given one.
     */
    void SetPCB( PCB* aPcb )
    {
        delete pcb;
        pcb = aPcb;
    }
    PCB*  GetPCB()  { return pcb; }

    /**
     * Function SetSESSION
     * deletes any existing SESSION and replaces it with the given one.
     */
    void SetSESSION( SESSION* aSession )
    {
        delete session;
        session = aSession;
    }
    SESSION* GetSESSION() { return session; }

    /**
     * Function LoadPCB
     * is a recursive descent parser for a SPECCTRA DSN "design" file.
     * A design file is nearly a full description of a PCB (seems to be
     * missing only the silkscreen stuff).
     *
     * @param filename The name of the dsn file to load.
     * @throw IO_ERROR if there is a lexer or parser error.
     */
    void LoadPCB( const wxString& filename ) throw( IO_ERROR, boost::bad_pointer );

    /**
     * Function LoadSESSION
     * is a recursive descent parser for a SPECCTRA DSN "session" file.
     * A session file is a file that is fed back from the router to the layout
     * tool (Pcbnew) and should be used to update a BOARD object with the new
     * tracks, vias, and component locations.
     *
     * @param filename The name of the dsn file to load.
     * @throw IO_ERROR if there is a lexer or parser error.
     */
    void LoadSESSION( const wxString& filename ) throw( IO_ERROR, boost::bad_pointer );

    void ThrowIOError( const wxString& fmt, ... ) throw( IO_ERROR );

    /**
     * Function ExportPCB
     * writes the internal PCB instance out as a SPECTRA DSN format file.
     *
     * @param aFilename The file to save to.
     * @param aNameChange If true, causes the pcb's name to change to "aFilename"
     *          and also to to be changed in the output file.
     * @throw IO_ERROR, if an i/o error occurs saving the file.
     */
    void ExportPCB( wxString aFilename,  bool aNameChange=false ) throw( IO_ERROR );

    /**
     * Function FromBOARD
     * adds the entire BOARD to the PCB but does not write it out.  Note that
     * the BOARD given to this function must have all the MODULEs on the component
     * side of the BOARD.
     *
     * See void PCB_EDIT_FRAME::ExportToSpecctra( wxCommandEvent& event )
     * for how this can be done before calling this function.
     *
     * @param aBoard The BOARD to convert to a PCB.
     */
    void FromBOARD( BOARD* aBoard ) throw( IO_ERROR, boost::bad_ptr_container_operation );

    /**
     * Function FromSESSION
     * adds the entire SESSION info to a BOARD but does not write it out.  The
     * the BOARD given to this function will have all its tracks and via's replaced,
     * and all its components are subject to being moved.
     *
     * @param aBoard The BOARD to merge the SESSION information into.
     */
    void FromSESSION( BOARD* aBoard ) throw( IO_ERROR );

    /**
     * Function ExportSESSION
     * writes the internal SESSION instance out as a SPECTRA DSN format file.
     *
     * @param aFilename The file to save to.
     */
    void ExportSESSION( wxString aFilename );

    /**
     * Function FlipMODULEs
     * flips the modules which are on the back side of the board to the front.
     */
    void FlipMODULEs( BOARD* aBoard );

    /**
     * Function RevertMODULEs
     * flips the modules which were on the back side of the board back to the back.
     */
    void RevertMODULEs( BOARD* aBoard );

    /**
     * Function GetBoardPolygonOutlines
     * Is not used in SPECCTRA export, but uses a lot of functions from it
     * and is used to extract a board outlines (3D view, automatic zones build ...)
     * makes the board perimeter by filling the BOUNDARY element
     * any closed outline inside the main outline is a hole
     * All contours should be closed, i.e. have valid vertices to build a closed polygon
     * @param aBoard The BOARD to get information from in order to make the outlines.
     * @param aOutlines The SHAPE_POLY_SET to fill in with main outlines.
     * @param aHoles The empty SHAPE_POLY_SET to fill in with holes, if any.
     * @param aErrorText = a wxString reference to display an error message
     *          with the coordinate of the point which creates the error
     *          (default = NULL , no message returned on error)
     * @return true if success, false if a contour is not valid
     */
    bool GetBoardPolygonOutlines( BOARD* aBoard,
                                  SHAPE_POLY_SET& aOutlines,
                                  SHAPE_POLY_SET& aHoles,
                                  wxString* aErrorText = NULL );
};


}           // namespace DSN

#endif      // SPECCTRA_H_

//EOF