This file is indexed.

/usr/share/pyshared/asn2wrs.py is in wireshark-dev 1.10.6-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
#!/usr/bin/env python

#
# asn2wrs.py
# ASN.1 to Wireshark dissector compiler
# 2004 Tomas Kukosa
#
# $Id$
#

"""ASN.1 to Wireshark dissector compiler"""

#
# Compiler from ASN.1 specification to the Wireshark dissector
#
# Based on ASN.1 to Python compiler from Aaron S. Lav's PyZ3950 package licensed under the X Consortium license
# http://www.pobox.com/~asl2/software/PyZ3950/
# (ASN.1 to Python compiler functionality is broken but not removed, it could be revived if necessary)
#
# It requires Dave Beazley's PLY parsing package licensed under the LGPL (tested with version 2.3)
# http://www.dabeaz.com/ply/
#
#
# ITU-T Recommendation X.680 (07/2002),
#   Information technology - Abstract Syntax Notation One (ASN.1): Specification of basic notation
#
# ITU-T Recommendation X.681 (07/2002),
#   Information technology - Abstract Syntax Notation One (ASN.1): Information object specification
#
# ITU-T Recommendation X.682 (07/2002),
#   Information technology - Abstract Syntax Notation One (ASN.1): Constraint specification
#
# ITU-T Recommendation X.683 (07/2002),
#   Information technology - Abstract Syntax Notation One (ASN.1): Parameterization of ASN.1 specifications
#
# ITU-T Recommendation X.880 (07/1994),
#   Information technology - Remote Operations: Concepts, model and notation
#

import warnings

import re
import sys
import os
import os.path
import time
import getopt
import traceback

from ply import lex
from ply import yacc

from string import maketrans
from functools import partial


# OID name -> number conversion table
oid_names = {
  '/itu-t' : 0,
  '/itu'   : 0,
  '/ccitt' : 0,
  '/itu-r' : 0,
  '0/recommendation' : 0,
  '0.0/a' : 1,
  '0.0/b' : 2,
  '0.0/c' : 3,
  '0.0/d' : 4,
  '0.0/e' : 5,
  '0.0/f' : 6,
  '0.0/g' : 7,
  '0.0/h' : 8,
  '0.0/i' : 9,
  '0.0/j' : 10,
  '0.0/k' : 11,
  '0.0/l' : 12,
  '0.0/m' : 13,
  '0.0/n' : 14,
  '0.0/o' : 15,
  '0.0/p' : 16,
  '0.0/q' : 17,
  '0.0/r' : 18,
  '0.0/s' : 19,
  '0.0/t' : 20,
  '0.0/tseries' : 20,
  '0.0/u' : 21,
  '0.0/v' : 22,
  '0.0/w' : 23,
  '0.0/x' : 24,
  '0.0/y' : 25,
  '0.0/z' : 26,
  '0/question' : 1,
  '0/administration' : 2,
  '0/network-operator' : 3,
  '0/identified-organization' : 4,
  '0/r-recommendation' : 5,
  '0/data' : 9,
  '/iso' : 1,
  '1/standard' : 0,
  '1/registration-authority' : 1,
  '1/member-body' : 2,
  '1/identified-organization' : 3,
  '/joint-iso-itu-t' : 2,
  '/joint-iso-ccitt' : 2,
  '2/presentation' : 0,
  '2/asn1' : 1,
  '2/association-control' : 2,
  '2/reliable-transfer' : 3,
  '2/remote-operations' : 4,
  '2/ds' : 5,
  '2/directory' : 5,
  '2/mhs' : 6,
  '2/mhs-motis' : 6,
  '2/ccr' : 7,
  '2/oda' : 8,
  '2/ms' : 9,
  '2/osi-management' : 9,
  '2/transaction-processing' : 10,
  '2/dor' : 11,
  '2/distinguished-object-reference' : 11,
  '2/reference-data-transfe' : 12,
  '2/network-layer' : 13,
  '2/network-layer-management' : 13,
  '2/transport-layer' : 14,
  '2/transport-layer-management' : 14,
  '2/datalink-layer' : 15,
  '2/datalink-layer-managemen' : 15,
  '2/datalink-layer-management-information' : 15,
  '2/country' : 16,
  '2/registration-procedures' : 17,
  '2/registration-procedure' : 17,
  '2/physical-layer' : 18,
  '2/physical-layer-management' : 18,
  '2/mheg' : 19,
  '2/genericULS' : 20,
  '2/generic-upper-layers-security' : 20,
  '2/guls' : 20,
  '2/transport-layer-security-protocol' : 21,
  '2/network-layer-security-protocol' : 22,
  '2/international-organizations' : 23,
  '2/internationalRA' : 23,
  '2/sios' : 24,
  '2/uuid' : 25,
  '2/odp' : 26,
  '2/upu' : 40,
}

ITEM_FIELD_NAME = '_item'
UNTAG_TYPE_NAME = '_untag'

def asn2c(id):
  return id.replace('-', '_').replace('.', '_').replace('&', '_')

input_file = None
g_conform = None
lexer = None
in_oid = False

class LexError(Exception):
  def __init__(self, tok, filename=None):
    self.tok = tok
    self.filename = filename
    self.msg =  "Unexpected character %r" % (self.tok.value[0])
    Exception.__init__(self, self.msg)
  def __repr__(self):
    return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
  __str__ = __repr__


class ParseError(Exception):
  def __init__(self, tok, filename=None):
    self.tok = tok
    self.filename = filename
    self.msg =  "Unexpected token %s(%r)" % (self.tok.type, self.tok.value)
    Exception.__init__(self, self.msg)
  def __repr__(self):
    return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
  __str__ = __repr__


class DuplicateError(Exception):
  def __init__(self, type, ident):
    self.type = type
    self.ident = ident
    self.msg =  "Duplicate %s for %s" % (self.type, self.ident)
    Exception.__init__(self, self.msg)
  def __repr__(self):
    return self.msg
  __str__ = __repr__

class CompError(Exception):
  def __init__(self, msg):
    self.msg =  msg
    Exception.__init__(self, self.msg)
  def __repr__(self):
    return self.msg
  __str__ = __repr__


states = (
  ('braceignore','exclusive'),
)

precedence = (
  ('left', 'UNION', 'BAR'),
  ('left', 'INTERSECTION', 'CIRCUMFLEX'),
)
# 11 ASN.1 lexical items

static_tokens = {
  r'::='    : 'ASSIGNMENT',  # 11.16 Assignment lexical item
  r'\.\.'   : 'RANGE',       # 11.17 Range separator
  r'\.\.\.' : 'ELLIPSIS',    # 11.18 Ellipsis
  r'\[\['   : 'LVERBRACK',   # 11.19 Left version brackets
  r'\]\]'   : 'RVERBRACK',   # 11.20 Right version brackets
  # 11.26 Single character lexical items
  r'\{' : 'LBRACE',
  r'\}' : 'RBRACE',
  r'<'  : 'LT',
  #r'>'  : 'GT',
  r','  : 'COMMA',
  r'\.' : 'DOT',
  r'\(' : 'LPAREN',
  r'\)' : 'RPAREN',
  r'\[' : 'LBRACK',
  r'\]' : 'RBRACK',
  r'-'  : 'MINUS',
  r':'  : 'COLON',
  #r'='  : 'EQ',
  #r'"'  : 'QUOTATION',
  #r"'"  : 'APOSTROPHE',
  r';'  : 'SEMICOLON',
  r'@'  : 'AT',
  r'\!' : 'EXCLAMATION',
  r'\^' : 'CIRCUMFLEX',
  r'\&' : 'AMPERSAND',
  r'\|' : 'BAR'
}

# 11.27 Reserved words

# all keys in reserved_words must start w/ upper case
reserved_words = {
  'ABSENT'      : 'ABSENT',
  'ABSTRACT-SYNTAX' : 'ABSTRACT_SYNTAX',
  'ALL'         : 'ALL',
  'APPLICATION' : 'APPLICATION',
  'AUTOMATIC'   : 'AUTOMATIC',
  'BEGIN'       : 'BEGIN',
  'BIT'         : 'BIT',
  'BOOLEAN'     : 'BOOLEAN',
  'BY'          : 'BY',
  'CHARACTER'   : 'CHARACTER',
  'CHOICE'      : 'CHOICE',
  'CLASS'       : 'CLASS',
  'COMPONENT'   : 'COMPONENT',
  'COMPONENTS'  : 'COMPONENTS',
  'CONSTRAINED' : 'CONSTRAINED',
  'CONTAINING'  : 'CONTAINING',
  'DEFAULT'     : 'DEFAULT',
  'DEFINITIONS' : 'DEFINITIONS',
  'EMBEDDED'    : 'EMBEDDED',
#  'ENCODED'     : 'ENCODED',
  'END'         : 'END',
  'ENUMERATED'  : 'ENUMERATED',
#  'EXCEPT'      : 'EXCEPT',
  'EXPLICIT'    : 'EXPLICIT',
  'EXPORTS'     : 'EXPORTS',
#  'EXTENSIBILITY' : 'EXTENSIBILITY',
  'EXTERNAL'    : 'EXTERNAL',
  'FALSE'       : 'FALSE',
  'FROM'        : 'FROM',
  'GeneralizedTime' : 'GeneralizedTime',
  'IDENTIFIER'  : 'IDENTIFIER',
  'IMPLICIT'    : 'IMPLICIT',
#  'IMPLIED'     : 'IMPLIED',
  'IMPORTS'     : 'IMPORTS',
  'INCLUDES'    : 'INCLUDES',
  'INSTANCE'    : 'INSTANCE',
  'INTEGER'     : 'INTEGER',
  'INTERSECTION' : 'INTERSECTION',
  'MAX'         : 'MAX',
  'MIN'         : 'MIN',
  'MINUS-INFINITY' : 'MINUS_INFINITY',
  'NULL'        : 'NULL',
  'OBJECT'      : 'OBJECT',
  'ObjectDescriptor' : 'ObjectDescriptor',
  'OCTET'       : 'OCTET',
  'OF'          : 'OF',
  'OPTIONAL'    : 'OPTIONAL',
  'PATTERN'     : 'PATTERN',
  'PDV'         : 'PDV',
  'PLUS-INFINITY' : 'PLUS_INFINITY',
  'PRESENT'     : 'PRESENT',
  'PRIVATE'     : 'PRIVATE',
  'REAL'        : 'REAL',
  'RELATIVE-OID' : 'RELATIVE_OID',
  'SEQUENCE'    : 'SEQUENCE',
  'SET'         : 'SET',
  'SIZE'        : 'SIZE',
  'STRING'      : 'STRING',
  'SYNTAX'      : 'SYNTAX',
  'TAGS'        : 'TAGS',
  'TRUE'        : 'TRUE',
  'TYPE-IDENTIFIER' : 'TYPE_IDENTIFIER',
  'UNION'       : 'UNION',
  'UNIQUE'      : 'UNIQUE',
  'UNIVERSAL'   : 'UNIVERSAL',
  'UTCTime'     : 'UTCTime',
  'WITH'        : 'WITH',
# X.208 obsolete but still used
  'ANY'         : 'ANY',
  'DEFINED'     : 'DEFINED',
}

for k in list(static_tokens.keys()):
  if static_tokens [k] == None:
    static_tokens [k] = k

StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8',
               'Teletex', 'T61', 'Videotex', 'Graphic', 'ISO646', 'Visible',
               'General']

for s in StringTypes:
  reserved_words[s + 'String'] = s + 'String'

tokens = list(static_tokens.values()) \
         + list(reserved_words.values()) \
         + ['BSTRING', 'HSTRING', 'QSTRING',
            'UCASE_IDENT', 'LCASE_IDENT', 'LCASE_IDENT_ASSIGNED', 'CLASS_IDENT',
            'REAL_NUMBER', 'NUMBER', 'PYQUOTE']


cur_mod = __import__ (__name__) # XXX blech!

for (k, v) in list(static_tokens.items ()):
    cur_mod.__dict__['t_' + v] = k

# 11.10 Binary strings
def t_BSTRING (t):
    r"'[01]*'B"
    return t

# 11.12 Hexadecimal strings
def t_HSTRING (t):
    r"'[0-9A-Fa-f]*'H"
    return t

def t_QSTRING (t):
    r'"([^"]|"")*"'
    return t

def t_UCASE_IDENT (t):
    r"[A-Z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
    if (is_class_ident(t.value)): t.type = 'CLASS_IDENT'
    if (is_class_syntax(t.value)): t.type = t.value
    t.type = reserved_words.get(t.value, t.type)
    return t

lcase_ident_assigned = {}
def t_LCASE_IDENT (t):
    r"[a-z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
    if (not in_oid and (t.value in lcase_ident_assigned)): t.type = 'LCASE_IDENT_ASSIGNED'
    return t

# 11.9 Real numbers
def t_REAL_NUMBER (t):
    r"[0-9]+\.[0-9]*(?!\.)"
    return t

# 11.8 Numbers
def t_NUMBER (t):
    r"0|([1-9][0-9]*)"
    return t

# 11.6 Comments
pyquote_str = 'PYQUOTE'
def t_COMMENT(t):
    r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
    if (t.value.find("\n") >= 0) : t.lexer.lineno += 1
    if t.value[2:2+len (pyquote_str)] == pyquote_str:
        t.value = t.value[2+len(pyquote_str):]
        t.value = t.value.lstrip ()
        t.type = pyquote_str
        return t
    return None

t_ignore = " \t\r"

def t_NEWLINE(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
  global input_file
  raise LexError(t, input_file)

# state 'braceignore'

def t_braceignore_lbrace(t):
  r'\{'
  t.lexer.level +=1

def t_braceignore_rbrace(t):
  r'\}'
  t.lexer.level -=1
  # If closing brace, return token
  if t.lexer.level == 0:
    t.type = 'RBRACE'
    return t

def t_braceignore_QSTRING (t):
  r'"([^"]|"")*"'
  t.lexer.lineno += t.value.count("\n")

def t_braceignore_COMMENT(t):
  r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
  if (t.value.find("\n") >= 0) : t.lexer.lineno += 1

def t_braceignore_nonspace(t):
   r'[^\s\{\}\"-]+|-(?!-)'

t_braceignore_ignore = " \t\r"

def t_braceignore_NEWLINE(t):
  r'\n+'
  t.lexer.lineno += t.value.count("\n")

def t_braceignore_error(t):
  t.lexer.skip(1)

class Ctx:
    def __init__ (self, defined_dict, indent = 0):
        self.tags_def = 'EXPLICIT' # default = explicit
        self.indent_lev = 0
        self.assignments = {}
        self.dependencies = {}
        self.pyquotes = []
        self.defined_dict = defined_dict
        self.name_ctr = 0
    def spaces (self):
        return " " * (4 * self.indent_lev)
    def indent (self):
        self.indent_lev += 1
    def outdent (self):
        self.indent_lev -= 1
        assert (self.indent_lev >= 0)
    def register_assignment (self, ident, val, dependencies):
        if ident in self.assignments:
            raise DuplicateError("assignment", ident)
        if ident in self.defined_dict:
            raise Exception("cross-module duplicates for %s" % ident)
        self.defined_dict [ident] = 1
        self.assignments[ident] = val
        self.dependencies [ident] = dependencies
        return ""
    #        return "#%s depends on %s" % (ident, str (dependencies))
    def register_pyquote (self, val):
        self.pyquotes.append (val)
        return ""
    def output_assignments (self):
        already_output = {}
        text_list = []
        assign_keys = list(self.assignments.keys())
        to_output_count = len (assign_keys)
        while True:
            any_output = 0
            for (ident, val) in list(self.assignments.items ()):
                if ident in already_output:
                    continue
                ok = 1
                for d in self.dependencies [ident]:
                    if ((d not in already_output) and
                        (d in assign_keys)):
                        ok = 0
                if ok:
                    text_list.append ("%s=%s" % (ident,
                                                self.assignments [ident]))
                    already_output [ident] = 1
                    any_output = 1
                    to_output_count -= 1
                    assert (to_output_count >= 0)
            if not any_output:
                if to_output_count == 0:
                    break
                # OK, we detected a cycle
                cycle_list = []
                for ident in list(self.assignments.keys ()):
                    if ident not in already_output:
                        depend_list = [d for d in self.dependencies[ident] if d in assign_keys]
                        cycle_list.append ("%s(%s)" % (ident, ",".join (depend_list)))

                text_list.append ("# Cycle XXX " + ",".join (cycle_list))
                for (ident, val) in list(self.assignments.items ()):
                    if ident not in already_output:
                        text_list.append ("%s=%s" % (ident, self.assignments [ident]))
                break

        return "\n".join (text_list)
    def output_pyquotes (self):
        return "\n".join (self.pyquotes)
    def make_new_name (self):
        self.name_ctr += 1
        return "_compiler_generated_name_%d" % (self.name_ctr,)

#--- Flags for EXPORT, USER_DEFINED, NO_EMIT, MAKE_ENUM -------------------------------
EF_TYPE    = 0x0001
EF_VALS    = 0x0002
EF_ENUM    = 0x0004
EF_WS_DLL  = 0x0010 #  exported from shared library
EF_EXTERN  = 0x0020
EF_NO_PROT = 0x0040
EF_NO_TYPE = 0x0080
EF_UCASE   = 0x0100
EF_TABLE   = 0x0400
EF_DEFINE  = 0x0800
EF_MODULE  = 0x1000

#--- common dependency computation ---
# Input  : list of items
#          dictionary with lists of dependency
#
#
# Output : list of two outputs:
#          [0] list of items in dependency
#          [1] list of cycle dependency cycles
def dependency_compute(items, dependency, map_fn = lambda t: t, ignore_fn = lambda t: False):
  item_ord = []
  item_cyc = []
  x = {}  # already emitted
  #print '# Dependency computation'
  for t in items:
    if map_fn(t) in x:
      #print 'Continue: %s : %s' % (t, (map_fn(t))
      continue
    stack = [t]
    stackx = {t : dependency.get(t, [])[:]}
    #print 'Push: %s : %s' % (t, str(stackx[t]))
    while stack:
      if stackx[stack[-1]]:  # has dependencies
        d = stackx[stack[-1]].pop(0)
        if map_fn(d) in x or ignore_fn(d):
          continue
        if d in stackx:  # cyclic dependency
          c = stack[:]
          c.reverse()
          c = [d] + c[0:c.index(d)+1]
          c.reverse()
          item_cyc.append(c)
          #print 'Cyclic: %s ' % (' -> '.join(c))
          continue
        stack.append(d)
        stackx[d] = dependency.get(d, [])[:]
        #print 'Push: %s : %s' % (d, str(stackx[d]))
      else:
        #print 'Pop: %s' % (stack[-1])
        del stackx[stack[-1]]
        e = map_fn(stack.pop())
        if e in x:
          continue
        #print 'Add: %s' % (e)
        item_ord.append(e)
        x[e] = True
  return (item_ord, item_cyc)

# Given a filename, return a relative path from epan/dissectors
def rel_dissector_path(filename):
  path_parts = os.path.abspath(filename).split(os.sep)
  while (len(path_parts) > 3 and path_parts[0] != 'asn1'):
    path_parts.pop(0)
  path_parts.insert(0, '..')
  path_parts.insert(0, '..')
  return '/'.join(path_parts)


#--- EthCtx -------------------------------------------------------------------
class EthCtx:
  def __init__(self, conform, output, indent = 0):
    self.conform = conform
    self.output = output
    self.conform.ectx = self
    self.output.ectx = self
    self.encoding = 'per'
    self.aligned = False
    self.default_oid_variant = ''
    self.default_opentype_variant = ''
    self.default_containing_variant = '_pdu_new'
    self.default_embedded_pdv_cb = None
    self.default_external_type_cb = None
    self.remove_prefix = None
    self.srcdir = None
    self.emitted_pdu = {}
    self.module = {}
    self.module_ord = []
    self.all_type_attr = {}
    self.all_tags = {}
    self.all_vals = {}

  def encp(self):  # encoding protocol
    encp = self.encoding
    return encp

  # Encoding
  def Per(self): return self.encoding == 'per'
  def Ber(self): return self.encoding == 'ber'
  def Aligned(self): return self.aligned
  def Unaligned(self): return not self.aligned
  def NeedTags(self): return self.tag_opt or self.Ber()
  def NAPI(self): return False  # disable planned features

  def Module(self):  # current module name
    return self.modules[-1][0]

  def groups(self):
    return self.group_by_prot or (self.conform.last_group > 0)

  def dbg(self, d):
    if (self.dbgopt.find(d) >= 0):
      return True
    else:
      return False

  def value_max(self, a, b):
    if (a == 'MAX') or (b == 'MAX'): return 'MAX';
    if a == 'MIN': return b;
    if b == 'MIN': return a;
    try:
      if (int(a) > int(b)):
        return a
      else:
        return b
    except (ValueError, TypeError):
      pass
    return "MAX((%s),(%s))" % (a, b)

  def value_min(self, a, b):
    if (a == 'MIN') or (b == 'MIN'): return 'MIN';
    if a == 'MAX': return b;
    if b == 'MAX': return a;
    try:
      if (int(a) < int(b)):
        return a
      else:
        return b
    except (ValueError, TypeError):
      pass
    return "MIN((%s),(%s))" % (a, b)

  def value_get_eth(self, val):
    if isinstance(val, Value):
      return val.to_str(self)
    ethname = val
    if val in self.value:
      ethname = self.value[val]['ethname']
    return ethname

  def value_get_val(self, nm):
    val = asn2c(nm)
    if nm in self.value:
      if self.value[nm]['import']:
        v = self.get_val_from_all(nm, self.value[nm]['import'])
        if v is None:
          msg = 'Need value of imported value identifier %s from %s (%s)' % (nm, self.value[nm]['import'], self.value[nm]['proto'])
          warnings.warn_explicit(msg, UserWarning, '', 0)
        else:
          val = v
      else:
        val = self.value[nm]['value']
        if isinstance (val, Value):
          val = val.to_str(self)
    else:
      msg = 'Need value of unknown value identifier %s' % (nm)
      warnings.warn_explicit(msg, UserWarning, '', 0)
    return val

  def eth_get_type_attr(self, type):
    #print "eth_get_type_attr(%s)" % (type)
    types = [type]
    while (not self.type[type]['import']):
      val =  self.type[type]['val']
      #print val
      ttype = type
      while (val.type == 'TaggedType'):
        val = val.val
        ttype += '/' + UNTAG_TYPE_NAME
      if (val.type != 'Type_Ref'):
        if (type != ttype):
          types.append(ttype)
        break
      type = val.val
      types.append(type)
    attr = {}
    #print " ", types
    while len(types):
      t = types.pop()
      if (self.type[t]['import']):
        attr.update(self.type[t]['attr'])
        attr.update(self.eth_get_type_attr_from_all(t, self.type[t]['import']))
      elif (self.type[t]['val'].type == 'SelectionType'):
        val = self.type[t]['val']
        (ftype, display) = val.eth_ftype(self)
        attr.update({ 'TYPE' : ftype, 'DISPLAY' : display,
                      'STRINGS' : val.eth_strings(), 'BITMASK' : '0' });
      else:
        attr.update(self.type[t]['attr'])
        attr.update(self.eth_type[self.type[t]['ethname']]['attr'])
    #print " ", attr
    return attr

  def eth_get_type_attr_from_all(self, type, module):
    attr = {}
    if module in self.all_type_attr and type in self.all_type_attr[module]:
      attr = self.all_type_attr[module][type]
    return attr

  def get_ttag_from_all(self, type, module):
    ttag = None
    if module in self.all_tags and type in self.all_tags[module]:
      ttag = self.all_tags[module][type]
    return ttag

  def get_val_from_all(self, nm, module):
    val = None
    if module in self.all_vals and nm in self.all_vals[module]:
      val = self.all_vals[module][nm]
    return val

  def get_obj_repr(self, ident, flds=[], not_flds=[]):
    def set_type_fn(cls, field, fnfield):
      obj[fnfield + '_fn'] = 'NULL'
      obj[fnfield + '_pdu'] = 'NULL'
      if field in val and isinstance(val[field], Type_Ref):
        p = val[field].eth_type_default_pars(self, '')
        obj[fnfield + '_fn'] = p['TYPE_REF_FN']
        obj[fnfield + '_fn'] = obj[fnfield + '_fn'] % p  # one iteration
        if (self.conform.check_item('PDU', cls + '.' + field)):
          obj[fnfield + '_pdu'] = 'dissect_' + self.field[val[field].val]['ethname']
      return
    # end of get_type_fn()
    obj = { '_name' : ident, '_ident' : asn2c(ident)}
    obj['_class'] = self.oassign[ident].cls
    obj['_module'] = self.oassign[ident].module
    val = self.oassign[ident].val
    for f in flds:
      if f not in val:
        return None
    for f in not_flds:
      if f in val:
        return None
    for f in list(val.keys()):
      if isinstance(val[f], Node):
        obj[f] = val[f].fld_obj_repr(self)
      else:
        obj[f] = str(val[f])
    if (obj['_class'] == 'TYPE-IDENTIFIER') or (obj['_class'] == 'ABSTRACT-SYNTAX'):
      set_type_fn(obj['_class'], '&Type', '_type')
    if (obj['_class'] == 'OPERATION'):
      set_type_fn(obj['_class'], '&ArgumentType', '_argument')
      set_type_fn(obj['_class'], '&ResultType', '_result')
    if (obj['_class'] == 'ERROR'):
      set_type_fn(obj['_class'], '&ParameterType', '_parameter')
    return obj

  #--- eth_reg_module -----------------------------------------------------------
  def eth_reg_module(self, module):
    #print "eth_reg_module(module='%s')" % (module)
    name = module.get_name()
    self.modules.append([name, module.get_proto(self)])
    if name in self.module:
      raise DuplicateError("module", name)
    self.module[name] = []
    self.module_ord.append(name)

  #--- eth_module_dep_add ------------------------------------------------------------
  def eth_module_dep_add(self, module, dep):
    self.module[module].append(dep)

  #--- eth_exports ------------------------------------------------------------
  def eth_exports(self, exports):
    self.exports_all = False
    if ((len(exports) == 1) and (exports[0] == 'ALL')):
      self.exports_all = True
      return
    for e in (exports):
      if isinstance(e, Type_Ref):
        self.exports.append(e.val)
      elif isinstance(e, Class_Ref):
        self.cexports.append(e.val)
      else:
        self.vexports.append(e)

  #--- eth_reg_assign ---------------------------------------------------------
  def eth_reg_assign(self, ident, val, virt=False):
    #print "eth_reg_assign(ident='%s')" % (ident)
    if ident in self.assign:
      raise DuplicateError("assignment", ident)
    self.assign[ident] = { 'val' : val , 'virt' : virt }
    self.assign_ord.append(ident)
    if  (self.exports_all):
      self.exports.append(ident)

  #--- eth_reg_vassign --------------------------------------------------------
  def eth_reg_vassign(self, vassign):
    ident = vassign.ident
    #print "eth_reg_vassign(ident='%s')" % (ident)
    if ident in self.vassign:
      raise DuplicateError("value assignment", ident)
    self.vassign[ident] = vassign
    self.vassign_ord.append(ident)
    if  (self.exports_all):
      self.vexports.append(ident)

  #--- eth_reg_oassign --------------------------------------------------------
  def eth_reg_oassign(self, oassign):
    ident = oassign.ident
    #print "eth_reg_oassign(ident='%s')" % (ident)
    if ident in self.oassign:
      if self.oassign[ident] == oassign:
        return  # OK - already defined
      else:
        raise DuplicateError("information object assignment", ident)
    self.oassign[ident] = oassign
    self.oassign_ord.append(ident)
    self.oassign_cls.setdefault(oassign.cls, []).append(ident)

  #--- eth_import_type --------------------------------------------------------
  def eth_import_type(self, ident, mod, proto):
    #print "eth_import_type(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
    if ident in self.type:
      #print "already defined '%s' import=%s, module=%s" % (ident, str(self.type[ident]['import']), self.type[ident].get('module', '-'))
      if not self.type[ident]['import'] and (self.type[ident]['module'] == mod) :
        return  # OK - already defined
      elif self.type[ident]['import'] and (self.type[ident]['import'] == mod) :
        return  # OK - already imported
      else:
        raise DuplicateError("type", ident)
    self.type[ident] = {'import'  : mod, 'proto' : proto,
                        'ethname' : '' }
    self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
                                 'STRINGS' : 'NULL', 'BITMASK' : '0' }
    mident = "$%s$%s" % (mod, ident)
    if (self.conform.check_item('TYPE_ATTR', mident)):
      self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', mident))
    else:
      self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
    if (self.conform.check_item('IMPORT_TAG', mident)):
      self.conform.copy_item('IMPORT_TAG', ident, mident)
    self.type_imp.append(ident)

  #--- dummy_import_type --------------------------------------------------------
  def dummy_import_type(self, ident):
    # dummy imported
    if ident in self.type:
        raise Exception("Try to dummy import for existing type :%s" % ident)
    ethtype = asn2c(ident)
    self.type[ident] = {'import'  : 'xxx', 'proto' : 'xxx',
                        'ethname' : ethtype }
    self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
                                 'STRINGS' : 'NULL', 'BITMASK' : '0' }
    self.eth_type[ethtype] = { 'import' : 'xxx', 'proto' : 'xxx' , 'attr' : {}, 'ref' : []}
    print "Dummy imported: %s (%s)" % (ident, ethtype)
    return ethtype

  #--- eth_import_class --------------------------------------------------------
  def eth_import_class(self, ident, mod, proto):
    #print "eth_import_class(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
    if ident in self.objectclass:
      #print "already defined import=%s, module=%s" % (str(self.objectclass[ident]['import']), self.objectclass[ident]['module'])
      if not self.objectclass[ident]['import'] and (self.objectclass[ident]['module'] == mod) :
        return  # OK - already defined
      elif self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == mod) :
        return  # OK - already imported
      else:
        raise DuplicateError("object class", ident)
    self.objectclass[ident] = {'import'  : mod, 'proto' : proto,
                        'ethname' : '' }
    self.objectclass_imp.append(ident)

  #--- eth_import_value -------------------------------------------------------
  def eth_import_value(self, ident, mod, proto):
    #print "eth_import_value(ident='%s', mod='%s', prot='%s')" % (ident, mod, prot)
    if ident in self.value:
      #print "already defined import=%s, module=%s" % (str(self.value[ident]['import']), self.value[ident]['module'])
      if not self.value[ident]['import'] and (self.value[ident]['module'] == mod) :
        return  # OK - already defined
      elif self.value[ident]['import'] and (self.value[ident]['import'] == mod) :
        return  # OK - already imported
      else:
        raise DuplicateError("value", ident)
    self.value[ident] = {'import'  : mod, 'proto' : proto,
                         'ethname' : ''}
    self.value_imp.append(ident)

  #--- eth_sel_req ------------------------------------------------------------
  def eth_sel_req(self, typ, sel):
    key = typ + '.' + sel
    if key not in self.sel_req:
      self.sel_req[key] = { 'typ' : typ , 'sel' : sel}
      self.sel_req_ord.append(key)
    return key

  #--- eth_comp_req ------------------------------------------------------------
  def eth_comp_req(self, type):
    self.comp_req_ord.append(type)

  #--- eth_dep_add ------------------------------------------------------------
  def eth_dep_add(self, type, dep):
    if type not in self.type_dep:
      self.type_dep[type] = []
    self.type_dep[type].append(dep)

  #--- eth_reg_type -----------------------------------------------------------
  def eth_reg_type(self, ident, val):
    #print "eth_reg_type(ident='%s', type='%s')" % (ident, val.type)
    if ident in self.type:
      if self.type[ident]['import'] and (self.type[ident]['import'] == self.Module()) :
        # replace imported type
        del self.type[ident]
        self.type_imp.remove(ident)
      else:
        raise DuplicateError("type", ident)
    val.ident = ident
    self.type[ident] = { 'val' : val, 'import' : None }
    self.type[ident]['module'] = self.Module()
    self.type[ident]['proto'] = self.proto
    if len(ident.split('/')) > 1:
      self.type[ident]['tname'] = val.eth_tname()
    else:
      self.type[ident]['tname'] = asn2c(ident)
    self.type[ident]['export'] = self.conform.use_item('EXPORTS', ident)
    self.type[ident]['enum'] = self.conform.use_item('MAKE_ENUM', ident)
    self.type[ident]['vals_ext'] = self.conform.use_item('USE_VALS_EXT', ident)
    self.type[ident]['user_def'] = self.conform.use_item('USER_DEFINED', ident)
    self.type[ident]['no_emit'] = self.conform.use_item('NO_EMIT', ident)
    self.type[ident]['tname'] = self.conform.use_item('TYPE_RENAME', ident, val_dflt=self.type[ident]['tname'])
    self.type[ident]['ethname'] = ''
    if (val.type == 'Type_Ref') or (val.type == 'TaggedType') or (val.type == 'SelectionType') :
      self.type[ident]['attr'] = {}
    else:
      (ftype, display) = val.eth_ftype(self)
      self.type[ident]['attr'] = { 'TYPE' : ftype, 'DISPLAY' : display,
                                   'STRINGS' : val.eth_strings(), 'BITMASK' : '0' }
    self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
    self.type_ord.append(ident)
    # PDU
    if (self.conform.check_item('PDU', ident)):
      self.eth_reg_field(ident, ident, impl=val.HasImplicitTag(self), pdu=self.conform.use_item('PDU', ident))

  #--- eth_reg_objectclass ----------------------------------------------------------
  def eth_reg_objectclass(self, ident, val):
    #print "eth_reg_objectclass(ident='%s')" % (ident)
    if ident in self.objectclass:
      if self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == self.Module()) :
        # replace imported object class
        del self.objectclass[ident]
        self.objectclass_imp.remove(ident)
      elif isinstance(self.objectclass[ident]['val'], Class_Ref) and \
           isinstance(val, Class_Ref) and \
           (self.objectclass[ident]['val'].val == val.val):
        pass  # ignore duplicated CLASS1 ::= CLASS2
      else:
        raise DuplicateError("object class", ident)
    self.objectclass[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto }
    self.objectclass[ident]['val'] = val
    self.objectclass[ident]['export'] = self.conform.use_item('EXPORTS', ident)
    self.objectclass_ord.append(ident)

  #--- eth_reg_value ----------------------------------------------------------
  def eth_reg_value(self, ident, type, value, ethname=None):
    #print "eth_reg_value(ident='%s')" % (ident)
    if ident in self.value:
      if self.value[ident]['import'] and (self.value[ident]['import'] == self.Module()) :
        # replace imported value
        del self.value[ident]
        self.value_imp.remove(ident)
      elif ethname:
        self.value[ident]['ethname'] = ethname
        return
      else:
        raise DuplicateError("value", ident)
    self.value[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto,
                          'type' : type, 'value' : value,
                          'no_emit' : False }
    self.value[ident]['export'] = self.conform.use_item('EXPORTS', ident)
    self.value[ident]['ethname'] = ''
    if (ethname): self.value[ident]['ethname'] = ethname
    self.value_ord.append(ident)

  #--- eth_reg_field ----------------------------------------------------------
  def eth_reg_field(self, ident, type, idx='', parent=None, impl=False, pdu=None):
    #print "eth_reg_field(ident='%s', type='%s')" % (ident, type)
    if ident in self.field:
      if pdu and (type == self.field[ident]['type']):
        pass  # OK already created PDU
      else:
        raise DuplicateError("field", ident)
    self.field[ident] = {'type' : type, 'idx' : idx, 'impl' : impl, 'pdu' : pdu,
                         'modified' : '', 'attr' : {} }
    name = ident.split('/')[-1]
    if self.remove_prefix and name.startswith(self.remove_prefix):
        name = name[len(self.remove_prefix):]

    if len(ident.split('/')) > 1 and name == ITEM_FIELD_NAME:  # Sequence/Set of type
      if len(self.field[ident]['type'].split('/')) > 1:
        self.field[ident]['attr']['NAME'] = '"%s item"' % ident.split('/')[-2]
        self.field[ident]['attr']['ABBREV'] = asn2c(ident.split('/')[-2] + name)
      else:
        self.field[ident]['attr']['NAME'] = '"%s"' % self.field[ident]['type']
        self.field[ident]['attr']['ABBREV'] = asn2c(self.field[ident]['type'])
    else:
      self.field[ident]['attr']['NAME'] = '"%s"' % name
      self.field[ident]['attr']['ABBREV'] = asn2c(name)
    if self.conform.check_item('FIELD_ATTR', ident):
      self.field[ident]['modified'] = '#' + str(id(self))
      self.field[ident]['attr'].update(self.conform.use_item('FIELD_ATTR', ident))
    if (pdu):
      self.field[ident]['pdu']['export'] = (self.conform.use_item('EXPORTS', ident + '_PDU') != 0)
      self.pdu_ord.append(ident)
    else:
      self.field_ord.append(ident)
    if parent:
      self.eth_dep_add(parent, type)

  def eth_dummy_eag_field_required(self):
    if (not self.dummy_eag_field):
      self.dummy_eag_field = 'dummy_eag_field'

  #--- eth_clean --------------------------------------------------------------
  def eth_clean(self):
    self.proto = self.proto_opt;
    #--- ASN.1 tables ----------------
    self.assign = {}
    self.assign_ord = []
    self.field = {}
    self.pdu_ord = []
    self.field_ord = []
    self.type = {}
    self.type_ord = []
    self.type_imp = []
    self.type_dep = {}
    self.sel_req = {}
    self.sel_req_ord = []
    self.comp_req_ord = []
    self.vassign = {}
    self.vassign_ord = []
    self.value = {}
    self.value_ord = []
    self.value_imp = []
    self.objectclass = {}
    self.objectclass_ord = []
    self.objectclass_imp = []
    self.oassign = {}
    self.oassign_ord = []
    self.oassign_cls = {}
    #--- Modules ------------
    self.modules = []
    self.exports_all = False
    self.exports = []
    self.cexports = []
    self.vexports = []
    #--- types -------------------
    self.eth_type = {}
    self.eth_type_ord = []
    self.eth_export_ord = []
    self.eth_type_dupl = {}
    self.named_bit = []
    #--- value dependencies -------------------
    self.value_dep = {}
    #--- values -------------------
    self.eth_value = {}
    self.eth_value_ord = []
    #--- fields -------------------------
    self.eth_hf = {}
    self.eth_hf_ord = []
    self.eth_hfpdu_ord = []
    self.eth_hf_dupl = {}
    self.dummy_eag_field = None
    #--- type dependencies -------------------
    self.eth_type_ord1 = []
    self.eth_dep_cycle = []
    self.dep_cycle_eth_type = {}
    #--- value dependencies and export -------------------
    self.eth_value_ord1 = []
    self.eth_vexport_ord = []

  #--- eth_prepare ------------------------------------------------------------
  def eth_prepare(self):
    self.eproto = asn2c(self.proto)

    #--- dummy types/fields for PDU registration ---
    nm = 'NULL'
    if (self.conform.check_item('PDU', nm)):
      self.eth_reg_type('_dummy/'+nm, NullType())
      self.eth_reg_field(nm, '_dummy/'+nm, pdu=self.conform.use_item('PDU', nm))

    #--- required PDUs ----------------------------
    for t in self.type_ord:
      pdu = self.type[t]['val'].eth_need_pdu(self)
      if not pdu: continue
      f = pdu['type']
      pdu['reg'] = None
      pdu['hidden'] = False
      pdu['need_decl'] = True
      if f not in self.field:
        self.eth_reg_field(f, f, pdu=pdu)

    #--- values -> named values -------------------
    t_for_update = {}
    for v in self.value_ord:
      if (self.value[v]['type'].type == 'Type_Ref') or self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v):
        if self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v):
          tnm = self.conform.use_item('ASSIGN_VALUE_TO_TYPE', v)
        else:
          tnm = self.value[v]['type'].val
        if tnm in self.type \
           and not self.type[tnm]['import'] \
           and (self.type[tnm]['val'].type == 'IntegerType'):
          self.type[tnm]['val'].add_named_value(v, self.value[v]['value'])
          self.value[v]['no_emit'] = True
          t_for_update[tnm] = True
    for t in list(t_for_update.keys()):
      self.type[t]['attr']['STRINGS'] = self.type[t]['val'].eth_strings()
      self.type[t]['attr'].update(self.conform.use_item('TYPE_ATTR', t))

    #--- required components of ---------------------------
    #print "self.comp_req_ord = ", self.comp_req_ord
    for t in self.comp_req_ord:
      self.type[t]['val'].eth_reg_sub(t, self, components_available=True)

    #--- required selection types ---------------------------
    #print "self.sel_req_ord = ", self.sel_req_ord
    for t in self.sel_req_ord:
      tt = self.sel_req[t]['typ']
      if tt not in self.type:
        self.dummy_import_type(t)
      elif self.type[tt]['import']:
        self.eth_import_type(t, self.type[tt]['import'], self.type[tt]['proto'])
      else:
        self.type[tt]['val'].sel_req(t, self.sel_req[t]['sel'], self)

    #--- types -------------------
    for t in self.type_imp: # imported types
      nm = asn2c(t)
      self.eth_type[nm] = { 'import' : self.type[t]['import'],
                            'proto' : asn2c(self.type[t]['proto']),
                            'attr' : {}, 'ref' : []}
      self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
      self.type[t]['ethname'] = nm
    for t in self.type_ord: # dummy import for missing type reference
      tp = self.type[t]['val']
      #print "X : %s %s " % (t, tp.type)
      if isinstance(tp, TaggedType):
        #print "%s : %s " % (tp.type, t)
        tp = tp.val
      if isinstance(tp, Type_Ref):
        #print "%s : %s ::= %s " % (tp.type, t, tp.val)
        if tp.val not in self.type:
          self.dummy_import_type(tp.val)
    for t in self.type_ord:
      nm = self.type[t]['tname']
      if ((nm.find('#') >= 0) or
          ((len(t.split('/'))>1) and
           (self.conform.get_fn_presence(t) or self.conform.check_item('FN_PARS', t) or
            self.conform.get_fn_presence('/'.join((t,ITEM_FIELD_NAME))) or self.conform.check_item('FN_PARS', '/'.join((t,ITEM_FIELD_NAME)))) and
           not self.conform.check_item('TYPE_RENAME', t))):
        if len(t.split('/')) == 2 and t.split('/')[1] == ITEM_FIELD_NAME:  # Sequence of type at the 1st level
          nm = t.split('/')[0] + t.split('/')[1]
        elif t.split('/')[-1] == ITEM_FIELD_NAME:  # Sequence/Set of type at next levels
          nm = 'T_' + self.conform.use_item('FIELD_RENAME', '/'.join(t.split('/')[0:-1]), val_dflt=t.split('/')[-2]) + t.split('/')[-1]
        elif t.split('/')[-1] == UNTAG_TYPE_NAME:  # Untagged type
          nm = self.type['/'.join(t.split('/')[0:-1])]['ethname'] + '_U'
        else:
          nm = 'T_' + self.conform.use_item('FIELD_RENAME', t, val_dflt=t.split('/')[-1])
        nm = asn2c(nm)
        if nm in self.eth_type:
          if nm in self.eth_type_dupl:
            self.eth_type_dupl[nm].append(t)
          else:
            self.eth_type_dupl[nm] = [self.eth_type[nm]['ref'][0], t]
          nm += '_%02d' % (len(self.eth_type_dupl[nm])-1)
      if nm in self.eth_type:
        self.eth_type[nm]['ref'].append(t)
      else:
        self.eth_type_ord.append(nm)
        self.eth_type[nm] = { 'import' : None, 'proto' : self.eproto, 'export' : 0, 'enum' : 0, 'vals_ext' : 0,
                              'user_def' : EF_TYPE|EF_VALS, 'no_emit' : EF_TYPE|EF_VALS,
                              'val' : self.type[t]['val'],
                              'attr' : {}, 'ref' : [t]}
      self.type[t]['ethname'] = nm
      if (not self.eth_type[nm]['export'] and self.type[t]['export']):  # new export
        self.eth_export_ord.append(nm)
      self.eth_type[nm]['export'] |= self.type[t]['export']
      self.eth_type[nm]['enum'] |= self.type[t]['enum']
      self.eth_type[nm]['vals_ext'] |= self.type[t]['vals_ext']
      self.eth_type[nm]['user_def'] &= self.type[t]['user_def']
      self.eth_type[nm]['no_emit'] &= self.type[t]['no_emit']
      if self.type[t]['attr'].get('STRINGS') == '$$':
        use_ext = self.type[t]['vals_ext']
        if (use_ext):
          self.eth_type[nm]['attr']['STRINGS'] = '&%s_ext' % (self.eth_vals_nm(nm))
        else:
          self.eth_type[nm]['attr']['STRINGS'] = 'VALS(%s)' % (self.eth_vals_nm(nm))
      self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
    for t in self.eth_type_ord:
      bits = self.eth_type[t]['val'].eth_named_bits()
      if (bits):
        for (val, id) in bits:
          self.named_bit.append({'name' : id, 'val' : val,
                                 'ethname' : 'hf_%s_%s_%s' % (self.eproto, t, asn2c(id)),
                                 'ftype'   : 'FT_BOOLEAN', 'display' : '8',
                                 'strings' : 'NULL',
                                 'bitmask' : '0x'+('80','40','20','10','08','04','02','01')[val%8]})
      if self.eth_type[t]['val'].eth_need_tree():
        self.eth_type[t]['tree'] = "ett_%s_%s" % (self.eth_type[t]['proto'], t)
      else:
        self.eth_type[t]['tree'] = None

    #--- register values from enums ------------
    for t in self.eth_type_ord:
      if (self.eth_type[t]['val'].eth_has_enum(t, self)):
        self.eth_type[t]['val'].reg_enum_vals(t, self)

    #--- value dependencies -------------------
    for v in self.value_ord:
      if isinstance (self.value[v]['value'], Value):
        dep = self.value[v]['value'].get_dep()
      else:
        dep = self.value[v]['value']
      if dep and dep in self.value:
        self.value_dep.setdefault(v, []).append(dep)

    #--- exports all necessary values
    for v in self.value_ord:
      if not self.value[v]['export']: continue
      deparr = self.value_dep.get(v, [])
      while deparr:
        d = deparr.pop()
        if not self.value[d]['import']:
          if not self.value[d]['export']:
            self.value[d]['export'] = EF_TYPE
            deparr.extend(self.value_dep.get(d, []))

    #--- values -------------------
    for v in self.value_imp:
      nm = asn2c(v)
      self.eth_value[nm] = { 'import' : self.value[v]['import'],
                             'proto' : asn2c(self.value[v]['proto']),
                             'ref' : []}
      self.value[v]['ethname'] = nm
    for v in self.value_ord:
      if (self.value[v]['ethname']):
        continue
      if (self.value[v]['no_emit']):
        continue
      nm = asn2c(v)
      self.eth_value[nm] = { 'import' : None,
                             'proto' : asn2c(self.value[v]['proto']),
                             'export' : self.value[v]['export'], 'ref' : [v] }
      self.eth_value[nm]['value'] = self.value[v]['value']
      self.eth_value_ord.append(nm)
      self.value[v]['ethname'] = nm

    #--- fields -------------------------
    for f in (self.pdu_ord + self.field_ord):
      if len(f.split('/')) > 1 and f.split('/')[-1] == ITEM_FIELD_NAME:  # Sequence/Set of type
        nm = self.conform.use_item('FIELD_RENAME', '/'.join(f.split('/')[0:-1]), val_dflt=f.split('/')[-2]) + f.split('/')[-1]
      else:
        nm = f.split('/')[-1]
      nm = self.conform.use_item('FIELD_RENAME', f, val_dflt=nm)
      nm = asn2c(nm)
      if (self.field[f]['pdu']):
        nm += '_PDU'
        if (not self.merge_modules or self.field[f]['pdu']['export']):
          nm = self.eproto + '_' + nm
      t = self.field[f]['type']
      if t in self.type:
        ethtype = self.type[t]['ethname']
      else:  # undefined type
        ethtype = self.dummy_import_type(t)
      ethtypemod = ethtype + self.field[f]['modified']
      if nm in self.eth_hf:
        if nm in self.eth_hf_dupl:
          if ethtypemod in self.eth_hf_dupl[nm]:
            nm = self.eth_hf_dupl[nm][ethtypemod]
            self.eth_hf[nm]['ref'].append(f)
            self.field[f]['ethname'] = nm
            continue
          else:
            nmx = nm + ('_%02d' % (len(self.eth_hf_dupl[nm])))
            self.eth_hf_dupl[nm][ethtype] = nmx
            nm = nmx
        else:
          if (self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified']) == ethtypemod:
            self.eth_hf[nm]['ref'].append(f)
            self.field[f]['ethname'] = nm
            continue
          else:
            nmx = nm + '_01'
            self.eth_hf_dupl[nm] = {self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified'] : nm, \
                                    ethtypemod : nmx}
            nm = nmx
      if (self.field[f]['pdu']):
        self.eth_hfpdu_ord.append(nm)
      else:
        self.eth_hf_ord.append(nm)
      fullname = 'hf_%s_%s' % (self.eproto, nm)
      attr = self.eth_get_type_attr(self.field[f]['type']).copy()
      attr.update(self.field[f]['attr'])
      if (self.NAPI() and 'NAME' in attr):
        attr['NAME'] += self.field[f]['idx']
      attr.update(self.conform.use_item('EFIELD_ATTR', nm))
      use_vals_ext = self.eth_type[ethtype].get('vals_ext')
      if (use_vals_ext):
        attr['DISPLAY'] += '|BASE_EXT_STRING'
      self.eth_hf[nm] = {'fullname' : fullname, 'pdu' : self.field[f]['pdu'],
                         'ethtype' : ethtype, 'modified' : self.field[f]['modified'],
                         'attr' : attr.copy(),
                         'ref' : [f]}
      self.field[f]['ethname'] = nm
    if (self.dummy_eag_field):
      self.dummy_eag_field = 'hf_%s_%s' % (self.eproto, self.dummy_eag_field)
    #--- type dependencies -------------------
    (self.eth_type_ord1, self.eth_dep_cycle) = dependency_compute(self.type_ord, self.type_dep, map_fn = lambda t: self.type[t]['ethname'], ignore_fn = lambda t: self.type[t]['import'])
    i = 0
    while i < len(self.eth_dep_cycle):
      t = self.type[self.eth_dep_cycle[i][0]]['ethname']
      self.dep_cycle_eth_type.setdefault(t, []).append(i)
      i += 1

    #--- value dependencies and export -------------------
    for v in self.eth_value_ord:
      if self.eth_value[v]['export']:
        self.eth_vexport_ord.append(v)
      else:
        self.eth_value_ord1.append(v)

    #--- export tags, values, ... ---
    for t in self.exports:
      if t not in self.type:
        continue
      if self.type[t]['import']:
        continue
      m = self.type[t]['module']
      if not self.Per():
        if m not in self.all_tags:
          self.all_tags[m] = {}
        self.all_tags[m][t] = self.type[t]['val'].GetTTag(self)
      if m not in self.all_type_attr:
        self.all_type_attr[m] = {}
      self.all_type_attr[m][t] = self.eth_get_type_attr(t).copy()
    for v in self.vexports:
      if v not in self.value:
        continue
      if self.value[v]['import']:
        continue
      m = self.value[v]['module']
      if m not in self.all_vals:
        self.all_vals[m] = {}
      vv = self.value[v]['value']
      if isinstance (vv, Value):
        vv = vv.to_str(self)
      self.all_vals[m][v] = vv

  #--- eth_vals_nm ------------------------------------------------------------
  def eth_vals_nm(self, tname):
    out = ""
    if (not self.eth_type[tname]['export'] & EF_NO_PROT):
      out += "%s_" % (self.eproto)
    out += "%s_vals" % (tname)
    return out

  #--- eth_vals ---------------------------------------------------------------
  def eth_vals(self, tname, vals):
    out = ""
    has_enum = self.eth_type[tname]['enum'] & EF_ENUM
    use_ext = self.eth_type[tname]['vals_ext']
    if (use_ext):
      vals.sort(key=lambda vals_entry: int(vals_entry[0]))
    if (not self.eth_type[tname]['export'] & EF_VALS):
      out += 'static '
    if (self.eth_type[tname]['export'] & EF_VALS) and (self.eth_type[tname]['export'] & EF_TABLE):
      out += 'static '
    out += "const value_string %s[] = {\n" % (self.eth_vals_nm(tname))
    for (val, id) in vals:
      if (has_enum):
        vval = self.eth_enum_item(tname, id)
      else:
        vval = val
      out += '  { %3s, "%s" },\n' % (vval, id)
    out += "  { 0, NULL }\n};\n"
    if (use_ext):
      out += "\nstatic value_string_ext %s_ext = VALUE_STRING_EXT_INIT(%s);\n" % (self.eth_vals_nm(tname), self.eth_vals_nm(tname))
    return out

  #--- eth_enum_prefix ------------------------------------------------------------
  def eth_enum_prefix(self, tname, type=False):
    out = ""
    if (self.eth_type[tname]['export'] & EF_ENUM):
      no_prot = self.eth_type[tname]['export'] & EF_NO_PROT
    else:
      no_prot = self.eth_type[tname]['enum'] & EF_NO_PROT
    if (not no_prot):
      out += self.eproto
    if ((not self.eth_type[tname]['enum'] & EF_NO_TYPE) or type):
      if (out): out += '_'
      out += tname
    if (self.eth_type[tname]['enum'] & EF_UCASE):
      out = out.upper()
    if (out): out += '_'
    return out

  #--- eth_enum_nm ------------------------------------------------------------
  def eth_enum_nm(self, tname):
    out = self.eth_enum_prefix(tname, type=True)
    out += "enum"
    return out

  #--- eth_enum_item ---------------------------------------------------------------
  def eth_enum_item(self, tname, ident):
    out = self.eth_enum_prefix(tname)
    out += asn2c(ident)
    if (self.eth_type[tname]['enum'] & EF_UCASE):
      out = out.upper()
    return out

  #--- eth_enum ---------------------------------------------------------------
  def eth_enum(self, tname, vals):
    out = ""
    if (self.eth_type[tname]['enum'] & EF_DEFINE):
      out += "/* enumerated values for %s */\n" % (tname)
      for (val, id) in vals:
        out += '#define %-12s %3s\n' % (self.eth_enum_item(tname, id), val)
    else:
      out += "typedef enum _%s {\n" % (self.eth_enum_nm(tname))
      first_line = 1
      for (val, id) in vals:
        if (first_line == 1):
          first_line = 0
        else:
          out += ",\n"
        out += '  %-12s = %3s' % (self.eth_enum_item(tname, id), val)
      out += "\n} %s;\n" % (self.eth_enum_nm(tname))
    return out

  #--- eth_bits ---------------------------------------------------------------
  def eth_bits(self, tname, bits):
    out = ""
    out += "static const "
    out += "asn_namedbit %(TABLE)s[] = {\n"
    for (val, id) in bits:
      out += '  { %2d, &hf_%s_%s_%s, -1, -1, "%s", NULL },\n' % (val, self.eproto, tname, asn2c(id), id)
    out += "  { 0, NULL, 0, 0, NULL, NULL }\n};\n"
    return out

  #--- eth_type_fn_h ----------------------------------------------------------
  def eth_type_fn_h(self, tname):
    out = ""
    if (not self.eth_type[tname]['export'] & EF_TYPE):
      out += 'static '
    out += "int "
    if (self.Ber()):
      out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname)
    elif (self.Per()):
      out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname)
    out += ";\n"
    return out

  #--- eth_fn_call ------------------------------------------------------------
  def eth_fn_call(self, fname, ret=None, indent=2, par=None):
    out = indent * ' '
    if (ret):
      if (ret == 'return'):
        out += 'return '
      else:
        out += ret + ' = '
    out += fname + '('
    ind = len(out)
    for i in range(len(par)):
      if (i>0): out += ind * ' '
      out += ', '.join(par[i])
      if (i<(len(par)-1)): out += ',\n'
    out += ');\n'
    return out

  #--- eth_type_fn_hdr --------------------------------------------------------
  def eth_type_fn_hdr(self, tname):
    out = '\n'
    if (not self.eth_type[tname]['export'] & EF_TYPE):
      out += 'static '
    out += "int\n"
    if (self.Ber()):
      out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname)
    elif (self.Per()):
      out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname)
    #if self.conform.get_fn_presence(tname):
    #  out += self.conform.get_fn_text(tname, 'FN_HDR')
    #el
    if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
      out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_HDR')
    return out

  #--- eth_type_fn_ftr --------------------------------------------------------
  def eth_type_fn_ftr(self, tname):
    out = '\n'
    #if self.conform.get_fn_presence(tname):
    #  out += self.conform.get_fn_text(tname, 'FN_FTR')
    #el
    if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
      out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_FTR')
    out += "  return offset;\n"
    out += "}\n"
    return out

  #--- eth_type_fn_body -------------------------------------------------------
  def eth_type_fn_body(self, tname, body, pars=None):
    out = body
    #if self.conform.get_fn_body_presence(tname):
    #  out = self.conform.get_fn_text(tname, 'FN_BODY')
    #el
    if self.conform.get_fn_body_presence(self.eth_type[tname]['ref'][0]):
      out = self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_BODY')
    if pars:
      try:
        out = out % pars
      except (TypeError):
        pass
    return out

  #--- eth_out_pdu_decl ----------------------------------------------------------
  def eth_out_pdu_decl(self, f):
    t = self.eth_hf[f]['ethtype']
    is_new = self.eth_hf[f]['pdu']['new']
    out = ''
    if (not self.eth_hf[f]['pdu']['export']):
      out += 'static '
    if (is_new):
      out += 'int '
      out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_);\n'
    else:
      out += 'void '
      out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_);\n'
    return out

  #--- eth_output_hf ----------------------------------------------------------
  def eth_output_hf (self):
    if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
    fx = self.output.file_open('hf')
    for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
      fx.write("%-50s/* %s */\n" % ("static int %s = -1;  " % (self.eth_hf[f]['fullname']), self.eth_hf[f]['ethtype']))
    if (self.named_bit):
      fx.write('/* named bits */\n')
    for nb in self.named_bit:
      fx.write("static int %s = -1;\n" % (nb['ethname']))
    if (self.dummy_eag_field):
      fx.write("static int %s = -1; /* never registered */ \n" % (self.dummy_eag_field))
    self.output.file_close(fx)

  #--- eth_output_hf_arr ------------------------------------------------------
  def eth_output_hf_arr (self):
    if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
    fx = self.output.file_open('hfarr')
    for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
      t = self.eth_hf[f]['ethtype']
      if self.remove_prefix and t.startswith(self.remove_prefix):
        t = t[len(self.remove_prefix):]
      name=self.eth_hf[f]['attr']['NAME']
      trantab=maketrans("- ", "__")
      name=name.translate(trantab)
      namelower=name.lower()
      tquoted_lower = '"' + t.lower() + '"'
      # Try to avoid giving blurbs that give no more info than the name
      if tquoted_lower == namelower or \
	 t == "NULL" or \
	 tquoted_lower.replace("t_", "") == namelower:
        blurb = 'NULL'
      else:
        blurb = '"%s"' % (t)
      attr = self.eth_hf[f]['attr'].copy()
      attr['ABBREV'] = '"%s.%s"' % (self.proto, attr['ABBREV'])
      if 'BLURB' not in attr:
        attr['BLURB'] = blurb
      fx.write('    { &%s,\n' % (self.eth_hf[f]['fullname']))
      fx.write('      { %(NAME)s, %(ABBREV)s,\n' % attr)
      fx.write('        %(TYPE)s, %(DISPLAY)s, %(STRINGS)s, %(BITMASK)s,\n' % attr)
      fx.write('        %(BLURB)s, HFILL }},\n' % attr)
    for nb in self.named_bit:
      fx.write('    { &%s,\n' % (nb['ethname']))
      fx.write('      { "%s", "%s.%s",\n' % (nb['name'], self.proto, nb['name']))
      fx.write('        %s, %s, %s, %s,\n' % (nb['ftype'], nb['display'], nb['strings'], nb['bitmask']))
      fx.write('        NULL, HFILL }},\n')
    self.output.file_close(fx)

  #--- eth_output_ett ---------------------------------------------------------
  def eth_output_ett (self):
    fx = self.output.file_open('ett')
    fempty = True
    #fx.write("static gint ett_%s = -1;\n" % (self.eproto))
    for t in self.eth_type_ord:
      if self.eth_type[t]['tree']:
        fx.write("static gint %s = -1;\n" % (self.eth_type[t]['tree']))
        fempty = False
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_ett_arr -----------------------------------------------------
  def eth_output_ett_arr(self):
    fx = self.output.file_open('ettarr')
    fempty = True
    #fx.write("    &ett_%s,\n" % (self.eproto))
    for t in self.eth_type_ord:
      if self.eth_type[t]['tree']:
        fx.write("    &%s,\n" % (self.eth_type[t]['tree']))
        fempty = False
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_export ------------------------------------------------------
  def eth_output_export(self):
    fx = self.output.file_open('exp', ext='h')
    for t in self.eth_export_ord:  # vals
      if (self.eth_type[t]['export'] & EF_ENUM) and self.eth_type[t]['val'].eth_has_enum(t, self):
        fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
      if (self.eth_type[t]['export'] & EF_VALS) and self.eth_type[t]['val'].eth_has_vals():
        if not self.eth_type[t]['export'] & EF_TABLE:
          if self.eth_type[t]['export'] & EF_WS_DLL:
            fx.write("WS_DLL_PUBLIC ")
          else:
            fx.write("extern ")
          fx.write("const value_string %s[];\n" % (self.eth_vals_nm(t)))
        else:
          fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
    for t in self.eth_export_ord:  # functions
      if (self.eth_type[t]['export'] & EF_TYPE):
        if self.eth_type[t]['export'] & EF_EXTERN:
          if self.eth_type[t]['export'] & EF_WS_DLL:
            fx.write("WS_DLL_PUBLIC ")
          else:
            fx.write("extern ")
        fx.write(self.eth_type_fn_h(t))
    for f in self.eth_hfpdu_ord:  # PDUs
      if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['export']):
        fx.write(self.eth_out_pdu_decl(f))
    self.output.file_close(fx)

  #--- eth_output_expcnf ------------------------------------------------------
  def eth_output_expcnf(self):
    fx = self.output.file_open('exp', ext='cnf')
    fx.write('#.MODULE\n')
    maxw = 0
    for (m, p) in self.modules:
      if (len(m) > maxw): maxw = len(m)
    for (m, p) in self.modules:
      fx.write("%-*s  %s\n" % (maxw, m, p))
    fx.write('#.END\n\n')
    for cls in self.objectclass_ord:
      if self.objectclass[cls]['export']:
        cnm = cls
        if self.objectclass[cls]['export'] & EF_MODULE:
          cnm = "$%s$%s" % (self.objectclass[cls]['module'], cnm)
        fx.write('#.CLASS %s\n' % (cnm))
        maxw = 2
        for fld in self.objectclass[cls]['val'].fields:
          w = len(fld.fld_repr()[0])
          if (w > maxw): maxw = w
        for fld in self.objectclass[cls]['val'].fields:
          repr = fld.fld_repr()
          fx.write('%-*s  %s\n' % (maxw, repr[0], ' '.join(repr[1:])))
        fx.write('#.END\n\n')
    if self.Ber():
      fx.write('#.IMPORT_TAG\n')
      for t in self.eth_export_ord:  # tags
        if (self.eth_type[t]['export'] & EF_TYPE):
          fx.write('%-24s ' % self.eth_type[t]['ref'][0])
          fx.write('%s %s\n' % self.eth_type[t]['val'].GetTag(self))
      fx.write('#.END\n\n')
    fx.write('#.TYPE_ATTR\n')
    for t in self.eth_export_ord:  # attributes
      if (self.eth_type[t]['export'] & EF_TYPE):
        tnm = self.eth_type[t]['ref'][0]
        if self.eth_type[t]['export'] & EF_MODULE:
          tnm = "$%s$%s" % (self.type[tnm]['module'], tnm)
        fx.write('%-24s ' % tnm)
        attr = self.eth_get_type_attr(self.eth_type[t]['ref'][0]).copy()
        fx.write('TYPE = %(TYPE)-9s  DISPLAY = %(DISPLAY)-9s  STRINGS = %(STRINGS)s  BITMASK = %(BITMASK)s\n' % attr)
    fx.write('#.END\n\n')
    self.output.file_close(fx, keep_anyway=True)

  #--- eth_output_val ------------------------------------------------------
  def eth_output_val(self):
    fx = self.output.file_open('val', ext='h')
    for v in self.eth_value_ord1:
      vv = self.eth_value[v]['value']
      if isinstance (vv, Value):
        vv = vv.to_str(self)
      fx.write("#define %-30s %s\n" % (v, vv))
    for t in self.eth_type_ord1:
      if self.eth_type[t]['import']:
        continue
      if self.eth_type[t]['val'].eth_has_enum(t, self) and not (self.eth_type[t]['export'] & EF_ENUM):
        fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
    self.output.file_close(fx)

  #--- eth_output_valexp ------------------------------------------------------
  def eth_output_valexp(self):
    if (not len(self.eth_vexport_ord)): return
    fx = self.output.file_open('valexp', ext='h')
    for v in self.eth_vexport_ord:
      vv = self.eth_value[v]['value']
      if isinstance (vv, Value):
        vv = vv.to_str(self)
      fx.write("#define %-30s %s\n" % (v, vv))
    self.output.file_close(fx)

  #--- eth_output_types -------------------------------------------------------
  def eth_output_types(self):
    def out_pdu(f):
      t = self.eth_hf[f]['ethtype']
      is_new = self.eth_hf[f]['pdu']['new']
      impl = 'FALSE'
      out = ''
      if (not self.eth_hf[f]['pdu']['export']):
        out += 'static '
      if (is_new):
        out += 'int '
        out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_) {\n'
      else:
        out += 'void '
        out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_) {\n'
      if (is_new):
        out += '  int offset = 0;\n'
        off_par = 'offset'
        ret_par = 'offset'
      else:
        off_par = '0'
        ret_par = None
      if (self.Per()):
        if (self.Aligned()):
          aligned = 'TRUE'
        else:
          aligned = 'FALSE'
        out += "  asn1_ctx_t asn1_ctx;\n"
        out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_PER', aligned, 'pinfo'),))
      if (self.Ber()):
        out += "  asn1_ctx_t asn1_ctx;\n"
        out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_BER', 'TRUE', 'pinfo'),))
        par=((impl, 'tvb', off_par,'&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
      elif (self.Per()):
        par=(('tvb', off_par, '&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
      else:
        par=((),)
      out += self.eth_fn_call('dissect_%s_%s' % (self.eth_type[t]['proto'], t), ret=ret_par, par=par)
      if (self.Per() and is_new):
        out += '  offset += 7; offset >>= 3;\n'
      if (is_new):
        out += '  return offset;\n'
      out += '}\n'
      return out
    #end out_pdu()
    fx = self.output.file_open('fn')
    pos = fx.tell()
    if (len(self.eth_hfpdu_ord)):
      first_decl = True
      for f in self.eth_hfpdu_ord:
        if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['need_decl']):
          if first_decl:
            fx.write('/*--- PDUs declarations ---*/\n')
            first_decl = False
          fx.write(self.eth_out_pdu_decl(f))
      if not first_decl:
        fx.write('\n')
    if self.eth_dep_cycle:
      fx.write('/*--- Cyclic dependencies ---*/\n\n')
      i = 0
      while i < len(self.eth_dep_cycle):
        t = self.type[self.eth_dep_cycle[i][0]]['ethname']
        if self.dep_cycle_eth_type[t][0] != i: i += 1; continue
        fx.write(''.join(['/* %s */\n' % ' -> '.join(self.eth_dep_cycle[i]) for i in self.dep_cycle_eth_type[t]]))
        fx.write(self.eth_type_fn_h(t))
        fx.write('\n')
        i += 1
      fx.write('\n')
    for t in self.eth_type_ord1:
      if self.eth_type[t]['import']:
        continue
      if self.eth_type[t]['val'].eth_has_vals():
        if self.eth_type[t]['no_emit'] & EF_VALS:
          pass
        elif self.eth_type[t]['user_def'] & EF_VALS:
          fx.write("extern const value_string %s[];\n" % (self.eth_vals_nm(t)))
        elif (self.eth_type[t]['export'] & EF_VALS) and (self.eth_type[t]['export'] & EF_TABLE):
          pass
        else:
          fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
      if self.eth_type[t]['no_emit'] & EF_TYPE:
        pass
      elif self.eth_type[t]['user_def'] & EF_TYPE:
        fx.write(self.eth_type_fn_h(t))
      else:
        fx.write(self.eth_type[t]['val'].eth_type_fn(self.eth_type[t]['proto'], t, self))
      fx.write('\n')
    if (len(self.eth_hfpdu_ord)):
      fx.write('/*--- PDUs ---*/\n\n')
      for f in self.eth_hfpdu_ord:
        if (self.eth_hf[f]['pdu']):
          if (f in self.emitted_pdu):
            fx.write("  /* %s already emitted */\n" % (f))
          else:
            fx.write(out_pdu(f))
            self.emitted_pdu[f] = True
      fx.write('\n')
    fempty = pos == fx.tell()
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_dis_hnd -----------------------------------------------------
  def eth_output_dis_hnd(self):
    fx = self.output.file_open('dis-hnd')
    fempty = True
    for f in self.eth_hfpdu_ord:
      pdu = self.eth_hf[f]['pdu']
      if (pdu and pdu['reg'] and not pdu['hidden']):
        dis = self.proto
        if (pdu['reg'] != '.'):
          dis += '.' + pdu['reg']
        fx.write('static dissector_handle_t %s_handle;\n' % (asn2c(dis)))
        fempty = False
    fx.write('\n')
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_dis_reg -----------------------------------------------------
  def eth_output_dis_reg(self):
    fx = self.output.file_open('dis-reg')
    fempty = True
    for f in self.eth_hfpdu_ord:
      pdu = self.eth_hf[f]['pdu']
      if (pdu and pdu['reg']):
        new_prefix = ''
        if (pdu['new']): new_prefix = 'new_'
        dis = self.proto
        if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
        fx.write('  %sregister_dissector("%s", dissect_%s, proto_%s);\n' % (new_prefix, dis, f, self.eproto))
        if (not pdu['hidden']):
          fx.write('  %s_handle = find_dissector("%s");\n' % (asn2c(dis), dis))
        fempty = False
    fx.write('\n')
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_dis_tab -----------------------------------------------------
  def eth_output_dis_tab(self):
    fx = self.output.file_open('dis-tab')
    fempty = True
    for k in self.conform.get_order('REGISTER'):
      reg = self.conform.use_item('REGISTER', k)
      if reg['pdu'] not in self.field: continue
      f = self.field[reg['pdu']]['ethname']
      pdu = self.eth_hf[f]['pdu']
      new_prefix = ''
      if (pdu['new']): new_prefix = 'new_'
      if (reg['rtype'] in ('NUM', 'STR')):
        rstr = ''
        if (reg['rtype'] == 'STR'):
	  rstr = 'string'
        else:
	  rstr = 'uint'
        if (pdu['reg']):
          dis = self.proto
          if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
          if  (not pdu['hidden']):
            hnd = '%s_handle' % (asn2c(dis))
          else:
            hnd = 'find_dissector("%s")' % (dis)
        else:
          hnd = '%screate_dissector_handle(dissect_%s, proto_%s)' % (new_prefix, f, self.eproto)
        rport = self.value_get_eth(reg['rport'])
        fx.write('  dissector_add_%s("%s", %s, %s);\n' % (rstr, reg['rtable'], rport, hnd))
      elif (reg['rtype'] in ('BER', 'PER')):
        roid = self.value_get_eth(reg['roid'])
        fx.write('  %sregister_%s_oid_dissector(%s, dissect_%s, proto_%s, %s);\n' % (new_prefix, reg['rtype'].lower(), roid, f, self.eproto, reg['roidname']))
      fempty = False
    fx.write('\n')
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_syn_reg -----------------------------------------------------
  def eth_output_syn_reg(self):
    fx = self.output.file_open('syn-reg')
    fempty = True
    first_decl = True
    for k in self.conform.get_order('SYNTAX'):
      reg = self.conform.use_item('SYNTAX', k)
      if first_decl:
        fx.write('  /*--- Syntax registrations ---*/\n')
        first_decl = False
      fx.write('  register_ber_syntax_dissector(%s, proto_%s, dissect_%s_PDU);\n' % (k, self.eproto, reg['pdu']));
      fempty=False
    self.output.file_close(fx, discard=fempty)

  #--- eth_output_tables -----------------------------------------------------
  def eth_output_tables(self):
    for num in list(self.conform.report.keys()):
      fx = self.output.file_open('table' + num)
      for rep in self.conform.report[num]:
        self.eth_output_table(fx, rep)
      self.output.file_close(fx)

  #--- eth_output_table -----------------------------------------------------
  def eth_output_table(self, fx, rep):
    def cmp_fn(a, b, cmp_flds, objs):
      if not cmp_flds: return 0
      obja = objs[a]
      objb = objs[b]
      res = 0
      for f in cmp_flds:
        if f[0] == '#':
          f = f[1:]
          res = int(obja[f]) - int(objb[f])
        else:
          res = cmp(obja[f], objb[f])
        if res: break
      return res
    if rep['type'] == 'HDR':
      fx.write('\n')
    if rep['var']:
      var = rep['var']
      var_list = var.split('.', 1)
      cls = var_list[0]
      del var_list[0]
      flds = []
      not_flds = []
      sort_flds = []
      for f in var_list:
         if f[0] == '!':
           not_flds.append(f[1:])
           continue
         if f[0] == '#':
           flds.append(f[1:])
           sort_flds.append(f)
           continue
         if f[0] == '@':
           flds.append(f[1:])
           sort_flds.append(f[1:])
           continue
         flds.append(f)
      objs = {}
      objs_ord = []
      if (cls in self.oassign_cls):
        for ident in self.oassign_cls[cls]:
          obj = self.get_obj_repr(ident, flds, not_flds)
          if not obj:
            continue
          obj['_LOOP'] = var
          obj['_DICT'] = str(obj)
          objs[ident] = obj
          objs_ord.append(ident)
        if (sort_flds):
          objs_ord.sort(cmp=partial(cmp_fn, cmp_flds=sort_flds, objs=objs))
        for ident in objs_ord:
          obj = objs[ident]
          try:
            text = rep['text'] % obj
          except (KeyError):
            raise sys.exc_info()[0], "%s:%s invalid key %s for information object %s of %s" % (rep['fn'], rep['lineno'], sys.exc_info()[1], ident, var)
          fx.write(text)
      else:
        fx.write("/* Unknown or empty loop list %s */\n" % (var))
    else:
      fx.write(rep['text'])
    if rep['type'] == 'FTR':
      fx.write('\n')

  #--- dupl_report -----------------------------------------------------
  def dupl_report(self):
    # types
    tmplist = sorted(self.eth_type_dupl.keys())
    for t in tmplist:
      msg = "The same type names for different types. Explicit type renaming is recommended.\n"
      msg += t + "\n"
      for tt in self.eth_type_dupl[t]:
        msg += " %-20s %s\n" % (self.type[tt]['ethname'], tt)
      warnings.warn_explicit(msg, UserWarning, '', 0)
    # fields
    tmplist = list(self.eth_hf_dupl.keys())
    tmplist.sort()
    for f in tmplist:
      msg = "The same field names for different types. Explicit field renaming is recommended.\n"
      msg += f + "\n"
      for tt in list(self.eth_hf_dupl[f].keys()):
        msg += " %-20s %-20s " % (self.eth_hf_dupl[f][tt], tt)
        msg += ", ".join(self.eth_hf[self.eth_hf_dupl[f][tt]]['ref'])
        msg += "\n"
      warnings.warn_explicit(msg, UserWarning, '', 0)

  #--- eth_do_output ------------------------------------------------------------
  def eth_do_output(self):
    if self.dbg('a'):
      print "\n# Assignments"
      for a in self.assign_ord:
        v = ' '
        if (self.assign[a]['virt']): v = '*'
        print v, a
      print "\n# Value assignments"
      for a in self.vassign_ord:
        print ' ', a
      print "\n# Information object assignments"
      for a in self.oassign_ord:
        print " %-12s (%s)" % (a, self.oassign[a].cls)
    if self.dbg('t'):
      print "\n# Imported Types"
      print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
      print "-" * 100
      for t in self.type_imp:
        print "%-40s %-24s %-24s" % (t, self.type[t]['import'], self.type[t]['proto'])
      print "\n# Imported Values"
      print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
      print "-" * 100
      for t in self.value_imp:
        print "%-40s %-24s %-24s" % (t, self.value[t]['import'], self.value[t]['proto'])
      print "\n# Imported Object Classes"
      print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
      print "-" * 100
      for t in self.objectclass_imp:
        print "%-40s %-24s %-24s" % (t, self.objectclass[t]['import'], self.objectclass[t]['proto'])
      print "\n# Exported Types"
      print "%-31s %s" % ("Wireshark type", "Export Flag")
      print "-" * 100
      for t in self.eth_export_ord:
        print "%-31s 0x%02X" % (t, self.eth_type[t]['export'])
      print "\n# Exported Values"
      print "%-40s %s" % ("Wireshark name", "Value")
      print "-" * 100
      for v in self.eth_vexport_ord:
        vv = self.eth_value[v]['value']
        if isinstance (vv, Value):
          vv = vv.to_str(self)
        print "%-40s %s" % (v, vv)
      print "\n# ASN.1 Object Classes"
      print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
      print "-" * 100
      for t in self.objectclass_ord:
        print "%-40s " % (t)
      print "\n# ASN.1 Types"
      print "%-49s %-24s %-24s" % ("ASN.1 unique name", "'tname'", "Wireshark type")
      print "-" * 100
      for t in self.type_ord:
        print "%-49s %-24s %-24s" % (t, self.type[t]['tname'], self.type[t]['ethname'])
      print "\n# Wireshark Types"
      print "Wireshark type                   References (ASN.1 types)"
      print "-" * 100
      for t in self.eth_type_ord:
        print "%-31s %d" % (t, len(self.eth_type[t]['ref'])),
        print ', '.join(self.eth_type[t]['ref'])
      print "\n# ASN.1 Values"
      print "%-40s %-18s %-20s %s" % ("ASN.1 unique name", "Type", "Value", "Wireshark value")
      print "-" * 100
      for v in self.value_ord:
        vv = self.value[v]['value']
        if isinstance (vv, Value):
          vv = vv.to_str(self)
        print "%-40s %-18s %-20s %s" % (v, self.value[v]['type'].eth_tname(), vv, self.value[v]['ethname'])
      #print "\n# Wireshark Values"
      #print "%-40s %s" % ("Wireshark name", "Value")
      #print "-" * 100
      #for v in self.eth_value_ord:
      #  vv = self.eth_value[v]['value']
      #  if isinstance (vv, Value):
      #    vv = vv.to_str(self)
      #  print "%-40s %s" % (v, vv)
      print "\n# ASN.1 Fields"
      print "ASN.1 unique name                        Wireshark name        ASN.1 type"
      print "-" * 100
      for f in (self.pdu_ord + self.field_ord):
        print "%-40s %-20s %s" % (f, self.field[f]['ethname'], self.field[f]['type'])
      print "\n# Wireshark Fields"
      print "Wireshark name                  Wireshark type        References (ASN.1 fields)"
      print "-" * 100
      for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
        print "%-30s %-20s %s" % (f, self.eth_hf[f]['ethtype'], len(self.eth_hf[f]['ref'])),
        print ', '.join(self.eth_hf[f]['ref'])
      #print "\n# Order after dependencies"
      #print '\n'.join(self.eth_type_ord1)
      print "\n# Cyclic dependencies"
      for c in self.eth_dep_cycle:
        print ' -> '.join(c)
    self.dupl_report()
    self.output.outnm = self.outnm_opt
    if (not self.output.outnm):
      self.output.outnm = self.proto
      self.output.outnm = self.output.outnm.replace('.', '-')
    if not self.justexpcnf:
      self.eth_output_hf()
      self.eth_output_ett()
      self.eth_output_types()
      self.eth_output_hf_arr()
      self.eth_output_ett_arr()
      self.eth_output_export()
      self.eth_output_val()
      self.eth_output_valexp()
      self.eth_output_dis_hnd()
      self.eth_output_dis_reg()
      self.eth_output_dis_tab()
      self.eth_output_syn_reg()
      self.eth_output_tables()
    if self.expcnf:
      self.eth_output_expcnf()

  def dbg_modules(self):
    def print_mod(m):
      print "%-30s " % (m),
      dep = self.module[m][:]
      for i in range(len(dep)):
        if dep[i] not in self.module:
          dep[i] = '*' + dep[i]
      print ', '.join(dep)
    # end of print_mod()
    (mod_ord, mod_cyc) = dependency_compute(self.module_ord, self.module, ignore_fn = lambda t: t not in self.module)
    print "\n# ASN.1 Moudules"
    print "Module name                     Dependency"
    print "-" * 100
    new_ord = False
    for m in (self.module_ord):
      print_mod(m)
      new_ord = new_ord or (self.module_ord.index(m) != mod_ord.index(m))
    if new_ord:
      print "\n# ASN.1 Moudules - in dependency order"
      print "Module name                     Dependency"
      print "-" * 100
      for m in (mod_ord):
        print_mod(m)
    if mod_cyc:
      print "\nCyclic dependencies:"
      for i in (range(len(mod_cyc))):
        print "%02d: %s" % (i + 1, str(mod_cyc[i]))


#--- EthCnf -------------------------------------------------------------------
class EthCnf:
  def __init__(self):
    self.ectx = None
    self.tblcfg = {}
    self.table = {}
    self.order = {}
    self.fn = {}
    self.report = {}
    self.suppress_line = False
    self.include_path = []
    #                                   Value name             Default value       Duplicity check   Usage check
    self.tblcfg['EXPORTS']         = { 'val_nm' : 'flag',     'val_dflt' : 0,     'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['MAKE_ENUM']       = { 'val_nm' : 'flag',     'val_dflt' : 0,     'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['USE_VALS_EXT']    = { 'val_nm' : 'flag',     'val_dflt' : 0,     'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['PDU']             = { 'val_nm' : 'attr',     'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['SYNTAX']             = { 'val_nm' : 'attr',     'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['REGISTER']        = { 'val_nm' : 'attr',     'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['USER_DEFINED']    = { 'val_nm' : 'flag',     'val_dflt' : 0,     'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['NO_EMIT']         = { 'val_nm' : 'flag',     'val_dflt' : 0,     'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['MODULE']          = { 'val_nm' : 'proto',    'val_dflt' : None,  'chk_dup' : True, 'chk_use' : False }
    self.tblcfg['OMIT_ASSIGNMENT'] = { 'val_nm' : 'omit',     'val_dflt' : False, 'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['NO_OMIT_ASSGN']   = { 'val_nm' : 'omit',     'val_dflt' : True,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['VIRTUAL_ASSGN']   = { 'val_nm' : 'name',     'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['SET_TYPE']        = { 'val_nm' : 'type',     'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['TYPE_RENAME']     = { 'val_nm' : 'eth_name', 'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['FIELD_RENAME']    = { 'val_nm' : 'eth_name', 'val_dflt' : None,  'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['IMPORT_TAG']      = { 'val_nm' : 'ttag',     'val_dflt' : (),    'chk_dup' : True, 'chk_use' : False }
    self.tblcfg['FN_PARS']         = { 'val_nm' : 'pars',     'val_dflt' : {},    'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['TYPE_ATTR']       = { 'val_nm' : 'attr',     'val_dflt' : {},    'chk_dup' : True, 'chk_use' : False }
    self.tblcfg['ETYPE_ATTR']      = { 'val_nm' : 'attr',     'val_dflt' : {},    'chk_dup' : True, 'chk_use' : False }
    self.tblcfg['FIELD_ATTR']      = { 'val_nm' : 'attr',     'val_dflt' : {},    'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['EFIELD_ATTR']     = { 'val_nm' : 'attr',     'val_dflt' : {},    'chk_dup' : True, 'chk_use' : True }
    self.tblcfg['ASSIGNED_ID']     = { 'val_nm' : 'ids',      'val_dflt' : {},    'chk_dup' : False,'chk_use' : False }
    self.tblcfg['ASSIGN_VALUE_TO_TYPE'] = { 'val_nm' : 'name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }

    for k in list(self.tblcfg.keys()) :
      self.table[k] = {}
      self.order[k] = []

  def add_item(self, table, key, fn, lineno, **kw):
    if self.tblcfg[table]['chk_dup'] and key in self.table[table]:
      warnings.warn_explicit("Duplicated %s for %s. Previous one is at %s:%d" %
                             (table, key, self.table[table][key]['fn'], self.table[table][key]['lineno']),
                             UserWarning, fn, lineno)
      return
    self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False}
    self.table[table][key].update(kw)
    self.order[table].append(key)

  def update_item(self, table, key, fn, lineno, **kw):
    if key not in self.table[table]:
      self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False}
      self.order[table].append(key)
      self.table[table][key][self.tblcfg[table]['val_nm']] = {}
    self.table[table][key][self.tblcfg[table]['val_nm']].update(kw[self.tblcfg[table]['val_nm']])

  def get_order(self, table):
    return self.order[table]

  def check_item(self, table, key):
    return key in self.table[table]

  def copy_item(self, table, dst_key, src_key):
    if (src_key in self.table[table]):
      self.table[table][dst_key] = self.table[table][src_key]

  def check_item_value(self, table, key, **kw):
    return key in self.table[table] and kw.get('val_nm', self.tblcfg[table]['val_nm']) in self.table[table][key]

  def use_item(self, table, key, **kw):
    vdflt = kw.get('val_dflt', self.tblcfg[table]['val_dflt'])
    if key not in self.table[table]: return vdflt
    vname = kw.get('val_nm', self.tblcfg[table]['val_nm'])
    #print "use_item() - set used for %s %s" % (table, key)
    self.table[table][key]['used'] = True
    return self.table[table][key].get(vname, vdflt)

  def omit_assignment(self, type, ident, module):
    if self.ectx.conform.use_item('OMIT_ASSIGNMENT', ident):
      return True
    if self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*') or \
       self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type) or \
       self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*/'+module) or \
       self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type+'/'+module):
      return self.ectx.conform.use_item('NO_OMIT_ASSGN', ident)
    return False

  def add_fn_line(self, name, ctx, line, fn, lineno):
    if name not in self.fn:
      self.fn[name] = {'FN_HDR' : None, 'FN_FTR' : None, 'FN_BODY' : None}
    if (self.fn[name][ctx]):
      self.fn[name][ctx]['text'] += line
    else:
      self.fn[name][ctx] = {'text' : line, 'used' : False,
                             'fn' : fn, 'lineno' : lineno}
  def get_fn_presence(self, name):
    #print "get_fn_presence('%s'):%s" % (name, str(self.fn.has_key(name)))
    #if self.fn.has_key(name): print self.fn[name]
    return name in self.fn
  def get_fn_body_presence(self, name):
    return name in self.fn and self.fn[name]['FN_BODY']
  def get_fn_text(self, name, ctx):
    if (name not in self.fn):
      return '';
    if (not self.fn[name][ctx]):
      return '';
    self.fn[name][ctx]['used'] = True
    out = self.fn[name][ctx]['text']
    if (not self.suppress_line):
      out = '#line %u "%s"\n%s\n' % (self.fn[name][ctx]['lineno'], rel_dissector_path(self.fn[name][ctx]['fn']), out);
    return out

  def add_pdu(self, par, is_new, fn, lineno):
    #print "add_pdu(par=%s, %s, %d)" % (str(par), fn, lineno)
    (reg, hidden) = (None, False)
    if (len(par) > 1): reg = par[1]
    if (reg and reg[0]=='@'): (reg, hidden) = (reg[1:], True)
    attr = {'new' : is_new, 'reg' : reg, 'hidden' : hidden, 'need_decl' : False, 'export' : False}
    self.add_item('PDU', par[0], attr=attr, fn=fn, lineno=lineno)
    return

  def add_syntax(self, par, fn, lineno):
    #print "add_syntax(par=%s, %s, %d)" % (str(par), fn, lineno)
    if( (len(par) >=2)):
      name = par[1]
    else:
      name = '"'+par[0]+'"'
    attr = { 'pdu' : par[0] }
    self.add_item('SYNTAX', name, attr=attr, fn=fn, lineno=lineno)
    return

  def add_register(self, pdu, par, fn, lineno):
    #print "add_register(pdu=%s, par=%s, %s, %d)" % (pdu, str(par), fn, lineno)
    if (par[0] in ('N', 'NUM')):   rtype = 'NUM'; (pmin, pmax) = (2, 2)
    elif (par[0] in ('S', 'STR')): rtype = 'STR'; (pmin, pmax) = (2, 2)
    elif (par[0] in ('B', 'BER')): rtype = 'BER'; (pmin, pmax) = (1, 2)
    elif (par[0] in ('P', 'PER')): rtype = 'PER'; (pmin, pmax) = (1, 2)
    else: warnings.warn_explicit("Unknown registration type '%s'" % (par[2]), UserWarning, fn, lineno); return
    if ((len(par)-1) < pmin):
      warnings.warn_explicit("Too few parameters for %s registration type. At least %d parameters are required" % (rtype, pmin), UserWarning, fn, lineno)
      return
    if ((len(par)-1) > pmax):
      warnings.warn_explicit("Too many parameters for %s registration type. Only %d parameters are allowed" % (rtype, pmax), UserWarning, fn, lineno)
    attr = {'pdu' : pdu, 'rtype' : rtype}
    if (rtype in ('NUM', 'STR')):
      attr['rtable'] = par[1]
      attr['rport'] = par[2]
      rkey = '/'.join([rtype, attr['rtable'], attr['rport']])
    elif (rtype in ('BER', 'PER')):
      attr['roid'] = par[1]
      attr['roidname'] = '""'
      if (len(par)>=3):
        attr['roidname'] = par[2]
      elif attr['roid'][0] != '"':
        attr['roidname'] = '"' + attr['roid'] + '"'
      rkey = '/'.join([rtype, attr['roid']])
    self.add_item('REGISTER', rkey, attr=attr, fn=fn, lineno=lineno)

  def check_par(self, par, pmin, pmax, fn, lineno):
    for i in range(len(par)):
      if par[i] == '-':
        par[i] = None
        continue
      if par[i][0] == '#':
        par[i:] = []
        break
    if len(par) < pmin:
      warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno)
      return None
    if (pmax >= 0) and (len(par) > pmax):
      warnings.warn_explicit("Too many parameters. Only %d parameters are allowed" % (pmax), UserWarning, fn, lineno)
      return par[0:pmax]
    return par

  def read(self, fn):
    def get_par(line, pmin, pmax, fn, lineno):
      par = line.split(None, pmax)
      par = self.check_par(par, pmin, pmax, fn, lineno)
      return par

    def get_par_nm(line, pmin, pmax, fn, lineno):
      if pmax:
        par = line.split(None, pmax)
      else:
        par = [line,]
      for i in range(len(par)):
        if par[i][0] == '#':
          par[i:] = []
          break
      if len(par) < pmin:
        warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno)
        return None
      if len(par) > pmax:
        nmpar = par[pmax]
      else:
        nmpar = ''
      nmpars = {}
      nmpar_first = re.compile(r'^\s*(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*')
      nmpar_next = re.compile(r'\s+(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*')
      nmpar_end = re.compile(r'\s*$')
      result = nmpar_first.search(nmpar)
      pos = 0
      while result:
        k = result.group('attr')
        pos = result.end()
        result = nmpar_next.search(nmpar, pos)
        p1 = pos
        if result:
          p2 = result.start()
        else:
          p2 = nmpar_end.search(nmpar, pos).start()
        v = nmpar[p1:p2]
        nmpars[k] = v
      if len(par) > pmax:
        par[pmax] = nmpars
      return par

    f = open(fn, "r")
    lineno = 0
    is_import = False
    directive = re.compile(r'^\s*#\.(?P<name>[A-Z_][A-Z_0-9]*)(\s+|$)')
    report = re.compile(r'^TABLE(?P<num>\d*)_(?P<type>HDR|BODY|FTR)$')
    comment = re.compile(r'^\s*#[^.]')
    empty = re.compile(r'^\s*$')
    ctx = None
    name = ''
    default_flags = 0x00
    stack = []
    while True:
      if not f.closed:
        line = f.readline()
        lineno += 1
      else:
        line = None
      if not line:
        if not f.closed:
          f.close()
        if stack:
          frec = stack.pop()
          fn, f, lineno, is_import = frec['fn'], frec['f'], frec['lineno'], frec['is_import']
          continue
        else:
          break
      if comment.search(line): continue
      result = directive.search(line)
      if result:  # directive
        rep_result = report.search(result.group('name'))
        if result.group('name') == 'END_OF_CNF':
          f.close()
        elif result.group('name') == 'OPT':
          ctx = result.group('name')
          par = get_par(line[result.end():], 0, -1, fn=fn, lineno=lineno)
          if not par: continue
          self.set_opt(par[0], par[1:], fn, lineno)
          ctx = None
        elif result.group('name') in ('PDU', 'PDU_NEW', 'REGISTER', 'REGISTER_NEW',
                                    'MODULE', 'MODULE_IMPORT',
                                    'OMIT_ASSIGNMENT', 'NO_OMIT_ASSGN',
                                    'VIRTUAL_ASSGN', 'SET_TYPE', 'ASSIGN_VALUE_TO_TYPE',
                                    'TYPE_RENAME', 'FIELD_RENAME', 'TF_RENAME', 'IMPORT_TAG',
                                    'TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR', 'SYNTAX'):
          ctx = result.group('name')
        elif result.group('name') in ('OMIT_ALL_ASSIGNMENTS', 'OMIT_ASSIGNMENTS_EXCEPT',
                                      'OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT',
                                      'OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
          ctx = result.group('name')
          key = '*'
          if ctx in ('OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT'):
            key += 'T'
          if ctx in ('OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
            key += 'V'
          par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno)
          if par:
            key += '/' + par[0]
          self.add_item('OMIT_ASSIGNMENT', key, omit=True, fn=fn, lineno=lineno)
          if ctx in ('OMIT_ASSIGNMENTS_EXCEPT', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
            ctx = 'NO_OMIT_ASSGN'
          else:
            ctx = None
        elif result.group('name') in ('EXPORTS', 'MODULE_EXPORTS', 'USER_DEFINED', 'NO_EMIT'):
          ctx = result.group('name')
          default_flags = EF_TYPE|EF_VALS
          if ctx == 'MODULE_EXPORTS':
            ctx = 'EXPORTS'
            default_flags |= EF_MODULE
          if ctx == 'EXPORTS':
            par = get_par(line[result.end():], 0, 5, fn=fn, lineno=lineno)
          else:
            par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno)
          if not par: continue
          p = 1
          if (par[0] == 'WITH_VALS'):      default_flags |= EF_TYPE|EF_VALS
          elif (par[0] == 'WITHOUT_VALS'): default_flags |= EF_TYPE; default_flags &= ~EF_TYPE
          elif (par[0] == 'ONLY_VALS'):    default_flags &= ~EF_TYPE; default_flags |= EF_VALS
          elif (ctx == 'EXPORTS'): p = 0
          else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[0]), UserWarning, fn, lineno)
          for i in range(p, len(par)):
            if (par[i] == 'ONLY_ENUM'):   default_flags &= ~(EF_TYPE|EF_VALS); default_flags |= EF_ENUM
            elif (par[i] == 'WITH_ENUM'): default_flags |= EF_ENUM
            elif (par[i] == 'VALS_WITH_TABLE'):  default_flags |= EF_TABLE
            elif (par[i] == 'WS_DLL'):    default_flags |= EF_WS_DLL
            elif (par[i] == 'EXTERN'):    default_flags |= EF_EXTERN
            elif (par[i] == 'NO_PROT_PREFIX'): default_flags |= EF_NO_PROT
            else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
        elif result.group('name') in ('MAKE_ENUM', 'MAKE_DEFINES'):
          ctx = result.group('name')
          default_flags = EF_ENUM
          if ctx == 'MAKE_ENUM': default_flags |= EF_NO_PROT|EF_NO_TYPE
          if ctx == 'MAKE_DEFINES': default_flags |= EF_DEFINE|EF_UCASE|EF_NO_TYPE
          par = get_par(line[result.end():], 0, 3, fn=fn, lineno=lineno)
          for i in range(0, len(par)):
            if (par[i] == 'NO_PROT_PREFIX'):   default_flags |= EF_NO_PROT
            elif (par[i] == 'PROT_PREFIX'):    default_flags &= ~ EF_NO_PROT
            elif (par[i] == 'NO_TYPE_PREFIX'): default_flags |= EF_NO_TYPE
            elif (par[i] == 'TYPE_PREFIX'):    default_flags &= ~ EF_NO_TYPE
            elif (par[i] == 'UPPER_CASE'):     default_flags |= EF_UCASE
            elif (par[i] == 'NO_UPPER_CASE'):  default_flags &= ~EF_UCASE
            else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
        elif result.group('name') == 'USE_VALS_EXT':
          ctx = result.group('name')
          default_flags = 0xFF
        elif result.group('name') == 'FN_HDR':
          minp = 1
          if (ctx in ('FN_PARS',)) and name: minp = 0
          par = get_par(line[result.end():], minp, 1, fn=fn, lineno=lineno)
          if (not par) and (minp > 0): continue
          ctx = result.group('name')
          if par: name = par[0]
        elif result.group('name') == 'FN_FTR':
          minp = 1
          if (ctx in ('FN_PARS','FN_HDR')) and name: minp = 0
          par = get_par(line[result.end():], minp, 1, fn=fn, lineno=lineno)
          if (not par) and (minp > 0): continue
          ctx = result.group('name')
          if par: name = par[0]
        elif result.group('name') == 'FN_BODY':
          par = get_par_nm(line[result.end():], 1, 1, fn=fn, lineno=lineno)
          if not par: continue
          ctx = result.group('name')
          name = par[0]
          if len(par) > 1:
            self.add_item('FN_PARS', name, pars=par[1], fn=fn, lineno=lineno)
        elif result.group('name') == 'FN_PARS':
          par = get_par_nm(line[result.end():], 0, 1, fn=fn, lineno=lineno)
          ctx = result.group('name')
          if not par:
            name = None
          elif len(par) == 1:
            name = par[0]
            self.add_item(ctx, name, pars={}, fn=fn, lineno=lineno)
          elif len(par) > 1:
            self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno)
            ctx = None
        elif result.group('name') == 'CLASS':
          par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
          if not par: continue
          ctx = result.group('name')
          name = par[0]
          add_class_ident(name)
          if not name.split('$')[-1].isupper():
            warnings.warn_explicit("No lower-case letters shall be included in information object class name (%s)" % (name),
                                    UserWarning, fn, lineno)
        elif result.group('name') == 'ASSIGNED_OBJECT_IDENTIFIER':
          par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
          if not par: continue
          self.update_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER', ids={par[0] : par[0]}, fn=fn, lineno=lineno)
        elif rep_result:  # Reports
          num = rep_result.group('num')
          type = rep_result.group('type')
          if type == 'BODY':
            par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
            if not par: continue
          else:
            par = get_par(line[result.end():], 0, 0, fn=fn, lineno=lineno)
          rep = { 'type' : type, 'var' : None, 'text' : '', 'fn' : fn, 'lineno' : lineno }
          if len(par) > 0:
            rep['var'] = par[0]
          self.report.setdefault(num, []).append(rep)
          ctx = 'TABLE'
          name = num
        elif result.group('name') in ('INCLUDE', 'IMPORT') :
          is_imp = result.group('name') == 'IMPORT'
          par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
          if not par:
            warnings.warn_explicit("%s requires parameter" % (result.group('name'),), UserWarning, fn, lineno)
            continue
          fname = par[0]
          #print "Try include: %s" % (fname)
          if (not os.path.exists(fname)):
            fname = os.path.join(os.path.split(fn)[0], par[0])
          #print "Try include: %s" % (fname)
          i = 0
          while not os.path.exists(fname) and (i < len(self.include_path)):
            fname = os.path.join(self.include_path[i], par[0])
            #print "Try include: %s" % (fname)
            i += 1
          if (not os.path.exists(fname)):
            if is_imp:
              continue  # just ignore
            else:
              fname = par[0]  # report error
          fnew = open(fname, "r")
          stack.append({'fn' : fn, 'f' : f, 'lineno' : lineno, 'is_import' : is_import})
          fn, f, lineno, is_import = par[0], fnew, 0, is_imp
        elif result.group('name') == 'END':
          ctx = None
        else:
          warnings.warn_explicit("Unknown directive '%s'" % (result.group('name')), UserWarning, fn, lineno)
        continue
      if not ctx:
        if not empty.match(line):
          warnings.warn_explicit("Non-empty line in empty context", UserWarning, fn, lineno)
      elif ctx == 'OPT':
        if empty.match(line): continue
        par = get_par(line, 1, -1, fn=fn, lineno=lineno)
        if not par: continue
        self.set_opt(par[0], par[1:], fn, lineno)
      elif ctx in ('EXPORTS', 'USER_DEFINED', 'NO_EMIT'):
        if empty.match(line): continue
        if ctx == 'EXPORTS':
          par = get_par(line, 1, 6, fn=fn, lineno=lineno)
        else:
          par = get_par(line, 1, 2, fn=fn, lineno=lineno)
        if not par: continue
        flags = default_flags
        p = 2
        if (len(par)>=2):
          if (par[1] == 'WITH_VALS'):      flags |= EF_TYPE|EF_VALS
          elif (par[1] == 'WITHOUT_VALS'): flags |= EF_TYPE; flags &= ~EF_TYPE
          elif (par[1] == 'ONLY_VALS'):    flags &= ~EF_TYPE; flags |= EF_VALS
          elif (ctx == 'EXPORTS'): p = 1
          else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[1]), UserWarning, fn, lineno)
        for i in range(p, len(par)):
          if (par[i] == 'ONLY_ENUM'):        flags &= ~(EF_TYPE|EF_VALS); flags |= EF_ENUM
          elif (par[i] == 'WITH_ENUM'):      flags |= EF_ENUM
          elif (par[i] == 'VALS_WITH_TABLE'):  flags |= EF_TABLE
          elif (par[i] == 'WS_DLL'):         flags |= EF_WS_DLL
          elif (par[i] == 'EXTERN'):         flags |= EF_EXTERN
          elif (par[i] == 'NO_PROT_PREFIX'): flags |= EF_NO_PROT
          else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
        self.add_item(ctx, par[0], flag=flags, fn=fn, lineno=lineno)
      elif ctx in ('MAKE_ENUM', 'MAKE_DEFINES'):
        if empty.match(line): continue
        par = get_par(line, 1, 4, fn=fn, lineno=lineno)
        if not par: continue
        flags = default_flags
        for i in range(1, len(par)):
          if (par[i] == 'NO_PROT_PREFIX'):   flags |= EF_NO_PROT
          elif (par[i] == 'PROT_PREFIX'):    flags &= ~ EF_NO_PROT
          elif (par[i] == 'NO_TYPE_PREFIX'): flags |= EF_NO_TYPE
          elif (par[i] == 'TYPE_PREFIX'):    flags &= ~ EF_NO_TYPE
          elif (par[i] == 'UPPER_CASE'):     flags |= EF_UCASE
          elif (par[i] == 'NO_UPPER_CASE'):  flags &= ~EF_UCASE
          else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
        self.add_item('MAKE_ENUM', par[0], flag=flags, fn=fn, lineno=lineno)
      elif ctx == 'USE_VALS_EXT':
        if empty.match(line): continue
        par = get_par(line, 1, 1, fn=fn, lineno=lineno)
        if not par: continue
        flags = default_flags
        self.add_item('USE_VALS_EXT', par[0], flag=flags, fn=fn, lineno=lineno)
      elif ctx in ('PDU', 'PDU_NEW'):
        if empty.match(line): continue
        par = get_par(line, 1, 5, fn=fn, lineno=lineno)
        if not par: continue
        is_new = False
        if (ctx == 'PDU_NEW'): is_new = True
        self.add_pdu(par[0:2], is_new, fn, lineno)
        if (len(par)>=3):
          self.add_register(par[0], par[2:5], fn, lineno)
      elif ctx in ('SYNTAX'):
        if empty.match(line): continue
        par = get_par(line, 1, 2, fn=fn, lineno=lineno)
        if not par: continue
        if not self.check_item('PDU', par[0]):
          self.add_pdu(par[0:1], False, fn, lineno)
        self.add_syntax(par, fn, lineno)
      elif ctx in ('REGISTER', 'REGISTER_NEW'):
        if empty.match(line): continue
        par = get_par(line, 3, 4, fn=fn, lineno=lineno)
        if not par: continue
        if not self.check_item('PDU', par[0]):
          is_new = False
          if (ctx == 'REGISTER_NEW'): is_new = True
          self.add_pdu(par[0:1], is_new, fn, lineno)
        self.add_register(par[0], par[1:4], fn, lineno)
      elif ctx in ('MODULE', 'MODULE_IMPORT'):
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item('MODULE', par[0], proto=par[1], fn=fn, lineno=lineno)
      elif ctx == 'IMPORT_TAG':
        if empty.match(line): continue
        par = get_par(line, 3, 3, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item(ctx, par[0], ttag=(par[1], par[2]), fn=fn, lineno=lineno)
      elif ctx == 'OMIT_ASSIGNMENT':
        if empty.match(line): continue
        par = get_par(line, 1, 1, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item(ctx, par[0], omit=True, fn=fn, lineno=lineno)
      elif ctx == 'NO_OMIT_ASSGN':
        if empty.match(line): continue
        par = get_par(line, 1, 1, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item(ctx, par[0], omit=False, fn=fn, lineno=lineno)
      elif ctx == 'VIRTUAL_ASSGN':
        if empty.match(line): continue
        par = get_par(line, 2, -1, fn=fn, lineno=lineno)
        if not par: continue
        if (len(par[1].split('/')) > 1) and not self.check_item('SET_TYPE', par[1]):
          self.add_item('SET_TYPE', par[1], type=par[0], fn=fn, lineno=lineno)
        self.add_item('VIRTUAL_ASSGN', par[1], name=par[0], fn=fn, lineno=lineno)
        for nm in par[2:]:
          self.add_item('SET_TYPE', nm, type=par[0], fn=fn, lineno=lineno)
        if not par[0][0].isupper():
          warnings.warn_explicit("Virtual assignment should have uppercase name (%s)" % (par[0]),
                                  UserWarning, fn, lineno)
      elif ctx == 'SET_TYPE':
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        if not self.check_item('VIRTUAL_ASSGN', par[0]):
          self.add_item('SET_TYPE', par[0], type=par[1], fn=fn, lineno=lineno)
        if not par[1][0].isupper():
          warnings.warn_explicit("Set type should have uppercase name (%s)" % (par[1]),
                                  UserWarning, fn, lineno)
      elif ctx == 'ASSIGN_VALUE_TO_TYPE':
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item(ctx, par[0], name=par[1], fn=fn, lineno=lineno)
      elif ctx == 'TYPE_RENAME':
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item('TYPE_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno)
        if not par[1][0].isupper():
          warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]),
                                  UserWarning, fn, lineno)
      elif ctx == 'FIELD_RENAME':
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item('FIELD_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno)
        if not par[1][0].islower():
          warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]),
                                  UserWarning, fn, lineno)
      elif ctx == 'TF_RENAME':
        if empty.match(line): continue
        par = get_par(line, 2, 2, fn=fn, lineno=lineno)
        if not par: continue
        tmpu = par[1][0].upper() + par[1][1:]
        tmpl = par[1][0].lower() + par[1][1:]
        self.add_item('TYPE_RENAME', par[0], eth_name=tmpu, fn=fn, lineno=lineno)
        if not tmpu[0].isupper():
          warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]),
                                  UserWarning, fn, lineno)
        self.add_item('FIELD_RENAME', par[0], eth_name=tmpl, fn=fn, lineno=lineno)
        if not tmpl[0].islower():
          warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]),
                                  UserWarning, fn, lineno)
      elif ctx in ('TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR'):
        if empty.match(line): continue
        par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno)
        if not par: continue
        self.add_item(ctx, par[0], attr=par[1], fn=fn, lineno=lineno)
      elif ctx == 'FN_PARS':
        if empty.match(line): continue
        if name:
          par = get_par_nm(line, 0, 0, fn=fn, lineno=lineno)
        else:
          par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno)
        if not par: continue
        if name:
          self.update_item(ctx, name, pars=par[0], fn=fn, lineno=lineno)
        else:
          self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno)
      elif ctx in ('FN_HDR', 'FN_FTR', 'FN_BODY'):
        self.add_fn_line(name, ctx, line, fn=fn, lineno=lineno)
      elif ctx == 'CLASS':
        if empty.match(line): continue
        par = get_par(line, 1, 3, fn=fn, lineno=lineno)
        if not par: continue
        if not set_type_to_class(name, par[0], par[1:]):
          warnings.warn_explicit("Could not set type of class member %s.&%s to %s" % (name, par[0], par[1]),
                                  UserWarning, fn, lineno)
      elif ctx == 'TABLE':
        self.report[name][-1]['text'] += line

  def set_opt(self, opt, par, fn, lineno):
    #print "set_opt: %s, %s" % (opt, par)
    if opt in ("-I",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.include_path.append(par[0])
    elif opt in ("-b", "BER", "CER", "DER"):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.encoding = 'ber'
    elif opt in ("PER",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.encoding = 'per'
    elif opt in ("-p", "PROTO"):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.proto_opt = par[0]
      self.ectx.merge_modules = True
    elif opt in ("ALIGNED",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.aligned = True
    elif opt in ("-u", "UNALIGNED"):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.aligned = False
    elif opt in ("-d",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.dbgopt = par[0]
    elif opt in ("-e",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.expcnf = True
    elif opt in ("-S",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.merge_modules = True
    elif opt in ("GROUP_BY_PROT",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.group_by_prot = True
    elif opt in ("-o",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.outnm_opt = par[0]
    elif opt in ("-O",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.output.outdir = par[0]
    elif opt in ("-s",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.output.single_file = par[0]
    elif opt in ("-k",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.ectx.output.keep = True
    elif opt in ("-L",):
      par = self.check_par(par, 0, 0, fn, lineno)
      self.suppress_line = True
    elif opt in ("EMBEDDED_PDV_CB",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.default_embedded_pdv_cb = par[0]
    elif opt in ("EXTERNAL_TYPE_CB",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.default_external_type_cb = par[0]
    elif opt in ("-r",):
      par = self.check_par(par, 1, 1, fn, lineno)
      if not par: return
      self.ectx.remove_prefix = par[0]
    else:
      warnings.warn_explicit("Unknown option %s" % (opt),
                             UserWarning, fn, lineno)

  def dbg_print(self):
    print "\n# Conformance values"
    print "%-15s %-4s %-15s %-20s %s" % ("File", "Line", "Table", "Key", "Value")
    print "-" * 100
    tbls = sorted(self.table.keys())
    for t in tbls:
      keys = sorted(self.table[t].keys())
      for k in keys:
        print "%-15s %4s %-15s %-20s %s" % (
              self.table[t][k]['fn'], self.table[t][k]['lineno'], t, k, str(self.table[t][k][self.tblcfg[t]['val_nm']]))

  def unused_report(self):
    tbls = sorted(self.table.keys())
    for t in tbls:
      if not self.tblcfg[t]['chk_use']: continue
      keys = sorted(self.table[t].keys())
      for k in keys:
        if not self.table[t][k]['used']:
          warnings.warn_explicit("Unused %s for %s" % (t, k),
                                  UserWarning, self.table[t][k]['fn'], self.table[t][k]['lineno'])
    fnms = list(self.fn.keys())
    fnms.sort()
    for f in fnms:
      keys = sorted(self.fn[f].keys())
      for k in keys:
        if not self.fn[f][k]: continue
        if not self.fn[f][k]['used']:
          warnings.warn_explicit("Unused %s for %s" % (k, f),
                                  UserWarning, self.fn[f][k]['fn'], self.fn[f][k]['lineno'])

#--- EthOut -------------------------------------------------------------------
class EthOut:
  def __init__(self):
    self.ectx = None
    self.outnm = None
    self.outdir = '.'
    self.single_file = None
    self.created_files = {}
    self.created_files_ord = []
    self.keep = False

  def outcomment(self, ln, comment=None):
    if comment:
      return '%s %s\n' % (comment, ln)
    else:
      return '/* %-74s */\n' % (ln)

  def created_file_add(self, name, keep_anyway):
    name = os.path.normcase(os.path.abspath(name))
    if name not in self.created_files:
      self.created_files_ord.append(name)
      self.created_files[name] = keep_anyway
    else:
      self.created_files[name] = self.created_files[name] or keep_anyway

  def created_file_exists(self, name):
    name = os.path.normcase(os.path.abspath(name))
    return name in self.created_files

  #--- output_fname -------------------------------------------------------
  def output_fname(self, ftype, ext='c'):
    fn = ''
    if not ext in ('cnf',):
      fn += 'packet-'
    fn += self.outnm
    if (ftype):
      fn += '-' + ftype
    fn += '.' + ext
    return fn
  #--- file_open -------------------------------------------------------
  def file_open(self, ftype, ext='c'):
    fn = self.output_fname(ftype, ext=ext)
    if self.created_file_exists(fn):
      fx = file(fn, 'a')
    else:
      fx = file(fn, 'w')
    comment = None
    if ext in ('cnf',):
      comment = '#'
      fx.write(self.fhdr(fn, comment = comment))
    else:
      if (not self.single_file and not self.created_file_exists(fn)):
        fx.write(self.fhdr(fn))
    if not self.ectx.merge_modules:
      fx.write('\n')
      mstr = "--- "
      if self.ectx.groups():
        mstr += "Module"
        if (len(self.ectx.modules) > 1):
          mstr += "s"
        for (m, p) in self.ectx.modules:
          mstr += " %s" % (m)
      else:
        mstr += "Module %s" % (self.ectx.Module())
      mstr += " --- --- ---"
      fx.write(self.outcomment(mstr, comment))
      fx.write('\n')
    return fx
  #--- file_close -------------------------------------------------------
  def file_close(self, fx, discard=False, keep_anyway=False):
    fx.close()
    if discard and not self.created_file_exists(fx.name):
      os.unlink(fx.name)
    else:
      self.created_file_add(fx.name, keep_anyway)
  #--- fhdr -------------------------------------------------------
  def fhdr(self, fn, comment=None):
    out = ''
    out += self.outcomment('Do not modify this file. Changes will be overwritten.', comment)
    out += self.outcomment('Generated automatically by the ASN.1 to Wireshark dissector compiler', comment)
    out += self.outcomment(os.path.basename(fn), comment)
    out += self.outcomment(' '.join(sys.argv), comment)
    out += '\n'
    # Make Windows path separator look like Unix path separator
    return out.replace('\\', '/')

  #--- dbg_print -------------------------------------------------------
  def dbg_print(self):
    print "\n# Output files"
    print "\n".join(self.created_files_ord)
    print "\n"

  #--- make_single_file -------------------------------------------------------
  def make_single_file(self):
    if (not self.single_file): return
    in_nm = self.single_file + '.c'
    out_nm = os.path.join(self.outdir, self.output_fname(''))
    self.do_include(out_nm, in_nm)
    in_nm = self.single_file + '.h'
    if (os.path.exists(in_nm)):
      out_nm = os.path.join(self.outdir, self.output_fname('', ext='h'))
      self.do_include(out_nm, in_nm)
    if (not self.keep):
      for fn in self.created_files_ord:
        if not self.created_files[fn]:
          os.unlink(fn)

  #--- do_include -------------------------------------------------------
  def do_include(self, out_nm, in_nm):
    def check_file(fn, fnlist):
      fnfull = os.path.normcase(os.path.abspath(fn))
      if (fnfull in fnlist and os.path.exists(fnfull)):
        return os.path.normpath(fn)
      return None
    fin = file(in_nm, "r")
    fout = file(out_nm, "w")
    fout.write(self.fhdr(out_nm))
    fout.write('/* Input file: ' + os.path.basename(in_nm) +' */\n')
    fout.write('\n')
    fout.write('#line %u "%s"\n' % (1, rel_dissector_path(in_nm)))

    include = re.compile(r'^\s*#\s*include\s+[<"](?P<fname>[^>"]+)[>"]', re.IGNORECASE)

    cont_linenum = 0;

    while (True):
      cont_linenum = cont_linenum + 1;
      line = fin.readline()
      if (line == ''): break
      ifile = None
      result = include.search(line)
      #if (result): print os.path.normcase(os.path.abspath(result.group('fname')))
      if (result):
        ifile = check_file(os.path.join(os.path.split(in_nm)[0], result.group('fname')), self.created_files)
        if (not ifile):
          ifile = check_file(os.path.join(self.outdir, result.group('fname')), self.created_files)
        if (not ifile):
          ifile = check_file(result.group('fname'), self.created_files)
      if (ifile):
        fout.write('\n')
        fout.write('/*--- Included file: ' + ifile + ' ---*/\n')
        fout.write('#line %u "%s"\n' % (1, rel_dissector_path(ifile)))
        finc = file(ifile, "r")
        fout.write(finc.read())
        fout.write('\n')
        fout.write('/*--- End of included file: ' + ifile + ' ---*/\n')
        fout.write('#line %u "%s"\n' % (cont_linenum+1, rel_dissector_path(in_nm)) )
        finc.close()
      else:
        fout.write(line)

    fout.close()
    fin.close()


#--- Node ---------------------------------------------------------------------
class Node:
    def __init__(self,*args, **kw):
        if len (args) == 0:
            self.type = self.__class__.__name__
        else:
            assert (len(args) == 1)
            self.type = args[0]
        self.__dict__.update (kw)
    def str_child (self, key, child, depth):
        indent = " " * (2 * depth)
        keystr = indent + key + ": "
        if key == 'type': # already processed in str_depth
            return ""
        if isinstance (child, Node): # ugh
            return keystr + "\n" + child.str_depth (depth+1)
        if isinstance(child, type ([])):
            l = []
            for x in child:
              if isinstance (x, Node):
                l.append (x.str_depth (depth+1))
              else:
                l.append (indent + "  " + str(x) + "\n")
            return keystr + "[\n" + ''.join(l) + indent + "]\n"
        else:
            return keystr + str (child) + "\n"
    def str_depth (self, depth): # ugh
        indent = " " * (2 * depth)
        l = ["%s%s" % (indent, self.type)]
        l.append ("".join (map (lambda (k,v): self.str_child (k, v, depth + 1),
                                list(self.__dict__.items ()))))
        return "\n".join (l)
    def __repr__(self):
        return "\n" + self.str_depth (0)
    def to_python (self, ctx):
        return self.str_depth (ctx.indent_lev)

    def eth_reg(self, ident, ectx):
        pass

    def fld_obj_repr(self, ectx):
        return "/* TO DO %s */" % (str(self))


#--- ValueAssignment -------------------------------------------------------------
class ValueAssignment (Node):
  def __init__(self,*args, **kw) :
    Node.__init__ (self,*args, **kw)

  def eth_reg(self, ident, ectx):
    if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit
    ectx.eth_reg_vassign(self)
    ectx.eth_reg_value(self.ident, self.typ, self.val)

#--- ObjectAssignment -------------------------------------------------------------
class ObjectAssignment (Node):
  def __init__(self,*args, **kw) :
    Node.__init__ (self,*args, **kw)

  def __eq__(self, other):
    if self.cls != other.cls:
      return False
    if len(self.val) != len(other.val):
      return False
    for f in (list(self.val.keys())):
      if f not in other.val:
        return False
      if isinstance(self.val[f], Node) and isinstance(other.val[f], Node):
        if not self.val[f].fld_obj_eq(other.val[f]):
          return False
      else:
        if str(self.val[f]) != str(other.val[f]):
          return False
    return True

  def eth_reg(self, ident, ectx):
    def make_virtual_type(cls, field, prefix):
      if isinstance(self.val, str): return
      if field in self.val and not isinstance(self.val[field], Type_Ref):
        vnm = prefix + '-' + self.ident
        virtual_tr = Type_Ref(val = vnm)
        t = self.val[field]
        self.val[field] = virtual_tr
        ectx.eth_reg_assign(vnm, t, virt=True)
        ectx.eth_reg_type(vnm, t)
        t.eth_reg_sub(vnm, ectx)
      if field in self.val and ectx.conform.check_item('PDU', cls + '.' + field):
        ectx.eth_reg_field(self.val[field].val, self.val[field].val, impl=self.val[field].HasImplicitTag(ectx), pdu=ectx.conform.use_item('PDU', cls + '.' + field))
      return
    # end of make_virtual_type()
    if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit
    self.module = ectx.Module()
    ectx.eth_reg_oassign(self)
    if (self.cls == 'TYPE-IDENTIFIER') or (self.cls == 'ABSTRACT-SYNTAX'):
      make_virtual_type(self.cls, '&Type', 'TYPE')
    if (self.cls == 'OPERATION'):
      make_virtual_type(self.cls, '&ArgumentType', 'ARG')
      make_virtual_type(self.cls, '&ResultType', 'RES')
    if (self.cls == 'ERROR'):
      make_virtual_type(self.cls, '&ParameterType', 'PAR')


#--- Type ---------------------------------------------------------------------
class Type (Node):
  def __init__(self,*args, **kw) :
    self.name = None
    self.constr = None
    self.tags = []
    self.named_list = None
    Node.__init__ (self,*args, **kw)

  def IsNamed(self):
    if self.name is None :
      return False
    else:
      return True

  def HasConstraint(self):
    if self.constr is None :
      return False
    else :
      return True

  def HasSizeConstraint(self):
    return self.HasConstraint() and self.constr.IsSize()

  def HasValueConstraint(self):
    return self.HasConstraint() and self.constr.IsValue()

  def HasPermAlph(self):
    return self.HasConstraint() and self.constr.IsPermAlph()

  def HasContentsConstraint(self):
    return self.HasConstraint() and self.constr.IsContents()

  def HasOwnTag(self):
    return len(self.tags) > 0

  def HasImplicitTag(self, ectx):
    return (self.HasOwnTag() and self.tags[0].IsImplicit(ectx))

  def IndetermTag(self, ectx):
    return False

  def AddTag(self, tag):
    self.tags[0:0] = [tag]

  def GetTag(self, ectx):
    #print "GetTag(%s)\n" % self.name;
    if (self.HasOwnTag()):
      return self.tags[0].GetTag(ectx)
    else:
      return self.GetTTag(ectx)

  def GetTTag(self, ectx):
    print "#Unhandled  GetTTag() in %s" % (self.type)
    print self.str_depth(1)
    return ('BER_CLASS_unknown', 'TAG_unknown')

  def SetName(self, name):
    self.name = name

  def AddConstraint(self, constr):
    if not self.HasConstraint():
      self.constr = constr
    else:
      self.constr = Constraint(type = 'Intersection', subtype = [self.constr, constr])

  def eth_tname(self):
    return '#' + self.type + '_' + str(id(self))

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def eth_strings(self):
    return 'NULL'

  def eth_omit_field(self):
    return False

  def eth_need_tree(self):
    return False

  def eth_has_vals(self):
    return False

  def eth_has_enum(self, tname, ectx):
    return self.eth_has_vals() and (ectx.eth_type[tname]['enum'] & EF_ENUM)

  def eth_need_pdu(self, ectx):
    return None

  def eth_named_bits(self):
    return None

  def eth_reg_sub(self, ident, ectx):
    pass

  def get_components(self, ectx):
    print "#Unhandled  get_components() in %s" % (self.type)
    print self.str_depth(1)
    return []

  def sel_req(self, sel, ectx):
    print "#Selection '%s' required for non-CHOICE type %s" % (sel, self.type)
    print self.str_depth(1)

  def fld_obj_eq(self, other):
    return isinstance(other, Type) and (self.eth_tname() == other.eth_tname())

  def eth_reg(self, ident, ectx, tstrip=0, tagflag=False, selflag=False, idx='', parent=None):
    #print "eth_reg(): %s, ident=%s, tstrip=%d, tagflag=%s, selflag=%s, parent=%s" %(self.type, ident, tstrip, str(tagflag), str(selflag), str(parent))
    #print " ", self
    if (ectx.NeedTags() and (len(self.tags) > tstrip)):
      tagged_type = self
      for i in range(len(self.tags)-1, tstrip-1, -1):
        tagged_type = TaggedType(val=tagged_type, tstrip=i)
        tagged_type.AddTag(self.tags[i])
      if not tagflag:  # 1st tagged level
        if self.IsNamed() and not selflag:
          tagged_type.SetName(self.name)
      tagged_type.eth_reg(ident, ectx, tstrip=1, tagflag=tagflag, idx=idx, parent=parent)
      return
    nm = ''
    if ident and self.IsNamed() and not tagflag and not selflag:
      nm = ident + '/' + self.name
    elif ident:
      nm = ident
    elif self.IsNamed():
      nm = self.name
    if not ident and ectx.conform.omit_assignment('T', nm, ectx.Module()): return # Assignment to omit
    if not ident:  # Assignment
      ectx.eth_reg_assign(nm, self)
      if self.type == 'Type_Ref' and not self.tr_need_own_fn(ectx):
        ectx.eth_reg_type(nm, self)
    virtual_tr = Type_Ref(val=ectx.conform.use_item('SET_TYPE', nm))
    if (self.type == 'Type_Ref') or ectx.conform.check_item('SET_TYPE', nm):
      if ident and (ectx.conform.check_item('TYPE_RENAME', nm) or ectx.conform.get_fn_presence(nm) or selflag):
        if ectx.conform.check_item('SET_TYPE', nm):
          ectx.eth_reg_type(nm, virtual_tr)  # dummy Type Reference
        else:
          ectx.eth_reg_type(nm, self)  # new type
        trnm = nm
      elif ectx.conform.check_item('SET_TYPE', nm):
        trnm = ectx.conform.use_item('SET_TYPE', nm)
      elif (self.type == 'Type_Ref') and self.tr_need_own_fn(ectx):
        ectx.eth_reg_type(nm, self)  # need own function, e.g. for constraints
        trnm = nm
      else:
        trnm = self.val
    else:
      ectx.eth_reg_type(nm, self)
      trnm = nm
    if ectx.conform.check_item('VIRTUAL_ASSGN', nm):
      vnm = ectx.conform.use_item('VIRTUAL_ASSGN', nm)
      ectx.eth_reg_assign(vnm, self, virt=True)
      ectx.eth_reg_type(vnm, self)
      self.eth_reg_sub(vnm, ectx)
    if parent and (ectx.type[parent]['val'].type == 'TaggedType'):
      ectx.type[parent]['val'].eth_set_val_name(parent, trnm, ectx)
    if ident and not tagflag and not self.eth_omit_field():
      ectx.eth_reg_field(nm, trnm, idx=idx, parent=parent, impl=self.HasImplicitTag(ectx))
    if ectx.conform.check_item('SET_TYPE', nm):
      virtual_tr.eth_reg_sub(nm, ectx)
    else:
      self.eth_reg_sub(nm, ectx)

  def eth_get_size_constr(self, ectx):
    (minv, maxv, ext) = ('MIN', 'MAX', False)
    if self.HasSizeConstraint():
      if self.constr.IsSize():
        (minv, maxv, ext) = self.constr.GetSize(ectx)
      if (self.constr.type == 'Intersection'):
        if self.constr.subtype[0].IsSize():
          (minv, maxv, ext) = self.constr.subtype[0].GetSize(ectx)
        elif self.constr.subtype[1].IsSize():
          (minv, maxv, ext) = self.constr.subtype[1].GetSize(ectx)
    if minv == 'MIN': minv = 'NO_BOUND'
    if maxv == 'MAX': maxv = 'NO_BOUND'
    if (ext): ext = 'TRUE'
    else: ext = 'FALSE'
    return (minv, maxv, ext)

  def eth_get_value_constr(self, ectx):
    (minv, maxv, ext) = ('MIN', 'MAX', False)
    if self.HasValueConstraint():
      (minv, maxv, ext) = self.constr.GetValue(ectx)
    if minv == 'MIN': minv = 'NO_BOUND'
    if maxv == 'MAX': maxv = 'NO_BOUND'
    if str(minv).isdigit():
      minv += 'U'
    elif (str(minv)[0] == "-") and str(minv)[1:].isdigit():
      if (long(minv) == -(2**31)):
        minv = "G_MININT32"
      elif (long(minv) < -(2**31)):
        minv = "G_GINT64_CONSTANT(%s)" % (str(minv))
    if str(maxv).isdigit():
      if (long(maxv) >= 2**32):
        maxv = "G_GINT64_CONSTANT(%sU)" % (str(maxv))
      else:
        maxv += 'U'
    if (ext): ext = 'TRUE'
    else: ext = 'FALSE'
    return (minv, maxv, ext)

  def eth_get_alphabet_constr(self, ectx):
    (alph, alphlen) = ('NULL', '0')
    if self.HasPermAlph():
      alph = self.constr.GetPermAlph(ectx)
      if not alph:
        alph = 'NULL'
      if (alph != 'NULL'):
        if (((alph[0] + alph[-1]) == '""') and (not alph.count('"', 1, -1))):
          alphlen = str(len(alph) - 2)
        else:
          alphlen = 'strlen(%s)' % (alph)
    return (alph, alphlen)

  def eth_type_vals(self, tname, ectx):
    if self.eth_has_vals():
      print "#Unhandled  eth_type_vals('%s') in %s" % (tname, self.type)
      print self.str_depth(1)
    return ''

  def eth_type_enum(self, tname, ectx):
    if self.eth_has_enum(tname, ectx):
      print "#Unhandled  eth_type_enum('%s') in %s" % (tname, self.type)
      print self.str_depth(1)
    return ''

  def eth_type_default_table(self, ectx, tname):
    return ''

  def eth_type_default_body(self, ectx):
    print "#Unhandled  eth_type_default_body() in %s" % (self.type)
    print self.str_depth(1)
    return ''

  def eth_type_default_pars(self, ectx, tname):
    pars = {
      'TNAME' : tname,
      'ER' : ectx.encp(),
      'FN_VARIANT' : '',
      'TREE' : 'tree',
      'TVB' : 'tvb',
      'OFFSET' : 'offset',
      'ACTX' : 'actx',
      'HF_INDEX' : 'hf_index',
      'VAL_PTR' : 'NULL',
      'IMPLICIT_TAG' : 'implicit_tag',
    }
    if (ectx.eth_type[tname]['tree']):
      pars['ETT_INDEX'] = ectx.eth_type[tname]['tree']
    if (ectx.merge_modules):
      pars['PROTOP'] = ''
    else:
      pars['PROTOP'] = ectx.eth_type[tname]['proto'] + '_'
    return pars

  def eth_type_fn(self, proto, tname, ectx):
    body = self.eth_type_default_body(ectx, tname)
    pars = self.eth_type_default_pars(ectx, tname)
    if ectx.conform.check_item('FN_PARS', tname):
      pars.update(ectx.conform.use_item('FN_PARS', tname))
    elif ectx.conform.check_item('FN_PARS', ectx.eth_type[tname]['ref'][0]):
      pars.update(ectx.conform.use_item('FN_PARS', ectx.eth_type[tname]['ref'][0]))
    pars['DEFAULT_BODY'] = body
    for i in range(4):
      for k in list(pars.keys()):
        try:
          pars[k] = pars[k] % pars
        except (ValueError,TypeError):
          raise sys.exc_info()[0], "%s\n%s" % (str(pars), sys.exc_info()[1])
    out = '\n'
    out += self.eth_type_default_table(ectx, tname) % pars
    out += ectx.eth_type_fn_hdr(tname)
    out += ectx.eth_type_fn_body(tname, body, pars=pars)
    out += ectx.eth_type_fn_ftr(tname)
    return out

#--- Value --------------------------------------------------------------------
class Value (Node):
  def __init__(self,*args, **kw) :
    self.name = None
    Node.__init__ (self,*args, **kw)

  def SetName(self, name) :
    self.name = name

  def to_str(self, ectx):
    return str(self.val)

  def get_dep(self):
    return None

  def fld_obj_repr(self, ectx):
    return self.to_str(ectx)

#--- Value_Ref -----------------------------------------------------------------
class Value_Ref (Value):
  def to_str(self, ectx):
    return asn2c(self.val)

#--- ObjectClass ---------------------------------------------------------------------
class ObjectClass (Node):
  def __init__(self,*args, **kw) :
    self.name = None
    Node.__init__ (self,*args, **kw)

  def SetName(self, name):
    self.name = name
    add_class_ident(self.name)

  def eth_reg(self, ident, ectx):
    if ectx.conform.omit_assignment('C', self.name, ectx.Module()): return # Assignment to omit
    ectx.eth_reg_objectclass(self.name, self)

#--- Class_Ref -----------------------------------------------------------------
class Class_Ref (ObjectClass):
  pass

#--- ObjectClassDefn ---------------------------------------------------------------------
class ObjectClassDefn (ObjectClass):
  def reg_types(self):
    for fld in self.fields:
      repr = fld.fld_repr()
      set_type_to_class(self.name, repr[0], repr[1:])


#--- Tag ---------------------------------------------------------------
class Tag (Node):
  def to_python (self, ctx):
    return 'asn1.TYPE(%s,%s)' % (mk_tag_str (ctx, self.tag.cls,
                                                self.tag_typ,
                                                self.tag.num),
                                    self.typ.to_python (ctx))
  def IsImplicit(self, ectx):
    return ((self.mode == 'IMPLICIT') or ((self.mode == 'default') and (ectx.tag_def != 'EXPLICIT')))

  def GetTag(self, ectx):
    tc = ''
    if (self.cls == 'UNIVERSAL'): tc = 'BER_CLASS_UNI'
    elif (self.cls == 'APPLICATION'): tc = 'BER_CLASS_APP'
    elif (self.cls == 'CONTEXT'): tc = 'BER_CLASS_CON'
    elif (self.cls == 'PRIVATE'): tc = 'BER_CLASS_PRI'
    return (tc, self.num)

  def eth_tname(self):
    n = ''
    if (self.cls == 'UNIVERSAL'): n = 'U'
    elif (self.cls == 'APPLICATION'): n = 'A'
    elif (self.cls == 'CONTEXT'): n = 'C'
    elif (self.cls == 'PRIVATE'): n = 'P'
    return n + str(self.num)

#--- Constraint ---------------------------------------------------------------
constr_cnt = 0
class Constraint (Node):
  def to_python (self, ctx):
    print "Ignoring constraint:", self.type
    return self.subtype.typ.to_python (ctx)
  def __str__ (self):
    return "Constraint: type=%s, subtype=%s" % (self.type, self.subtype)

  def eth_tname(self):
    return '#' + self.type + '_' + str(id(self))

  def IsSize(self):
    return (self.type == 'Size' and self.subtype.IsValue()) \
           or (self.type == 'Intersection' and (self.subtype[0].IsSize() or self.subtype[1].IsSize())) \

  def GetSize(self, ectx):
    (minv, maxv, ext) = ('MIN', 'MAX', False)
    if self.IsSize():
      if self.type == 'Size':
        (minv, maxv, ext) = self.subtype.GetValue(ectx)
      elif self.type == 'Intersection':
        if self.subtype[0].IsSize() and not self.subtype[1].IsSize():
          (minv, maxv, ext) = self.subtype[0].GetSize(ectx)
        elif not self.subtype[0].IsSize() and self.subtype[1].IsSize():
          (minv, maxv, ext) = self.subtype[1].GetSize(ectx)
    return (minv, maxv, ext)

  def IsValue(self):
    return self.type == 'SingleValue' \
           or self.type == 'ValueRange' \
           or (self.type == 'Intersection' and (self.subtype[0].IsValue() or self.subtype[1].IsValue())) \
           or (self.type == 'Union' and (self.subtype[0].IsValue() and self.subtype[1].IsValue()))

  def GetValue(self, ectx):
    (minv, maxv, ext) = ('MIN', 'MAX', False)
    if self.IsValue():
      if self.type == 'SingleValue':
        minv = ectx.value_get_eth(self.subtype)
        maxv = ectx.value_get_eth(self.subtype)
        ext = hasattr(self, 'ext') and self.ext
      elif self.type == 'ValueRange':
        minv = ectx.value_get_eth(self.subtype[0])
        maxv = ectx.value_get_eth(self.subtype[1])
        ext = hasattr(self, 'ext') and self.ext
      elif self.type == 'Intersection':
        if self.subtype[0].IsValue() and not self.subtype[1].IsValue():
          (minv, maxv, ext) = self.subtype[0].GetValue(ectx)
        elif not self.subtype[0].IsValue() and self.subtype[1].IsValue():
          (minv, maxv, ext) = self.subtype[1].GetValue(ectx)
        elif self.subtype[0].IsValue() and self.subtype[1].IsValue():
          v0 = self.subtype[0].GetValue(ectx)
          v1 = self.subtype[1].GetValue(ectx)
          (minv, maxv, ext) = (ectx.value_max(v0[0],v1[0]), ectx.value_min(v0[1],v1[1]), v0[2] and v1[2])
      elif self.type == 'Union':
        if self.subtype[0].IsValue() and self.subtype[1].IsValue():
          v0 = self.subtype[0].GetValue(ectx)
          v1 = self.subtype[1].GetValue(ectx)
          (minv, maxv, ext) = (ectx.value_min(v0[0],v1[0]), ectx.value_max(v0[1],v1[1]), v0[2] or v1[2])
    return (minv, maxv, ext)

  def IsAlphabet(self):
    return self.type == 'SingleValue' \
           or self.type == 'ValueRange' \
           or (self.type == 'Intersection' and (self.subtype[0].IsAlphabet() or self.subtype[1].IsAlphabet())) \
           or (self.type == 'Union' and (self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet()))

  def GetAlphabet(self, ectx):
    alph = None
    if self.IsAlphabet():
      if self.type == 'SingleValue':
        alph = ectx.value_get_eth(self.subtype)
      elif self.type == 'ValueRange':
        if ((len(self.subtype[0]) == 3) and ((self.subtype[0][0] + self.subtype[0][-1]) == '""') \
            and (len(self.subtype[1]) == 3) and ((self.subtype[1][0] + self.subtype[1][-1]) == '""')):
          alph = '"'
          for c in range(ord(self.subtype[0][1]), ord(self.subtype[1][1]) + 1):
            alph += chr(c)
          alph += '"'
      elif self.type == 'Union':
        if self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet():
          a0 = self.subtype[0].GetAlphabet(ectx)
          a1 = self.subtype[1].GetAlphabet(ectx)
          if (((a0[0] + a0[-1]) == '""') and not a0.count('"', 1, -1) \
              and ((a1[0] + a1[-1]) == '""') and not a1.count('"', 1, -1)):
            alph = '"' + a0[1:-1] + a1[1:-1] + '"'
          else:
            alph = a0 + ' ' + a1
    return alph

  def IsPermAlph(self):
    return self.type == 'From' and self.subtype.IsAlphabet() \
           or (self.type == 'Intersection' and (self.subtype[0].IsPermAlph() or self.subtype[1].IsPermAlph())) \

  def GetPermAlph(self, ectx):
    alph = None
    if self.IsPermAlph():
      if self.type == 'From':
        alph = self.subtype.GetAlphabet(ectx)
      elif self.type == 'Intersection':
        if self.subtype[0].IsPermAlph() and not self.subtype[1].IsPermAlph():
          alph = self.subtype[0].GetPermAlph(ectx)
        elif not self.subtype[0].IsPermAlph() and self.subtype[1].IsPermAlph():
          alph = self.subtype[1].GetPermAlph(ectx)
    return alph

  def IsContents(self):
    return self.type == 'Contents' \
           or (self.type == 'Intersection' and (self.subtype[0].IsContents() or self.subtype[1].IsContents())) \

  def GetContents(self, ectx):
    contents = None
    if self.IsContents():
      if self.type == 'Contents':
        if self.subtype.type == 'Type_Ref':
          contents = self.subtype.val
      elif self.type == 'Intersection':
        if self.subtype[0].IsContents() and not self.subtype[1].IsContents():
          contents = self.subtype[0].GetContents(ectx)
        elif not self.subtype[0].IsContents() and self.subtype[1].IsContents():
          contents = self.subtype[1].GetContents(ectx)
    return contents

  def IsNegativ(self):
    def is_neg(sval):
      return isinstance(sval, str) and (sval[0] == '-')
    if self.type == 'SingleValue':
      return is_neg(self.subtype)
    elif self.type == 'ValueRange':
      if self.subtype[0] == 'MIN': return True
      return is_neg(self.subtype[0])
    return False

  def eth_constrname(self):
    def int2str(val):
      if isinstance(val, Value_Ref):
        return asn2c(val.val)
      try:
        if (int(val) < 0):
          return 'M' + str(-int(val))
        else:
          return str(int(val))
      except (ValueError, TypeError):
        return asn2c(str(val))

    ext = ''
    if hasattr(self, 'ext') and self.ext:
      ext = '_'
    if self.type == 'SingleValue':
      return int2str(self.subtype) + ext
    elif self.type == 'ValueRange':
      return int2str(self.subtype[0]) + '_' + int2str(self.subtype[1]) + ext
    elif self.type == 'Size':
      return 'SIZE_' + self.subtype.eth_constrname() + ext
    else:
      if (not hasattr(self, 'constr_num')):
        global constr_cnt
        constr_cnt += 1
        self.constr_num = constr_cnt
      return 'CONSTR%03d%s' % (self.constr_num, ext)


class Module (Node):
  def to_python (self, ctx):
    ctx.tag_def = self.tag_def.dfl_tag
    return """#%s
%s""" % (self.ident, self.body.to_python (ctx))

  def get_name(self):
    return self.ident.val

  def get_proto(self, ectx):
    if (ectx.proto):
      prot = ectx.proto
    else:
      prot = ectx.conform.use_item('MODULE', self.get_name(), val_dflt=self.get_name())
    return prot

  def to_eth(self, ectx):
    ectx.tags_def = 'EXPLICIT' # default = explicit
    ectx.proto = self.get_proto(ectx)
    ectx.tag_def = self.tag_def.dfl_tag
    ectx.eth_reg_module(self)
    self.body.to_eth(ectx)

class Module_Body (Node):
  def to_python (self, ctx):
    # XXX handle exports, imports.
    l = [x.to_python (ctx) for x in self.assign_list]
    l = [a for a in l if a != '']
    return "\n".join (l)

  def to_eth(self, ectx):
    # Exports
    ectx.eth_exports(self.exports)
    # Imports
    for i in self.imports:
      mod = i.module.val
      proto = ectx.conform.use_item('MODULE', mod, val_dflt=mod)
      ectx.eth_module_dep_add(ectx.Module(), mod)
      for s in i.symbol_list:
        if isinstance(s, Type_Ref):
          ectx.eth_import_type(s.val, mod, proto)
        elif isinstance(s, Value_Ref):
          ectx.eth_import_value(s.val, mod, proto)
        elif isinstance(s, Class_Ref):
          ectx.eth_import_class(s.val, mod, proto)
        else:
          msg = 'Unknown kind of imported symbol %s from %s' % (str(s), mod)
          warnings.warn_explicit(msg, UserWarning, '', 0)
    # AssignmentList
    for a in self.assign_list:
      a.eth_reg('', ectx)

class Default_Tags (Node):
    def to_python (self, ctx): # not to be used directly
        assert (0)

# XXX should just calculate dependencies as we go along.
def calc_dependencies (node, dict, trace = 0):
    if not hasattr (node, '__dict__'):
        if trace: print "#returning, node=", node
        return
    if isinstance (node, Type_Ref):
        dict [node.val] = 1
        if trace: print "#Setting", node.val
        return
    for (a, val) in list(node.__dict__.items ()):
        if trace: print "# Testing node ", node, "attr", a, " val", val
        if a[0] == '_':
            continue
        elif isinstance (val, Node):
            calc_dependencies (val, dict, trace)
        elif isinstance (val, type ([])):
            for v in val:
                calc_dependencies (v, dict, trace)


class Type_Assign (Node):
    def __init__ (self, *args, **kw):
        Node.__init__ (self, *args, **kw)
        if isinstance (self.val, Tag): # XXX replace with generalized get_typ_ignoring_tag (no-op for Node, override in Tag)
            to_test = self.val.typ
        else:
            to_test = self.val
        if isinstance (to_test, SequenceType):
            to_test.sequence_name = self.name.name

    def to_python (self, ctx):
        dep_dict = {}
        calc_dependencies (self.val, dep_dict, 0)
        depend_list = list(dep_dict.keys ())
        return ctx.register_assignment (self.name.name,
                                        self.val.to_python (ctx),
                                        depend_list)

class PyQuote (Node):
    def to_python (self, ctx):
        return ctx.register_pyquote (self.val)

#--- Type_Ref -----------------------------------------------------------------
class Type_Ref (Type):
  def to_python (self, ctx):
    return self.val

  def eth_reg_sub(self, ident, ectx):
    ectx.eth_dep_add(ident, self.val)

  def eth_tname(self):
    if self.HasSizeConstraint():
      return asn2c(self.val) + '_' + self.constr.eth_constrname()
    else:
      return asn2c(self.val)

  def tr_need_own_fn(self, ectx):
    return ectx.Per() and self.HasSizeConstraint()

  def fld_obj_repr(self, ectx):
    return self.val

  def get_components(self, ectx):
    if self.val not in ectx.type or ectx.type[self.val]['import']:
      msg = "Can not get COMPONENTS OF %s which is imported type" % (self.val)
      warnings.warn_explicit(msg, UserWarning, '', 0)
      return []
    else:
      return ectx.type[self.val]['val'].get_components(ectx)

  def GetTTag(self, ectx):
    #print "GetTTag(%s)\n" % self.val;
    if (ectx.type[self.val]['import']):
      if 'ttag' not in ectx.type[self.val]:
        ttag = ectx.get_ttag_from_all(self.val, ectx.type[self.val]['import'])
        if not ttag and not ectx.conform.check_item('IMPORT_TAG', self.val):
          msg = 'Missing tag information for imported type %s from %s (%s)' % (self.val, ectx.type[self.val]['import'], ectx.type[self.val]['proto'])
          warnings.warn_explicit(msg, UserWarning, '', 0)
          ttag = ('-1/*imported*/', '-1/*imported*/')
        ectx.type[self.val]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.val, val_dflt=ttag)
      return ectx.type[self.val]['ttag']
    else:
      return ectx.type[self.val]['val'].GetTag(ectx)

  def IndetermTag(self, ectx):
    if (ectx.type[self.val]['import']):
      return False
    else:
      return ectx.type[self.val]['val'].IndetermTag(ectx)

  def eth_type_default_pars(self, ectx, tname):
    if tname:
      pars = Type.eth_type_default_pars(self, ectx, tname)
    else:
      pars = {}
    t = ectx.type[self.val]['ethname']
    pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
    pars['TYPE_REF_TNAME'] = t
    pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
    if self.HasSizeConstraint():
      (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
    elif (ectx.Per()):
      if self.HasSizeConstraint():
        body = ectx.eth_fn_call('dissect_%(ER)s_size_constrained_type', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),
                                     ('"%(TYPE_REF_TNAME)s"', '%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),))
      else:
        body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- SelectionType ------------------------------------------------------------
class SelectionType (Type):
  def to_python (self, ctx):
    return self.val

  def sel_of_typeref(self):
    return self.typ.type == 'Type_Ref'

  def eth_reg_sub(self, ident, ectx):
    if not self.sel_of_typeref():
      self.seltype = ''
      return
    self.seltype = ectx.eth_sel_req(self.typ.val, self.sel)
    ectx.eth_dep_add(ident, self.seltype)

  def eth_ftype(self, ectx):
    (ftype, display) = ('FT_NONE', 'BASE_NONE')
    if self.sel_of_typeref() and not ectx.type[self.seltype]['import']:
      (ftype, display) = ectx.type[self.typ.val]['val'].eth_ftype_sel(self.sel, ectx)
    return (ftype, display)

  def GetTTag(self, ectx):
    #print "GetTTag(%s)\n" % self.seltype;
    if (ectx.type[self.seltype]['import']):
      if 'ttag' not in ectx.type[self.seltype]:
        if not ectx.conform.check_item('IMPORT_TAG', self.seltype):
          msg = 'Missing tag information for imported type %s from %s (%s)' % (self.seltype, ectx.type[self.seltype]['import'], ectx.type[self.seltype]['proto'])
          warnings.warn_explicit(msg, UserWarning, '', 0)
        ectx.type[self.seltype]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.seltype, val_dflt=('-1 /*imported*/', '-1 /*imported*/'))
      return ectx.type[self.seltype]['ttag']
    else:
      return ectx.type[self.typ.val]['val'].GetTTagSel(self.sel, ectx)

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    if self.sel_of_typeref():
      t = ectx.type[self.seltype]['ethname']
      pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
      pars['TYPE_REF_TNAME'] = t
      pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if not self.sel_of_typeref():
      body = '#error Can not decode %s' % (tname)
    elif (ectx.Ber()):
      body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- TaggedType -----------------------------------------------------------------
class TaggedType (Type):
  def eth_tname(self):
    tn = ''
    for i in range(self.tstrip, len(self.val.tags)):
      tn += self.val.tags[i].eth_tname()
      tn += '_'
    tn += self.val.eth_tname()
    return tn

  def eth_set_val_name(self, ident, val_name, ectx):
    #print "TaggedType::eth_set_val_name(): ident=%s, val_name=%s" % (ident, val_name)
    self.val_name = val_name
    ectx.eth_dep_add(ident, self.val_name)

  def eth_reg_sub(self, ident, ectx):
    self.val_name = ident + '/' + UNTAG_TYPE_NAME
    self.val.eth_reg(self.val_name, ectx, tstrip=self.tstrip+1, tagflag=True, parent=ident)

  def GetTTag(self, ectx):
    #print "GetTTag(%s)\n" % self.seltype;
    return self.GetTag(ectx)

  def eth_ftype(self, ectx):
    return self.val.eth_ftype(ectx)

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    t = ectx.type[self.val_name]['ethname']
    pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
    pars['TYPE_REF_TNAME'] = t
    pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
    (pars['TAG_CLS'], pars['TAG_TAG']) = self.GetTag(ectx)
    if self.HasImplicitTag(ectx):
      pars['TAG_IMPL'] = 'TRUE'
    else:
      pars['TAG_IMPL'] = 'FALSE'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_tagged_type', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                   ('%(HF_INDEX)s', '%(TAG_CLS)s', '%(TAG_TAG)s', '%(TAG_IMPL)s', '%(TYPE_REF_FN)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- SqType -----------------------------------------------------------
class SqType (Type):
  def out_item(self, f, val, optional, ext, ectx):
    if (val.eth_omit_field()):
      t = ectx.type[val.ident]['ethname']
      fullname = ectx.dummy_eag_field
    else:
      ef = ectx.field[f]['ethname']
      t = ectx.eth_hf[ef]['ethtype']
      fullname = ectx.eth_hf[ef]['fullname']
    if (ectx.Ber()):
      #print "optional=%s, e.val.HasOwnTag()=%s, e.val.IndetermTag()=%s" % (str(e.optional), str(e.val.HasOwnTag()), str(e.val.IndetermTag(ectx)))
      #print val.str_depth(1)
      opt = ''
      if (optional):
        opt = 'BER_FLAGS_OPTIONAL'
      if (not val.HasOwnTag()):
        if (opt): opt += '|'
        opt += 'BER_FLAGS_NOOWNTAG'
      elif (val.HasImplicitTag(ectx)):
        if (opt): opt += '|'
        opt += 'BER_FLAGS_IMPLTAG'
      if (val.IndetermTag(ectx)):
        if (opt): opt += '|'
        opt += 'BER_FLAGS_NOTCHKTAG'
      if (not opt): opt = '0'
    else:
      if optional:
        opt = 'ASN1_OPTIONAL'
      else:
        opt = 'ASN1_NOT_OPTIONAL'
    if (ectx.Ber()):
      (tc, tn) = val.GetTag(ectx)
      out = '  { %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \
            % ('&'+fullname, tc, tn, opt, ectx.eth_type[t]['proto'], t)
    elif (ectx.Per()):
      out = '  { %-24s, %-23s, %-17s, dissect_%s_%s },\n' \
            % ('&'+fullname, ext, opt, ectx.eth_type[t]['proto'], t)
    else:
      out = ''
    return out

#--- SeqType -----------------------------------------------------------
class SeqType (SqType):

  def all_components(self):
    lst = self.elt_list[:]
    if hasattr(self, 'ext_list'):
      lst.extend(self.ext_list)
    if hasattr(self, 'elt_list2'):
      lst.extend(self.elt_list2)
    return lst

  def need_components(self):
    lst = self.all_components()
    for e in (lst):
      if e.type == 'components_of':
        return True
    return False

  def expand_components(self, ectx):
    while self.need_components():
      for i in range(len(self.elt_list)):
        if self.elt_list[i].type == 'components_of':
          comp = self.elt_list[i].typ.get_components(ectx)
          self.elt_list[i:i+1] = comp
          break
      if hasattr(self, 'ext_list'):
        for i in range(len(self.ext_list)):
          if self.ext_list[i].type == 'components_of':
            comp = self.ext_list[i].typ.get_components(ectx)
            self.ext_list[i:i+1] = comp
            break
      if hasattr(self, 'elt_list2'):
        for i in range(len(self.elt_list2)):
          if self.elt_list2[i].type == 'components_of':
            comp = self.elt_list2[i].typ.get_components(ectx)
            self.elt_list2[i:i+1] = comp
            break

  def get_components(self, ectx):
    lst = self.elt_list[:]
    if hasattr(self, 'elt_list2'):
      lst.extend(self.elt_list2)
    return lst

  def eth_reg_sub(self, ident, ectx, components_available=False):
    # check if autotag is required
    autotag = False
    if (ectx.NeedTags() and (ectx.tag_def == 'AUTOMATIC')):
      autotag = True
      lst = self.all_components()
      for e in (self.elt_list):
        if e.val.HasOwnTag(): autotag = False; break;
    # expand COMPONENTS OF
    if self.need_components():
      if components_available:
        self.expand_components(ectx)
      else:
        ectx.eth_comp_req(ident)
        return
    # extension addition groups
    if hasattr(self, 'ext_list'):
      if (ectx.Per()):  # add names
        eag_num = 1
        for e in (self.ext_list):
          if isinstance(e.val, ExtensionAdditionGroup):
            e.val.parent_ident = ident
            e.val.parent_tname = ectx.type[ident]['tname']
            if (e.val.ver):
              e.val.SetName("eag_v%s" % (e.val.ver))
            else:
              e.val.SetName("eag_%d" % (eag_num))
              eag_num += 1;
      else:  # expand
        new_ext_list = []
        for e in (self.ext_list):
          if isinstance(e.val, ExtensionAdditionGroup):
            new_ext_list.extend(e.val.elt_list)
          else:
            new_ext_list.append(e)
        self.ext_list = new_ext_list
    # do autotag
    if autotag:
      atag = 0
      for e in (self.elt_list):
        e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT'))
        atag += 1
      if autotag and hasattr(self, 'elt_list2'):
        for e in (self.elt_list2):
          e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT'))
          atag += 1
      if autotag and hasattr(self, 'ext_list'):
        for e in (self.ext_list):
          e.val.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT'))
          atag += 1
    # register components
    for e in (self.elt_list):
      e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
    if hasattr(self, 'ext_list'):
      for e in (self.ext_list):
        e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
    if hasattr(self, 'elt_list2'):
      for e in (self.elt_list2):
        e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)

  def eth_type_default_table(self, ectx, tname):
    #print "eth_type_default_table(tname='%s')" % (tname)
    fname = ectx.eth_type[tname]['ref'][0]
    table = "static const %(ER)s_sequence_t %(TABLE)s[] = {\n"
    if hasattr(self, 'ext_list'):
      ext = 'ASN1_EXTENSION_ROOT'
    else:
      ext = 'ASN1_NO_EXTENSIONS'
    empty_ext_flag = '0'
    if (len(self.elt_list)==0) and hasattr(self, 'ext_list') and (len(self.ext_list)==0) and (not hasattr(self, 'elt_list2') or (len(self.elt_list2)==0)):
      empty_ext_flag = ext
    for e in (self.elt_list):
      f = fname + '/' + e.val.name
      table += self.out_item(f, e.val, e.optional, ext, ectx)
    if hasattr(self, 'ext_list'):
      for e in (self.ext_list):
        f = fname + '/' + e.val.name
        table += self.out_item(f, e.val, e.optional, 'ASN1_NOT_EXTENSION_ROOT', ectx)
    if hasattr(self, 'elt_list2'):
      for e in (self.elt_list2):
        f = fname + '/' + e.val.name
        table += self.out_item(f, e.val, e.optional, ext, ectx)
    if (ectx.Ber()):
      table += "  { NULL, 0, 0, 0, NULL }\n};\n"
    else:
      table += "  { NULL, %s, 0, NULL }\n};\n" % (empty_ext_flag)
    return table

#--- SeqOfType -----------------------------------------------------------
class SeqOfType (SqType):
  def eth_type_default_table(self, ectx, tname):
    #print "eth_type_default_table(tname='%s')" % (tname)
    fname = ectx.eth_type[tname]['ref'][0]
    if self.val.IsNamed ():
      f = fname + '/' + self.val.name
    else:
      f = fname + '/' + ITEM_FIELD_NAME
    table = "static const %(ER)s_sequence_t %(TABLE)s[1] = {\n"
    table += self.out_item(f, self.val, False, 'ASN1_NO_EXTENSIONS', ectx)
    table += "};\n"
    return table

#--- SequenceOfType -----------------------------------------------------------
class SequenceOfType (SeqOfType):
  def to_python (self, ctx):
    # name, tag (None for no tag, EXPLICIT() for explicit), typ)
    # or '' + (1,) for optional
    sizestr = ''
    if self.size_constr != None:
        print "#Ignoring size constraint:", self.size_constr.subtype
    return "%sasn1.SEQUENCE_OF (%s%s)" % (ctx.spaces (),
                                          self.val.to_python (ctx),
                                          sizestr)

  def eth_reg_sub(self, ident, ectx):
    itmnm = ident
    if not self.val.IsNamed ():
      itmnm += '/' + ITEM_FIELD_NAME
    self.val.eth_reg(itmnm, ectx, tstrip=1, idx='[##]', parent=ident)

  def eth_tname(self):
    if self.val.type != 'Type_Ref':
      return '#' + self.type + '_' + str(id(self))
    if not self.HasConstraint():
      return "SEQUENCE_OF_" + self.val.eth_tname()
    elif self.constr.IsSize():
      return 'SEQUENCE_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname()
    else:
      return '#' + self.type + '_' + str(id(self))

  def eth_ftype(self, ectx):
    return ('FT_UINT32', 'BASE_DEC')

  def eth_need_tree(self):
    return True

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence_of'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasSizeConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_sequence_of', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
    elif (ectx.Per() and not self.HasConstraint()):
      body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),))
    elif (ectx.Per() and self.constr.type == 'Size'):
      body = ectx.eth_fn_call('dissect_%(ER)s_constrained_sequence_of', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),
                                   ('%(MIN_VAL)s', '%(MAX_VAL)s','%(EXT)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body


#--- SetOfType ----------------------------------------------------------------
class SetOfType (SeqOfType):
  def eth_reg_sub(self, ident, ectx):
    itmnm = ident
    if not self.val.IsNamed ():
      itmnm += '/' + ITEM_FIELD_NAME
    self.val.eth_reg(itmnm, ectx, tstrip=1, idx='(##)', parent=ident)

  def eth_tname(self):
    if self.val.type != 'Type_Ref':
      return '#' + self.type + '_' + str(id(self))
    if not self.HasConstraint():
      return "SET_OF_" + self.val.eth_tname()
    elif self.constr.IsSize():
      return 'SET_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname()
    else:
      return '#' + self.type + '_' + str(id(self))

  def eth_ftype(self, ectx):
    return ('FT_UINT32', 'BASE_DEC')

  def eth_need_tree(self):
    return True

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set_of'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasSizeConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_set_of', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
    elif (ectx.Per() and not self.HasConstraint()):
      body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),))
    elif (ectx.Per() and self.constr.type == 'Size'):
      body = ectx.eth_fn_call('dissect_%(ER)s_constrained_set_of', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),
                                   ('%(MIN_VAL)s', '%(MAX_VAL)s','%(EXT)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

def mk_tag_str (ctx, cls, typ, num):

    # XXX should do conversion to int earlier!
    val = int (num)
    typ = typ.upper()
    if typ == 'DEFAULT':
        typ = ctx.tags_def
    return 'asn1.%s(%d,cls=asn1.%s_FLAG)' % (typ, val, cls) # XXX still ned

#--- SequenceType -------------------------------------------------------------
class SequenceType (SeqType):
  def to_python (self, ctx):
      # name, tag (None for no tag, EXPLICIT() for explicit), typ)
      # or '' + (1,) for optional
      # XXX should also collect names for SEQUENCE inside SEQUENCE or
      # CHOICE or SEQUENCE_OF (where should the SEQUENCE_OF name come
      # from?  for others, element or arm name would be fine)
      seq_name = getattr (self, 'sequence_name', None)
      if seq_name == None:
          seq_name = 'None'
      else:
          seq_name = "'" + seq_name + "'"
      if 'ext_list' in self.__dict__:
        return "%sasn1.SEQUENCE ([%s], ext=[%s], seq_name = %s)" % (ctx.spaces (),
                                 self.elts_to_py (self.elt_list, ctx),
                                 self.elts_to_py (self.ext_list, ctx), seq_name)
      else:
        return "%sasn1.SEQUENCE ([%s]), seq_name = %s" % (ctx.spaces (),
                                 self.elts_to_py (self.elt_list, ctx), seq_name)
  def elts_to_py (self, list, ctx):
      # we have elt_type, val= named_type, maybe default=, optional=
      # named_type node: either ident = or typ =
      # need to dismember these in order to generate Python output syntax.
      ctx.indent ()
      def elt_to_py (e):
          assert (e.type == 'elt_type')
          nt = e.val
          optflag = e.optional
          #assert (not hasattr (e, 'default')) # XXX add support for DEFAULT!
          assert (nt.type == 'named_type')
          tagstr = 'None'
          identstr = nt.ident
          if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh
              tagstr = mk_tag_str (ctx,nt.typ.tag.cls,
                                   nt.typ.tag.tag_typ,nt.typ.tag.num)


              nt = nt.typ
          return "('%s',%s,%s,%d)" % (identstr, tagstr,
                                    nt.typ.to_python (ctx), optflag)
      indentstr = ",\n" + ctx.spaces ()
      rv = indentstr.join ([elt_to_py (e) for e in list])
      ctx.outdent ()
      return rv

  def eth_need_tree(self):
    return True

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
        body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                   ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ExtensionAdditionGroup ---------------------------------------------------
class ExtensionAdditionGroup (SeqType):
  def __init__(self,*args, **kw) :
    self.parent_ident = None
    self.parent_tname = None
    SeqType.__init__ (self,*args, **kw)

  def eth_omit_field(self):
    return True

  def eth_tname(self):
    if (self.parent_tname and self.IsNamed()):
      return self.parent_tname + "_" + self.name
    else:
      return SeqType.eth_tname(self)

  def eth_reg_sub(self, ident, ectx):
    ectx.eth_dummy_eag_field_required()
    ectx.eth_dep_add(self.parent_ident, ident)
    SeqType.eth_reg_sub(self, ident, ectx)

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_sequence_eag', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(TABLE)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body


#--- SetType ------------------------------------------------------------------
class SetType (SeqType):

  def eth_need_tree(self):
    return True

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                   ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ChoiceType ---------------------------------------------------------------
class ChoiceType (Type):
  def to_python (self, ctx):
      # name, tag (None for no tag, EXPLICIT() for explicit), typ)
      # or '' + (1,) for optional
      if 'ext_list' in self.__dict__:
        return "%sasn1.CHOICE ([%s], ext=[%s])" % (ctx.spaces (),
                               self.elts_to_py (self.elt_list, ctx),
                               self.elts_to_py (self.ext_list, ctx))
      else:
        return "%sasn1.CHOICE ([%s])" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx))
  def elts_to_py (self, list, ctx):
      ctx.indent ()
      def elt_to_py (nt):
          assert (nt.type == 'named_type')
          tagstr = 'None'
          if hasattr (nt, 'ident'):
              identstr = nt.ident
          else:
              if hasattr (nt.typ, 'val'):
                  identstr = nt.typ.val # XXX, making up name
              elif hasattr (nt.typ, 'name'):
                  identstr = nt.typ.name
              else:
                  identstr = ctx.make_new_name ()

          if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh
              tagstr = mk_tag_str (ctx,nt.typ.tag.cls,
                                   nt.typ.tag.tag_typ,nt.typ.tag.num)


              nt = nt.typ
          return "('%s',%s,%s)" % (identstr, tagstr,
                                    nt.typ.to_python (ctx))
      indentstr = ",\n" + ctx.spaces ()
      rv =  indentstr.join ([elt_to_py (e) for e in list])
      ctx.outdent ()
      return rv

  def eth_reg_sub(self, ident, ectx):
    #print "eth_reg_sub(ident='%s')" % (ident)
    # check if autotag is required
    autotag = False
    if (ectx.NeedTags() and (ectx.tag_def == 'AUTOMATIC')):
      autotag = True
      for e in (self.elt_list):
        if e.HasOwnTag(): autotag = False; break;
      if autotag and hasattr(self, 'ext_list'):
        for e in (self.ext_list):
          if e.HasOwnTag(): autotag = False; break;
    # do autotag
    if autotag:
      atag = 0
      for e in (self.elt_list):
        e.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT'))
        atag += 1
      if autotag and hasattr(self, 'ext_list'):
        for e in (self.ext_list):
          e.AddTag(Tag(cls = 'CONTEXT', num = str(atag), mode = 'IMPLICIT'))
          atag += 1
    for e in (self.elt_list):
        e.eth_reg(ident, ectx, tstrip=1, parent=ident)
        if ectx.conform.check_item('EXPORTS', ident + '.' + e.name):
          ectx.eth_sel_req(ident, e.name)
    if hasattr(self, 'ext_list'):
        for e in (self.ext_list):
            e.eth_reg(ident, ectx, tstrip=1, parent=ident)
            if ectx.conform.check_item('EXPORTS', ident + '.' + e.name):
              ectx.eth_sel_req(ident, e.name)

  def sel_item(self, ident, sel, ectx):
    lst = self.elt_list[:]
    if hasattr(self, 'ext_list'):
      lst.extend(self.ext_list)
    ee = None
    for e in (self.elt_list):
      if e.IsNamed() and (e.name == sel):
        ee = e
        break
    if not ee:
      print "#CHOICE %s does not contain item %s" % (ident, sel)
    return ee

  def sel_req(self, ident, sel, ectx):
    #print "sel_req(ident='%s', sel=%s)\n%s" % (ident, sel, str(self))
    ee = self.sel_item(ident, sel, ectx)
    if ee:
      ee.eth_reg(ident, ectx, tstrip=0, selflag=True)

  def eth_ftype(self, ectx):
    return ('FT_UINT32', 'BASE_DEC')

  def eth_ftype_sel(self, sel, ectx):
    ee = self.sel_item('', sel, ectx)
    if ee:
      return ee.eth_ftype(ectx)
    else:
      return ('FT_NONE', 'BASE_NONE')

  def eth_strings(self):
    return '$$'

  def eth_need_tree(self):
    return True

  def eth_has_vals(self):
    return True

  def GetTTag(self, ectx):
    lst = self.elt_list
    cls = 'BER_CLASS_ANY/*choice*/'
    #if hasattr(self, 'ext_list'):
    #  lst.extend(self.ext_list)
    #if (len(lst) > 0):
    #  cls = lst[0].GetTag(ectx)[0]
    #for e in (lst):
    #  if (e.GetTag(ectx)[0] != cls):
    #    cls = '-1/*choice*/'
    return (cls, '-1/*choice*/')

  def GetTTagSel(self, sel, ectx):
    ee = self.sel_item('', sel, ectx)
    if ee:
      return ee.GetTag(ectx)
    else:
      return ('BER_CLASS_ANY/*unknown selection*/', '-1/*unknown selection*/')

  def IndetermTag(self, ectx):
    #print "Choice IndetermTag()=%s" % (str(not self.HasOwnTag()))
    return not self.HasOwnTag()

  def detect_tagval(self, ectx):
    tagval = False
    lst = self.elt_list[:]
    if hasattr(self, 'ext_list'):
      lst.extend(self.ext_list)
    if (len(lst) > 0) and (not ectx.Per() or lst[0].HasOwnTag()):
      t = lst[0].GetTag(ectx)[0]
      tagval = True
    else:
      t = ''
      tagval = False
    if (t == 'BER_CLASS_UNI'):
      tagval = False
    for e in (lst):
      if not ectx.Per() or e.HasOwnTag():
        tt = e.GetTag(ectx)[0]
      else:
        tt = ''
        tagval = False
      if (tt != t):
        tagval = False
    return tagval

  def get_vals(self, ectx):
    tagval = self.detect_tagval(ectx)
    vals = []
    cnt = 0
    for e in (self.elt_list):
      if (tagval): val = e.GetTag(ectx)[1]
      else: val = str(cnt)
      vals.append((val, e.name))
      cnt += 1
    if hasattr(self, 'ext_list'):
      for e in (self.ext_list):
        if (tagval): val = e.GetTag(ectx)[1]
        else: val = str(cnt)
        vals.append((val, e.name))
        cnt += 1
    return vals

  def eth_type_vals(self, tname, ectx):
    out = '\n'
    vals = self.get_vals(ectx)
    out += ectx.eth_vals(tname, vals)
    return out

  def reg_enum_vals(self, tname, ectx):
    vals = self.get_vals(ectx)
    for (val, id) in vals:
      ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id))

  def eth_type_enum(self, tname, ectx):
    out = '\n'
    vals = self.get_vals(ectx)
    out += ectx.eth_enum(tname, vals)
    return out

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['TABLE'] = '%(PROTOP)s%(TNAME)s_choice'
    return pars

  def eth_type_default_table(self, ectx, tname):
    def out_item(val, e, ext, ectx):
      has_enum = ectx.eth_type[tname]['enum'] & EF_ENUM
      if (has_enum):
        vval = ectx.eth_enum_item(tname, e.name)
      else:
        vval = val
      f = fname + '/' + e.name
      ef = ectx.field[f]['ethname']
      t = ectx.eth_hf[ef]['ethtype']
      if (ectx.Ber()):
        opt = ''
        if (not e.HasOwnTag()):
          opt = 'BER_FLAGS_NOOWNTAG'
        elif (e.HasImplicitTag(ectx)):
          if (opt): opt += '|'
          opt += 'BER_FLAGS_IMPLTAG'
        if (not opt): opt = '0'
      if (ectx.Ber()):
        (tc, tn) = e.GetTag(ectx)
        out = '  { %3s, %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \
              % (vval, '&'+ectx.eth_hf[ef]['fullname'], tc, tn, opt, ectx.eth_type[t]['proto'], t)
      elif (ectx.Per()):
        out = '  { %3s, %-24s, %-23s, dissect_%s_%s },\n' \
              % (vval, '&'+ectx.eth_hf[ef]['fullname'], ext, ectx.eth_type[t]['proto'], t)
      else:
        out = ''
      return out
    # end out_item()
    #print "eth_type_default_table(tname='%s')" % (tname)
    fname = ectx.eth_type[tname]['ref'][0]
    tagval = self.detect_tagval(ectx)
    table = "static const %(ER)s_choice_t %(TABLE)s[] = {\n"
    cnt = 0
    if hasattr(self, 'ext_list'):
      ext = 'ASN1_EXTENSION_ROOT'
    else:
      ext = 'ASN1_NO_EXTENSIONS'
    empty_ext_flag = '0'
    if (len(self.elt_list)==0) and hasattr(self, 'ext_list') and (len(self.ext_list)==0):
      empty_ext_flag = ext
    for e in (self.elt_list):
      if (tagval): val = e.GetTag(ectx)[1]
      else: val = str(cnt)
      table += out_item(val, e, ext, ectx)
      cnt += 1
    if hasattr(self, 'ext_list'):
      for e in (self.ext_list):
        if (tagval): val = e.GetTag(ectx)[1]
        else: val = str(cnt)
        table += out_item(val, e, 'ASN1_NOT_EXTENSION_ROOT', ectx)
        cnt += 1
    if (ectx.Ber()):
      table += "  { 0, NULL, 0, 0, 0, NULL }\n};\n"
    else:
      table += "  { 0, NULL, %s, NULL }\n};\n" % (empty_ext_flag)
    return table

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset',
                              par=(('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                   ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s'),
                                   ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ETT_INDEX)s', '%(TABLE)s',),
                                   ('%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ChoiceValue ----------------------------------------------------
class ChoiceValue (Value):
  def to_str(self, ectx):
    return self.val.to_str(ectx)

  def fld_obj_eq(self, other):
    return isinstance(other, ChoiceValue) and (self.choice == other.choice) and (str(self.val.val) == str(other.val.val))

#--- EnumeratedType -----------------------------------------------------------
class EnumeratedType (Type):
  def to_python (self, ctx):
    def strify_one (named_num):
      return "%s=%s" % (named_num.ident, named_num.val)
    return "asn1.ENUM(%s)" % ",".join (map (strify_one, self.val))

  def eth_ftype(self, ectx):
    return ('FT_UINT32', 'BASE_DEC')

  def eth_strings(self):
    return '$$'

  def eth_has_vals(self):
    return True

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_ENUMERATED')

  def get_vals_etc(self, ectx):
    vals = []
    lastv = 0
    used = {}
    maxv = 0
    root_num = 0
    ext_num = 0
    map_table = []
    for e in (self.val):
      if e.type == 'NamedNumber':
        used[int(e.val)] = True
    for e in (self.val):
      if e.type == 'NamedNumber':
        val = int(e.val)
      else:
        while lastv in used:
          lastv += 1
        val = lastv
        used[val] = True
      vals.append((val, e.ident))
      map_table.append(val)
      root_num += 1
      if val > maxv:
        maxv = val
    if self.ext is not None:
      for e in (self.ext):
        if e.type == 'NamedNumber':
          used[int(e.val)] = True
      for e in (self.ext):
        if e.type == 'NamedNumber':
          val = int(e.val)
        else:
          while lastv in used:
            lastv += 1
          val = lastv
          used[val] = True
        vals.append((val, e.ident))
        map_table.append(val)
        ext_num += 1
        if val > maxv:
          maxv = val
    need_map = False
    for i in range(len(map_table)):
      need_map = need_map or (map_table[i] != i)
    if (not need_map):
      map_table = None
    return (vals, root_num, ext_num, map_table)

  def eth_type_vals(self, tname, ectx):
    out = '\n'
    vals = self.get_vals_etc(ectx)[0]
    out += ectx.eth_vals(tname, vals)
    return out

  def reg_enum_vals(self, tname, ectx):
    vals = self.get_vals_etc(ectx)[0]
    for (val, id) in vals:
      ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id))

  def eth_type_enum(self, tname, ectx):
    out = '\n'
    vals = self.get_vals_etc(ectx)[0]
    out += ectx.eth_enum(tname, vals)
    return out

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (root_num, ext_num, map_table) = self.get_vals_etc(ectx)[1:]
    if (self.ext != None):
      ext = 'TRUE'
    else:
      ext = 'FALSE'
    pars['ROOT_NUM'] = str(root_num)
    pars['EXT'] = ext
    pars['EXT_NUM'] = str(ext_num)
    if (map_table):
      pars['TABLE'] = '%(PROTOP)s%(TNAME)s_value_map'
    else:
      pars['TABLE'] = 'NULL'
    return pars

  def eth_type_default_table(self, ectx, tname):
    if (not ectx.Per()): return ''
    map_table = self.get_vals_etc(ectx)[3]
    if (map_table == None): return ''
    table = "static guint32 %(TABLE)s[%(ROOT_NUM)s+%(EXT_NUM)s] = {"
    table += ", ".join([str(v) for v in map_table])
    table += "};\n"
    return table

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasValueConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_integer', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
                                     ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_enumerated', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(ROOT_NUM)s', '%(VAL_PTR)s', '%(EXT)s', '%(EXT_NUM)s', '%(TABLE)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- EmbeddedPDVType -----------------------------------------------------------
class EmbeddedPDVType (Type):
  def eth_tname(self):
    return 'EMBEDDED_PDV'

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_EMBEDDED_PDV')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    if ectx.default_embedded_pdv_cb:
      pars['TYPE_REF_FN'] = ectx.default_embedded_pdv_cb
    else:
      pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_EmbeddedPDV_Type', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_embedded_pdv', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ExternalType -----------------------------------------------------------
class ExternalType (Type):
  def eth_tname(self):
    return 'EXTERNAL'

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    if ectx.default_external_type_cb:
      pars['TYPE_REF_FN'] = ectx.default_external_type_cb
    else:
      pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- OpenType -----------------------------------------------------------
class OpenType (Type):
  def to_python (self, ctx):
    return "asn1.ANY"

  def single_type(self):
    if (self.HasConstraint() and
        self.constr.type == 'Type' and
        self.constr.subtype.type == 'Type_Ref'):
      return self.constr.subtype.val
    return None

  def eth_reg_sub(self, ident, ectx):
    t = self.single_type()
    if t:
      ectx.eth_dep_add(ident, t)

  def eth_tname(self):
    t = self.single_type()
    if t:
      return 'OpenType_' + t
    else:
      return Type.eth_tname(self)

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_ANY', '0')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['FN_VARIANT'] = ectx.default_opentype_variant
    t = self.single_type()
    if t:
      t = ectx.type[t]['ethname']
      pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
      pars['TYPE_REF_TNAME'] = t
      pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
    else:
      pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_open_type%(FN_VARIANT)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- InstanceOfType -----------------------------------------------------------
class InstanceOfType (Type):
  def eth_tname(self):
    return 'INSTANCE_OF'

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    if ectx.default_external_type_cb:
      pars['TYPE_REF_FN'] = ectx.default_external_type_cb
    else:
      pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
    elif (ectx.Per()):
      body = '#error Can not decode %s' % (tname)
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- AnyType -----------------------------------------------------------
class AnyType (Type):
  def to_python (self, ctx):
    return "asn1.ANY"

  def eth_ftype(self, ectx):
    return ('FT_NONE', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_ANY', '0')

  def eth_type_default_body(self, ectx, tname):
    body = '#error Can not decode %s' % (tname)
    return body

class Literal (Node):
    def to_python (self, ctx):
        return self.val

#--- NullType -----------------------------------------------------------------
class NullType (Type):
  def to_python (self, ctx):
    return 'asn1.NULL'

  def eth_tname(self):
    return 'NULL'

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_NULL')

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- NullValue ----------------------------------------------------
class NullValue (Value):
  def to_str(self, ectx):
    return 'NULL'

#--- RealType -----------------------------------------------------------------
class RealType (Type):
  def to_python (self, ctx):
    return 'asn1.REAL'

  def eth_tname(self):
    return 'REAL'

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_REAL')

  def eth_ftype(self, ectx):
    return ('FT_DOUBLE', 'BASE_NONE')

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
                                   ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- BooleanType --------------------------------------------------------------
class BooleanType (Type):
  def to_python (self, ctx):
    return 'asn1.BOOLEAN'

  def eth_tname(self):
    return 'BOOLEAN'

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_BOOLEAN')

  def eth_ftype(self, ectx):
    return ('FT_BOOLEAN', 'BASE_NONE')

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s'),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- OctetStringType ----------------------------------------------------------
class OctetStringType (Type):
  def to_python (self, ctx):
    return 'asn1.OCTSTRING'

  def eth_tname(self):
    if not self.HasConstraint():
      return 'OCTET_STRING'
    elif self.constr.type == 'Size':
      return 'OCTET_STRING' + '_' + self.constr.eth_constrname()
    else:
      return '#' + self.type + '_' + str(id(self))

  def eth_ftype(self, ectx):
    return ('FT_BYTES', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_OCTETSTRING')

  def eth_need_pdu(self, ectx):
    pdu = None
    if self.HasContentsConstraint():
      t = self.constr.GetContents(ectx)
      if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')):
        pdu = { 'type' : t,
                'new' : ectx.default_containing_variant == '_pdu_new' }
    return pdu

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    if self.HasContentsConstraint():
      pars['FN_VARIANT'] = ectx.default_containing_variant
      t = self.constr.GetContents(ectx)
      if t:
        if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'):
          t = ectx.field[t]['ethname']
          pars['TYPE_REF_PROTO'] = ''
          pars['TYPE_REF_TNAME'] = t
          pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s'
        else:
          t = ectx.type[t]['ethname']
          pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
          pars['TYPE_REF_TNAME'] = t
          pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
      else:
        pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasSizeConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_octet_string', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
                                     ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      if self.HasContentsConstraint():
        body = ectx.eth_fn_call('dissect_%(ER)s_octet_string_containing%(FN_VARIANT)s', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(TYPE_REF_FN)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- CharacterStringType ------------------------------------------------------
class CharacterStringType (Type):
  def eth_tname(self):
    if not self.HasConstraint():
      return self.eth_tsname()
    elif self.constr.type == 'Size':
      return self.eth_tsname() + '_' + self.constr.eth_constrname()
    else:
      return '#' + self.type + '_' + str(id(self))

  def eth_ftype(self, ectx):
    return ('FT_STRING', 'BASE_NONE')

class RestrictedCharacterStringType (CharacterStringType):
  def to_python (self, ctx):
    return 'asn1.' + self.eth_tsname()

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_' + self.eth_tsname())

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    (pars['STRING_TYPE'], pars['STRING_TAG']) = (self.eth_tsname(), self.GetTTag(ectx)[1])
    (pars['ALPHABET'], pars['ALPHABET_LEN']) = self.eth_get_alphabet_constr(ectx)
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasSizeConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_restricted_string', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(STRING_TAG)s'),
                                     ('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_restricted_string', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(STRING_TAG)s'),
                                     ('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
                                     ('%(VAL_PTR)s',),))
    elif (ectx.Per() and self.HasPermAlph()):
      body = ectx.eth_fn_call('dissect_%(ER)s_restricted_character_string', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(ALPHABET)s', '%(ALPHABET_LEN)s'),
                                   ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      if (self.eth_tsname() == 'GeneralString'):
        body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
      elif (self.eth_tsname() == 'GeneralizedTime'):
        body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),))
      elif (self.eth_tsname() == 'UTCTime'):
        body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

class BMPStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'BMPString'

class GeneralStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'GeneralString'

class GraphicStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'GraphicString'

class IA5StringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'IA5String'

class NumericStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'NumericString'

class PrintableStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'PrintableString'

class TeletexStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'TeletexString'

class T61StringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'T61String'
  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_TeletexString')

class UniversalStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'UniversalString'

class UTF8StringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'UTF8String'

class VideotexStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'VideotexString'

class VisibleStringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'VisibleString'

class ISO646StringType (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'ISO646String'
  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_VisibleString')

class UnrestrictedCharacterStringType (CharacterStringType):
  def to_python (self, ctx):
    return 'asn1.UnrestrictedCharacterString'
  def eth_tsname(self):
    return 'CHARACTER_STRING'

#--- UsefulType ---------------------------------------------------------------
class GeneralizedTime (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'GeneralizedTime'

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
      return body
    else:
      return RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname)

class UTCTime (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'UTCTime'

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
      return body
    else:
      return RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname)

class ObjectDescriptor (RestrictedCharacterStringType):
  def eth_tsname(self):
    return 'ObjectDescriptor'

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname)
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_object_descriptor', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ObjectIdentifierType -----------------------------------------------------
class ObjectIdentifierType (Type):
  def to_python (self, ctx):
    return 'asn1.OBJECT_IDENTIFIER'

  def eth_tname(self):
    return 'OBJECT_IDENTIFIER'

  def eth_ftype(self, ectx):
    return ('FT_OID', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_OID')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['FN_VARIANT'] = ectx.default_oid_variant
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- ObjectIdentifierValue ----------------------------------------------------
class ObjectIdentifierValue (Value):
  def get_num(self, path, val):
    return str(oid_names.get(path + '/' + val, val))

  def to_str(self, ectx):
    out = ''
    path = ''
    first = True
    sep = ''
    for v in self.comp_list:
      if isinstance(v, Node) and (v.type == 'name_and_number'):
        vstr = v.number
      elif v.isdigit():
        vstr = v
      else:
        vstr = self.get_num(path, v)
      if not first and not vstr.isdigit():
        vstr = ectx.value_get_val(vstr)
      if first:
        if vstr.isdigit():
          out += '"' + vstr
        else:
          out += ectx.value_get_eth(vstr) + '"'
      else:
       out += sep + vstr
      path += sep + vstr
      first = False
      sep = '.'
    out += '"'
    return out

  def get_dep(self):
    v = self.comp_list[0]
    if isinstance(v, Node) and (v.type == 'name_and_number'):
      return None
    elif v.isdigit():
      return None
    else:
      vstr = self.get_num('', v)
    if vstr.isdigit():
      return None
    else:
      return vstr

class NamedNumber(Node):
    def to_python (self, ctx):
        return "('%s',%s)" % (self.ident, self.val)

class NamedNumListBase(Node):
    def to_python (self, ctx):
        return "asn1.%s_class ([%s])" % (self.asn1_typ,",".join (
            [x.to_python (ctx) for x in self.named_list]))

#--- RelativeOIDType ----------------------------------------------------------
class RelativeOIDType (Type):

  def eth_tname(self):
    return 'RELATIVE_OID'

  def eth_ftype(self, ectx):
    return ('FT_BYTES', 'BASE_NONE')

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_RELATIVE_OID')

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    pars['FN_VARIANT'] = ectx.default_oid_variant
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      body = ectx.eth_fn_call('dissect_%(ER)s_relative_oid%(FN_VARIANT)s', ret='offset',
                              par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    elif (ectx.Per()):
      body = ectx.eth_fn_call('dissect_%(ER)s_relative_oid%(FN_VARIANT)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body


#--- IntegerType --------------------------------------------------------------
class IntegerType (Type):
  def to_python (self, ctx):
        return "asn1.INTEGER_class ([%s])" % (",".join (
            [x.to_python (ctx) for x in self.named_list]))

  def add_named_value(self, ident, val):
    e = NamedNumber(ident = ident, val = val)
    if not self.named_list:
      self.named_list = []
    self.named_list.append(e)

  def eth_tname(self):
    if self.named_list:
      return Type.eth_tname(self)
    if not self.HasConstraint():
      return 'INTEGER'
    elif self.constr.type == 'SingleValue' or self.constr.type == 'ValueRange':
      return 'INTEGER' + '_' + self.constr.eth_constrname()
    else:
      return 'INTEGER' + '_' + self.constr.eth_tname()

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_INTEGER')


  def eth_ftype(self, ectx):
    if self.HasConstraint():
      if not self.constr.IsNegativ():
        return ('FT_UINT32', 'BASE_DEC')
    return ('FT_INT32', 'BASE_DEC')

  def eth_strings(self):
    if (self.named_list):
      return '$$'
    else:
      return 'NULL'

  def eth_has_vals(self):
    if (self.named_list):
      return True
    else:
      return False

  def get_vals(self, ectx):
    vals = []
    for e in (self.named_list):
      vals.append((int(e.val), e.ident))
    return vals

  def eth_type_vals(self, tname, ectx):
    if not self.eth_has_vals(): return ''
    out = '\n'
    vals = self.get_vals(ectx)
    out += ectx.eth_vals(tname, vals)
    return out

  def reg_enum_vals(self, tname, ectx):
    vals = self.get_vals(ectx)
    for (val, id) in vals:
      ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id))

  def eth_type_enum(self, tname, ectx):
    if not self.eth_has_enum(tname, ectx): return ''
    out = '\n'
    vals = self.get_vals(ectx)
    out += ectx.eth_enum(tname, vals)
    return out

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    if self.HasValueConstraint():
      (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_value_constr(ectx)
    return pars

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasValueConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer%(FN_VARIANT)s', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_integer%(FN_VARIANT)s', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
                                     ('%(VAL_PTR)s',),))
    elif (ectx.Per() and not self.HasValueConstraint()):
      body = ectx.eth_fn_call('dissect_%(ER)s_integer%(FN_VARIANT)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s'),))
    elif (ectx.Per() and self.HasValueConstraint()):
      body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer%(FN_VARIANT)s', ret='offset',
                              par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                   ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(VAL_PTR)s', '%(EXT)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- BitStringType ------------------------------------------------------------
class BitStringType (Type):
  def to_python (self, ctx):
        return "asn1.BITSTRING_class ([%s])" % (",".join (
            [x.to_python (ctx) for x in self.named_list]))

  def eth_tname(self):
    if self.named_list:
      return Type.eth_tname(self)
    elif not self.HasConstraint():
      return 'BIT_STRING'
    elif self.constr.IsSize():
      return 'BIT_STRING' + '_' + self.constr.eth_constrname()
    else:
      return '#' + self.type + '_' + str(id(self))

  def GetTTag(self, ectx):
    return ('BER_CLASS_UNI', 'BER_UNI_TAG_BITSTRING')

  def eth_ftype(self, ectx):
    return ('FT_BYTES', 'BASE_NONE')

  def eth_need_tree(self):
    return self.named_list

  def eth_need_pdu(self, ectx):
    pdu = None
    if self.HasContentsConstraint():
      t = self.constr.GetContents(ectx)
      if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')):
        pdu = { 'type' : t,
                'new' : ectx.default_containing_variant == '_pdu_new' }
    return pdu

  def eth_named_bits(self):
    bits = []
    if (self.named_list):
      for e in (self.named_list):
        bits.append((int(e.val), e.ident))
    return bits

  def eth_type_default_pars(self, ectx, tname):
    pars = Type.eth_type_default_pars(self, ectx, tname)
    (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
    if 'ETT_INDEX' not in pars:
      pars['ETT_INDEX'] = '-1'
    pars['TABLE'] = 'NULL'
    if self.eth_named_bits():
      pars['TABLE'] = '%(PROTOP)s%(TNAME)s_bits'
    if self.HasContentsConstraint():
      pars['FN_VARIANT'] = ectx.default_containing_variant
      t = self.constr.GetContents(ectx)
      if t:
        if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'):
          t = ectx.field[t]['ethname']
          pars['TYPE_REF_PROTO'] = ''
          pars['TYPE_REF_TNAME'] = t
          pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s'
        else:
          t = ectx.type[t]['ethname']
          pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
          pars['TYPE_REF_TNAME'] = t
          pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
      else:
        pars['TYPE_REF_FN'] = 'NULL'
    return pars

  def eth_type_default_table(self, ectx, tname):
    #print "eth_type_default_table(tname='%s')" % (tname)
    table = ''
    bits = self.eth_named_bits()
    if (bits and ectx.Ber()):
      table = ectx.eth_bits(tname, bits)
    return table

  def eth_type_default_body(self, ectx, tname):
    if (ectx.Ber()):
      if (ectx.constraints_check and self.HasSizeConstraint()):
        body = ectx.eth_fn_call('dissect_%(ER)s_constrained_bitstring', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),
                                     ('%(VAL_PTR)s',),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_bitstring', ret='offset',
                                par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
                                     ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),
                                     ('%(VAL_PTR)s',),))
    elif (ectx.Per()):
      if self.HasContentsConstraint():
        body = ectx.eth_fn_call('dissect_%(ER)s_bit_string_containing%(FN_VARIANT)s', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(TYPE_REF_FN)s'),))
      else:
        body = ectx.eth_fn_call('dissect_%(ER)s_bit_string', ret='offset',
                                par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
                                     ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(VAL_PTR)s'),))
    else:
      body = '#error Can not decode %s' % (tname)
    return body

#--- BStringValue ------------------------------------------------------------
bstring_tab = {
  '0000' : '0',
  '0001' : '1',
  '0010' : '2',
  '0011' : '3',
  '0100' : '4',
  '0101' : '5',
  '0110' : '6',
  '0111' : '7',
  '1000' : '8',
  '1001' : '9',
  '1010' : 'A',
  '1011' : 'B',
  '1100' : 'C',
  '1101' : 'D',
  '1110' : 'E',
  '1111' : 'F',
}
class BStringValue (Value):
  def to_str(self, ectx):
    v = self.val[1:-2]
    if len(v) % 8:
      v += '0' * (8 - len(v) % 8)
    vv = '0x'
    for i in (range(0, len(v), 4)):
      vv += bstring_tab[v[i:i+4]]
    return vv

#--- HStringValue ------------------------------------------------------------
class HStringValue (Value):
  def to_str(self, ectx):
    vv = '0x'
    vv += self.val[1:-2]
    return vv
  def __int__(self):
    return int(self.val[1:-2], 16)

#--- FieldSpec ----------------------------------------------------------------
class FieldSpec (Node):
  def __init__(self,*args, **kw) :
    self.name = None
    Node.__init__ (self,*args, **kw)

  def SetName(self, name):
    self.name = name

  def get_repr(self):
    return ['#UNSUPPORTED_' + self.type]

  def fld_repr(self):
    repr = [self.name]
    repr.extend(self.get_repr())
    return repr

class TypeFieldSpec (FieldSpec):
  def get_repr(self):
    return []

class FixedTypeValueFieldSpec (FieldSpec):
  def get_repr(self):
    if isinstance(self.typ, Type_Ref):
      repr = ['TypeReference', self.typ.val]
    else:
      repr = [self.typ.type]
    return repr

class VariableTypeValueFieldSpec (FieldSpec):
  def get_repr(self):
    return ['_' + self.type]

class FixedTypeValueSetFieldSpec (FieldSpec):
  def get_repr(self):
    return ['_' + self.type]

class ObjectFieldSpec (FieldSpec):
  def get_repr(self):
    return ['ClassReference', self.cls.val]

class ObjectSetFieldSpec (FieldSpec):
  def get_repr(self):
    return ['ClassReference', self.cls.val]

#==============================================================================

def p_module_list_1 (t):
    'module_list : module_list ModuleDefinition'
    t[0] = t[1] + [t[2]]

def p_module_list_2 (t):
    'module_list : ModuleDefinition'
    t[0] = [t[1]]


#--- ITU-T Recommendation X.680 -----------------------------------------------


# 11 ASN.1 lexical items --------------------------------------------------------

# 11.2 Type references
def p_type_ref (t):
  'type_ref : UCASE_IDENT'
  t[0] = Type_Ref(val=t[1])

# 11.3 Identifiers
def p_identifier (t):
  'identifier : LCASE_IDENT'
  t[0] = t[1]

# 11.4 Value references
# cause reduce/reduce conflict
#def p_valuereference (t):
#  'valuereference : LCASE_IDENT'
#  t[0] = Value_Ref(val=t[1])

# 11.5 Module references
def p_modulereference (t):
  'modulereference : UCASE_IDENT'
  t[0] = t[1]


# 12 Module definition --------------------------------------------------------

# 12.1
def p_ModuleDefinition (t):
  'ModuleDefinition : ModuleIdentifier DEFINITIONS TagDefault ASSIGNMENT ModuleBegin BEGIN ModuleBody END'
  t[0] = Module (ident = t[1], tag_def = t[3], body = t[7])

def p_ModuleBegin (t):
  'ModuleBegin : '
  if t[-4].val == 'Remote-Operations-Information-Objects':
    x880_module_begin()

def p_TagDefault_1 (t):
  '''TagDefault : EXPLICIT TAGS
                | IMPLICIT TAGS
                | AUTOMATIC TAGS '''
  t[0] = Default_Tags (dfl_tag = t[1])

def p_TagDefault_2 (t):
  'TagDefault : '
  # 12.2 The "TagDefault" is taken as EXPLICIT TAGS if it is "empty".
  t[0] = Default_Tags (dfl_tag = 'EXPLICIT')

def p_ModuleIdentifier_1 (t):
  'ModuleIdentifier : modulereference DefinitiveIdentifier' # name, oid
  t [0] = Node('module_ident', val = t[1], ident = t[2])

def p_ModuleIdentifier_2 (t):
  'ModuleIdentifier : modulereference' # name, oid
  t [0] = Node('module_ident', val = t[1], ident = None)

def p_DefinitiveIdentifier (t):
  'DefinitiveIdentifier : ObjectIdentifierValue'
  t[0] = t[1]

#def p_module_ref (t):
#    'module_ref : UCASE_IDENT'
#    t[0] = t[1]

def p_ModuleBody_1 (t):
  'ModuleBody : Exports Imports AssignmentList'
  t[0] = Module_Body (exports = t[1], imports = t[2], assign_list = t[3])

def p_ModuleBody_2 (t):
  'ModuleBody : '
  t[0] = Node ('module_body', exports = [], imports = [], assign_list = [])

def p_Exports_1 (t):
    'Exports : EXPORTS syms_exported SEMICOLON'
    t[0] = t[2]

def p_Exports_2 (t):
    'Exports : EXPORTS ALL SEMICOLON'
    t[0] = [ 'ALL' ]

def p_Exports_3 (t):
    'Exports : '
    t[0] = [ 'ALL' ]

def p_syms_exported_1 (t):
    'syms_exported : exp_sym_list'
    t[0] = t[1]

def p_syms_exported_2 (t):
    'syms_exported : '
    t[0] = []

def p_exp_sym_list_1 (t):
    'exp_sym_list : Symbol'
    t[0] = [t[1]]

def p_exp_sym_list_2 (t):
    'exp_sym_list : exp_sym_list COMMA Symbol'
    t[0] = t[1] + [t[3]]


def p_Imports_1 (t):
  'Imports : importsbegin IMPORTS SymbolsImported SEMICOLON'
  t[0] = t[3]
  global lcase_ident_assigned
  lcase_ident_assigned = {}

def p_importsbegin (t):
  'importsbegin : '
  global lcase_ident_assigned
  global g_conform
  lcase_ident_assigned = {}
  lcase_ident_assigned.update(g_conform.use_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER'))

def p_Imports_2 (t):
  'Imports : '
  t[0] = []

def p_SymbolsImported_1(t):
  'SymbolsImported : '
  t[0] = []

def p_SymbolsImported_2 (t):
  'SymbolsImported : SymbolsFromModuleList'
  t[0] = t[1]

def p_SymbolsFromModuleList_1 (t):
   'SymbolsFromModuleList : SymbolsFromModuleList SymbolsFromModule'
   t[0] = t[1] + [t[2]]

def p_SymbolsFromModuleList_2 (t):
   'SymbolsFromModuleList : SymbolsFromModule'
   t[0] = [t[1]]

def p_SymbolsFromModule (t):
  'SymbolsFromModule : SymbolList FROM GlobalModuleReference'
  t[0] = Node ('SymbolList', symbol_list = t[1], module = t[3])
  for s in (t[0].symbol_list):
    if (isinstance(s, Value_Ref)): lcase_ident_assigned[s.val] = t[3]
  import_symbols_from_module(t[0].module, t[0].symbol_list)

def import_symbols_from_module(module, symbol_list):
  if module.val == 'Remote-Operations-Information-Objects':
    for i in range(len(symbol_list)):
      s = symbol_list[i]
      if isinstance(s, Type_Ref) or isinstance(s, Class_Ref):
        x880_import(s.val)
        if isinstance(s, Type_Ref) and is_class_ident(s.val):
          symbol_list[i] = Class_Ref (val = s.val)
    return
  for i in range(len(symbol_list)):
    s = symbol_list[i]
    if isinstance(s, Type_Ref) and is_class_ident("$%s$%s" % (module.val, s.val)):
      import_class_from_module(module.val, s.val)
    if isinstance(s, Type_Ref) and is_class_ident(s.val):
      symbol_list[i] = Class_Ref (val = s.val)

def p_GlobalModuleReference (t):
  'GlobalModuleReference : modulereference AssignedIdentifier'
  t [0] = Node('module_ident', val = t[1], ident = t[2])

def p_AssignedIdentifier_1 (t):
  'AssignedIdentifier : ObjectIdentifierValue'
  t[0] = t[1]

def p_AssignedIdentifier_2 (t):
  'AssignedIdentifier : LCASE_IDENT_ASSIGNED'
  t[0] = t[1]

def p_AssignedIdentifier_3 (t):
  'AssignedIdentifier : '
  pass

def p_SymbolList_1 (t):
  'SymbolList : Symbol'
  t[0] = [t[1]]

def p_SymbolList_2 (t):
  'SymbolList : SymbolList COMMA Symbol'
  t[0] = t[1] + [t[3]]

def p_Symbol (t):
  '''Symbol : Reference
            | ParameterizedReference'''
  t[0] = t[1]

def p_Reference_1 (t):
  '''Reference : type_ref
               | objectclassreference '''
  t[0] = t[1]

def p_Reference_2 (t):
  '''Reference : LCASE_IDENT_ASSIGNED
               | identifier '''  # instead of valuereference wich causes reduce/reduce conflict
  t[0] = Value_Ref(val=t[1])

def p_AssignmentList_1 (t):
  'AssignmentList : AssignmentList Assignment'
  t[0] = t[1] + [t[2]]

def p_AssignmentList_2 (t):
  'AssignmentList : Assignment SEMICOLON'
  t[0] = [t[1]]

def p_AssignmentList_3 (t):
  'AssignmentList : Assignment'
  t[0] = [t[1]]

def p_Assignment (t):
  '''Assignment : TypeAssignment
                | ValueAssignment
                | ValueSetTypeAssignment
                | ObjectClassAssignment
                | ObjectAssignment
                | ObjectSetAssignment
                | ParameterizedAssignment
                | pyquote '''
  t[0] = t[1]


# 13 Referencing type and value definitions -----------------------------------

# 13.1
def p_DefinedType (t):
  '''DefinedType : ExternalTypeReference
                 | type_ref
                 | ParameterizedType'''
  t[0] = t[1]

def p_DefinedValue_1(t):
  '''DefinedValue : ExternalValueReference'''
  t[0] = t[1]

def p_DefinedValue_2(t):
  '''DefinedValue : identifier '''  # instead of valuereference wich causes reduce/reduce conflict
  t[0] = Value_Ref(val=t[1])

# 13.6
def p_ExternalTypeReference (t):
  'ExternalTypeReference : modulereference DOT type_ref'
  t[0] = Node ('ExternalTypeReference', module = t[1], typ = t[3])

def p_ExternalValueReference (t):
  'ExternalValueReference : modulereference DOT identifier'
  t[0] = Node ('ExternalValueReference', module = t[1], ident = t[3])


# 15 Assigning types and values -----------------------------------------------

# 15.1
def p_TypeAssignment (t):
  'TypeAssignment : UCASE_IDENT ASSIGNMENT Type'
  t[0] = t[3]
  t[0].SetName(t[1])

# 15.2
def p_ValueAssignment (t):
  'ValueAssignment : LCASE_IDENT ValueType ASSIGNMENT Value'
  t[0] = ValueAssignment(ident = t[1], typ = t[2], val = t[4])

# only "simple" types are supported to simplify grammer
def p_ValueType (t):
  '''ValueType : type_ref
               | BooleanType
               | IntegerType
               | ObjectIdentifierType
               | OctetStringType
               | RealType '''

  t[0] = t[1]

# 15.6
def p_ValueSetTypeAssignment (t):
  'ValueSetTypeAssignment : UCASE_IDENT ValueType ASSIGNMENT ValueSet'
  t[0] = Node('ValueSetTypeAssignment', name=t[1], typ=t[2], val=t[4])

# 15.7
def p_ValueSet (t):
  'ValueSet : lbraceignore rbraceignore'
  t[0] = None


# 16 Definition of types and values -------------------------------------------

# 16.1
def p_Type (t):
  '''Type : BuiltinType
          | ReferencedType
          | ConstrainedType'''
  t[0] = t[1]

# 16.2
def p_BuiltinType (t):
  '''BuiltinType : AnyType
                 | BitStringType
                 | BooleanType
                 | CharacterStringType
                 | ChoiceType
                 | EmbeddedPDVType
                 | EnumeratedType
                 | ExternalType
                 | InstanceOfType
                 | IntegerType
                 | NullType
                 | ObjectClassFieldType
                 | ObjectIdentifierType
                 | OctetStringType
                 | RealType
                 | RelativeOIDType
                 | SequenceType
                 | SequenceOfType
                 | SetType
                 | SetOfType
                 | TaggedType'''
  t[0] = t[1]

# 16.3
def p_ReferencedType (t):
  '''ReferencedType : DefinedType
                    | UsefulType
                    | SelectionType'''
  t[0] = t[1]

# 16.5
def p_NamedType (t):
  'NamedType : identifier Type'
  t[0] = t[2]
  t[0].SetName (t[1])

# 16.7
def p_Value (t):
  '''Value : BuiltinValue
           | ReferencedValue
           | ObjectClassFieldValue'''
  t[0] = t[1]

# 16.9
def p_BuiltinValue (t):
  '''BuiltinValue : BooleanValue
                  | ChoiceValue
                  | IntegerValue
                  | ObjectIdentifierValue
                  | RealValue
                  | SequenceValue
                  | hex_string
                  | binary_string
                  | char_string''' # XXX we don't support {data} here
  t[0] = t[1]

# 16.11
def p_ReferencedValue (t):
  '''ReferencedValue : DefinedValue
                     | ValueFromObject'''
  t[0] = t[1]

# 16.13
#def p_NamedValue (t):
#  'NamedValue : identifier Value'
#  t[0] = Node ('NamedValue', ident = t[1], value = t[2])


# 17 Notation for the boolean type --------------------------------------------

# 17.1
def p_BooleanType (t):
  'BooleanType : BOOLEAN'
  t[0] = BooleanType ()

# 17.2
def p_BooleanValue (t):
  '''BooleanValue : TRUE
                  | FALSE'''
  t[0] = t[1]


# 18 Notation for the integer type --------------------------------------------

# 18.1
def p_IntegerType_1 (t):
  'IntegerType : INTEGER'
  t[0] = IntegerType (named_list = None)

def p_IntegerType_2 (t):
  'IntegerType : INTEGER LBRACE NamedNumberList RBRACE'
  t[0] = IntegerType(named_list = t[3])

def p_NamedNumberList_1 (t):
  'NamedNumberList : NamedNumber'
  t[0] = [t[1]]

def p_NamedNumberList_2 (t):
  'NamedNumberList : NamedNumberList COMMA NamedNumber'
  t[0] = t[1] + [t[3]]

def p_NamedNumber (t):
  '''NamedNumber : identifier LPAREN SignedNumber RPAREN
                 | identifier LPAREN DefinedValue RPAREN'''
  t[0] = NamedNumber(ident = t[1], val = t[3])

def p_SignedNumber_1 (t):
  'SignedNumber : NUMBER'
  t[0] = t [1]

def p_SignedNumber_2 (t):
  'SignedNumber : MINUS NUMBER'
  t[0] = '-' + t[2]

# 18.9
def p_IntegerValue (t):
  'IntegerValue : SignedNumber'
  t[0] = t [1]

# 19 Notation for the enumerated type -----------------------------------------

# 19.1
def p_EnumeratedType (t):
    'EnumeratedType : ENUMERATED LBRACE Enumerations RBRACE'
    t[0] = EnumeratedType (val = t[3]['val'], ext = t[3]['ext'])

def p_Enumerations_1 (t):
    'Enumerations : Enumeration'
    t[0] = { 'val' : t[1], 'ext' : None }

def p_Enumerations_2 (t):
    'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec'
    t[0] = { 'val' : t[1], 'ext' : [] }

def p_Enumerations_3 (t):
    'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec COMMA Enumeration'
    t[0] = { 'val' : t[1], 'ext' : t[6] }

def p_Enumeration_1 (t):
    'Enumeration : EnumerationItem'
    t[0] = [t[1]]

def p_Enumeration_2 (t):
    'Enumeration : Enumeration COMMA EnumerationItem'
    t[0] = t[1] + [t[3]]

def p_EnumerationItem (t):
    '''EnumerationItem : Identifier
                       | NamedNumber'''
    t[0] = t[1]

def p_Identifier (t):
    'Identifier : identifier'
    t[0] = Node ('Identifier', ident = t[1])


# 20 Notation for the real type -----------------------------------------------

# 20.1
def p_RealType (t):
  'RealType : REAL'
  t[0] = RealType ()

# 20.6
def p_RealValue (t):
  '''RealValue : REAL_NUMBER
               | SpecialRealValue'''
  t[0] = t [1]

def p_SpecialRealValue (t):
  '''SpecialRealValue : PLUS_INFINITY
                      | MINUS_INFINITY'''
  t[0] = t[1]


# 21 Notation for the bitstring type ------------------------------------------

# 21.1
def p_BitStringType_1 (t):
    'BitStringType : BIT STRING'
    t[0] = BitStringType (named_list = None)

def p_BitStringType_2 (t):
    'BitStringType : BIT STRING LBRACE NamedBitList RBRACE'
    t[0] = BitStringType (named_list = t[4])

def p_NamedBitList_1 (t):
    'NamedBitList : NamedBit'
    t[0] = [t[1]]

def p_NamedBitList_2 (t):
    'NamedBitList : NamedBitList COMMA NamedBit'
    t[0] = t[1] + [t[3]]

def p_NamedBit (t):
    '''NamedBit : identifier LPAREN NUMBER RPAREN
                | identifier LPAREN DefinedValue RPAREN'''
    t[0] = NamedNumber (ident = t[1], val = t[3])


# 22 Notation for the octetstring type ----------------------------------------

# 22.1
def p_OctetStringType (t):
    'OctetStringType : OCTET STRING'
    t[0] = OctetStringType ()


# 23 Notation for the null type -----------------------------------------------

# 23.1
def p_NullType (t):
  'NullType : NULL'
  t[0] = NullType ()

# 23.3
def p_NullValue (t):
  'NullValue : NULL'
  t[0] = NullValue ()


# 24 Notation for sequence types ----------------------------------------------

# 24.1
def p_SequenceType_1 (t):
  'SequenceType : SEQUENCE LBRACE RBRACE'
  t[0] = SequenceType (elt_list = [])

def p_SequenceType_2 (t):
  'SequenceType : SEQUENCE LBRACE ComponentTypeLists RBRACE'
  t[0] = SequenceType (elt_list = t[3]['elt_list'])
  if 'ext_list' in t[3]:
    t[0].ext_list = t[3]['ext_list']
  if 'elt_list2' in t[3]:
    t[0].elt_list2 = t[3]['elt_list2']

def p_ExtensionAndException_1 (t):
  'ExtensionAndException : ELLIPSIS'
  t[0] = []

def p_OptionalExtensionMarker_1 (t):
  'OptionalExtensionMarker : COMMA ELLIPSIS'
  t[0] = True

def p_OptionalExtensionMarker_2 (t):
  'OptionalExtensionMarker : '
  t[0] = False

def p_ComponentTypeLists_1 (t):
  'ComponentTypeLists : ComponentTypeList'
  t[0] = {'elt_list' : t[1]}

def p_ComponentTypeLists_2 (t):
    'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException OptionalExtensionMarker'
    t[0] = {'elt_list' : t[1], 'ext_list' : []}

def p_ComponentTypeLists_3 (t):
    'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList OptionalExtensionMarker'
    t[0] = {'elt_list' : t[1], 'ext_list' : t[4]}

def p_ComponentTypeLists_4 (t):
    'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionEndMarker COMMA ComponentTypeList'
    t[0] = {'elt_list' : t[1], 'ext_list' : [], 'elt_list2' : t[6]}

def p_ComponentTypeLists_5 (t):
    'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList ExtensionEndMarker COMMA ComponentTypeList'
    t[0] = {'elt_list' : t[1], 'ext_list' : t[4], 'elt_list2' : t[7]}

def p_ComponentTypeLists_6 (t):
    'ComponentTypeLists : ExtensionAndException OptionalExtensionMarker'
    t[0] = {'elt_list' : [], 'ext_list' : []}

def p_ComponentTypeLists_7 (t):
    'ComponentTypeLists : ExtensionAndException ExtensionAdditionList OptionalExtensionMarker'
    t[0] = {'elt_list' : [], 'ext_list' : t[2]}

def p_ExtensionEndMarker (t):
  'ExtensionEndMarker : COMMA ELLIPSIS'
  pass

def p_ExtensionAdditionList_1 (t):
  'ExtensionAdditionList : COMMA ExtensionAddition'
  t[0] = [t[2]]

def p_ExtensionAdditionList_2 (t):
  'ExtensionAdditionList : ExtensionAdditionList COMMA ExtensionAddition'
  t[0] = t[1] + [t[3]]

def p_ExtensionAddition_1 (t):
  'ExtensionAddition : ExtensionAdditionGroup'
  t[0] = Node ('elt_type', val = t[1], optional = 0)

def p_ExtensionAddition_2 (t):
  'ExtensionAddition : ComponentType'
  t[0] = t[1]

def p_ExtensionAdditionGroup (t):
  'ExtensionAdditionGroup : LVERBRACK VersionNumber ComponentTypeList RVERBRACK'
  t[0] = ExtensionAdditionGroup (ver = t[2], elt_list = t[3])

def p_VersionNumber_1 (t):
  'VersionNumber : '

def p_VersionNumber_2 (t):
  'VersionNumber : NUMBER COLON'
  t[0] = t[1]

def p_ComponentTypeList_1 (t):
  'ComponentTypeList : ComponentType'
  t[0] = [t[1]]

def p_ComponentTypeList_2 (t):
  'ComponentTypeList : ComponentTypeList COMMA ComponentType'
  t[0] = t[1] + [t[3]]

def p_ComponentType_1 (t):
  'ComponentType : NamedType'
  t[0] = Node ('elt_type', val = t[1], optional = 0)

def p_ComponentType_2 (t):
  'ComponentType : NamedType OPTIONAL'
  t[0] = Node ('elt_type', val = t[1], optional = 1)

def p_ComponentType_3 (t):
  'ComponentType : NamedType DEFAULT DefaultValue'
  t[0] = Node ('elt_type', val = t[1], optional = 1, default = t[3])

def p_ComponentType_4 (t):
  'ComponentType : COMPONENTS OF Type'
  t[0] = Node ('components_of', typ = t[3])

def p_DefaultValue_1 (t):
  '''DefaultValue : ReferencedValue
                  | BooleanValue
                  | ChoiceValue
                  | IntegerValue
                  | RealValue
                  | hex_string
                  | binary_string
                  | char_string
                  | ObjectClassFieldValue'''
  t[0] = t[1]

def p_DefaultValue_2 (t):
  'DefaultValue : lbraceignore rbraceignore'
  t[0] = ''

# 24.17
def p_SequenceValue_1 (t):
  'SequenceValue : LBRACE RBRACE'
  t[0] = []


#def p_SequenceValue_2 (t):
#  'SequenceValue : LBRACE ComponentValueList RBRACE'
#  t[0] = t[2]

#def p_ComponentValueList_1 (t):
#    'ComponentValueList : NamedValue'
#    t[0] = [t[1]]

#def p_ComponentValueList_2 (t):
#    'ComponentValueList : ComponentValueList COMMA NamedValue'
#    t[0] = t[1] + [t[3]]


# 25 Notation for sequence-of types -------------------------------------------

# 25.1
def p_SequenceOfType (t):
    '''SequenceOfType : SEQUENCE OF Type
                      | SEQUENCE OF NamedType'''
    t[0] = SequenceOfType (val = t[3], size_constr = None)


# 26 Notation for set types ---------------------------------------------------

# 26.1
def p_SetType_1 (t):
  'SetType : SET LBRACE RBRACE'
  t[0] = SetType (elt_list = [])

def p_SetType_2 (t):
  'SetType : SET LBRACE ComponentTypeLists RBRACE'
  t[0] = SetType (elt_list = t[3]['elt_list'])
  if 'ext_list' in t[3]:
    t[0].ext_list = t[3]['ext_list']
  if 'elt_list2' in t[3]:
    t[0].elt_list2 = t[3]['elt_list2']


# 27 Notation for set-of types ------------------------------------------------

# 27.1
def p_SetOfType (t):
    '''SetOfType : SET OF Type
                 | SET OF NamedType'''
    t[0] = SetOfType (val = t[3])

# 28 Notation for choice types ------------------------------------------------

# 28.1
def p_ChoiceType (t):
    'ChoiceType : CHOICE LBRACE AlternativeTypeLists RBRACE'
    if 'ext_list' in t[3]:
        t[0] = ChoiceType (elt_list = t[3]['elt_list'], ext_list = t[3]['ext_list'])
    else:
        t[0] = ChoiceType (elt_list = t[3]['elt_list'])

def p_AlternativeTypeLists_1 (t):
    'AlternativeTypeLists : AlternativeTypeList'
    t[0] = {'elt_list' : t[1]}

def p_AlternativeTypeLists_2 (t):
    'AlternativeTypeLists : AlternativeTypeList COMMA ExtensionAndException ExtensionAdditionAlternatives OptionalExtensionMarker'
    t[0] = {'elt_list' : t[1], 'ext_list' : t[4]}

def p_ExtensionAdditionAlternatives_1 (t):
    'ExtensionAdditionAlternatives : ExtensionAdditionAlternativesList'
    t[0] = t[1]

def p_ExtensionAdditionAlternatives_2 (t):
    'ExtensionAdditionAlternatives : '
    t[0] = []

def p_ExtensionAdditionAlternativesList_1 (t):
    'ExtensionAdditionAlternativesList : COMMA ExtensionAdditionAlternative'
    t[0] = t[2]

def p_ExtensionAdditionAlternativesList_2 (t):
    'ExtensionAdditionAlternativesList : ExtensionAdditionAlternativesList COMMA ExtensionAdditionAlternative'
    t[0] = t[1] + t[3]

def p_ExtensionAdditionAlternative_1 (t):
    'ExtensionAdditionAlternative : NamedType'
    t[0] = [t[1]]

def p_ExtensionAdditionAlternative_2 (t):
    'ExtensionAdditionAlternative : ExtensionAdditionAlternativesGroup'
    t[0] = t[1]

def p_ExtensionAdditionAlternativesGroup (t):
  'ExtensionAdditionAlternativesGroup : LVERBRACK VersionNumber AlternativeTypeList RVERBRACK'
  t[0] = t[3]

def p_AlternativeTypeList_1 (t):
    'AlternativeTypeList : NamedType'
    t[0] = [t[1]]

def p_AlternativeTypeList_2 (t):
    'AlternativeTypeList : AlternativeTypeList COMMA NamedType'
    t[0] = t[1] + [t[3]]

# 28.10
def p_ChoiceValue_1 (t):
  '''ChoiceValue : identifier COLON Value
                 | identifier COLON NullValue '''
  val = t[3]
  if not isinstance(val, Value):
    val = Value(val=val)
  t[0] = ChoiceValue (choice = t[1], val = val)

# 29 Notation for selection types

# 29.1
def p_SelectionType (t): #
  'SelectionType : identifier LT Type'
  t[0] = SelectionType (typ = t[3], sel = t[1])

# 30 Notation for tagged types ------------------------------------------------

# 30.1
def p_TaggedType_1 (t):
    'TaggedType : Tag Type'
    t[1].mode = 'default'
    t[0] = t[2]
    t[0].AddTag(t[1])

def p_TaggedType_2 (t):
    '''TaggedType : Tag IMPLICIT Type
                  | Tag EXPLICIT Type'''
    t[1].mode = t[2]
    t[0] = t[3]
    t[0].AddTag(t[1])

def p_Tag (t):
    'Tag : LBRACK Class ClassNumber RBRACK'
    t[0] = Tag(cls = t[2], num = t[3])

def p_ClassNumber_1 (t):
    'ClassNumber : number'
    t[0] = t[1]

def p_ClassNumber_2 (t):
    'ClassNumber : DefinedValue'
    t[0] = t[1]

def p_Class_1 (t):
    '''Class : UNIVERSAL
             | APPLICATION
             | PRIVATE'''
    t[0] = t[1]

def p_Class_2 (t):
    'Class :'
    t[0] = 'CONTEXT'


# 31 Notation for the object identifier type ----------------------------------

# 31.1
def p_ObjectIdentifierType (t):
  'ObjectIdentifierType : OBJECT IDENTIFIER'
  t[0] = ObjectIdentifierType()

# 31.3
def p_ObjectIdentifierValue (t):
    'ObjectIdentifierValue : LBRACE oid_comp_list RBRACE'
    t[0] = ObjectIdentifierValue (comp_list=t[2])

def p_oid_comp_list_1 (t):
    'oid_comp_list : oid_comp_list ObjIdComponents'
    t[0] = t[1] + [t[2]]

def p_oid_comp_list_2 (t):
    'oid_comp_list : ObjIdComponents'
    t[0] = [t[1]]

def p_ObjIdComponents (t):
  '''ObjIdComponents : NameForm
                     | NumberForm
                     | NameAndNumberForm'''
  t[0] = t[1]

def p_NameForm (t):
  '''NameForm : LCASE_IDENT
              | LCASE_IDENT_ASSIGNED'''
  t [0] = t[1]

def p_NumberForm (t):
  '''NumberForm : NUMBER'''
#                | DefinedValue'''
  t [0] = t[1]

def p_NameAndNumberForm (t):
  '''NameAndNumberForm : LCASE_IDENT_ASSIGNED LPAREN NumberForm RPAREN
                       | LCASE_IDENT LPAREN NumberForm RPAREN'''
  t[0] = Node('name_and_number', ident = t[1], number = t[3])

# 32 Notation for the relative object identifier type -------------------------

# 32.1
def p_RelativeOIDType (t):
  'RelativeOIDType : RELATIVE_OID'
  t[0] = RelativeOIDType()

# 33 Notation for the embedded-pdv type ---------------------------------------

# 33.1
def p_EmbeddedPDVType (t):
  'EmbeddedPDVType : EMBEDDED PDV'
  t[0] = EmbeddedPDVType()

# 34 Notation for the external type -------------------------------------------

# 34.1
def p_ExternalType (t):
  'ExternalType : EXTERNAL'
  t[0] = ExternalType()

# 36 Notation for character string types --------------------------------------

# 36.1
def p_CharacterStringType (t):
    '''CharacterStringType : RestrictedCharacterStringType
    | UnrestrictedCharacterStringType'''
    t[0] = t[1]


# 37 Definition of restricted character string types --------------------------

def p_RestrictedCharacterStringType_1 (t):
    'RestrictedCharacterStringType : BMPString'
    t[0] = BMPStringType ()
def p_RestrictedCharacterStringType_2 (t):
    'RestrictedCharacterStringType : GeneralString'
    t[0] = GeneralStringType ()
def p_RestrictedCharacterStringType_3 (t):
    'RestrictedCharacterStringType : GraphicString'
    t[0] = GraphicStringType ()
def p_RestrictedCharacterStringType_4 (t):
    'RestrictedCharacterStringType : IA5String'
    t[0] = IA5StringType ()
def p_RestrictedCharacterStringType_5 (t):
    'RestrictedCharacterStringType : ISO646String'
    t[0] = ISO646StringType ()
def p_RestrictedCharacterStringType_6 (t):
    'RestrictedCharacterStringType : NumericString'
    t[0] = NumericStringType ()
def p_RestrictedCharacterStringType_7 (t):
    'RestrictedCharacterStringType : PrintableString'
    t[0] = PrintableStringType ()
def p_RestrictedCharacterStringType_8 (t):
    'RestrictedCharacterStringType : TeletexString'
    t[0] = TeletexStringType ()
def p_RestrictedCharacterStringType_9 (t):
    'RestrictedCharacterStringType : T61String'
    t[0] = T61StringType ()
def p_RestrictedCharacterStringType_10 (t):
    'RestrictedCharacterStringType : UniversalString'
    t[0] = UniversalStringType ()
def p_RestrictedCharacterStringType_11 (t):
    'RestrictedCharacterStringType : UTF8String'
    t[0] = UTF8StringType ()
def p_RestrictedCharacterStringType_12 (t):
    'RestrictedCharacterStringType : VideotexString'
    t[0] = VideotexStringType ()
def p_RestrictedCharacterStringType_13 (t):
    'RestrictedCharacterStringType : VisibleString'
    t[0] = VisibleStringType ()


# 40 Definition of unrestricted character string types ------------------------

# 40.1
def p_UnrestrictedCharacterStringType (t):
    'UnrestrictedCharacterStringType : CHARACTER STRING'
    t[0] = UnrestrictedCharacterStringType ()


# 41 Notation for types defined in clauses 42 to 44 ---------------------------

# 42 Generalized time ---------------------------------------------------------

def p_UsefulType_1 (t):
  'UsefulType : GeneralizedTime'
  t[0] = GeneralizedTime()

# 43 Universal time -----------------------------------------------------------

def p_UsefulType_2 (t):
  'UsefulType : UTCTime'
  t[0] = UTCTime()

# 44 The object descriptor type -----------------------------------------------

def p_UsefulType_3 (t):
  'UsefulType : ObjectDescriptor'
  t[0] = ObjectDescriptor()


# 45 Constrained types --------------------------------------------------------

# 45.1
def p_ConstrainedType_1 (t):
    'ConstrainedType : Type Constraint'
    t[0] = t[1]
    t[0].AddConstraint(t[2])

def p_ConstrainedType_2 (t):
    'ConstrainedType : TypeWithConstraint'
    t[0] = t[1]

# 45.5
def p_TypeWithConstraint_1 (t):
    '''TypeWithConstraint : SET Constraint OF Type
                          | SET SizeConstraint OF Type'''
    t[0] = SetOfType (val = t[4], constr = t[2])

def p_TypeWithConstraint_2 (t):
    '''TypeWithConstraint : SEQUENCE Constraint OF Type
                          | SEQUENCE SizeConstraint OF Type'''
    t[0] = SequenceOfType (val = t[4], constr = t[2])

def p_TypeWithConstraint_3 (t):
    '''TypeWithConstraint : SET Constraint OF NamedType
                          | SET SizeConstraint OF NamedType'''
    t[0] = SetOfType (val = t[4], constr = t[2])

def p_TypeWithConstraint_4 (t):
    '''TypeWithConstraint : SEQUENCE Constraint OF NamedType
                          | SEQUENCE SizeConstraint OF NamedType'''
    t[0] = SequenceOfType (val = t[4], constr = t[2])

# 45.6
# 45.7
def p_Constraint (t):
    'Constraint : LPAREN ConstraintSpec ExceptionSpec RPAREN'
    t[0] = t[2]

def p_ConstraintSpec (t):
    '''ConstraintSpec : ElementSetSpecs
                      | GeneralConstraint'''
    t[0] = t[1]

# 46 Element set specification ------------------------------------------------

# 46.1
def p_ElementSetSpecs_1 (t):
  'ElementSetSpecs : RootElementSetSpec'
  t[0] = t[1]

def p_ElementSetSpecs_2 (t):
  'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS'
  t[0] = t[1]
  t[0].ext = True

def p_ElementSetSpecs_3 (t):
  'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS COMMA AdditionalElementSetSpec'
  t[0] = t[1]
  t[0].ext = True

def p_RootElementSetSpec (t):
  'RootElementSetSpec : ElementSetSpec'
  t[0] = t[1]

def p_AdditionalElementSetSpec (t):
  'AdditionalElementSetSpec : ElementSetSpec'
  t[0] = t[1]

def p_ElementSetSpec (t):
  'ElementSetSpec : Unions'
  t[0] = t[1]

def p_Unions_1 (t):
  'Unions : Intersections'
  t[0] = t[1]

def p_Unions_2 (t):
  'Unions : UElems UnionMark Intersections'
  t[0] = Constraint(type = 'Union', subtype = [t[1], t[3]])

def p_UElems (t):
  'UElems : Unions'
  t[0] = t[1]

def p_Intersections_1 (t):
  'Intersections : IntersectionElements'
  t[0] = t[1]

def p_Intersections_2 (t):
  'Intersections : IElems IntersectionMark IntersectionElements'
  t[0] = Constraint(type = 'Intersection', subtype = [t[1], t[3]])

def p_IElems (t):
  'IElems : Intersections'
  t[0] = t[1]

def p_IntersectionElements (t):
  'IntersectionElements : Elements'
  t[0] = t[1]

def p_UnionMark (t):
  '''UnionMark : BAR
               | UNION'''

def p_IntersectionMark (t):
  '''IntersectionMark : CIRCUMFLEX
                      | INTERSECTION'''

# 46.5
def p_Elements_1 (t):
  'Elements : SubtypeElements'
  t[0] = t[1]

def p_Elements_2 (t):
  'Elements : LPAREN ElementSetSpec RPAREN'
  t[0] = t[2]

# 47 Subtype elements ---------------------------------------------------------

# 47.1 General
def p_SubtypeElements (t):
    '''SubtypeElements : SingleValue
                       | ContainedSubtype
                       | ValueRange
                       | PermittedAlphabet
                       | SizeConstraint
                       | TypeConstraint
                       | InnerTypeConstraints
                       | PatternConstraint'''
    t[0] = t[1]

# 47.2 Single value
# 47.2.1
def p_SingleValue (t):
    'SingleValue : Value'
    t[0] = Constraint(type = 'SingleValue', subtype = t[1])

# 47.3 Contained subtype
# 47.3.1
def p_ContainedSubtype (t):
  'ContainedSubtype : Includes Type'
  t[0] = Constraint(type = 'ContainedSubtype', subtype = t[2])

def p_Includes (t):
  '''Includes : INCLUDES
              | '''

# 47.4 Value range
# 47.4.1
def p_ValueRange (t):
  'ValueRange : LowerEndpoint RANGE UpperEndpoint'
  t[0] = Constraint(type = 'ValueRange', subtype = [t[1], t[3]])

# 47.4.3
def p_LowerEndpoint_1 (t):
  'LowerEndpoint : LowerEndValue'
  t[0] = t[1]

def p_LowerEndpoint_2 (t):
  'LowerEndpoint : LowerEndValue LT'
  t[0] = t[1] # but not inclusive range

def p_UpperEndpoint_1 (t):
  'UpperEndpoint : UpperEndValue'
  t[0] = t[1]

def p_UpperEndpoint_2 (t):
  'UpperEndpoint : LT UpperEndValue'
  t[0] = t[1] # but not inclusive range

# 47.4.4
def p_LowerEndValue (t):
  '''LowerEndValue : Value
                   | MIN'''
  t[0] = t[1] # XXX

def p_UpperEndValue (t):
  '''UpperEndValue : Value
                    | MAX'''
  t[0] = t[1]

# 47.5 Size constraint
# 47.5.1
def p_SizeConstraint (t):
    'SizeConstraint : SIZE Constraint'
    t[0] = Constraint (type = 'Size', subtype = t[2])

# 47.6 Type constraint
# 47.6.1
def p_TypeConstraint (t):
    'TypeConstraint : Type'
    t[0] = Constraint (type = 'Type', subtype = t[1])

# 47.7 Permitted alphabet
# 47.7.1
def p_PermittedAlphabet (t):
    'PermittedAlphabet : FROM Constraint'
    t[0] = Constraint (type = 'From', subtype = t[2])

# 47.8 Inner subtyping
# 47.8.1
def p_InnerTypeConstraints (t):
    '''InnerTypeConstraints : WITH COMPONENT SingleTypeConstraint
                            | WITH COMPONENTS MultipleTypeConstraints'''
    pass # ignore PER invisible constraint

# 47.8.3
def p_SingleTypeConstraint (t):
    'SingleTypeConstraint : Constraint'
    t[0] = t[1]

# 47.8.4
def p_MultipleTypeConstraints (t):
    '''MultipleTypeConstraints : FullSpecification
                               | PartialSpecification'''
    t[0] = t[1]

def p_FullSpecification (t):
    'FullSpecification : LBRACE TypeConstraints RBRACE'
    t[0] = t[2]

def p_PartialSpecification (t):
    'PartialSpecification : LBRACE ELLIPSIS COMMA TypeConstraints RBRACE'
    t[0] = t[4]

def p_TypeConstraints_1 (t):
    'TypeConstraints : named_constraint'
    t [0] = [t[1]]

def p_TypeConstraints_2 (t):
    'TypeConstraints : TypeConstraints COMMA named_constraint'
    t[0] = t[1] + [t[3]]

def p_named_constraint_1 (t):
    'named_constraint : identifier constraint'
    return Node ('named_constraint', ident = t[1], constr = t[2])

def p_named_constraint_2 (t):
    'named_constraint : constraint'
    return Node ('named_constraint', constr = t[1])

def p_constraint (t):
    'constraint : value_constraint presence_constraint'
    t[0] = Node ('constraint', value = t[1], presence = t[2])

def p_value_constraint_1 (t):
    'value_constraint : Constraint'
    t[0] = t[1]

def p_value_constraint_2 (t):
    'value_constraint : '
    pass

def p_presence_constraint_1 (t):
    '''presence_constraint : PRESENT
                 | ABSENT
                 | OPTIONAL'''
    t[0] = t[1]

def p_presence_constraint_2 (t):
    '''presence_constraint : '''
    pass

# 47.9 Pattern constraint
# 47.9.1
def p_PatternConstraint (t):
    'PatternConstraint : PATTERN Value'
    t[0] = Constraint (type = 'Pattern', subtype = t[2])

# 49 The exception identifier

# 49.4
def p_ExceptionSpec_1 (t):
  'ExceptionSpec : EXCLAMATION ExceptionIdentification'
  pass

def p_ExceptionSpec_2 (t):
  'ExceptionSpec : '
  pass

def p_ExceptionIdentification (t):
  '''ExceptionIdentification : SignedNumber
                             | DefinedValue
                             | Type COLON Value '''
  pass

#  /*-----------------------------------------------------------------------*/
#  /* Value Notation Productions */
#  /*-----------------------------------------------------------------------*/



def p_binary_string (t):
  'binary_string : BSTRING'
  t[0] = BStringValue(val = t[1])

def p_hex_string (t):
  'hex_string : HSTRING'
  t[0] = HStringValue(val = t[1])

def p_char_string (t):
    'char_string : QSTRING'
    t[0] = t[1]

def p_number (t):
  'number : NUMBER'
  t[0] = t[1]


#--- ITU-T Recommendation X.208 -----------------------------------------------

# 27 Notation for the any type ------------------------------------------------

# 27.1
def p_AnyType (t):
  '''AnyType : ANY
             | ANY DEFINED BY identifier'''
  t[0] = AnyType()

#--- ITU-T Recommendation X.681 -----------------------------------------------

# 7 ASN.1 lexical items -------------------------------------------------------

# 7.1 Information object class references

def p_objectclassreference (t):
  'objectclassreference : CLASS_IDENT'
  t[0] = Class_Ref(val=t[1])

# 7.2 Information object references

def p_objectreference (t):
  'objectreference : LCASE_IDENT'
  t[0] = t[1]

# 7.3 Information object set references

#def p_objectsetreference (t):
#  'objectsetreference : UCASE_IDENT'
#  t[0] = t[1]

# 7.4 Type field references
# ucasefieldreference
# 7.5 Value field references
# lcasefieldreference
# 7.6 Value set field references
# ucasefieldreference
# 7.7 Object field references
# lcasefieldreference
# 7.8 Object set field references
# ucasefieldreference

def p_ucasefieldreference (t):
  'ucasefieldreference : AMPERSAND UCASE_IDENT'
  t[0] = '&' + t[2]

def p_lcasefieldreference (t):
  'lcasefieldreference : AMPERSAND LCASE_IDENT'
  t[0] = '&' + t[2]

# 8 Referencing definitions

# 8.1
def p_DefinedObjectClass (t):
  '''DefinedObjectClass : objectclassreference
                        | UsefulObjectClassReference'''
  t[0] = t[1]
  global obj_class
  obj_class = t[0].val

def p_DefinedObject (t):
  '''DefinedObject : objectreference'''
  t[0] = t[1]

# 8.4
def p_UsefulObjectClassReference (t):
  '''UsefulObjectClassReference : TYPE_IDENTIFIER
                                | ABSTRACT_SYNTAX'''
  t[0] = Class_Ref(val=t[1])

# 9 Information object class definition and assignment

# 9.1
def p_ObjectClassAssignment (t):
  '''ObjectClassAssignment : CLASS_IDENT ASSIGNMENT ObjectClass
                           | UCASE_IDENT ASSIGNMENT ObjectClass'''
  t[0] = t[3]
  t[0].SetName(t[1])
  if isinstance(t[0], ObjectClassDefn):
    t[0].reg_types()

# 9.2
def p_ObjectClass (t):
  '''ObjectClass : DefinedObjectClass
                 | ObjectClassDefn
                 | ParameterizedObjectClass '''
  t[0] = t[1]

# 9.3
def p_ObjectClassDefn (t):
  '''ObjectClassDefn : CLASS LBRACE FieldSpecs RBRACE
                     | CLASS LBRACE FieldSpecs RBRACE WithSyntaxSpec'''
  t[0] = ObjectClassDefn(fields = t[3])

def p_FieldSpecs_1 (t):
  'FieldSpecs : FieldSpec'
  t[0] = [t[1]]

def p_FieldSpecs_2 (t):
  'FieldSpecs : FieldSpecs COMMA FieldSpec'
  t[0] = t[1] + [t[3]]

def p_WithSyntaxSpec (t):
  'WithSyntaxSpec : WITH SYNTAX lbraceignore rbraceignore'
  t[0] = None

# 9.4
def p_FieldSpec (t):
  '''FieldSpec : TypeFieldSpec
               | FixedTypeValueFieldSpec
               | VariableTypeValueFieldSpec
               | FixedTypeValueSetFieldSpec
               | ObjectFieldSpec
               | ObjectSetFieldSpec '''
  t[0] = t[1]

# 9.5
def p_TypeFieldSpec (t):
  '''TypeFieldSpec : ucasefieldreference
                   | ucasefieldreference TypeOptionalitySpec '''
  t[0] = TypeFieldSpec()
  t[0].SetName(t[1])

def p_TypeOptionalitySpec_1 (t):
  'TypeOptionalitySpec ::= OPTIONAL'
  pass

def p_TypeOptionalitySpec_2 (t):
  'TypeOptionalitySpec ::= DEFAULT Type'
  pass

# 9.6
def p_FixedTypeValueFieldSpec (t):
  '''FixedTypeValueFieldSpec : lcasefieldreference Type
                             | lcasefieldreference Type UNIQUE
                             | lcasefieldreference Type ValueOptionalitySpec
                             | lcasefieldreference Type UNIQUE ValueOptionalitySpec '''
  t[0] = FixedTypeValueFieldSpec(typ = t[2])
  t[0].SetName(t[1])

def p_ValueOptionalitySpec_1 (t):
  'ValueOptionalitySpec ::= OPTIONAL'
  pass

def p_ValueOptionalitySpec_2 (t):
  'ValueOptionalitySpec ::= DEFAULT Value'
  pass

# 9.8

def p_VariableTypeValueFieldSpec (t):
  '''VariableTypeValueFieldSpec : lcasefieldreference FieldName
                                | lcasefieldreference FieldName ValueOptionalitySpec '''
  t[0] = VariableTypeValueFieldSpec()
  t[0].SetName(t[1])

# 9.9
def p_FixedTypeValueSetFieldSpec (t):
  '''FixedTypeValueSetFieldSpec : ucasefieldreference Type
                                | ucasefieldreference Type ValueSetOptionalitySpec '''
  t[0] = FixedTypeValueSetFieldSpec()
  t[0].SetName(t[1])

def p_ValueSetOptionalitySpec_1 (t):
  'ValueSetOptionalitySpec ::= OPTIONAL'
  pass

def p_ValueSetOptionalitySpec_2 (t):
  'ValueSetOptionalitySpec ::= DEFAULT ValueSet'
  pass

# 9.11
def p_ObjectFieldSpec (t):
  '''ObjectFieldSpec : lcasefieldreference DefinedObjectClass
                     | lcasefieldreference DefinedObjectClass ObjectOptionalitySpec '''
  t[0] = ObjectFieldSpec(cls=t[2])
  t[0].SetName(t[1])
  global obj_class
  obj_class = None

def p_ObjectOptionalitySpec_1 (t):
  'ObjectOptionalitySpec ::= OPTIONAL'
  pass

def p_ObjectOptionalitySpec_2 (t):
  'ObjectOptionalitySpec ::= DEFAULT Object'
  pass

# 9.12
def p_ObjectSetFieldSpec (t):
  '''ObjectSetFieldSpec : ucasefieldreference DefinedObjectClass
                        | ucasefieldreference DefinedObjectClass ObjectSetOptionalitySpec '''
  t[0] = ObjectSetFieldSpec(cls=t[2])
  t[0].SetName(t[1])

def p_ObjectSetOptionalitySpec_1 (t):
  'ObjectSetOptionalitySpec ::= OPTIONAL'
  pass

def p_ObjectSetOptionalitySpec_2 (t):
  'ObjectSetOptionalitySpec ::= DEFAULT ObjectSet'
  pass

# 9.13
def p_PrimitiveFieldName (t):
  '''PrimitiveFieldName : ucasefieldreference
                        | lcasefieldreference '''
  t[0] = t[1]

# 9.13
def p_FieldName_1 (t):
  'FieldName : PrimitiveFieldName'
  t[0] = t[1]

def p_FieldName_2 (t):
  'FieldName : FieldName DOT PrimitiveFieldName'
  t[0] = t[1] + '.' + t[3]

# 11 Information object definition and assignment

# 11.1
def p_ObjectAssignment (t):
  'ObjectAssignment : objectreference DefinedObjectClass ASSIGNMENT Object'
  t[0] = ObjectAssignment (ident = t[1], cls=t[2].val, val=t[4])
  global obj_class
  obj_class = None

# 11.3
def p_Object (t):
  '''Object : DefinedObject
            | ObjectDefn
            | ParameterizedObject'''
  t[0] = t[1]

# 11.4
def p_ObjectDefn (t):
  'ObjectDefn : lbraceobject bodyobject rbraceobject'
  t[0] = t[2]

#  {...} block of object definition
def p_lbraceobject(t):
  'lbraceobject : braceobjectbegin LBRACE'
  t[0] = t[1]

def p_braceobjectbegin(t):
  'braceobjectbegin : '
  global lexer
  global obj_class
  if set_class_syntax(obj_class):
    state = 'INITIAL'
  else:
    lexer.level = 1
    state = 'braceignore'
  lexer.push_state(state)

def p_rbraceobject(t):
  'rbraceobject : braceobjectend RBRACE'
  t[0] = t[2]

def p_braceobjectend(t):
  'braceobjectend : '
  global lexer
  lexer.pop_state()
  set_class_syntax(None)

def p_bodyobject_1 (t):
  'bodyobject : '
  t[0] = { }

def p_bodyobject_2 (t):
  'bodyobject : cls_syntax_list'
  t[0] = t[1]

def p_cls_syntax_list_1 (t):
  'cls_syntax_list : cls_syntax_list cls_syntax'
  t[0] = t[1]
  t[0].update(t[2])

def p_cls_syntax_list_2 (t):
  'cls_syntax_list : cls_syntax'
  t[0] = t[1]

# X.681
def p_cls_syntax_1 (t):
  'cls_syntax : Type IDENTIFIED BY Value'
  t[0] = { get_class_fieled(' ') : t[1], get_class_fieled(' '.join((t[2], t[3]))) : t[4] }

def p_cls_syntax_2 (t):
  'cls_syntax : HAS PROPERTY Value'
  t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] }

# X.880
def p_cls_syntax_3 (t):
  '''cls_syntax : ERRORS ObjectSet
                 | LINKED ObjectSet
                 | RETURN RESULT BooleanValue
                 | SYNCHRONOUS BooleanValue
                 | INVOKE PRIORITY Value
                 | RESULT_PRIORITY Value
                 | PRIORITY Value
                 | ALWAYS RESPONDS BooleanValue
                 | IDEMPOTENT BooleanValue '''
  t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] }

def p_cls_syntax_4 (t):
  '''cls_syntax : ARGUMENT Type
                 | RESULT Type
                 | PARAMETER Type '''
  t[0] = { get_class_fieled(t[1]) : t[2] }

def p_cls_syntax_5 (t):
  'cls_syntax : CODE Value'
  fld = get_class_fieled(t[1]);
  t[0] = { fld : t[2] }
  if isinstance(t[2], ChoiceValue):
    fldt = fld + '.' + t[2].choice
    t[0][fldt] = t[2]

def p_cls_syntax_6 (t):
  '''cls_syntax : ARGUMENT Type OPTIONAL BooleanValue
                 | RESULT Type OPTIONAL BooleanValue
                 | PARAMETER Type OPTIONAL BooleanValue '''
  t[0] = { get_class_fieled(t[1]) : t[2], get_class_fieled(' '.join((t[1], t[3]))) : t[4] }

# 12 Information object set definition and assignment

# 12.1
def p_ObjectSetAssignment (t):
  'ObjectSetAssignment : UCASE_IDENT CLASS_IDENT ASSIGNMENT ObjectSet'
  t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[2], val=t[4])

# 12.3
def p_ObjectSet (t):
  'ObjectSet : lbraceignore rbraceignore'
  t[0] = None

# 14 Notation for the object class field type ---------------------------------

# 14.1
def p_ObjectClassFieldType (t):
  'ObjectClassFieldType : DefinedObjectClass DOT FieldName'
  t[0] = get_type_from_class(t[1], t[3])

# 14.6
def p_ObjectClassFieldValue (t):
  '''ObjectClassFieldValue : OpenTypeFieldVal'''
  t[0] = t[1]

def p_OpenTypeFieldVal (t):
  '''OpenTypeFieldVal : Type COLON Value
                      | NullType COLON NullValue'''
  t[0] = t[3]


# 15 Information from objects -------------------------------------------------

# 15.1

def p_ValueFromObject (t):
  'ValueFromObject : LCASE_IDENT DOT FieldName'
  t[0] = t[1] + '.' + t[3]


# Annex C - The instance-of type ----------------------------------------------

# C.2
def p_InstanceOfType (t):
  'InstanceOfType : INSTANCE OF DefinedObjectClass'
  t[0] = InstanceOfType()


# ---  tables ---

useful_object_class_types = {
  # Annex A
  'TYPE-IDENTIFIER.&id'   : lambda : ObjectIdentifierType(),
  'TYPE-IDENTIFIER.&Type' : lambda : OpenType(),
  # Annex B
  'ABSTRACT-SYNTAX.&id'       : lambda : ObjectIdentifierType(),
  'ABSTRACT-SYNTAX.&Type'     : lambda : OpenType(),
  'ABSTRACT-SYNTAX.&property' : lambda : BitStringType(),
}

object_class_types = { }

object_class_typerefs = { }

object_class_classrefs = { }

# dummy types
class _VariableTypeValueFieldSpec (AnyType):
  pass

class _FixedTypeValueSetFieldSpec (AnyType):
  pass

class_types_creator = {
  'BooleanType'          : lambda : BooleanType(),
  'IntegerType'          : lambda : IntegerType(),
  'ObjectIdentifierType' : lambda : ObjectIdentifierType(),
  'OpenType'             : lambda : OpenType(),
  # dummy types
  '_VariableTypeValueFieldSpec' : lambda : _VariableTypeValueFieldSpec(),
  '_FixedTypeValueSetFieldSpec' : lambda : _FixedTypeValueSetFieldSpec(),
}

class_names = { }

x681_syntaxes = {
  'TYPE-IDENTIFIER' : {
    ' '             : '&Type',
    'IDENTIFIED'    : 'IDENTIFIED',
    #'BY'            : 'BY',
    'IDENTIFIED BY' : '&id',
  },
  'ABSTRACT-SYNTAX' : {
    ' '             : '&Type',
    'IDENTIFIED'    : 'IDENTIFIED',
    #'BY'            : 'BY',
    'IDENTIFIED BY' : '&id',
    'HAS'           : 'HAS',
    'PROPERTY'      : 'PROPERTY',
    'HAS PROPERTY'  : '&property',
  },
}

class_syntaxes_enabled = {
  'TYPE-IDENTIFIER' : True,
  'ABSTRACT-SYNTAX' : True,
}

class_syntaxes = {
  'TYPE-IDENTIFIER' : x681_syntaxes['TYPE-IDENTIFIER'],
  'ABSTRACT-SYNTAX' : x681_syntaxes['ABSTRACT-SYNTAX'],
}

class_current_syntax = None

def get_syntax_tokens(syntaxes):
  tokens = { }
  for s in (syntaxes):
    for k in (list(syntaxes[s].keys())):
      if k.find(' ') < 0:
        tokens[k] = k
        tokens[k] = tokens[k].replace('-', '_')
  return list(tokens.values())

tokens = tokens + get_syntax_tokens(x681_syntaxes)

def set_class_syntax(syntax):
  global class_syntaxes_enabled
  global class_current_syntax
  #print "set_class_syntax", syntax, class_current_syntax
  if class_syntaxes_enabled.get(syntax, False):
    class_current_syntax = syntax
    return True
  else:
    class_current_syntax = None
    return False

def is_class_syntax(name):
  global class_syntaxes
  global class_current_syntax
  #print "is_class_syntax", name, class_current_syntax
  if not class_current_syntax:
    return False
  return name in class_syntaxes[class_current_syntax]

def get_class_fieled(name):
  if not class_current_syntax:
    return None
  return class_syntaxes[class_current_syntax][name]

def is_class_ident(name):
  return name in class_names

def add_class_ident(name):
  #print "add_class_ident", name
  class_names[name] = name

def get_type_from_class(cls, fld):
  flds = fld.split('.')
  if (isinstance(cls, Class_Ref)):
    key = cls.val + '.' + flds[0]
  else:
    key = cls + '.' + flds[0]

  if key in object_class_classrefs:
    return get_type_from_class(object_class_classrefs[key], '.'.join(flds[1:]))

  if key in object_class_typerefs:
    return Type_Ref(val=object_class_typerefs[key])

  creator = lambda : AnyType()
  creator = useful_object_class_types.get(key, creator)
  creator = object_class_types.get(key, creator)
  return creator()

def set_type_to_class(cls, fld, pars):
  #print "set_type_to_class", cls, fld, pars
  key = cls + '.' + fld
  typename = 'OpenType'
  if (len(pars) > 0):
    typename = pars[0]
  else:
    pars.append(typename)
  typeref = None
  if (len(pars) > 1):
    if (isinstance(pars[1], Class_Ref)):
      pars[1] = pars[1].val
    typeref = pars[1]

  msg = None
  if key in object_class_types:
    msg = object_class_types[key]().type
  if key in object_class_typerefs:
    msg = "TypeReference " + object_class_typerefs[key]
  if key in object_class_classrefs:
    msg = "ClassReference " + object_class_classrefs[key]

  if msg == ' '.join(pars):
    msg = None

  if msg:
    msg0 = "Can not define CLASS field %s as '%s'\n" % (key, ' '.join(pars))
    msg1 = "Already defined as '%s'" % (msg)
    raise CompError(msg0 + msg1)

  if (typename == 'ClassReference'):
    if not typeref: return False
    object_class_classrefs[key] = typeref
    return True

  if (typename == 'TypeReference'):
    if not typeref: return False
    object_class_typerefs[key] = typeref
    return True

  creator = class_types_creator.get(typename)
  if creator:
    object_class_types[key] = creator
    return True
  else:
    return False

def import_class_from_module(mod, cls):
  add_class_ident(cls)
  mcls = "$%s$%s" % (mod, cls)
  for k in list(object_class_classrefs.keys()):
    kk = k.split('.', 1)
    if kk[0] == mcls:
      object_class_classrefs[cls + '.' + kk[0]] = object_class_classrefs[k]
  for k in list(object_class_typerefs.keys()):
    kk = k.split('.', 1)
    if kk[0] == mcls:
      object_class_typerefs[cls + '.' + kk[0]] = object_class_typerefs[k]
  for k in list(object_class_types.keys()):
    kk = k.split('.', 1)
    if kk[0] == mcls:
      object_class_types[cls + '.' + kk[0]] = object_class_types[k]

#--- ITU-T Recommendation X.682 -----------------------------------------------

# 8 General constraint specification ------------------------------------------

# 8.1
def p_GeneralConstraint (t):
  '''GeneralConstraint : UserDefinedConstraint
                       | TableConstraint
                       | ContentsConstraint'''
  t[0] = t[1]

# 9 User-defined constraints --------------------------------------------------

# 9.1
def p_UserDefinedConstraint (t):
  'UserDefinedConstraint : CONSTRAINED BY LBRACE UserDefinedConstraintParameterList RBRACE'
  t[0] = Constraint(type = 'UserDefined', subtype = t[4])

def p_UserDefinedConstraintParameterList_1 (t):
  'UserDefinedConstraintParameterList : '
  t[0] = []

def p_UserDefinedConstraintParameterList_2 (t):
  'UserDefinedConstraintParameterList : UserDefinedConstraintParameter'
  t[0] = [t[1]]

def p_UserDefinedConstraintParameterList_3 (t):
  'UserDefinedConstraintParameterList : UserDefinedConstraintParameterList COMMA UserDefinedConstraintParameter'
  t[0] = t[1] + [t[3]]

# 9.3
def p_UserDefinedConstraintParameter (t):
  'UserDefinedConstraintParameter : Type'
  t[0] = t[1]

# 10 Table constraints, including component relation constraints --------------

# 10.3
def p_TableConstraint (t):
  '''TableConstraint : SimpleTableConstraint
                     | ComponentRelationConstraint'''
  t[0] = Constraint(type = 'Table', subtype = t[1])

def p_SimpleTableConstraint (t):
  'SimpleTableConstraint : LBRACE UCASE_IDENT RBRACE'
  t[0] = t[2]

# 10.7
def p_ComponentRelationConstraint (t):
  'ComponentRelationConstraint : LBRACE UCASE_IDENT RBRACE LBRACE AtNotations RBRACE'
  t[0] = t[2] + str(t[5])

def p_AtNotations_1 (t):
  'AtNotations : AtNotation'
  t[0] = [t[1]]

def p_AtNotations_2 (t):
  'AtNotations : AtNotations COMMA  AtNotation'
  t[0] = t[1] + [t[3]]

def p_AtNotation_1 (t):
  'AtNotation : AT ComponentIdList'
  t[0] = '@' + t[2]

def p_AtNotation_2 (t):
  'AtNotation : AT DOT Level ComponentIdList'
  t[0] = '@.' + t[3] + t[4]

def p_Level_1 (t):
  'Level : DOT Level'
  t[0] = '.' + t[2]

def p_Level_2 (t):
  'Level : '
  t[0] = ''

def p_ComponentIdList_1 (t):
  'ComponentIdList : LCASE_IDENT'
  t[0] = t[1]

def p_ComponentIdList_2 (t):
  'ComponentIdList : ComponentIdList DOT LCASE_IDENT'
  t[0] = t[1] + '.' + t[3]

# 11 Contents constraints -----------------------------------------------------

# 11.1
def p_ContentsConstraint (t):
  'ContentsConstraint : CONTAINING type_ref'
  t[0] = Constraint(type = 'Contents', subtype = t[2])


#--- ITU-T Recommendation X.683 -----------------------------------------------

# 8 Parameterized assignments -------------------------------------------------

# 8.1
def p_ParameterizedAssignment (t):
  '''ParameterizedAssignment : ParameterizedTypeAssignment
                             | ParameterizedObjectClassAssignment
                             | ParameterizedObjectAssignment
                             | ParameterizedObjectSetAssignment'''
  t[0] = t[1]

# 8.2
def p_ParameterizedTypeAssignment (t):
  'ParameterizedTypeAssignment : UCASE_IDENT ParameterList ASSIGNMENT Type'
  t[0] = t[4]
  t[0].SetName(t[1])  # t[0].SetName(t[1] + 'xxx')

def p_ParameterizedObjectClassAssignment (t):
  '''ParameterizedObjectClassAssignment : CLASS_IDENT ParameterList ASSIGNMENT ObjectClass
                                        | UCASE_IDENT ParameterList ASSIGNMENT ObjectClass'''
  t[0] = t[4]
  t[0].SetName(t[1])
  if isinstance(t[0], ObjectClassDefn):
    t[0].reg_types()

def p_ParameterizedObjectAssignment (t):
  'ParameterizedObjectAssignment : objectreference ParameterList DefinedObjectClass ASSIGNMENT Object'
  t[0] = ObjectAssignment (ident = t[1], cls=t[3].val, val=t[5])
  global obj_class
  obj_class = None

def p_ParameterizedObjectSetAssignment (t):
  'ParameterizedObjectSetAssignment : UCASE_IDENT ParameterList DefinedObjectClass ASSIGNMENT ObjectSet'
  t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[3].val, val=t[5])

# 8.3
def p_ParameterList (t):
  'ParameterList : lbraceignore rbraceignore'

#def p_ParameterList (t):
#  'ParameterList : LBRACE Parameters RBRACE'
#  t[0] = t[2]

#def p_Parameters_1 (t):
#  'Parameters : Parameter'
#  t[0] = [t[1]]

#def p_Parameters_2 (t):
#  'Parameters : Parameters COMMA Parameter'
#  t[0] = t[1] + [t[3]]

#def p_Parameter_1 (t):
#  'Parameter : Type COLON Reference'
#  t[0] = [t[1], t[3]]

#def p_Parameter_2 (t):
#  'Parameter : Reference'
#  t[0] = t[1]


# 9 Referencing parameterized definitions -------------------------------------

# 9.1
def p_ParameterizedReference (t):
  'ParameterizedReference : Reference LBRACE RBRACE'
  t[0] = t[1]
  #t[0].val += 'xxx'

# 9.2
def p_ParameterizedType (t):
  'ParameterizedType : type_ref ActualParameterList'
  t[0] = t[1]
  #t[0].val += 'xxx'


def p_ParameterizedObjectClass (t):
  'ParameterizedObjectClass : DefinedObjectClass ActualParameterList'
  t[0] = t[1]
  #t[0].val += 'xxx'

def p_ParameterizedObject (t):
  'ParameterizedObject : DefinedObject ActualParameterList'
  t[0] = t[1]
  #t[0].val += 'xxx'

# 9.5
def p_ActualParameterList (t):
  'ActualParameterList : lbraceignore rbraceignore'

#def p_ActualParameterList (t):
#  'ActualParameterList : LBRACE ActualParameters RBRACE'
#  t[0] = t[2]

#def p_ActualParameters_1 (t):
#  'ActualParameters : ActualParameter'
#  t[0] = [t[1]]

#def p_ActualParameters_2 (t):
#  'ActualParameters : ActualParameters COMMA ActualParameter'
#  t[0] = t[1] + [t[3]]

#def p_ActualParameter (t):
#  '''ActualParameter : Type
#                     | Value'''
#  t[0] = t[1]


#--- ITU-T Recommendation X.880 -----------------------------------------------

x880_classes = {
  'OPERATION' : {
    '&ArgumentType'         : [],
    '&argumentTypeOptional' : [ 'BooleanType' ],
    '&returnResult'         : [ 'BooleanType' ],
    '&ResultType'           : [],
    '&resultTypeOptional'   : [ 'BooleanType' ],
    '&Errors'               : [ 'ClassReference', 'ERROR' ],
    '&Linked'               : [ 'ClassReference', 'OPERATION' ],
    '&synchronous'          : [ 'BooleanType' ],
    '&idempotent'           : [ 'BooleanType' ],
    '&alwaysReturns'        : [ 'BooleanType' ],
    '&InvokePriority'       : [ '_FixedTypeValueSetFieldSpec' ],
    '&ResultPriority'       : [ '_FixedTypeValueSetFieldSpec' ],
    '&operationCode'        : [ 'TypeReference', 'Code' ],
  },
  'ERROR' : {
    '&ParameterType'         : [],
    '&parameterTypeOptional' : [ 'BooleanType' ],
    '&ErrorPriority'         : [ '_FixedTypeValueSetFieldSpec' ],
    '&errorCode'             : [ 'TypeReference', 'Code' ],
  },
  'OPERATION-PACKAGE' : {
    '&Both'     : [ 'ClassReference', 'OPERATION' ],
    '&Consumer' : [ 'ClassReference', 'OPERATION' ],
    '&Supplier' : [ 'ClassReference', 'OPERATION' ],
    '&id'       : [ 'ObjectIdentifierType' ],
  },
  'CONNECTION-PACKAGE' : {
    '&bind'               : [ 'ClassReference', 'OPERATION' ],
    '&unbind'             : [ 'ClassReference', 'OPERATION' ],
    '&responderCanUnbind' : [ 'BooleanType' ],
    '&unbindCanFail'      : [ 'BooleanType' ],
    '&id'                 : [ 'ObjectIdentifierType' ],
  },
  'CONTRACT' : {
    '&connection'          : [ 'ClassReference', 'CONNECTION-PACKAGE' ],
    '&OperationsOf'        : [ 'ClassReference', 'OPERATION-PACKAGE' ],
    '&InitiatorConsumerOf' : [ 'ClassReference', 'OPERATION-PACKAGE' ],
    '&InitiatorSupplierOf' : [ 'ClassReference', 'OPERATION-PACKAGE' ],
    '&id'                  : [ 'ObjectIdentifierType' ],
  },
  'ROS-OBJECT-CLASS' : {
    '&Is'                   : [ 'ClassReference', 'ROS-OBJECT-CLASS' ],
    '&Initiates'            : [ 'ClassReference', 'CONTRACT' ],
    '&Responds'             : [ 'ClassReference', 'CONTRACT' ],
    '&InitiatesAndResponds' : [ 'ClassReference', 'CONTRACT' ],
    '&id'                   : [ 'ObjectIdentifierType' ],
  },
}

x880_syntaxes = {
  'OPERATION' : {
    'ARGUMENT'       : '&ArgumentType',
    'ARGUMENT OPTIONAL' : '&argumentTypeOptional',
    'RESULT'         : '&ResultType',
    'RESULT OPTIONAL' : '&resultTypeOptional',
    'RETURN'         : 'RETURN',
    'RETURN RESULT'  : '&returnResult',
    'ERRORS'         : '&Errors',
    'LINKED'         : '&Linked',
    'SYNCHRONOUS'    : '&synchronous',
    'IDEMPOTENT'     : '&idempotent',
    'ALWAYS'         : 'ALWAYS',
    'RESPONDS'       : 'RESPONDS',
    'ALWAYS RESPONDS' : '&alwaysReturns',
    'INVOKE'         : 'INVOKE',
    'PRIORITY'       : 'PRIORITY',
    'INVOKE PRIORITY' : '&InvokePriority',
    'RESULT-PRIORITY': '&ResultPriority',
    'CODE'           : '&operationCode',
  },
  'ERROR' : {
    'PARAMETER'      : '&ParameterType',
    'PARAMETER OPTIONAL' : '&parameterTypeOptional',
    'PRIORITY'       : '&ErrorPriority',
    'CODE'           : '&errorCode',
  },
#  'OPERATION-PACKAGE' : {
#  },
#  'CONNECTION-PACKAGE' : {
#  },
#  'CONTRACT' : {
#  },
#  'ROS-OBJECT-CLASS' : {
#  },
}

def x880_module_begin():
  #print "x880_module_begin()"
  for name in list(x880_classes.keys()):
    add_class_ident(name)

def x880_import(name):
  if name in x880_syntaxes:
    class_syntaxes_enabled[name] = True
    class_syntaxes[name] = x880_syntaxes[name]
  if name in x880_classes:
    add_class_ident(name)
    for f in (list(x880_classes[name].keys())):
      set_type_to_class(name, f, x880_classes[name][f])

tokens = tokens + get_syntax_tokens(x880_syntaxes)

#  {...} OID value
#def p_lbrace_oid(t):
#  'lbrace_oid : brace_oid_begin LBRACE'
#  t[0] = t[1]

#def p_brace_oid_begin(t):
#  'brace_oid_begin : '
#  global in_oid
#  in_oid = True

#def p_rbrace_oid(t):
#  'rbrace_oid : brace_oid_end RBRACE'
#  t[0] = t[2]

#def p_brace_oid_end(t):
#  'brace_oid_end : '
#  global in_oid
#  in_oid = False

#  {...} block to be ignored
def p_lbraceignore(t):
  'lbraceignore : braceignorebegin LBRACE'
  t[0] = t[1]

def p_braceignorebegin(t):
  'braceignorebegin : '
  global lexer
  lexer.level = 1
  lexer.push_state('braceignore')

def p_rbraceignore(t):
  'rbraceignore : braceignoreend RBRACE'
  t[0] = t[2]

def p_braceignoreend(t):
  'braceignoreend : '
  global lexer
  lexer.pop_state()

def p_error(t):
  global input_file
  raise ParseError(t, input_file)

def p_pyquote (t):
    '''pyquote : PYQUOTE'''
    t[0] = PyQuote (val = t[1])


def testlex (s):
    lexer.input (s)
    while True:
        token = lexer.token ()
        if not token:
            break
        print token


def do_module (ast, defined_dict):
    assert (ast.type == 'Module')
    ctx = Ctx (defined_dict)
    print ast.to_python (ctx)
    print ctx.output_assignments ()
    print ctx.output_pyquotes ()

def eth_do_module (ast, ectx):
    assert (ast.type == 'Module')
    if ectx.dbg('s'): print ast.str_depth(0)
    ast.to_eth(ectx)

def testyacc(s, fn, defined_dict):
    ast = yacc.parse(s, debug=0)
    time_str = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
    print """#!/usr/bin/env python
# Auto-generated from %s at %s
from PyZ3950 import asn1""" % (fn, time_str)
    for module in ast:
      eth_do_module (module, defined_dict)


# Wireshark compiler
def eth_usage():
  print """
asn2wrs [-h|?] [-d dbg] [-b] [-p proto] [-c cnf_file] [-e] input_file(s) ...
  -h|?          : Usage
  -b            : BER (default is PER)
  -u            : Unaligned (default is aligned)
  -p proto      : Protocol name (implies -S). Default is module-name
                  from input_file (renamed by #.MODULE if present)
  -o name       : Output files name core (default is <proto>)
  -O dir        : Output directory for dissector
  -c cnf_file   : Conformance file
  -I path       : Path for conformance file includes
  -e            : Create conformance file for exported types
  -E            : Just create conformance file for exported types
  -S            : Single output for multiple modules
  -s template   : Single file output (template is input file
                  without .c/.h extension)
  -k            : Keep intermediate files though single file output is used
  -L            : Suppress #line directive from .cnf file
  -D dir        : Directory for input_file(s) (default: '.')
  -C            : Add check for SIZE constraints
  -r prefix     : Remove the prefix from type names

  input_file(s) : Input ASN.1 file(s)

  -d dbg        : Debug output, dbg = [l][y][p][s][a][t][c][m][o]
                  l - lex
                  y - yacc
                  p - parsing
                  s - internal ASN.1 structure
                  a - list of assignments
                  t - tables
                  c - conformance values
                  m - list of compiled modules with dependency
                  o - list of output files
"""

def eth_main():
  global input_file
  global g_conform
  global lexer
  print "ASN.1 to Wireshark dissector compiler";
  try:
    opts, args = getopt.getopt(sys.argv[1:], "h?d:D:buXp:FTo:O:c:I:eESs:kLCr:");
  except getopt.GetoptError:
    eth_usage(); sys.exit(2)
  if len(args) < 1:
    eth_usage(); sys.exit(2)

  conform = EthCnf()
  conf_to_read = None
  output = EthOut()
  ectx = EthCtx(conform, output)
  ectx.encoding = 'per'
  ectx.proto_opt = None
  ectx.fld_opt = {}
  ectx.tag_opt = False
  ectx.outnm_opt = None
  ectx.aligned = True
  ectx.dbgopt = ''
  ectx.new = True
  ectx.expcnf = False
  ectx.justexpcnf = False
  ectx.merge_modules = False
  ectx.group_by_prot = False
  ectx.conform.last_group = 0
  ectx.conform.suppress_line = False;
  ectx.output.outnm = None
  ectx.output.single_file = None
  ectx.constraints_check = False;
  for o, a in opts:
    if o in ("-h", "-?"):
      eth_usage(); sys.exit(2)
    if o in ("-c",):
      conf_to_read = a
    if o in ("-I",):
      ectx.conform.include_path.append(a)
    if o in ("-E",):
      ectx.expcnf = True
      ectx.justexpcnf = True
    if o in ("-D",):
      ectx.srcdir = a
    if o in ("-C",):
      ectx.constraints_check = True
    if o in ("-X",):
        warnings.warn("Command line option -X is obsolete and can be removed")
    if o in ("-T",):
        warnings.warn("Command line option -T is obsolete and can be removed")

  if conf_to_read:
    ectx.conform.read(conf_to_read)

  for o, a in opts:
    if o in ("-h", "-?", "-c", "-I", "-E", "-D", "-C", "-X", "-T"):
      pass  # already processed
    else:
      par = []
      if a: par.append(a)
      ectx.conform.set_opt(o, par, "commandline", 0)

  (ld, yd, pd) = (0, 0, 0);
  if ectx.dbg('l'): ld = 1
  if ectx.dbg('y'): yd = 1
  if ectx.dbg('p'): pd = 2
  lexer = lex.lex(debug=ld)
  yacc.yacc(method='LALR', debug=yd)
  g_conform = ectx.conform
  ast = []
  for fn in args:
    input_file = fn
    lexer.lineno = 1
    if (ectx.srcdir): fn = ectx.srcdir + '/' + fn
    f = open (fn, "r")
    ast.extend(yacc.parse(f.read(), lexer=lexer, debug=pd))
    f.close ()
  ectx.eth_clean()
  if (ectx.merge_modules):  # common output for all module
    ectx.eth_clean()
    for module in ast:
      eth_do_module(module, ectx)
    ectx.eth_prepare()
    ectx.eth_do_output()
  elif (ectx.groups()):  # group by protocols/group
    groups = []
    pr2gr = {}
    if (ectx.group_by_prot):  # group by protocols
      for module in ast:
        prot = module.get_proto(ectx)
        if prot not in pr2gr:
          pr2gr[prot] = len(groups)
          groups.append([])
        groups[pr2gr[prot]].append(module)
    else:  # group by groups
      pass
    for gm in (groups):
      ectx.eth_clean()
      for module in gm:
        eth_do_module(module, ectx)
      ectx.eth_prepare()
      ectx.eth_do_output()
  else:   # output for each module
    for module in ast:
      ectx.eth_clean()
      eth_do_module(module, ectx)
      ectx.eth_prepare()
      ectx.eth_do_output()

  if ectx.dbg('m'):
    ectx.dbg_modules()

  if ectx.dbg('c'):
    ectx.conform.dbg_print()
  if not ectx.justexpcnf:
    ectx.conform.unused_report()

  if ectx.dbg('o'):
    ectx.output.dbg_print()
  ectx.output.make_single_file()


# Python compiler
def main():
    testfn = testyacc
    if len (sys.argv) == 1:
        while True:
            s = raw_input ('Query: ')
            if len (s) == 0:
                break
            testfn (s, 'console', {})
    else:
        defined_dict = {}
        for fn in sys.argv [1:]:
            f = open (fn, "r")
            testfn (f.read (), fn, defined_dict)
            f.close ()
            lexer.lineno = 1


#--- BODY ---------------------------------------------------------------------

if __name__ == '__main__':
  if (os.path.splitext(os.path.basename(sys.argv[0]))[0].lower() in ('asn2wrs', 'asn2eth')):
    eth_main()
  else:
    main()

#------------------------------------------------------------------------------