aboutsummaryrefslogtreecommitdiffstats
path: root/lib/dialyzer/test/r9c_SUITE_data/src/asn1/asn1ct_check.erl
blob: 2f0ada122e952723a7216529208d1dfc966098aa (plain) (blame)
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
%% ``The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved via the world wide web at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
%% AB. All Rights Reserved.''
%%
%%     $Id: asn1ct_check.erl,v 1.1 2008/12/17 09:53:29 mikpe Exp $
%%
-module(asn1ct_check).

%% Main Module for ASN.1 compile time functions

%-compile(export_all).
-export([check/2,storeindb/1]).
-include("asn1_records.hrl").
%%% The tag-number for universal types
-define(N_BOOLEAN, 1).
-define(N_INTEGER, 2).
-define(N_BIT_STRING, 3).
-define(N_OCTET_STRING, 4).
-define(N_NULL, 5).
-define(N_OBJECT_IDENTIFIER, 6).
-define(N_OBJECT_DESCRIPTOR, 7).
-define(N_EXTERNAL, 8). % constructed
-define(N_INSTANCE_OF,8).
-define(N_REAL, 9).
-define(N_ENUMERATED, 10).
-define(N_EMBEDDED_PDV, 11). % constructed
-define(N_SEQUENCE, 16).
-define(N_SET, 17).
-define(N_NumericString, 18).
-define(N_PrintableString, 19).
-define(N_TeletexString, 20).
-define(N_VideotexString, 21).
-define(N_IA5String, 22).
-define(N_UTCTime, 23).
-define(N_GeneralizedTime, 24).
-define(N_GraphicString, 25).
-define(N_VisibleString, 26).
-define(N_GeneralString, 27).
-define(N_UniversalString, 28).
-define(N_CHARACTER_STRING, 29). % constructed
-define(N_BMPString, 30).

-define(TAG_PRIMITIVE(Num),
	case S#state.erule of
	    ber_bin_v2 ->
		#tag{class='UNIVERSAL',number=Num,type='IMPLICIT',form=0};
	    _ -> []
	end).
-define(TAG_CONSTRUCTED(Num),
	case S#state.erule of
	    ber_bin_v2 ->
		#tag{class='UNIVERSAL',number=Num,type='IMPLICIT',form=32};
	    _ -> []
	end).

-record(newt,{type=unchanged,tag=unchanged,constraint=unchanged,inlined=no}). % used in check_type to update type and tag
-record(newv,{type=unchanged,value=unchanged}). % used in check_value to update type and value

check(S,{Types,Values,ParameterizedTypes,Classes,Objects,ObjectSets}) ->
    %%Predicates used to filter errors
    TupleIs = fun({T,_},T) -> true;
		 (_,_) -> false
	      end,
    IsClass = fun(X) -> TupleIs(X,asn1_class) end,
    IsObjSet = fun(X) -> TupleIs(X,objectsetdef) end,
    IsPObjSet = fun(X) -> TupleIs(X,pobjectsetdef) end,
    IsObject = fun(X) -> TupleIs(X,objectdef) end,
    IsValueSet = fun(X) -> TupleIs(X,valueset) end,
    Element2 = fun(X) -> element(2,X) end,

    _Perror = checkp(S,ParameterizedTypes,[]), % must do this before the templates are used
    Terror = checkt(S,Types,[]),

    %% get parameterized object sets sent to checkt/3
    %% and update Terror

    {PObjSetNames1,Terror2} = filter_errors(IsPObjSet,Terror),

    Verror = checkv(S,Values ++ ObjectSets,[]), %value sets may be parsed as object sets

     %% get information object classes wrongly sent to checkt/3
     %% and update Terror2

    {AddClasses,Terror3} = filter_errors(IsClass,Terror2),

    NewClasses = Classes++AddClasses,

    Cerror = checkc(S,NewClasses,[]),

     %% get object sets incorrectly sent to checkv/3
     %% and update Verror

    {ObjSetNames,Verror2} = filter_errors(IsObjSet,Verror),

     %% get parameterized object sets incorrectly sent to checkv/3
     %% and update Verror2

    {PObjSetNames,Verror3} = filter_errors(IsPObjSet,Verror2),

     %% get objects incorrectly sent to checkv/3
     %% and update Verror3

    {ObjectNames,Verror4} = filter_errors(IsObject,Verror3),

    NewObjects = Objects++ObjectNames,
    NewObjectSets = ObjSetNames ++ PObjSetNames ++ PObjSetNames1,

     %% get value sets
     %% and update Verror4

    {ValueSetNames,Verror5} = filter_errors(IsValueSet,Verror4),

    asn1ct:create_ets_table(inlined_objects,[named_table]),
    {Oerror,ExclO,ExclOS} = checko(S,NewObjects ++
				   NewObjectSets,
				   [],[],[]),
    InlinedObjTuples = ets:tab2list(inlined_objects),
    InlinedObjects = lists:map(Element2,InlinedObjTuples),
    ets:delete(inlined_objects),

    Exporterror = check_exports(S,S#state.module),
    case {Terror3,Verror5,Cerror,Oerror,Exporterror} of
	{[],[],[],[],[]} ->
	    ContextSwitchTs = context_switch_in_spec(),
	    InstanceOf = instance_of_in_spec(),
	    NewTypes = lists:subtract(Types,AddClasses) ++ ContextSwitchTs
		++ InstanceOf,
	    NewValues = lists:subtract(Values,PObjSetNames++ObjectNames++
				       ValueSetNames),
	    {ok,
	     {NewTypes,NewValues,ParameterizedTypes,
	      NewClasses,NewObjects,NewObjectSets},
	     {NewTypes,NewValues,ParameterizedTypes,NewClasses,
	      lists:subtract(NewObjects,ExclO)++InlinedObjects,
	      lists:subtract(NewObjectSets,ExclOS)}};
	_ ->{error,{asn1,lists:flatten([Terror3,Verror5,Cerror,
					Oerror,Exporterror])}}
    end.

context_switch_in_spec() ->
    L = [{external,'EXTERNAL'},
	 {embedded_pdv,'EMBEDDED PDV'},
	 {character_string,'CHARACTER STRING'}],
    F = fun({T,TName},Acc) ->
		case get(T) of
		    generate -> erase(T),
				[TName|Acc];
		    _ -> Acc
		end
	end,
    lists:foldl(F,[],L).

instance_of_in_spec() ->
    case get(instance_of) of
	generate ->
	    erase(instance_of),
	    ['INSTANCE OF'];
	_ ->
	    []
    end.

filter_errors(Pred,ErrorList) ->
    Element2 = fun(X) -> element(2,X) end,
    RemovedTupleElements = lists:filter(Pred,ErrorList),
    RemovedNames = lists:map(Element2,RemovedTupleElements),
    %% remove value set name tuples from Verror
    RestErrors = lists:subtract(ErrorList,RemovedTupleElements),
    {RemovedNames,RestErrors}.


check_exports(S,Module = #module{}) ->
    case Module#module.exports of
	{exports,[]} ->
	    [];
	{exports,all} ->
	    [];
	{exports,ExportList} when list(ExportList) ->
	    IsNotDefined =
		fun(X) ->
			case catch get_referenced_type(S,X) of
			    {error,{asn1,_}} ->
				true;
			    _ -> false
			end
		end,
	    case lists:filter(IsNotDefined,ExportList) of
		[] ->
		    [];
		NoDefExp ->
		    GetName =
			fun(T = #'Externaltypereference'{type=N})->
				%%{exported,undefined,entity,N}
				NewS=S#state{type=T,tname=N},
				error({export,"exported undefined entity",NewS})
			end,
		    lists:map(GetName,NoDefExp)
	    end
    end.

checkt(S,[Name|T],Acc) ->
    %%io:format("check_typedef:~p~n",[Name]),
    Result =
	case asn1_db:dbget(S#state.mname,Name) of
	    undefined ->
		error({type,{internal_error,'???'},S});
	    Type when record(Type,typedef) ->
		NewS = S#state{type=Type,tname=Name},
		case catch(check_type(NewS,Type,Type#typedef.typespec)) of
		    {error,Reason} ->
			error({type,Reason,NewS});
		    {'EXIT',Reason} ->
			error({type,{internal_error,Reason},NewS});
		    {asn1_class,_ClassDef} ->
			{asn1_class,Name};
		    pobjectsetdef ->
			{pobjectsetdef,Name};
		    pvalueset ->
			{pvalueset,Name};
		    Ts ->
			case Type#typedef.checked of
			    true -> % already checked and updated
				ok;
			    _ ->
				NewTypeDef = Type#typedef{checked=true,typespec = Ts},
				%io:format("checkt:dbput:~p, ~p~n",[S#state.mname,NewTypeDef#typedef.name]),
				asn1_db:dbput(NewS#state.mname,Name,NewTypeDef), % update the type
				ok
			end
		end
	end,
    case Result of
	ok ->
	    checkt(S,T,Acc);
	_ ->
	    checkt(S,T,[Result|Acc])
    end;
checkt(S,[],Acc) ->
    case check_contextswitchingtypes(S,[]) of
	[] ->
	    lists:reverse(Acc);
	L ->
	    checkt(S,L,Acc)
    end.

check_contextswitchingtypes(S,Acc) ->
    CSTList=[{external,'EXTERNAL'},
	     {embedded_pdv,'EMBEDDED PDV'},
	     {character_string,'CHARACTER STRING'}],
    check_contextswitchingtypes(S,CSTList,Acc).

check_contextswitchingtypes(S,[{T,TName}|Ts],Acc) ->
     case get(T) of
	unchecked ->
	    put(T,generate),
	    check_contextswitchingtypes(S,Ts,[TName|Acc]);
	_ ->
	    check_contextswitchingtypes(S,Ts,Acc)
     end;
check_contextswitchingtypes(_,[],Acc) ->
    Acc.

checkv(S,[Name|T],Acc) ->
    %%io:format("check_valuedef:~p~n",[Name]),
    Result = case asn1_db:dbget(S#state.mname,Name) of
		 undefined -> error({value,{internal_error,'???'},S});
		 Value when record(Value,valuedef);
			    record(Value,typedef); %Value set may be parsed as object set.
			    record(Value,pvaluedef);
			    record(Value,pvaluesetdef) ->
		     NewS = S#state{value=Value},
		     case catch(check_value(NewS,Value)) of
			 {error,Reason} ->
			     error({value,Reason,NewS});
			 {'EXIT',Reason} ->
			     error({value,{internal_error,Reason},NewS});
			 {pobjectsetdef} ->
			     {pobjectsetdef,Name};
			 {objectsetdef} ->
			     {objectsetdef,Name};
			 {objectdef} ->
			     %% this is an object, save as typedef
			     #valuedef{checked=C,pos=Pos,name=N,type=Type,
				       value=Def}=Value,
%			     Currmod = S#state.mname,
%			     #type{def=
%				   #'Externaltypereference'{module=Mod,
%							    type=CName}} = Type,
			     ClassName =
				 Type#type.def,
% 				 case Mod of
% 				     Currmod ->
% 					 {objectclassname,CName};
% 				     _ ->
% 					 {objectclassname,Mod,CName}
% 				 end,
			     NewSpec = #'Object'{classname=ClassName,
						 def=Def},
			     NewDef = #typedef{checked=C,pos=Pos,name=N,
					       typespec=NewSpec},
			     asn1_db:dbput(NewS#state.mname,Name,NewDef),
			     {objectdef,Name};
			 {valueset,VSet} ->
			     Pos = asn1ct:get_pos_of_def(Value),
			     CheckedVSDef = #typedef{checked=true,pos=Pos,
						     name=Name,typespec=VSet},
			     asn1_db:dbput(NewS#state.mname,Name,CheckedVSDef),
			     {valueset,Name};
			 V ->
			     %% update the valuedef
			     asn1_db:dbput(NewS#state.mname,Name,V),
			     ok
		     end
	     end,
    case Result of
	ok ->
	    checkv(S,T,Acc);
	_ ->
	    checkv(S,T,[Result|Acc])
    end;
checkv(_S,[],Acc) ->
    lists:reverse(Acc).


checkp(S,[Name|T],Acc) ->
    %io:format("check_ptypedef:~p~n",[Name]),
    Result = case asn1_db:dbget(S#state.mname,Name) of
	undefined ->
	    error({type,{internal_error,'???'},S});
	Type when record(Type,ptypedef) ->
	    NewS = S#state{type=Type,tname=Name},
	    case catch(check_ptype(NewS,Type,Type#ptypedef.typespec)) of
		{error,Reason} ->
		    error({type,Reason,NewS});
		{'EXIT',Reason} ->
		    error({type,{internal_error,Reason},NewS});
		{asn1_class,_ClassDef} ->
		    {asn1_class,Name};
		Ts ->
		    NewType = Type#ptypedef{checked=true,typespec = Ts},
		    asn1_db:dbput(NewS#state.mname,Name,NewType), % update the type
		    ok
	    end
	     end,
    case Result of
	ok ->
	    checkp(S,T,Acc);
	_ ->
	    checkp(S,T,[Result|Acc])
    end;
checkp(_S,[],Acc) ->
    lists:reverse(Acc).




checkc(S,[Name|Cs],Acc) ->
    Result =
	case asn1_db:dbget(S#state.mname,Name) of
	    undefined ->
		error({class,{internal_error,'???'},S});
	    Class  ->
		ClassSpec = if
			       record(Class,classdef) ->
				   Class#classdef.typespec;
			       record(Class,typedef) ->
				   Class#typedef.typespec
			   end,
		NewS = S#state{type=Class,tname=Name},
		case catch(check_class(NewS,ClassSpec)) of
		    {error,Reason} ->
			error({class,Reason,NewS});
		    {'EXIT',Reason} ->
			error({class,{internal_error,Reason},NewS});
		    C ->
			%% update the classdef
			NewClass =
			    if
				record(Class,classdef) ->
				    Class#classdef{checked=true,typespec=C};
				record(Class,typedef) ->
				    #classdef{checked=true,name=Name,typespec=C}
			    end,
			asn1_db:dbput(NewS#state.mname,Name,NewClass),
			ok
		end
	end,
    case Result of
	ok ->
	    checkc(S,Cs,Acc);
	_ ->
	    checkc(S,Cs,[Result|Acc])
    end;
checkc(_S,[],Acc) ->
%%    include_default_class(S#state.mname),
    lists:reverse(Acc).

checko(S,[Name|Os],Acc,ExclO,ExclOS) ->
    Result =
	case asn1_db:dbget(S#state.mname,Name) of
	    undefined ->
		error({type,{internal_error,'???'},S});
	    Object when record(Object,typedef) ->
		NewS = S#state{type=Object,tname=Name},
		case catch(check_object(NewS,Object,Object#typedef.typespec)) of
		    {error,Reason} ->
			error({type,Reason,NewS});
		    {'EXIT',Reason} ->
			error({type,{internal_error,Reason},NewS});
		    {asn1,Reason} ->
			error({type,Reason,NewS});
		    O ->
			NewObj = Object#typedef{checked=true,typespec=O},
			asn1_db:dbput(NewS#state.mname,Name,NewObj),
			if
			    record(O,'Object') ->
				case O#'Object'.gen of
				    true ->
					{ok,ExclO,ExclOS};
				    false ->
					{ok,[Name|ExclO],ExclOS}
				end;
			    record(O,'ObjectSet') ->
				case O#'ObjectSet'.gen of
				    true ->
					{ok,ExclO,ExclOS};
				    false ->
					{ok,ExclO,[Name|ExclOS]}
				end
			end
		end;
	    PObject when record(PObject,pobjectdef) ->
		NewS = S#state{type=PObject,tname=Name},
		case (catch check_pobject(NewS,PObject)) of
		    {error,Reason} ->
			error({type,Reason,NewS});
		    {'EXIT',Reason} ->
			error({type,{internal_error,Reason},NewS});
		    {asn1,Reason} ->
			error({type,Reason,NewS});
		    PO ->
			NewPObj = PObject#pobjectdef{def=PO},
			asn1_db:dbput(NewS#state.mname,Name,NewPObj),
			{ok,[Name|ExclO],ExclOS}
		end;
	    PObjSet when record(PObjSet,pvaluesetdef) ->
		%% this is a parameterized object set. Might be a parameterized
		%% value set, couldn't it?
		NewS = S#state{type=PObjSet,tname=Name},
		case (catch check_pobjectset(NewS,PObjSet)) of
		    {error,Reason} ->
			error({type,Reason,NewS});
		    {'EXIT',Reason} ->
			error({type,{internal_error,Reason},NewS});
		    {asn1,Reason} ->
			error({type,Reason,NewS});
		    POS ->
			%%NewPObjSet = PObjSet#pvaluesetdef{valueset=POS},
			asn1_db:dbput(NewS#state.mname,Name,POS),
			{ok,ExclO,[Name|ExclOS]}
		end
	end,
    case Result of
	{ok,NewExclO,NewExclOS} ->
	    checko(S,Os,Acc,NewExclO,NewExclOS);
	_ ->
	    checko(S,Os,[Result|Acc],ExclO,ExclOS)
    end;
checko(_S,[],Acc,ExclO,ExclOS) ->
    {lists:reverse(Acc),lists:reverse(ExclO),lists:reverse(ExclOS)}.

check_class(S,CDef=#classdef{checked=Ch,name=Name,typespec=TS}) ->
    case Ch of
	true -> TS;
	idle -> TS;
	_ ->
	    NewCDef = CDef#classdef{checked=idle},
	    asn1_db:dbput(S#state.mname,Name,NewCDef),
	    CheckedTS = check_class(S,TS),
	    asn1_db:dbput(S#state.mname,Name,
			  NewCDef#classdef{checked=true,
					   typespec=CheckedTS}),
	    CheckedTS
    end;
check_class(S = #state{mname=M,tname=T},ClassSpec)
  when record(ClassSpec,type) ->
    Def = ClassSpec#type.def,
    case Def of
	#'Externaltypereference'{module=M,type=T} ->
	    #objectclass{fields=Def}; % in case of recursive definitions
	Tref when record(Tref,'Externaltypereference') ->
	    {_,RefType} = get_referenced_type(S,Tref),
% 	    case RefType of
% 		RefClass when record(RefClass,classdef) ->
% 		    check_class(S,RefClass#classdef.typespec)
% 	    end
	    case is_class(S,RefType) of
		true ->
		    check_class(S,get_class_def(S,RefType));
		_ ->
		    error({class,{internal_error,RefType},S})
	    end
    end;
% check_class(S,{objectclassname,ModuleName,ClassName}) when atom(ModuleName),atom(ClassName) ->
%     'fix this';
check_class(S,C) when record(C,objectclass) ->
    NewFieldSpec = check_class_fields(S,C#objectclass.fields),
    C#objectclass{fields=NewFieldSpec};
%check_class(S,{objectclassname,ClassName}) ->
check_class(S,ClassName) ->
    {_,Def} = get_referenced_type(S,ClassName),
    case Def of
	ClassDef when record(ClassDef,classdef) ->
	    case ClassDef#classdef.checked of
		true ->
		    ClassDef#classdef.typespec;
		idle ->
		    ClassDef#classdef.typespec;
		false ->
		    check_class(S,ClassDef#classdef.typespec)
	    end;
	TypeDef when record(TypeDef,typedef) ->
	    %% this case may occur when a definition is a reference
	    %% to a class definition.
	    case TypeDef#typedef.typespec of
		#type{def=Ext} when record(Ext,'Externaltypereference') ->
		    check_class(S,Ext)
	    end
    end;
check_class(_S,{poc,_ObjSet,_Params}) ->
    'fix this later'.

check_class_fields(S,Fields) ->
    check_class_fields(S,Fields,[]).

check_class_fields(S,[F|Fields],Acc) ->
    NewField =
	case element(1,F) of
	    fixedtypevaluefield ->
		{_,Name,Type,Unique,OSpec} = F,
		RefType = check_type(S,#typedef{typespec=Type},Type),
		{fixedtypevaluefield,Name,RefType,Unique,OSpec};
	    object_or_fixedtypevalue_field ->
		{_,Name,Type,Unique,OSpec} = F,
		Cat =
		    case asn1ct_gen:type(asn1ct_gen:get_inner(Type#type.def)) of
			Def when record(Def,typereference);
				 record(Def,'Externaltypereference') ->
			    {_,D} = get_referenced_type(S,Def),
			    D;
			{undefined,user} ->
			    %% neither of {primitive,bif} or {constructed,bif}
%%			    {_,D} = get_referenced_type(S,#typereference{val=Type#type.def}),
			    {_,D} = get_referenced_type(S,#'Externaltypereference'{module=S#state.mname,type=Type#type.def}),
			    D;
			_ ->
			    Type
		    end,
		case Cat of
		    Class when record(Class,classdef) ->
			{objectfield,Name,Type,Unique,OSpec};
		    _ ->
			RefType = check_type(S,#typedef{typespec=Type},Type),
			{fixedtypevaluefield,Name,RefType,Unique,OSpec}
		end;
	    objectset_or_fixedtypevalueset_field ->
		{_,Name,Type,OSpec} = F,
%%		RefType = check_type(S,#typedef{typespec=Type},Type),
		RefType =
		    case (catch check_type(S,#typedef{typespec=Type},Type)) of
			{asn1_class,_ClassDef} ->
			    case if_current_checked_type(S,Type) of
				true ->
				    Type#type.def;
				_ ->
				    check_class(S,Type)
			    end;
			CheckedType when record(CheckedType,type) ->
			    CheckedType;
			_ ->
			    error({class,"internal error, check_class_fields",S})
		    end,
		if
		    record(RefType,'Externaltypereference') ->
			{objectsetfield,Name,Type,OSpec};
		    record(RefType,classdef) ->
			{objectsetfield,Name,Type,OSpec};
		    record(RefType,objectclass) ->
			{objectsetfield,Name,Type,OSpec};
		    true ->
			{fixedtypevaluesetfield,Name,RefType,OSpec}
		end;
	    typefield ->
		case F of
		    {TF,Name,{'DEFAULT',Type}} ->
			{TF,Name,{'DEFAULT',check_type(S,#typedef{typespec=Type},Type)}};
		    _ -> F
		end;
	    _ -> F
	end,
    check_class_fields(S,Fields,[NewField|Acc]);
check_class_fields(_S,[],Acc) ->
    lists:reverse(Acc).

if_current_checked_type(S,#type{def=Def}) ->
    CurrentCheckedName = S#state.tname,
    MergedModules = S#state.inputmodules,
 %   CurrentCheckedModule = S#state.mname,
    case Def of
	#'Externaltypereference'{module=CurrentCheckedName,
				 type=CurrentCheckedName} ->
	    true;
	#'Externaltypereference'{module=ModuleName,
				 type=CurrentCheckedName} ->
	    case MergedModules of
		undefined ->
		    false;
		_ ->
		    lists:member(ModuleName,MergedModules)
	    end;
	_ ->
	    false
    end.



check_pobject(_S,PObject) when record(PObject,pobjectdef) ->
    Def = PObject#pobjectdef.def,
    Def.


check_pobjectset(S,PObjSet) ->
    #pvaluesetdef{pos=Pos,name=Name,args=Args,type=Type,
		  valueset=ValueSet}=PObjSet,
    {Mod,Def} = get_referenced_type(S,Type#type.def),
    case Def of
	#classdef{} ->
	    ClassName = #'Externaltypereference'{module=Mod,
						 type=Def#classdef.name},
	    {valueset,Set} = ValueSet,
%	    ObjectSet = #'ObjectSet'{class={objectclassname,ClassName},
	    ObjectSet = #'ObjectSet'{class=ClassName,
				     set=Set},
	    #pobjectsetdef{pos=Pos,name=Name,args=Args,class=Type#type.def,
			   def=ObjectSet};
	_ ->
	    PObjSet
    end.

check_object(_S,ObjDef,ObjSpec) when (ObjDef#typedef.checked == true) ->
    ObjSpec;
check_object(S,_ObjDef,#'Object'{classname=ClassRef,def=ObjectDef}) ->
    {_,_ClassDef} = get_referenced_type(S,ClassRef),
    NewClassRef = check_externaltypereference(S,ClassRef),
    ClassDef =
	case _ClassDef#classdef.checked of
	    false ->
		#classdef{checked=true,
			  typespec=check_class(S,_ClassDef#classdef.typespec)};
	    _ ->
		_ClassDef
	end,
    NewObj =
	case ObjectDef of
	    Def when tuple(Def), (element(1,Def)==object) ->
		NewSettingList = check_objectdefn(S,Def,ClassDef),
		#'Object'{def=NewSettingList};
%	    Def when tuple(Def), (element(1,Def)=='ObjectFromObject') ->
%		fixa;
	    {po,{object,DefObj},ArgsList} ->
		{_,Object} = get_referenced_type(S,DefObj),%DefObj is a
		%%#'Externalvaluereference' or a #'Externaltypereference'
		%% Maybe this call should be catched and in case of an exception
		%% an nonallocated parameterized object should be returned.
		instantiate_po(S,ClassDef,Object,ArgsList);
	    #'Externalvaluereference'{} ->
		{_,Object} = get_referenced_type(S,ObjectDef),
		check_object(S,Object,Object#typedef.typespec);
	    _  ->
		exit({error,{no_object,ObjectDef},S})
	end,
    Gen = gen_incl(S,NewObj#'Object'.def,
		   (ClassDef#classdef.typespec)#objectclass.fields),
    NewObj#'Object'{classname=NewClassRef,gen=Gen};

%%check_object(S,ObjSetDef,ObjSet=#type{def={pt,ObjSetRef,Args}}) ->
    %% A parameterized

check_object(S,
	     _ObjSetDef,
	     ObjSet=#'ObjectSet'{class=ClassRef}) ->
    {_,ClassDef} = get_referenced_type(S,ClassRef),
    NewClassRef = check_externaltypereference(S,ClassRef),
    UniqueFieldName =
	case (catch get_unique_fieldname(ClassDef)) of
	    {error,'__undefined_'} -> {unique,undefined};
	    {asn1,Msg,_} -> error({class,Msg,S});
	    Other -> Other
	end,
    NewObjSet=
	case ObjSet#'ObjectSet'.set of
	    {'SingleValue',Set} when list(Set) ->
		CheckedSet = check_object_list(S,NewClassRef,Set),
		NewSet = get_unique_valuelist(S,CheckedSet,UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet};
	    {'SingleValue',{definedvalue,ObjName}} ->
		{_,ObjDef} = get_referenced_type(S,#identifier{val=ObjName}),
		#'Object'{def=CheckedObj} =
		    check_object(S,ObjDef,ObjDef#typedef.typespec),
		NewSet = get_unique_valuelist(S,[{ObjDef#typedef.name,
						  CheckedObj}],
					      UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet};
	    {'SingleValue',#'Externalvaluereference'{value=ObjName}} ->
		{_,ObjDef} = get_referenced_type(S,#identifier{val=ObjName}),
		#'Object'{def=CheckedObj} =
		    check_object(S,ObjDef,ObjDef#typedef.typespec),
		NewSet = get_unique_valuelist(S,[{ObjDef#typedef.name,
						  CheckedObj}],
					      UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet};
	    ['EXTENSIONMARK'] ->
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=['EXTENSIONMARK']};
	    Set when list(Set) ->
		CheckedSet = check_object_list(S,NewClassRef,Set),
		NewSet = get_unique_valuelist(S,CheckedSet,UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet};
	    {Set,Ext} when list(Set) ->
		CheckedSet = check_object_list(S,NewClassRef,Set++Ext),
		NewSet = get_unique_valuelist(S,CheckedSet,UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet++['EXTENSIONMARK']};
	    {{'SingleValue',Set},Ext} ->
		CheckedSet = check_object_list(S,NewClassRef,
					       merge_sets(Set,Ext)),
		NewSet = get_unique_valuelist(S,CheckedSet,UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet++['EXTENSIONMARK']};
	    {Type,{'EXCEPT',Exclusion}} when record(Type,type) ->
		{_,TDef} = get_referenced_type(S,Type#type.def),
		OS = TDef#typedef.typespec,
		NewSet = reduce_objectset(OS#'ObjectSet'.set,Exclusion),
		NewOS = OS#'ObjectSet'{set=NewSet},
		check_object(S,TDef#typedef{typespec=NewOS},
			     NewOS);
	    #type{def={pt,DefinedObjSet,ParamList}} ->
		{_,PObjSetDef} = get_referenced_type(S,DefinedObjSet),
		instantiate_pos(S,ClassDef,PObjSetDef,ParamList);
	    {ObjDef={object,definedsyntax,_ObjFields},_Ext} ->
		CheckedSet = check_object_list(S,NewClassRef,[ObjDef]),
		NewSet = get_unique_valuelist(S,CheckedSet,UniqueFieldName),
		ObjSet#'ObjectSet'{uniquefname=UniqueFieldName,
				   set=NewSet++['EXTENSIONMARK']}
	end,
    Gen = gen_incl_set(S,NewObjSet#'ObjectSet'.set,
		       ClassDef),
    NewObjSet#'ObjectSet'{class=NewClassRef,gen=Gen}.


merge_sets(Set,Ext) when list(Set),list(Ext) ->
    Set ++ Ext;
merge_sets(Set,Ext) when list(Ext) ->
    [Set|Ext];
merge_sets(Set,{'SingleValue',Ext}) when list(Set) ->
    Set ++ [Ext];
merge_sets(Set,{'SingleValue',Ext}) ->
    [Set] ++ [Ext].

reduce_objectset(ObjectSet,Exclusion) ->
    case Exclusion of
	{'SingleValue',#'Externalvaluereference'{value=Name}} ->
	    case lists:keysearch(Name,1,ObjectSet) of
		{value,El} ->
		    lists:subtract(ObjectSet,[El]);
		_ ->
		    ObjectSet
	    end
    end.

%% Checks a list of objects or object sets and returns a list of selected
%% information for the code generation.
check_object_list(S,ClassRef,ObjectList) ->
    check_object_list(S,ClassRef,ObjectList,[]).

check_object_list(S,ClassRef,[ObjOrSet|Objs],Acc) ->
    case ObjOrSet of
	ObjDef when tuple(ObjDef),(element(1,ObjDef)==object) ->
	    Def =
		check_object(S,#typedef{typespec=ObjDef},
%			     #'Object'{classname={objectclassname,ClassRef},
			     #'Object'{classname=ClassRef,
				       def=ObjDef}),
	    check_object_list(S,ClassRef,Objs,[{no_name,Def#'Object'.def}|Acc]);
	{'SingleValue',{definedvalue,ObjName}} ->
	    {_,ObjectDef} = get_referenced_type(S,#identifier{val=ObjName}),
	    #'Object'{def=Def} = check_object(S,ObjectDef,ObjectDef#typedef.typespec),
	    check_object_list(S,ClassRef,Objs,[{ObjectDef#typedef.name,Def}|Acc]);
	{'SingleValue',Ref = #'Externalvaluereference'{}} ->
	    {_,ObjectDef} = get_referenced_type(S,Ref),
	    #'Object'{def=Def} = check_object(S,ObjectDef,ObjectDef#typedef.typespec),
	    check_object_list(S,ClassRef,Objs,[{ObjectDef#typedef.name,Def}|Acc]);
	ObjRef when record(ObjRef,'Externalvaluereference') ->
	    {_,ObjectDef} = get_referenced_type(S,ObjRef),
	    #'Object'{def=Def} = check_object(S,ObjectDef,ObjectDef#typedef.typespec),
	    check_object_list(S,ClassRef,Objs,
%%			      [{ObjRef#'Externalvaluereference'.value,Def}|Acc]);
			      [{ObjectDef#typedef.name,Def}|Acc]);
	{'ValueFromObject',{_,Object},FieldName} ->
	    {_,Def} = get_referenced_type(S,Object),
%%	    TypeOrVal = get_fieldname_element(S,Def,FieldName);%% this must result in an object set
	    TypeDef = get_fieldname_element(S,Def,FieldName),
	    (TypeDef#typedef.typespec)#'ObjectSet'.set;
	ObjSet when record(ObjSet,type) ->
	    ObjSetDef =
		case ObjSet#type.def of
		    Ref when record(Ref,typereference);
			     record(Ref,'Externaltypereference') ->
			{_,D} = get_referenced_type(S,ObjSet#type.def),
			D;
		    Other ->
			throw({asn1_error,{'unknown objecset',Other,S}})
		end,
	    #'ObjectSet'{set=ObjectsInSet} =
		check_object(S,ObjSetDef,ObjSetDef#typedef.typespec),
	    AccList = transform_set_to_object_list(ObjectsInSet,[]),
	    check_object_list(S,ClassRef,Objs,AccList++Acc);
	union ->
	    check_object_list(S,ClassRef,Objs,Acc);
	Other ->
	    exit({error,{'unknown object',Other},S})
    end;
%% Finally reverse the accumulated list and if there are any extension
%% marks in the object set put one indicator of that in the end of the
%% list.
check_object_list(_,_,[],Acc) ->
    lists:reverse(Acc).
%%    case lists:member('EXTENSIONMARK',RevAcc) of
%%	true ->
%%	    ExclRevAcc = lists:filter(fun(X)->X /= 'EXTENSIONMARK' end,
%%				      RevAcc),
%%	    ExclRevAcc ++ ['EXTENSIONMARK'];
%%	false ->
%%	    RevAcc
%%    end.


%%  get_fieldname_element/3
%%  gets the type/value/object/... of the referenced element in FieldName
%%  FieldName is a list and may have more than one element.
%%  Each element in FieldName can be either {typefieldreference,AnyFieldName}
%%  or {valuefieldreference,AnyFieldName}
%%  Def is the def of the first object referenced by FieldName
get_fieldname_element(S,Def,[{_RefType,FieldName}]) when record(Def,typedef) ->
    {_,_,ObjComps} = (Def#typedef.typespec)#'Object'.def,
    case lists:keysearch(FieldName,1,ObjComps) of
	{value,{_,TDef}} when record(TDef,typedef) ->
	    %%    ORec = TDef#typedef.typespec, %% XXX This must be made general
% 	    case TDef#typedef.typespec of
% 		ObjSetRec when record(ObjSetRec,'ObjectSet') ->
% 		    ObjSet = ObjSetRec#'ObjectSet'.set;
% 		ObjRec when record(ObjRec,'Object') ->
% 		    %% now get the field in ObjRec that RestFName points out
% 		    %ObjRec
% 		    TDef
% 	    end;
	    TDef;
	{value,{_,VDef}} when record(VDef,valuedef) ->
	    check_value(S,VDef);
	_ ->
	    throw({assigned_object_error,"not_assigned_object",S})
    end;
get_fieldname_element(_S,Def,[{_RefType,_FieldName}|_RestFName])
  when record(Def,typedef) ->
    ok.

transform_set_to_object_list([{Name,_UVal,Fields}|Objs],Acc) ->
    transform_set_to_object_list(Objs,[{Name,{object,generatesyntax,Fields}}|Acc]);
transform_set_to_object_list(['EXTENSIONMARK'|Objs],Acc) ->
%%    transform_set_to_object_list(Objs,['EXTENSIONMARK'|Acc]);
    transform_set_to_object_list(Objs,Acc);
transform_set_to_object_list([],Acc) ->
    Acc.

get_unique_valuelist(_S,ObjSet,{unique,undefined}) -> % no unique field in object
    lists:map(fun({N,{_,_,F}})->{N,F};
		 (V={_,_,_}) ->V end, ObjSet);
get_unique_valuelist(S,ObjSet,UFN) ->
    get_unique_vlist(S,ObjSet,UFN,[]).

get_unique_vlist(S,[],_,Acc) ->
    case catch check_uniqueness(Acc) of
	{asn1_error,_} ->
%	    exit({error,Reason,S});
	    error({'ObjectSet',"not unique objects in object set",S});
	true ->
	    lists:reverse(Acc)
    end;
get_unique_vlist(S,[{ObjName,Obj}|Rest],UniqueFieldName,Acc) ->
    {_,_,Fields} = Obj,
    VDef = get_unique_value(S,Fields,UniqueFieldName),
    get_unique_vlist(S,Rest,UniqueFieldName,
		     [{ObjName,VDef#valuedef.value,Fields}|Acc]);
get_unique_vlist(S,[V={_,_,_}|Rest],UniqueFieldName,Acc) ->
    get_unique_vlist(S,Rest,UniqueFieldName,[V|Acc]).

get_unique_value(S,Fields,UniqueFieldName) ->
    Module = S#state.mname,
    case lists:keysearch(UniqueFieldName,1,Fields) of
	{value,Field} ->
	    case element(2,Field) of
		VDef when record(VDef,valuedef) ->
		    VDef;
		{definedvalue,ValName} ->
		    ValueDef = asn1_db:dbget(Module,ValName),
		    case ValueDef of
			VDef when record(VDef,valuedef) ->
			    ValueDef;
			undefined ->
			    #valuedef{value=ValName}
		    end;
		{'ValueFromObject',Object,Name} ->
		    case Object of
			{object,Ext} when record(Ext,'Externaltypereference') ->
			    OtherModule = Ext#'Externaltypereference'.module,
			    ExtObjName = Ext#'Externaltypereference'.type,
			    ObjDef = asn1_db:dbget(OtherModule,ExtObjName),
			    ObjSpec = ObjDef#typedef.typespec,
			    get_unique_value(OtherModule,element(3,ObjSpec),Name);
			{object,{_,_,ObjName}} ->
			    ObjDef = asn1_db:dbget(Module,ObjName),
			    ObjSpec = ObjDef#typedef.typespec,
			    get_unique_value(Module,element(3,ObjSpec),Name);
			{po,Object,_Params} ->
			    exit({error,{'parameterized object not implemented yet',
					 Object},S})
		    end;
		Value when atom(Value);number(Value) ->
		    #valuedef{value=Value};
		{'CHOICE',{_,Value}} when atom(Value);number(Value) ->
		    #valuedef{value=Value}
	    end;
	false ->
	    exit({error,{'no unique value',Fields,UniqueFieldName},S})
%%	    io:format("WARNING: no unique value in object"),
%%	    exit(uniqueFieldName)
    end.

check_uniqueness(NameValueList) ->
    check_uniqueness1(lists:keysort(2,NameValueList)).

check_uniqueness1([]) ->
    true;
check_uniqueness1([_]) ->
    true;
check_uniqueness1([{_,N,_},{_,N,_}|_Rest]) ->
    throw({asn1_error,{'objects in set must have unique values in UNIQUE fields',N}});
check_uniqueness1([_|Rest]) ->
    check_uniqueness1(Rest).

%% instantiate_po/4
%% ClassDef is the class of Object,
%% Object is the Parameterized object, which is referenced,
%% ArgsList is the list of actual parameters
%% returns an #'Object' record.
instantiate_po(S,_ClassDef,Object,ArgsList) when record(Object,pobjectdef) ->
    FormalParams = get_pt_args(Object),
    MatchedArgs = match_args(FormalParams,ArgsList,[]),
    NewS = S#state{type=Object,parameters=MatchedArgs},
    check_object(NewS,Object,#'Object'{classname=Object#pobjectdef.class,
				    def=Object#pobjectdef.def}).

%% instantiate_pos/4
%% ClassDef is the class of ObjectSetDef,
%% ObjectSetDef is the Parameterized object set, which is referenced
%% on the right side of the assignment,
%% ArgsList is the list of actual parameters, i.e. real objects
instantiate_pos(S,ClassDef,ObjectSetDef,ArgsList) ->
    ClassName = ClassDef#classdef.name,
    FormalParams = get_pt_args(ObjectSetDef),
    Set = case get_pt_spec(ObjectSetDef) of
	      {valueset,_Set} -> _Set;
	      _Set -> _Set
	  end,
    MatchedArgs = match_args(FormalParams,ArgsList,[]),
    NewS = S#state{type=ObjectSetDef,parameters=MatchedArgs},
    check_object(NewS,ObjectSetDef,
		 #'ObjectSet'{class=name2Extref(S#state.mname,ClassName),
			      set=Set}).


%% gen_incl -> boolean()
%% If object with Fields has any of the corresponding class' typefields
%% then return value is true otherwise it is false.
%% If an object lacks a typefield but the class has a type field that
%% is OPTIONAL then we want gen to be true
gen_incl(S,{_,_,Fields},CFields)->
    gen_incl1(S,Fields,CFields).

gen_incl1(_,_,[]) ->
    false;
gen_incl1(S,Fields,[C|CFields]) ->
    case element(1,C) of
	typefield ->
% 	    case lists:keymember(element(2,C),1,Fields) of
% 		true ->
% 		    true;
% 		false ->
% 		    gen_incl1(S,Fields,CFields)
% 	    end;
	    true; %% should check that field is OPTIONAL or DEFUALT if
                  %% the object lacks this field
	objectfield ->
	    case lists:keysearch(element(2,C),1,Fields) of
		{value,Field} ->
		    Type = element(3,C),
		    {_,ClassDef} = get_referenced_type(S,Type#type.def),
%		    {_,ClassFields,_} = ClassDef#classdef.typespec,
		    #objectclass{fields=ClassFields} =
			ClassDef#classdef.typespec,
		    ObjTDef = element(2,Field),
		    case gen_incl(S,(ObjTDef#typedef.typespec)#'Object'.def,
				  ClassFields) of
			true ->
			    true;
			_ ->
			    gen_incl1(S,Fields,CFields)
		    end;
		_ ->
		    gen_incl1(S,Fields,CFields)
	    end;
	_ ->
	    gen_incl1(S,Fields,CFields)
    end.

%% first if no unique field in the class return false.(don't generate code)
gen_incl_set(S,Fields,ClassDef) ->
    case catch get_unique_fieldname(ClassDef) of
	Tuple when tuple(Tuple) ->
	    false;
	_ ->
	    gen_incl_set1(S,Fields,
			  (ClassDef#classdef.typespec)#objectclass.fields)
    end.

%% if any of the existing or potentially existing objects has a typefield
%% then return true.
gen_incl_set1(_,[],_CFields)->
    false;
gen_incl_set1(_,['EXTENSIONMARK'],_) ->
    true;
%% Fields are the fields of an object in the object set.
%% CFields are the fields of the class of the object set.
gen_incl_set1(S,[Object|Rest],CFields)->
    Fields = element(size(Object),Object),
    case gen_incl1(S,Fields,CFields) of
	true ->
	    true;
	false ->
	    gen_incl_set1(S,Rest,CFields)
    end.

check_objectdefn(S,Def,CDef) when record(CDef,classdef) ->
    WithSyntax = (CDef#classdef.typespec)#objectclass.syntax,
    ClassFields = (CDef#classdef.typespec)#objectclass.fields,
    case Def of
	{object,defaultsyntax,Fields} ->
	    check_defaultfields(S,Fields,ClassFields);
	{object,definedsyntax,Fields} ->
	    {_,WSSpec} = WithSyntax,
	    NewFields =
		case catch( convert_definedsyntax(S,Fields,WSSpec,
						  ClassFields,[])) of
		    {asn1,{_ErrorType,ObjToken,ClassToken}} ->
			throw({asn1,{'match error in object',ObjToken,
				     'found in object',ClassToken,'found in class'}});
		    Err={asn1,_} -> throw(Err);
		    Err={'EXIT',_} -> throw(Err);
		    DefaultFields when list(DefaultFields) ->
			DefaultFields
		end,
	    {object,defaultsyntax,NewFields};
	{object,_ObjectId} -> % This is a DefinedObject
	    fixa;
	Other ->
	    exit({error,{objectdefn,Other}})
    end.

check_defaultfields(S,Fields,ClassFields) ->
    check_defaultfields(S,Fields,ClassFields,[]).

check_defaultfields(_S,[],_ClassFields,Acc) ->
    {object,defaultsyntax,lists:reverse(Acc)};
check_defaultfields(S,[{FName,Spec}|Fields],ClassFields,Acc) ->
    case lists:keysearch(FName,2,ClassFields) of
	{value,CField} ->
	    NewField = convert_to_defaultfield(S,FName,Spec,CField),
	    check_defaultfields(S,Fields,ClassFields,[NewField|Acc]);
	_ ->
	    throw({error,{asn1,{'unvalid field in object',FName}}})
    end.
%%    {object,defaultsyntax,Fields}.

convert_definedsyntax(_S,[],[],_ClassFields,Acc) ->
    lists:reverse(Acc);
convert_definedsyntax(S,Fields,WithSyntax,ClassFields,Acc) ->
    case match_field(S,Fields,WithSyntax,ClassFields) of
	{MatchedField,RestFields,RestWS} ->
	    if
		list(MatchedField) ->
		    convert_definedsyntax(S,RestFields,RestWS,ClassFields,
					  lists:append(MatchedField,Acc));
		true ->
		    convert_definedsyntax(S,RestFields,RestWS,ClassFields,
					  [MatchedField|Acc])
	    end
%%	    throw({error,{asn1,{'unvalid syntax in object',WorS}}})
    end.

match_field(S,Fields,WithSyntax,ClassFields) ->
    match_field(S,Fields,WithSyntax,ClassFields,[]).

match_field(S,Fields,[W|Ws],ClassFields,Acc) when list(W) ->
    case catch(match_optional_field(S,Fields,W,ClassFields,[])) of
	{'EXIT',_} ->
	    match_field(Fields,Ws,ClassFields,Acc); %% add S
%%	{[Result],RestFields} ->
%%	    {Result,RestFields,Ws};
	{Result,RestFields} when list(Result) ->
	    {Result,RestFields,Ws};
	_ ->
	    match_field(S,Fields,Ws,ClassFields,Acc)
    end;
match_field(S,Fields,WithSyntax,ClassFields,_Acc) ->
    match_mandatory_field(S,Fields,WithSyntax,ClassFields,[]).

match_optional_field(_S,RestFields,[],_,Ret) ->
    {Ret,RestFields};
%% An additional optional field within an optional field
match_optional_field(S,Fields,[W|Ws],ClassFields,Ret) when list(W) ->
    case catch match_optional_field(S,Fields,W,ClassFields,[]) of
	{'EXIT',_} ->
	    {Ret,Fields};
	{asn1,{optional_matcherror,_,_}} ->
	    {Ret,Fields};
	{OptionalField,RestFields} ->
	    match_optional_field(S,RestFields,Ws,ClassFields,
				 lists:append(OptionalField,Ret))
    end;
%% identify and skip word
%match_optional_field(S,[#'Externaltypereference'{type=WorS}|Rest],
match_optional_field(S,[{_,_,WorS}|Rest],
		     [WorS|Ws],ClassFields,Ret) ->
    match_optional_field(S,Rest,Ws,ClassFields,Ret);
match_optional_field(S,[],_,ClassFields,Ret) ->
    match_optional_field(S,[],[],ClassFields,Ret);
%% identify and skip comma
match_optional_field(S,[{WorS,_}|Rest],[{WorS,_}|Ws],ClassFields,Ret) ->
    match_optional_field(S,Rest,Ws,ClassFields,Ret);
%% identify and save field data
match_optional_field(S,[Setting|Rest],[{_,W}|Ws],ClassFields,Ret) ->
    WorS =
	case Setting of
	    Type when record(Type,type) -> Type;
%%	    #'Externalvaluereference'{value=WordOrSetting} -> WordOrSetting;
	    {'ValueFromObject',_,_} -> Setting;
	    {object,_,_} -> Setting;
	    {_,_,WordOrSetting} -> WordOrSetting;
%%	    Atom when atom(Atom) -> Atom
	    Other -> Other
	end,
    case lists:keysearch(W,2,ClassFields) of
	false ->
	    throw({asn1,{optional_matcherror,WorS,W}});
	{value,CField} ->
	    NewField = convert_to_defaultfield(S,W,WorS,CField),
	    match_optional_field(S,Rest,Ws,ClassFields,[NewField|Ret])
    end;
match_optional_field(_S,[WorS|_Rest],[W|_Ws],_ClassFields,_Ret) ->
    throw({asn1,{optional_matcherror,WorS,W}}).

match_mandatory_field(_S,[],[],_,[Acc]) ->
    {Acc,[],[]};
match_mandatory_field(_S,[],[],_,Acc) ->
    {Acc,[],[]};
match_mandatory_field(S,[],[H|T],CF,Acc) when list(H) ->
    match_mandatory_field(S,[],T,CF,Acc);
match_mandatory_field(_S,[],WithSyntax,_,_Acc) ->
    throw({asn1,{mandatory_matcherror,[],WithSyntax}});
%match_mandatory_field(_S,Fields,WithSyntax=[W|_Ws],_ClassFields,[Acc]) when list(W) ->
match_mandatory_field(_S,Fields,WithSyntax=[W|_Ws],_ClassFields,Acc) when list(W), length(Acc) >= 1 ->
    {Acc,Fields,WithSyntax};
%% identify and skip word
match_mandatory_field(S,[{_,_,WorS}|Rest],
		      [WorS|Ws],ClassFields,Acc) ->
    match_mandatory_field(S,Rest,Ws,ClassFields,Acc);
%% identify and skip comma
match_mandatory_field(S,[{WorS,_}|Rest],[{WorS,_}|Ws],ClassFields,Ret) ->
    match_mandatory_field(S,Rest,Ws,ClassFields,Ret);
%% identify and save field data
match_mandatory_field(S,[Setting|Rest],[{_,W}|Ws],ClassFields,Acc) ->
    WorS =
	case Setting of
%%	    Atom when atom(Atom) -> Atom;
%%	    #'Externalvaluereference'{value=WordOrSetting} -> WordOrSetting;
	    {object,_,_} -> Setting;
	    {_,_,WordOrSetting} -> WordOrSetting;
	    Type when record(Type,type) -> Type;
	    Other -> Other
	end,
    case lists:keysearch(W,2,ClassFields) of
	false ->
	    throw({asn1,{mandatory_matcherror,WorS,W}});
	{value,CField} ->
	    NewField = convert_to_defaultfield(S,W,WorS,CField),
	    match_mandatory_field(S,Rest,Ws,ClassFields,[NewField|Acc])
    end;

match_mandatory_field(_S,[WorS|_Rest],[W|_Ws],_ClassFields,_Acc) ->
    throw({asn1,{mandatory_matcherror,WorS,W}}).

%% Converts a field of an object from defined syntax to default syntax
convert_to_defaultfield(S,ObjFieldName,ObjFieldSetting,CField)->
    CurrMod = S#state.mname,
    case element(1,CField) of
	typefield ->
	    TypeDef=
		case ObjFieldSetting of
		    TypeRec when record(TypeRec,type) -> TypeRec#type.def;
		    TDef when record(TDef,typedef) ->
			TDef#typedef{typespec=check_type(S,TDef,
							 TDef#typedef.typespec)};
		    _ -> ObjFieldSetting
		end,
	    Type =
		if
		    record(TypeDef,typedef) -> TypeDef;
		    true ->
			case asn1ct_gen:type(asn1ct_gen:get_inner(TypeDef)) of
			    ERef = #'Externaltypereference'{module=CurrMod} ->
				{_,T} = get_referenced_type(S,ERef),
				T#typedef{checked=true,
					  typespec=check_type(S,T,
							      T#typedef.typespec)};
			    ERef = #'Externaltypereference'{module=ExtMod} ->
				{_,T} = get_referenced_type(S,ERef),
				#typedef{name=Name} = T,
				check_type(S,T,T#typedef.typespec),
				#typedef{checked=true,
					 name={ExtMod,Name},
					 typespec=ERef};
			    Bif when Bif=={primitive,bif};Bif=={constructed,bif} ->
				T = check_type(S,#typedef{typespec=ObjFieldSetting},
					       ObjFieldSetting),
				#typedef{checked=true,name=Bif,typespec=T};
			    _ ->
				{Mod,T} =
				    %% get_referenced_type(S,#typereference{val=ObjFieldSetting}),
				    get_referenced_type(S,#'Externaltypereference'{module=S#state.mname,type=ObjFieldSetting}),
				case Mod of
				    CurrMod ->
					T;
				    ExtMod ->
					#typedef{name=Name} = T,
					T#typedef{name={ExtMod,Name}}
				end
			end
		end,
	    {ObjFieldName,Type};
	fixedtypevaluefield ->
	    case ObjFieldName of
		Val when atom(Val) ->
		    %% ObjFieldSetting can be a value,an objectidentifiervalue,
		    %% an element in an enumeration or namednumberlist etc.
		    ValRef =
			case ObjFieldSetting of
			    #'Externalvaluereference'{} -> ObjFieldSetting;
			    {'ValueFromObject',{_,ObjRef},FieldName} ->
				{_,Object} = get_referenced_type(S,ObjRef),
				ChObject = check_object(S,Object,
							Object#typedef.typespec),
				get_fieldname_element(S,Object#typedef{typespec=ChObject},
						      FieldName);
			    #valuedef{} ->
				ObjFieldSetting;
			    _ ->
				#identifier{val=ObjFieldSetting}
			end,
		    case ValRef of
			#valuedef{} ->
			    {ObjFieldName,check_value(S,ValRef)};
			_ ->
			    ValDef =
				case catch get_referenced_type(S,ValRef) of
				    {error,_} ->
					check_value(S,#valuedef{name=Val,
								type=element(3,CField),
								value=ObjFieldSetting});
				    {_,VDef} when record(VDef,valuedef) ->
					check_value(S,VDef);%% XXX
				    {_,VDef} ->
					check_value(S,#valuedef{name=Val,
								type=element(3,CField),
								value=VDef})
				end,
			    {ObjFieldName,ValDef}
		    end;
		Val ->
		    {ObjFieldName,Val}
	    end;
	fixedtypevaluesetfield ->
	    {ObjFieldName,ObjFieldSetting};
	objectfield ->
	    ObjectSpec =
		case ObjFieldSetting of
		    Ref when record(Ref,typereference);record(Ref,identifier);
			     record(Ref,'Externaltypereference');
			     record(Ref,'Externalvaluereference') ->
			{_,R} = get_referenced_type(S,ObjFieldSetting),
			R;
		    {'ValueFromObject',{_,ObjRef},FieldName} ->
			%% This is an ObjectFromObject
			{_,Object} = get_referenced_type(S,ObjRef),
			ChObject = check_object(S,Object,
						Object#typedef.typespec),
			_ObjFromObj=
			    get_fieldname_element(S,Object#typedef{
						      typespec=ChObject},
						  FieldName);
			%%ClassName = ObjFromObj#'Object'.classname,
			%%#typedef{name=,
			%%	 typespec=
			%%	 ObjFromObj#'Object'{classname=
			%%			     {objectclassname,ClassName}}};
		    {object,_,_} ->
			%% An object defined inlined in another object
			#type{def=Ref} = element(3,CField),
% 			CRef = case Ref of
% 				   #'Externaltypereference'{module=CurrMod,
% 							    type=CName} ->
% 				       CName;
% 				    #'Externaltypereference'{module=ExtMod,
% 							    type=CName} ->
% 				       {ExtMod,CName}
% 			       end,
			InlinedObjName=
			    list_to_atom(lists:concat([S#state.tname]++
						      ['_',ObjFieldName])),
%			ObjSpec = #'Object'{classname={objectclassname,CRef},
			ObjSpec = #'Object'{classname=Ref,
					    def=ObjFieldSetting},
			CheckedObj=
			    check_object(S,#typedef{typespec=ObjSpec},ObjSpec),
			InlObj = #typedef{checked=true,name=InlinedObjName,
					  typespec=CheckedObj},
			asn1ct_gen:insert_once(inlined_objects,{InlinedObjName,
								InlinedObjName}),
			asn1_db:dbput(S#state.mname,InlinedObjName,InlObj),
			InlObj;
		    #type{def=Eref} when record(Eref,'Externaltypereference') ->
			{_,R} = get_referenced_type(S,Eref),
			R;
		    _ ->
%%			{_,R} = get_referenced_type(S,#typereference{val=ObjFieldSetting}),
			{_,R} = get_referenced_type(S,#'Externaltypereference'{module=S#state.mname,type=ObjFieldSetting}),
			R
		end,
	    {ObjFieldName,
	     ObjectSpec#typedef{checked=true,
		      typespec=check_object(S,ObjectSpec,
					    ObjectSpec#typedef.typespec)}};
	variabletypevaluefield ->
	    {ObjFieldName,ObjFieldSetting};
	variabletypevaluesetfield ->
	    {ObjFieldName,ObjFieldSetting};
	objectsetfield ->
	    {_,ObjSetSpec} =
		case ObjFieldSetting of
		    Ref when record(Ref,'Externaltypereference');
			     record(Ref,'Externalvaluereference') ->
			get_referenced_type(S,ObjFieldSetting);
		    ObjectList when list(ObjectList) ->
			%% an objctset defined in the object,though maybe
			%% parsed as a SequenceOfValue
			%% The ObjectList may be a list of references to
			%% objects, a ValueFromObject
			{_,_,Type,_} = CField,
			ClassDef = Type#type.def,
			case ClassDef#'Externaltypereference'.module of
			    CurrMod ->
				ClassDef#'Externaltypereference'.type;
			    ExtMod ->
				{ExtMod,
				 ClassDef#'Externaltypereference'.type}
			end,
			{no_name,
			 #typedef{typespec=
				  #'ObjectSet'{class=
%					       {objectclassname,ClassRef},
					       ClassDef,
					       set=ObjectList}}};
		    ObjectSet={'SingleValue',_} ->
			%% a Union of defined objects
			{_,_,Type,_} = CField,
			ClassDef = Type#type.def,
% 			ClassRef =
% 			    case ClassDef#'Externaltypereference'.module of
% 				CurrMod ->
% 				    ClassDef#'Externaltypereference'.type;
% 				ExtMod ->
% 				    {ExtMod,
% 				     ClassDef#'Externaltypereference'.type}
% 			    end,
			{no_name,
%			 #typedef{typespec=#'ObjectSet'{class={objectclassname,ClassRef},
			 #typedef{typespec=#'ObjectSet'{class=ClassDef,
							set=ObjectSet}}};
		    {object,_,[#type{def={'TypeFromObject',
					 {object,RefedObj},
					 FieldName}}]} ->
			%% This case occurs when an ObjectSetFromObjects
			%% production is used
			{M,Def} = get_referenced_type(S,RefedObj),
			{M,get_fieldname_element(S,Def,FieldName)};
		    #type{def=Eref} when
			  record(Eref,'Externaltypereference') ->
			get_referenced_type(S,Eref);
		    _ ->
%%			get_referenced_type(S,#typereference{val=ObjFieldSetting})
			get_referenced_type(S,#'Externaltypereference'{module=S#state.mname,type=ObjFieldSetting})
		end,
	    {ObjFieldName,
	     ObjSetSpec#typedef{checked=true,
				typespec=check_object(S,ObjSetSpec,
						      ObjSetSpec#typedef.typespec)}}
    end.

check_value(OldS,V) when record(V,pvaluesetdef) ->
    #pvaluesetdef{checked=Checked,type=Type} = V,
    case Checked of
	true -> V;
	{error,_} -> V;
	false ->
	    case get_referenced_type(OldS,Type#type.def) of
		{_,Class} when record(Class,classdef) ->
		    throw({pobjectsetdef});
		_ -> continue
	    end
    end;
check_value(_OldS,V) when record(V,pvaluedef) ->
    %% Fix this case later
    V;
check_value(OldS,V) when record(V,typedef) ->
    %% This case when a value set has been parsed as an object set.
    %% It may be a value set
    #typedef{typespec=TS} = V,
    case TS of
	#'ObjectSet'{class=ClassRef} ->
	    {_,TSDef} = get_referenced_type(OldS,ClassRef),
	    %%IsObjectSet(TSDef);
	    case TSDef of
		#classdef{} -> throw({objectsetdef});
		#typedef{typespec=#type{def=Eref}} when
		      record(Eref,'Externaltypereference') ->
		    %% This case if the class reference is a defined
		    %% reference to class
		    check_value(OldS,V#typedef{typespec=TS#'ObjectSet'{class=Eref}});
		#typedef{} ->
		    % an ordinary value set with a type in #typedef.typespec
		    ValueSet = TS#'ObjectSet'.set,
		    Type=check_type(OldS,TSDef,TSDef#typedef.typespec),
		    Value = check_value(OldS,#valuedef{type=Type,
						       value=ValueSet}),
		    {valueset,Type#type{constraint=Value#valuedef.value}}
	    end;
	_ ->
	    throw({objectsetdef})
    end;
check_value(S,#valuedef{pos=Pos,name=Name,type=Type,
			  value={valueset,Constr}}) ->
    NewType = Type#type{constraint=[Constr]},
    {valueset,
     check_type(S,#typedef{pos=Pos,name=Name,typespec=NewType},NewType)};
check_value(OldS=#state{recordtopname=TopName},V) when record(V,valuedef) ->
    #valuedef{name=Name,checked=Checked,type=Vtype,value=Value} = V,
    case Checked of
	true ->
	    V;
	{error,_} ->
	    V;
	false ->
	    Def = Vtype#type.def,
	    Constr = Vtype#type.constraint,
	    S = OldS#state{type=Vtype,tname=Def,value=V,vname=Name},
	    NewDef =
		case Def of
		    Ext when record(Ext,'Externaltypereference') ->
			RecName = Ext#'Externaltypereference'.type,
			{_,Type} = get_referenced_type(S,Ext),
			%% If V isn't a value but an object Type is a #classdef{}
			case Type of
			    #classdef{} ->
				throw({objectdef});
			    #typedef{} ->
				case is_contextswitchtype(Type) of
				    true ->
					#valuedef{value=CheckedVal}=
					    check_value(S,V#valuedef{type=Type#typedef.typespec}),
					#newv{value=CheckedVal};
				    _ ->
					#valuedef{value=CheckedVal}=
					    check_value(S#state{recordtopname=[RecName|TopName]},
							V#valuedef{type=Type#typedef.typespec}),
					#newv{value=CheckedVal}
				end
			end;
		    'ANY' ->
			throw({error,{asn1,{'cant check value of type',Def}}});
		    'INTEGER' ->
			validate_integer(S,Value,[],Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    {'INTEGER',NamedNumberList} ->
			validate_integer(S,Value,NamedNumberList,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    {'BIT STRING',NamedNumberList} ->
			validate_bitstring(S,Value,NamedNumberList,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'NULL' ->
			validate_null(S,Value,Constr),
			#newv{};
		    'OBJECT IDENTIFIER' ->
			validate_objectidentifier(S,Value,Constr),
			#newv{value = normalize_value(S,Vtype,Value,[])};
		    'ObjectDescriptor' ->
			validate_objectdescriptor(S,Value,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    {'ENUMERATED',NamedNumberList} ->
			validate_enumerated(S,Value,NamedNumberList,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'BOOLEAN'->
			validate_boolean(S,Value,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'OCTET STRING' ->
			validate_octetstring(S,Value,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'NumericString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'TeletexString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'VideotexString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'UTCTime' ->
			#newv{value=normalize_value(S,Vtype,Value,[])};
%			exit({'cant check value of type' ,Def});
		    'GeneralizedTime' ->
			#newv{value=normalize_value(S,Vtype,Value,[])};
%			exit({'cant check value of type' ,Def});
		    'GraphicString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'VisibleString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'GeneralString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'PrintableString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'IA5String' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
		    'BMPString' ->
			validate_restrictedstring(S,Value,Def,Constr),
			#newv{value=normalize_value(S,Vtype,Value,[])};
%%		    'UniversalString' -> %added 6/12 -00
%%			#newv{value=validate_restrictedstring(S,Value,Def,Constr)};
		    Seq when record(Seq,'SEQUENCE') ->
			SeqVal = validate_sequence(S,Value,
						   Seq#'SEQUENCE'.components,
						   Constr),
			#newv{value=normalize_value(S,Vtype,SeqVal,TopName)};
		    {'SEQUENCE OF',Components} ->
			validate_sequenceof(S,Value,Components,Constr),
			#newv{value=normalize_value(S,Vtype,Value,TopName)};
		    {'CHOICE',Components} ->
			validate_choice(S,Value,Components,Constr),
			#newv{value=normalize_value(S,Vtype,Value,TopName)};
		    Set when record(Set,'SET') ->
			validate_set(S,Value,Set#'SET'.components,
					      Constr),
			#newv{value=normalize_value(S,Vtype,Value,TopName)};
		    {'SET OF',Components} ->
			validate_setof(S,Value,Components,Constr),
			#newv{value=normalize_value(S,Vtype,Value,TopName)};
		    Other ->
			exit({'cant check value of type' ,Other})
		end,
	    case NewDef#newv.value of
		unchanged ->
		    V#valuedef{checked=true,value=Value};
		ok ->
		    V#valuedef{checked=true,value=Value};
		{error,Reason} ->
		    V#valuedef{checked={error,Reason},value=Value};
		_V ->
		    V#valuedef{checked=true,value=_V}
	    end
    end.

is_contextswitchtype(#typedef{name='EXTERNAL'})->
    true;
is_contextswitchtype(#typedef{name='EMBEDDED PDV'}) ->
    true;
is_contextswitchtype(#typedef{name='CHARACTER STRING'}) ->
    true;
is_contextswitchtype(_) ->
    false.

% validate_integer(S,{identifier,Pos,Id},NamedNumberList,Constr) ->
%     case lists:keysearch(Id,1,NamedNumberList) of
% 	{value,_} -> ok;
% 	false -> error({value,"unknown NamedNumber",S})
%     end;
%% This case occurs when there is a valuereference
validate_integer(S=#state{mname=M},
		 #'Externalvaluereference'{module=M,value=Id},
		 NamedNumberList,_Constr) ->
    case lists:keysearch(Id,1,NamedNumberList) of
	{value,_} -> ok;
	false -> error({value,"unknown NamedNumber",S})
    end;
validate_integer(S,Id,NamedNumberList,_Constr) when atom(Id) ->
    case lists:keysearch(Id,1,NamedNumberList) of
	{value,_} -> ok;
	false -> error({value,"unknown NamedNumber",S})
    end;
validate_integer(_S,Value,_NamedNumberList,Constr) when integer(Value) ->
    check_integer_range(Value,Constr).

check_integer_range(Int,Constr) when list(Constr) ->
    NewConstr = [X || #constraint{c=X} <- Constr],
    check_constr(Int,NewConstr);

check_integer_range(_Int,_Constr) ->
    %%io:format("~p~n",[Constr]),
    ok.

check_constr(Int,[{'ValueRange',Lb,Ub}|T]) when Int >= Lb, Int =< Ub ->
    check_constr(Int,T);
check_constr(_Int,[]) ->
    ok.

validate_bitstring(_S,_Value,_NamedNumberList,_Constr) ->
    ok.

validate_null(_S,'NULL',_Constr) ->
    ok.

%%------------
%% This can be removed when the old parser is removed
%% The function removes 'space' atoms from the list

is_space_list([H],Acc) ->
    lists:reverse([H|Acc]);
is_space_list([H,space|T],Acc) ->
    is_space_list(T,[H|Acc]);
is_space_list([],Acc) ->
    lists:reverse(Acc);
is_space_list([H|T],Acc) ->
    is_space_list(T,[H|Acc]).

validate_objectidentifier(S,L,_) ->
    case is_space_list(L,[]) of
	NewL when list(NewL) ->
	    case validate_objectidentifier1(S,NewL) of
		NewL2 when list(NewL2) ->
		    list_to_tuple(NewL2);
		Other -> Other
	    end;
	{error,_} ->
	    error({value, "illegal OBJECT IDENTIFIER", S})
    end.

validate_objectidentifier1(S, [Id|T]) when record(Id,'Externalvaluereference') ->
    case catch get_referenced_type(S,Id) of
	{_,V} when record(V,valuedef) ->
	    case check_value(S,V) of
		#valuedef{type=#type{def='OBJECT IDENTIFIER'},
			  checked=true,value=Value} when tuple(Value) ->
		    validate_objectid(S, T, lists:reverse(tuple_to_list(Value)));
		_ ->
		    error({value, "illegal OBJECT IDENTIFIER", S})
	    end;
	_ ->
	    validate_objectid(S, [Id|T], [])
    end;
validate_objectidentifier1(S,V) ->
    validate_objectid(S,V,[]).

validate_objectid(_, [], Acc) ->
    lists:reverse(Acc);
validate_objectid(S, [Value|Vrest], Acc) when integer(Value) ->
    validate_objectid(S, Vrest, [Value|Acc]);
validate_objectid(S, [{'NamedNumber',_Name,Value}|Vrest], Acc)
  when integer(Value) ->
    validate_objectid(S, Vrest, [Value|Acc]);
validate_objectid(S, [Id|Vrest], Acc)
  when record(Id,'Externalvaluereference') ->
    case catch get_referenced_type(S, Id) of
	{_,V} when record(V,valuedef) ->
	    case check_value(S, V) of
		#valuedef{checked=true,value=Value} when integer(Value) ->
		    validate_objectid(S, Vrest, [Value|Acc]);
		_ ->
		    error({value, "illegal OBJECT IDENTIFIER", S})
	    end;
	_ ->
	    case reserved_objectid(Id#'Externalvaluereference'.value, Acc) of
		Value when integer(Value) ->
		    validate_objectid(S, Vrest, [Value|Acc]);
		false ->
		    error({value, "illegal OBJECT IDENTIFIER", S})
	    end
    end;
validate_objectid(S, [{Atom,Value}],[]) when atom(Atom),integer(Value) ->
    %% this case when an OBJECT IDENTIFIER value has been parsed as a
    %% SEQUENCE value
    Rec = #'Externalvaluereference'{module=S#state.mname,
				    value=Atom},
    validate_objectidentifier1(S,[Rec,Value]);
validate_objectid(S, [{Atom,EVRef}],[])
  when atom(Atom),record(EVRef,'Externalvaluereference') ->
    %% this case when an OBJECT IDENTIFIER value has been parsed as a
    %% SEQUENCE value OTP-4354
    Rec = #'Externalvaluereference'{module=S#state.mname,
				    value=Atom},
    validate_objectidentifier1(S,[Rec,EVRef]);
validate_objectid(S, _V, _Acc) ->
    error({value, "illegal OBJECT IDENTIFIER",S}).


%% ITU-T Rec. X.680 Annex B - D
reserved_objectid('itu-t',[]) -> 0;
reserved_objectid('ccitt',[]) -> 0;
%% arcs below "itu-t"
reserved_objectid('recommendation',[0]) -> 0;
reserved_objectid('question',[0]) -> 1;
reserved_objectid('administration',[0]) -> 2;
reserved_objectid('network-operator',[0]) -> 3;
reserved_objectid('identified-organization',[0]) -> 4;
%% arcs below "recommendation"
reserved_objectid('a',[0,0]) -> 1;
reserved_objectid('b',[0,0]) -> 2;
reserved_objectid('c',[0,0]) -> 3;
reserved_objectid('d',[0,0]) -> 4;
reserved_objectid('e',[0,0]) -> 5;
reserved_objectid('f',[0,0]) -> 6;
reserved_objectid('g',[0,0]) -> 7;
reserved_objectid('h',[0,0]) -> 8;
reserved_objectid('i',[0,0]) -> 9;
reserved_objectid('j',[0,0]) -> 10;
reserved_objectid('k',[0,0]) -> 11;
reserved_objectid('l',[0,0]) -> 12;
reserved_objectid('m',[0,0]) -> 13;
reserved_objectid('n',[0,0]) -> 14;
reserved_objectid('o',[0,0]) -> 15;
reserved_objectid('p',[0,0]) -> 16;
reserved_objectid('q',[0,0]) -> 17;
reserved_objectid('r',[0,0]) -> 18;
reserved_objectid('s',[0,0]) -> 19;
reserved_objectid('t',[0,0]) -> 20;
reserved_objectid('u',[0,0]) -> 21;
reserved_objectid('v',[0,0]) -> 22;
reserved_objectid('w',[0,0]) -> 23;
reserved_objectid('x',[0,0]) -> 24;
reserved_objectid('y',[0,0]) -> 25;
reserved_objectid('z',[0,0]) -> 26;


reserved_objectid(iso,[]) -> 1;
%% arcs below "iso", note that number 1 is not used
reserved_objectid('standard',[1]) -> 0;
reserved_objectid('member-body',[1]) -> 2;
reserved_objectid('identified-organization',[1]) -> 3;

reserved_objectid('joint-iso-itu-t',[]) -> 2;
reserved_objectid('joint-iso-ccitt',[]) -> 2;

reserved_objectid(_,_) -> false.





validate_objectdescriptor(_S,_Value,_Constr) ->
    ok.

validate_enumerated(S,Id,NamedNumberList,_Constr) when atom(Id) ->
    case lists:keysearch(Id,1,NamedNumberList) of
	{value,_} -> ok;
	false -> error({value,"unknown ENUMERATED",S})
    end;
validate_enumerated(S,{identifier,_Pos,Id},NamedNumberList,_Constr) ->
    case lists:keysearch(Id,1,NamedNumberList) of
	{value,_} -> ok;
	false -> error({value,"unknown ENUMERATED",S})
    end;
validate_enumerated(S,#'Externalvaluereference'{value=Id},
		    NamedNumberList,_Constr) ->
    case lists:keysearch(Id,1,NamedNumberList) of
	{value,_} -> ok;
	false -> error({value,"unknown ENUMERATED",S})
    end.

validate_boolean(_S,_Value,_Constr) ->
    ok.

validate_octetstring(_S,_Value,_Constr) ->
    ok.

validate_restrictedstring(_S,_Value,_Def,_Constr) ->
    ok.

validate_sequence(S=#state{type=Vtype},Value,_Components,_Constr) ->
    case Vtype of
	#type{tag=[{tag,'UNIVERSAL',8,'IMPLICIT',32}]} ->
	    %% this is an 'EXTERNAL' (or INSTANCE OF)
	    case Value of
		[{identification,_}|_RestVal] ->
		    to_EXTERNAL1990(S,Value);
		_ ->
		    Value
	    end;
	_ ->
	    Value
    end.

validate_sequenceof(_S,_Value,_Components,_Constr) ->
    ok.

validate_choice(_S,_Value,_Components,_Constr) ->
    ok.

validate_set(_S,_Value,_Components,_Constr) ->
    ok.

validate_setof(_S,_Value,_Components,_Constr) ->
    ok.

to_EXTERNAL1990(S,[{identification,{'CHOICE',{syntax,Stx}}}|Rest]) ->
    to_EXTERNAL1990(S,Rest,[{'direct-reference',Stx}]);
to_EXTERNAL1990(S,[{identification,{'CHOICE',{'presentation-context-id',I}}}|Rest]) ->
    to_EXTERNAL1990(S,Rest,[{'indirect-reference',I}]);
to_EXTERNAL1990(S,[{identification,{'CHOICE',{'context-negotiation',[{_,PCid},{_,TrStx}]}}}|Rest]) ->
    to_EXTERNAL1990(S,Rest,[{'indirect-reference',PCid},{'direct-reference',TrStx}]);
to_EXTERNAL1990(S,_) ->
    error({value,"illegal value in EXTERNAL type",S}).

to_EXTERNAL1990(S,[V={'data-value-descriptor',_}|Rest],Acc) ->
    to_EXTERNAL1990(S,Rest,[V|Acc]);
to_EXTERNAL1990(_S,[{'data-value',Val}],Acc) ->
    Encoding = {encoding,{'CHOICE',{'octet-aligned',Val}}},
    lists:reverse([Encoding|Acc]);
to_EXTERNAL1990(S,_,_) ->
    error({value,"illegal value in EXTERNAL type",S}).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Functions to normalize the default values of SEQUENCE
%% and SET components into Erlang valid format
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
normalize_value(_,_,mandatory,_) ->
    mandatory;
normalize_value(_,_,'OPTIONAL',_) ->
    'OPTIONAL';
normalize_value(S,Type,{'DEFAULT',Value},NameList) ->
    case catch get_canonic_type(S,Type,NameList) of
	{'BOOLEAN',CType,_} ->
	    normalize_boolean(S,Value,CType);
	{'INTEGER',CType,_} ->
	    normalize_integer(S,Value,CType);
	{'BIT STRING',CType,_} ->
	    normalize_bitstring(S,Value,CType);
	{'OCTET STRING',CType,_} ->
	    normalize_octetstring(S,Value,CType);
	{'NULL',_CType,_} ->
	    %%normalize_null(Value);
	    'NULL';
	{'OBJECT IDENTIFIER',_,_} ->
	    normalize_objectidentifier(S,Value);
	{'ObjectDescriptor',_,_} ->
	    normalize_objectdescriptor(Value);
	{'REAL',_,_} ->
	    normalize_real(Value);
	{'ENUMERATED',CType,_} ->
	    normalize_enumerated(Value,CType);
	{'CHOICE',CType,NewNameList} ->
	    normalize_choice(S,Value,CType,NewNameList);
	{'SEQUENCE',CType,NewNameList} ->
	    normalize_sequence(S,Value,CType,NewNameList);
	{'SEQUENCE OF',CType,NewNameList} ->
	    normalize_seqof(S,Value,CType,NewNameList);
	{'SET',CType,NewNameList} ->
	    normalize_set(S,Value,CType,NewNameList);
	{'SET OF',CType,NewNameList} ->
	    normalize_setof(S,Value,CType,NewNameList);
	{restrictedstring,CType,_} ->
	    normalize_restrictedstring(S,Value,CType);
	_ ->
	    io:format("WARNING: could not check default value ~p~n",[Value]),
	    Value
    end;
normalize_value(S,Type,Val,NameList) ->
    normalize_value(S,Type,{'DEFAULT',Val},NameList).

normalize_boolean(S,{Name,Bool},CType) when atom(Name) ->
    normalize_boolean(S,Bool,CType);
normalize_boolean(_,true,_) ->
    true;
normalize_boolean(_,false,_) ->
    false;
normalize_boolean(S,Bool=#'Externalvaluereference'{},CType) ->
    get_normalized_value(S,Bool,CType,fun normalize_boolean/3,[]);
normalize_boolean(_,Other,_) ->
    throw({error,{asn1,{'invalid default value',Other}}}).

normalize_integer(_S,Int,_) when integer(Int) ->
    Int;
normalize_integer(_S,{Name,Int},_) when atom(Name),integer(Int) ->
    Int;
normalize_integer(S,{Name,Int=#'Externalvaluereference'{}},
		  Type) when atom(Name) ->
    normalize_integer(S,Int,Type);
normalize_integer(S,Int=#'Externalvaluereference'{value=Name},Type) ->
    case Type of
	NNL when list(NNL) ->
	    case lists:keysearch(Name,1,NNL) of
		{value,{Name,Val}} ->
		    Val;
		false ->
		    get_normalized_value(S,Int,Type,
					 fun normalize_integer/3,[])
	    end;
	_ ->
	    get_normalized_value(S,Int,Type,fun normalize_integer/3,[])
    end;
normalize_integer(_,Int,_) ->
    exit({'Unknown INTEGER value',Int}).

normalize_bitstring(S,Value,Type)->
    %% There are four different Erlang formats of BIT STRING:
    %% 1 - a list of ones and zeros.
    %% 2 - a list of atoms.
    %% 3 - as an integer, for instance in hexadecimal form.
    %% 4 - as a tuple {Unused, Binary} where Unused is an integer
    %%   and tells how many bits of Binary are unused.
    %%
    %% normalize_bitstring/3 transforms Value according to:
    %% A to 3,
    %% B to 1,
    %% C to 1 or 3
    %% D to 2,
    %% Value can be on format:
    %% A - {hstring, String}, where String is a hexadecimal string.
    %% B - {bstring, String}, where String is a string on bit format
    %% C - #'Externalvaluereference'{value=V}, where V is a defined value
    %% D - list of #'Externalvaluereference', where each value component
    %%     is an identifier corresponing to NamedBits in Type.
    case Value of
	{hstring,String} when list(String) ->
	    hstring_to_int(String);
	{bstring,String} when list(String) ->
	    bstring_to_bitlist(String);
	Rec when record(Rec,'Externalvaluereference') ->
	    get_normalized_value(S,Value,Type,
				 fun normalize_bitstring/3,[]);
	RecList when list(RecList) ->
	    case Type of
		NBL when list(NBL) ->
		    F = fun(#'Externalvaluereference'{value=Name}) ->
				case lists:keysearch(Name,1,NBL) of
				    {value,{Name,_}} ->
					Name;
				    Other ->
					throw({error,Other})
				end;
			   (Other) ->
				throw({error,Other})
			end,
		    case catch lists:map(F,RecList) of
			{error,Reason} ->
			    io:format("WARNING: default value not "
				      "compatible with type definition ~p~n",
				      [Reason]),
			    Value;
			NewList ->
			    NewList
		    end;
		_ ->
		    io:format("WARNING: default value not "
			      "compatible with type definition ~p~n",
			      [RecList]),
		    Value
	    end;
	{Name,String} when atom(Name) ->
	    normalize_bitstring(S,String,Type);
	Other ->
	    io:format("WARNING: illegal default value ~p~n",[Other]),
	    Value
    end.

hstring_to_int(L) when list(L) ->
    hstring_to_int(L,0).
hstring_to_int([H|T],Acc) when H >= $A, H =< $F ->
    hstring_to_int(T,(Acc bsl 4) + (H - $A + 10) ) ;
hstring_to_int([H|T],Acc) when H >= $0, H =< $9 ->
    hstring_to_int(T,(Acc bsl 4) + (H - $0));
hstring_to_int([],Acc) ->
    Acc.

bstring_to_bitlist([H|T]) when H == $0; H == $1 ->
    [H - $0 | bstring_to_bitlist(T)];
bstring_to_bitlist([]) ->
    [].

%% normalize_octetstring/1 changes representation of input Value to a
%% list of octets.
%% Format of Value is one of:
%% {bstring,String} each element in String corresponds to one bit in an octet
%% {hstring,String} each element in String corresponds to one byte in an octet
%% #'Externalvaluereference'
normalize_octetstring(S,Value,CType) ->
    case Value of
	{bstring,String} ->
	    bstring_to_octetlist(String);
	{hstring,String} ->
	    hstring_to_octetlist(String);
	Rec when record(Rec,'Externalvaluereference') ->
	    get_normalized_value(S,Value,CType,
				 fun normalize_octetstring/3,[]);
	{Name,String} when atom(Name) ->
	    normalize_octetstring(S,String,CType);
	List when list(List) ->
	    %% check if list elements are valid octet values
	    lists:map(fun([])-> ok;
			 (H)when H > 255->
			      io:format("WARNING: not legal octet value ~p in OCTET STRING, ~p~n",[H,List]);
			 (_)-> ok
		      end, List),
	    List;
	Other ->
	    io:format("WARNING: unknown default value ~p~n",[Other]),
	    Value
    end.


bstring_to_octetlist([]) ->
    [];
bstring_to_octetlist([H|T]) when H == $0 ; H == $1 ->
    bstring_to_octetlist(T,6,[(H - $0) bsl 7]).
bstring_to_octetlist([H|T],0,[Hacc|Tacc]) when H == $0; H == $1 ->
    bstring_to_octetlist(T, 7, [0,Hacc + (H -$0)| Tacc]);
bstring_to_octetlist([H|T],BSL,[Hacc|Tacc]) when H == $0; H == $1 ->
    bstring_to_octetlist(T, BSL-1, [Hacc + ((H - $0) bsl BSL)| Tacc]);
bstring_to_octetlist([],7,[0|Acc]) ->
    lists:reverse(Acc);
bstring_to_octetlist([],_,Acc) ->
    lists:reverse(Acc).

hstring_to_octetlist([]) ->
    [];
hstring_to_octetlist(L) ->
    hstring_to_octetlist(L,4,[]).
hstring_to_octetlist([H|T],0,[Hacc|Tacc]) when H >= $A, H =< $F ->
    hstring_to_octetlist(T,4,[Hacc + (H - $A + 10)|Tacc]);
hstring_to_octetlist([H|T],BSL,Acc) when H >= $A, H =< $F ->
    hstring_to_octetlist(T,0,[(H - $A + 10) bsl BSL|Acc]);
hstring_to_octetlist([H|T],0,[Hacc|Tacc]) when H >= $0; H =< $9 ->
    hstring_to_octetlist(T,4,[Hacc + (H - $0)|Tacc]);
hstring_to_octetlist([H|T],BSL,Acc) when H >= $0; H =< $9 ->
    hstring_to_octetlist(T,0,[(H - $0) bsl BSL|Acc]);
hstring_to_octetlist([],_,Acc) ->
    lists:reverse(Acc).

normalize_objectidentifier(S,Value) ->
    validate_objectidentifier(S,Value,[]).

normalize_objectdescriptor(Value) ->
    Value.

normalize_real(Value) ->
    Value.

normalize_enumerated(#'Externalvaluereference'{value=V},CType)
  when list(CType) ->
    normalize_enumerated2(V,CType);
normalize_enumerated(Value,CType) when atom(Value),list(CType) ->
    normalize_enumerated2(Value,CType);
normalize_enumerated({Name,EnumV},CType) when atom(Name) ->
    normalize_enumerated(EnumV,CType);
normalize_enumerated(Value,{CType1,CType2}) when list(CType1), list(CType2)->
    normalize_enumerated(Value,CType1++CType2);
normalize_enumerated(V,CType) ->
    io:format("WARNING: Enumerated unknown type ~p~n",[CType]),
    V.
normalize_enumerated2(V,Enum) ->
    case lists:keysearch(V,1,Enum) of
	{value,{Val,_}} -> Val;
	_ ->
	    io:format("WARNING: Enumerated value is not correct ~p~n",[V]),
	    V
    end.

normalize_choice(S,{'CHOICE',{C,V}},CType,NameList) when atom(C) ->
    Value =
	case V of
	    Rec when record(Rec,'Externalvaluereference') ->
		get_normalized_value(S,V,CType,
				     fun normalize_choice/4,
				     [NameList]);
	    _ -> V
	end,
    case catch lists:keysearch(C,#'ComponentType'.name,CType) of
	{value,#'ComponentType'{typespec=CT,name=Name}} ->
	    {C,normalize_value(S,CT,{'DEFAULT',Value},
			       [Name|NameList])};
	Other ->
	    io:format("WARNING: Wrong format of type/value ~p/~p~n",
		      [Other,Value]),
	    {C,Value}
    end;
normalize_choice(S,{'DEFAULT',ValueList},CType,NameList) ->
    lists:map(fun(X)-> normalize_choice(S,X,CType,NameList) end, ValueList);
normalize_choice(S,Val=#'Externalvaluereference'{},CType,NameList) ->
    {_,#valuedef{value=V}}=get_referenced_type(S,Val),
    normalize_choice(S,{'CHOICE',V},CType,NameList);
%    get_normalized_value(S,Val,CType,fun normalize_choice/4,[NameList]);
normalize_choice(S,{Name,ChoiceVal},CType,NameList)
  when atom(Name) ->
    normalize_choice(S,ChoiceVal,CType,NameList).

normalize_sequence(S,{Name,Value},Components,NameList)
  when atom(Name),list(Value) ->
    normalize_sequence(S,Value,Components,NameList);
normalize_sequence(S,Value,Components,NameList) ->
    normalized_record('SEQUENCE',S,Value,Components,NameList).

normalize_set(S,{Name,Value},Components,NameList)
  when atom(Name),list(Value) ->
    normalized_record('SET',S,Value,Components,NameList);
normalize_set(S,Value,Components,NameList) ->
    normalized_record('SET',S,Value,Components,NameList).

normalized_record(SorS,S,Value,Components,NameList) ->
    NewName = list_to_atom(asn1ct_gen:list2name(NameList)),
    NoComps = length(Components),
    case normalize_seq_or_set(SorS,S,Value,Components,NameList,[]) of
	ListOfVals when length(ListOfVals) == NoComps ->
	    list_to_tuple([NewName|ListOfVals]);
	_ ->
	    error({type,{illegal,default,value,Value},S})
    end.

normalize_seq_or_set(SorS,S,[{Cname,V}|Vs],
		     [#'ComponentType'{name=Cname,typespec=TS}|Cs],
		     NameList,Acc) ->
    NewNameList =
	case TS#type.def of
	    #'Externaltypereference'{type=TName} ->
		[TName];
	    _ -> [Cname|NameList]
	end,
    NVal = normalize_value(S,TS,{'DEFAULT',V},NewNameList),
    normalize_seq_or_set(SorS,S,Vs,Cs,NameList,[NVal|Acc]);
normalize_seq_or_set(SorS,S,Values=[{_Cname1,_V}|_Vs],
		     [#'ComponentType'{prop='OPTIONAL'}|Cs],
		     NameList,Acc) ->
    normalize_seq_or_set(SorS,S,Values,Cs,NameList,[asn1_NOVALUE|Acc]);
normalize_seq_or_set(SorS,S,Values=[{_Cname1,_V}|_Vs],
		    [#'ComponentType'{name=Cname2,typespec=TS,
				      prop={'DEFAULT',Value}}|Cs],
		    NameList,Acc) ->
    NewNameList =
	case TS#type.def of
	    #'Externaltypereference'{type=TName} ->
		[TName];
	    _ -> [Cname2|NameList]
	end,
    NVal =  normalize_value(S,TS,{'DEFAULT',Value},NewNameList),
    normalize_seq_or_set(SorS,S,Values,Cs,NameList,[NVal|Acc]);
normalize_seq_or_set(_SorS,_S,[],[],_,Acc) ->
    lists:reverse(Acc);
%% If default value is {} ComponentTypes in SEQUENCE are marked DEFAULT
%% or OPTIONAL (or the type is defined SEQUENCE{}, which is handled by
%% the previous case).
normalize_seq_or_set(SorS,S,[],
		     [#'ComponentType'{name=Name,typespec=TS,
				       prop={'DEFAULT',Value}}|Cs],
		     NameList,Acc) ->
    NewNameList =
	case TS#type.def of
	    #'Externaltypereference'{type=TName} ->
		[TName];
	    _ -> [Name|NameList]
	end,
    NVal =  normalize_value(S,TS,{'DEFAULT',Value},NewNameList),
    normalize_seq_or_set(SorS,S,[],Cs,NameList,[NVal|Acc]);
normalize_seq_or_set(SorS,S,[],[#'ComponentType'{prop='OPTIONAL'}|Cs],
		     NameList,Acc) ->
    normalize_seq_or_set(SorS,S,[],Cs,NameList,[asn1_NOVALUE|Acc]);
normalize_seq_or_set(SorS,S,Value=#'Externalvaluereference'{},
		     Cs,NameList,Acc) ->
    get_normalized_value(S,Value,Cs,fun normalize_seq_or_set/6,
			 [SorS,NameList,Acc]);
normalize_seq_or_set(_SorS,S,V,_,_,_) ->
    error({type,{illegal,default,value,V},S}).

normalize_seqof(S,Value,Type,NameList) ->
    normalize_s_of('SEQUENCE OF',S,Value,Type,NameList).

normalize_setof(S,Value,Type,NameList) ->
    normalize_s_of('SET OF',S,Value,Type,NameList).

normalize_s_of(SorS,S,Value,Type,NameList) when list(Value) ->
    DefValueList = lists:map(fun(X) -> {'DEFAULT',X} end,Value),
    Suffix = asn1ct_gen:constructed_suffix(SorS,Type),
    Def = Type#type.def,
    InnerType = asn1ct_gen:get_inner(Def),
    WhatKind = asn1ct_gen:type(InnerType),
    NewNameList =
	case WhatKind of
	    {constructed,bif} ->
		[Suffix|NameList];
	    #'Externaltypereference'{type=Name} ->
		[Name];
	    _ -> []
	end,
    NormFun = 	fun (X) -> normalize_value(S,Type,X,
					   NewNameList) end,
    case catch lists:map(NormFun, DefValueList) of
	List when list(List) ->
	    List;
	_ ->
	    io:format("WARNING: ~p could not handle value ~p~n",
		      [SorS,Value]),
	    Value
    end;
normalize_s_of(SorS,S,Value,Type,NameList)
  when record(Value,'Externalvaluereference') ->
    get_normalized_value(S,Value,Type,fun normalize_s_of/5,
			 [SorS,NameList]).
%     case catch get_referenced_type(S,Value) of
% 	{_,#valuedef{value=V}} ->
% 	    normalize_s_of(SorS,S,V,Type);
% 	{error,Reason} ->
% 	    io:format("WARNING: ~p could not handle value ~p~n",
% 		      [SorS,Value]),
% 	    Value;
% 	{_,NewVal} ->
% 	    normalize_s_of(SorS,S,NewVal,Type);
% 	_ ->
% 	    io:format("WARNING: ~p could not handle value ~p~n",
% 		      [SorS,Value]),
% 	    Value
%     end.


%% normalize_restrictedstring handles all format of restricted strings.
%% tuple case
normalize_restrictedstring(_S,[Int1,Int2],_) when integer(Int1),integer(Int2) ->
    {Int1,Int2};
%% quadruple case
normalize_restrictedstring(_S,[Int1,Int2,Int3,Int4],_) when integer(Int1),
							   integer(Int2),
							   integer(Int3),
							   integer(Int4) ->
    {Int1,Int2,Int3,Int4};
%% character string list case
normalize_restrictedstring(S,[H|T],CType) when list(H);tuple(H) ->
    [normalize_restrictedstring(S,H,CType)|normalize_restrictedstring(S,T,CType)];
%% character sting case
normalize_restrictedstring(_S,CString,_) when list(CString) ->
    Fun =
	fun(X) ->
		if
		    $X =< 255, $X >= 0 ->
			ok;
		    true ->
			io:format("WARNING: illegal character in string"
				  " ~p~n",[X])
		end
	end,
    lists:foreach(Fun,CString),
    CString;
%% definedvalue case or argument in a parameterized type
normalize_restrictedstring(S,ERef,CType) when record(ERef,'Externalvaluereference') ->
    get_normalized_value(S,ERef,CType,
			 fun normalize_restrictedstring/3,[]);
%%
normalize_restrictedstring(S,{Name,Val},CType) when atom(Name) ->
    normalize_restrictedstring(S,Val,CType).


get_normalized_value(S,Val,Type,Func,AddArg) ->
    case catch get_referenced_type(S,Val) of
	{_,#valuedef{type=_T,value=V}} ->
	    %% should check that Type and T equals
	    call_Func(S,V,Type,Func,AddArg);
	{error,_} ->
	    io:format("WARNING: default value not "
		      "comparable ~p~n",[Val]),
	    Val;
	{_,NewVal} ->
	    call_Func(S,NewVal,Type,Func,AddArg);
	_ ->
	    io:format("WARNING: default value not "
		      "comparable ~p~n",[Val]),
	    Val
    end.

call_Func(S,Val,Type,Func,ArgList) ->
    case ArgList of
	[] ->
	    Func(S,Val,Type);
	[LastArg] ->
	    Func(S,Val,Type,LastArg);
	[Arg1,LastArg1] ->
	    Func(Arg1,S,Val,Type,LastArg1);
	[Arg1,LastArg1,LastArg2] ->
	    Func(Arg1,S,Val,Type,LastArg1,LastArg2)
    end.


get_canonic_type(S,Type,NameList) ->
    {InnerType,NewType,NewNameList} =
	case Type#type.def of
	    Name when atom(Name) ->
		{Name,Type,NameList};
	    Ref when record(Ref,'Externaltypereference') ->
		{_,#typedef{name=Name,typespec=RefedType}} =
		    get_referenced_type(S,Ref),
		get_canonic_type(S,RefedType,[Name]);
	    {Name,T} when atom(Name) ->
		{Name,T,NameList};
	    Seq when record(Seq,'SEQUENCE') ->
		{'SEQUENCE',Seq#'SEQUENCE'.components,NameList};
	    Set when record(Set,'SET') ->
		{'SET',Set#'SET'.components,NameList}
	end,
    {asn1ct_gen:unify_if_string(InnerType),NewType,NewNameList}.



check_ptype(_S,Type,Ts) when record(Ts,type) ->
    %Tag = Ts#type.tag,
    %Constr = Ts#type.constraint,
    Def = Ts#type.def,
    NewDef=
	case Def of
	    Seq when record(Seq,'SEQUENCE') ->
		#newt{type=Seq#'SEQUENCE'{pname=Type#ptypedef.name}};
	    Set when record(Set,'SET') ->
		#newt{type=Set#'SET'{pname=Type#ptypedef.name}};
	    _Other ->
		#newt{}
	end,
    Ts2 = case NewDef of
	      #newt{type=unchanged} ->
		  Ts;
	      #newt{type=TDef}->
		  Ts#type{def=TDef}
	  end,
    Ts2.


% check_type(S,Type,ObjSpec={{objectclassname,_},_}) ->
%     check_class(S,ObjSpec);
check_type(_S,Type,Ts) when record(Type,typedef),
			   (Type#typedef.checked==true) ->
    Ts;
check_type(_S,Type,Ts) when record(Type,typedef),
			   (Type#typedef.checked==idle) -> % the check is going on
    Ts;
check_type(S=#state{recordtopname=TopName},Type,Ts) when record(Ts,type) ->
    {Def,Tag,Constr} =
	case match_parameters(Ts#type.def,S#state.parameters) of
	    #type{constraint=_Ctmp,def=Dtmp} ->
		{Dtmp,Ts#type.tag,Ts#type.constraint};
	    Dtmp ->
		{Dtmp,Ts#type.tag,Ts#type.constraint}
	end,
    TempNewDef = #newt{type=Def,tag=Tag,constraint=Constr},
    TestFun =
	fun(Tref) ->
		{_,MaybeChoice} = get_referenced_type(S,Tref),
		case catch((MaybeChoice#typedef.typespec)#type.def) of
		    {'CHOICE',_} ->
			maybe_illicit_implicit_tag(choice,Tag);
		    'ANY' ->
			maybe_illicit_implicit_tag(open_type,Tag);
		    'ANY DEFINED BY' ->
			maybe_illicit_implicit_tag(open_type,Tag);
		    'ASN1_OPEN_TYPE' ->
			maybe_illicit_implicit_tag(open_type,Tag);
		    _ ->
			Tag
		end
	end,
    NewDef=
	case Def of
	    Ext when record(Ext,'Externaltypereference') ->
		{_,RefTypeDef} = get_referenced_type(S,Ext),
% 		case RefTypeDef of
% 		    Class when record(Class,classdef) ->
% 			throw({asn1_class,Class});
% 		    _ -> ok
% 		end,
		case is_class(S,RefTypeDef) of
		    true -> throw({asn1_class,RefTypeDef});
		    _ -> ok
		end,
		Ct = TestFun(Ext),
		RefType =
%case  S#state.erule of
%			      ber_bin_v2 ->
		    case RefTypeDef#typedef.checked of
			true ->
			    RefTypeDef#typedef.typespec;
			_ ->
			    NewRefTypeDef1 = RefTypeDef#typedef{checked=idle},
			    asn1_db:dbput(S#state.mname,
					  NewRefTypeDef1#typedef.name,NewRefTypeDef1),
			    RefType1 =
				check_type(S,RefTypeDef,RefTypeDef#typedef.typespec),
			    NewRefTypeDef2 =
				RefTypeDef#typedef{checked=true,typespec = RefType1},
			    asn1_db:dbput(S#state.mname,
					  NewRefTypeDef2#typedef.name,NewRefTypeDef2),
			    %% update the type and mark as checked
			    RefType1
		    end,
%			      _ -> RefTypeDef#typedef.typespec
%			  end,

		case asn1ct_gen:prim_bif(asn1ct_gen:get_inner(RefType#type.def)) of
		    true ->
			%% Here we expand to a built in type and inline it
			TempNewDef#newt{
			  type=
			  RefType#type.def,
			  tag=
			  merge_tags(Ct,RefType#type.tag),
			  constraint=
			  merge_constraints(check_constraints(S,Constr),
					    RefType#type.constraint)};
		    _ ->
			%% Here we only expand the tags and keep the ext ref

			TempNewDef#newt{
			  type=
			  check_externaltypereference(S,Ext),
			  tag =
			  case S#state.erule of
			      ber_bin_v2 ->
				  merge_tags(Ct,RefType#type.tag);
			      _ ->
				  Ct
			  end
			 }
		end;
	    'ANY' ->
		Ct=maybe_illicit_implicit_tag(open_type,Tag),
		TempNewDef#newt{type='ASN1_OPEN_TYPE',tag=Ct};
	    {'ANY_DEFINED_BY',_} ->
		Ct=maybe_illicit_implicit_tag(open_type,Tag),
		TempNewDef#newt{type='ASN1_OPEN_TYPE',tag=Ct};
	    'INTEGER' ->
		check_integer(S,[],Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_INTEGER))};

	    {'INTEGER',NamedNumberList} ->
		TempNewDef#newt{type={'INTEGER',check_integer(S,NamedNumberList,Constr)},
				tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_INTEGER))};
	    {'BIT STRING',NamedNumberList} ->
		NewL = check_bitstring(S,NamedNumberList,Constr),
%%		erlang:display({asn1ct_check,NamedNumberList,NewL}),
		TempNewDef#newt{type={'BIT STRING',NewL},
				tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_BIT_STRING))};
	    'NULL' ->
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_NULL))};
	    'OBJECT IDENTIFIER' ->
		check_objectidentifier(S,Constr),
		TempNewDef#newt{tag=
			       merge_tags(Tag,?TAG_PRIMITIVE(?N_OBJECT_IDENTIFIER))};
	    'ObjectDescriptor' ->
		TempNewDef#newt{tag=
			       merge_tags(Tag,?TAG_PRIMITIVE(?N_OBJECT_DESCRIPTOR))};
	    'EXTERNAL' ->
%%		AssociatedType = asn1_db:dbget(S#state.mname,'EXTERNAL'),
%%		#newt{type=check_type(S,Type,AssociatedType)};
		put(external,unchecked),
		TempNewDef#newt{type=
				#'Externaltypereference'{module=S#state.mname,
							 type='EXTERNAL'},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_EXTERNAL))};
	    {'INSTANCE OF',DefinedObjectClass,Constraint} ->
		%% check that DefinedObjectClass is of TYPE-IDENTIFIER class
		%% If Constraint is empty make it the general INSTANCE OF type
		%% If Constraint is not empty make an inlined type
		%% convert INSTANCE OF to the associated type
		IOFDef=check_instance_of(S,DefinedObjectClass,Constraint),
		TempNewDef#newt{type=IOFDef,
				tag=merge_tags(Tag,?TAG_CONSTRUCTED(?N_INSTANCE_OF))};
	    {'ENUMERATED',NamedNumberList} ->
		TempNewDef#newt{type=
				{'ENUMERATED',
				 check_enumerated(S,NamedNumberList,Constr)},
				tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_ENUMERATED))};
	    'EMBEDDED PDV' ->
%		AssociatedType = asn1_db:dbget(S#state.mname,'EMBEDDED PDV'),
%		CheckedType = check_type(S,Type,
%					 AssociatedType#typedef.typespec),
		put(embedded_pdv,unchecked),
		TempNewDef#newt{type=
				#'Externaltypereference'{module=S#state.mname,
							 type='EMBEDDED PDV'},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_EMBEDDED_PDV))};
	    'BOOLEAN'->
		check_boolean(S,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_BOOLEAN))};
	    'OCTET STRING' ->
		check_octetstring(S,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_OCTET_STRING))};
	    'NumericString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_NumericString))};
	    'TeletexString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_TeletexString))};
	    'VideotexString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_VideotexString))};
	    'UTCTime' ->
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_UTCTime))};
	    'GeneralizedTime' ->
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_GeneralizedTime))};
	    'GraphicString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_GraphicString))};
	    'VisibleString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_VisibleString))};
	    'GeneralString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_GeneralString))};
	    'PrintableString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_PrintableString))};
	    'IA5String' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_IA5String))};
	    'BMPString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_BMPString))};
	    'UniversalString' ->
		check_restrictedstring(S,Def,Constr),
		TempNewDef#newt{tag=
				merge_tags(Tag,?TAG_PRIMITIVE(?N_UniversalString))};
	    'CHARACTER STRING' ->
%		AssociatedType = asn1_db:dbget(S#state.mname,
%					       'CHARACTER STRING'),
%		CheckedType = check_type(S,Type,
%					 AssociatedType#typedef.typespec),
		put(character_string,unchecked),
		TempNewDef#newt{type=
				#'Externaltypereference'{module=S#state.mname,
							 type='CHARACTER STRING'},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_CHARACTER_STRING))};
	    Seq when record(Seq,'SEQUENCE') ->
		RecordName =
		    case TopName of
			[] ->
			    [Type#typedef.name];
			_ ->
			    TopName
		    end,
		{TableCInf,Components} =
		    check_sequence(S#state{recordtopname=
					   RecordName},
					   Type,Seq#'SEQUENCE'.components),
		TempNewDef#newt{type=Seq#'SEQUENCE'{tablecinf=TableCInf,
					  components=Components},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_SEQUENCE))};
	    {'SEQUENCE OF',Components} ->
		TempNewDef#newt{type={'SEQUENCE OF',check_sequenceof(S,Type,Components)},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_SEQUENCE))};
	    {'CHOICE',Components} ->
		Ct = maybe_illicit_implicit_tag(choice,Tag),
		TempNewDef#newt{type={'CHOICE',check_choice(S,Type,Components)},tag=Ct};
	    Set when record(Set,'SET') ->
		RecordName=
		    case TopName of
			[] ->
			    [Type#typedef.name];
			_ ->
			    TopName
		    end,
		{Sorted,TableCInf,Components} =
		    check_set(S#state{recordtopname=RecordName},
			      Type,Set#'SET'.components),
		TempNewDef#newt{type=Set#'SET'{sorted=Sorted,
				     tablecinf=TableCInf,
				     components=Components},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_SET))};
	    {'SET OF',Components} ->
		TempNewDef#newt{type={'SET OF',check_setof(S,Type,Components)},
				tag=
				merge_tags(Tag,?TAG_CONSTRUCTED(?N_SET))};
	    %% This is a temporary hack until the full Information Obj Spec
	    %% in X.681 is supported
	    {{typereference,_,'TYPE-IDENTIFIER'},[{typefieldreference,_,'Type'}]} ->
		Ct=maybe_illicit_implicit_tag(open_type,Tag),
		TempNewDef#newt{type='ASN1_OPEN_TYPE',tag=Ct};

	    {#'Externaltypereference'{type='TYPE-IDENTIFIER'},
	     [{typefieldreference,_,'Type'}]} ->
		Ct=maybe_illicit_implicit_tag(open_type,Tag),
		TempNewDef#newt{type='ASN1_OPEN_TYPE',tag=Ct};

	    {pt,Ptype,ParaList} ->
		%% Ptype might be a parameterized - type, object set or
		%% value set. If it isn't a parameterized type notify the
		%% calling function.
		{_,Ptypedef} = get_referenced_type(S,Ptype),
		notify_if_not_ptype(S,Ptypedef),
		NewParaList = [match_parameters(TmpParam,S#state.parameters)||
				  TmpParam <- ParaList],
		Instance = instantiate_ptype(S,Ptypedef,NewParaList),
		TempNewDef#newt{type=Instance#type.def,
				tag=merge_tags(Tag,Instance#type.tag),
				constraint=Instance#type.constraint,
				inlined=yes};

%	    {ClRef,FieldRefList} when record(ClRef,'Externaltypereference') ->
	    OCFT=#'ObjectClassFieldType'{class=ClRef} ->
		%% this case occures in a SEQUENCE when
		%% the type of the component is a ObjectClassFieldType
		ClassSpec = check_class(S,ClRef),
		NewTypeDef = maybe_open_type(S,ClassSpec,OCFT,Constr),
		InnerTag = get_innertag(S,NewTypeDef),
		MergedTag = merge_tags(Tag,InnerTag),
		Ct =
		    case is_open_type(NewTypeDef) of
			true ->
			    maybe_illicit_implicit_tag(open_type,MergedTag);
			_ ->
			    MergedTag
		    end,
		TempNewDef#newt{type=NewTypeDef,tag=Ct};
	    {valueset,Vtype} ->
		TempNewDef#newt{type={valueset,check_type(S,Type,Vtype)}};
	    Other ->
		exit({'cant check' ,Other})
	end,
    Ts2 = case NewDef of
	      #newt{type=unchanged} ->
		  Ts#type{def=Def};
	      #newt{type=TDef}->
		  Ts#type{def=TDef}
	  end,
    NewTag = case NewDef of
		 #newt{tag=unchanged} ->
		     Tag;
		 #newt{tag=TT} ->
		     TT
	     end,
    T3 = Ts2#type{tag = lists:map(fun(TempTag = #tag{type={default,TTx}}) ->
					  TempTag#tag{type=TTx};
				     (Else) -> Else end, NewTag)},
    T4 = case NewDef of
	     #newt{constraint=unchanged} ->
		 T3#type{constraint=Constr};
	     #newt{constraint=NewConstr} ->
		 T3#type{constraint=NewConstr}
	 end,
    T5 = T4#type{inlined=NewDef#newt.inlined},
    T5#type{constraint=check_constraints(S,T5#type.constraint)}.


get_innertag(_S,#'ObjectClassFieldType'{type=Type}) ->
    case Type of
	#type{tag=Tag} -> Tag;
	{fixedtypevaluefield,_,#type{tag=Tag}} -> Tag;
	{TypeFieldName,_} when atom(TypeFieldName) -> [];
	_ -> []
    end;
get_innertag(_S,_) ->
    [].

is_class(_S,#classdef{}) ->
    true;
is_class(S,#typedef{typespec=#type{def=Eref}})
  when record(Eref,'Externaltypereference')->
    {_,NextDef} = get_referenced_type(S,Eref),
    is_class(S,NextDef);
is_class(_,_) ->
    false.

get_class_def(_S,CD=#classdef{}) ->
    CD;
get_class_def(S,#typedef{typespec=#type{def=Eref}})
  when record(Eref,'Externaltypereference') ->
    {_,NextDef} = get_referenced_type(S,Eref),
    get_class_def(S,NextDef).

maybe_illicit_implicit_tag(Kind,Tag) ->
    case Tag of
	[#tag{type='IMPLICIT'}|_T] ->
	    throw({error,{asn1,{implicit_tag_before,Kind}}});
	[ChTag = #tag{type={default,_}}|T] ->
	    case Kind of
		open_type ->
		    [ChTag#tag{type='EXPLICIT',form=32}|T]; %X.680 30.6c, X.690 8.14.2
		choice ->
		    [ChTag#tag{type='EXPLICIT',form=32}|T] % X.680 28.6 c, 30.6c
	    end;
	_ ->
	    Tag % unchanged
    end.

%% maybe_open_type/2 -> {ClassSpec,FieldRefList} | 'ASN1_OPEN_TYPE'
%% if the FieldRefList points out a typefield and the class don't have
%% any UNIQUE field, so that a component relation constraint cannot specify
%% the type of a typefield, return 'ASN1_OPEN_TYPE', otherwise return
%% {ClassSpec,FieldRefList}.
maybe_open_type(S,ClassSpec=#objectclass{fields=Fs},
		OCFT=#'ObjectClassFieldType'{fieldname=FieldRefList},
		Constr) ->
    Type = get_ObjectClassFieldType(S,Fs,FieldRefList),
    FieldNames=get_referenced_fieldname(FieldRefList),
    case lists:last(FieldRefList) of
	{valuefieldreference,_} ->
	    OCFT#'ObjectClassFieldType'{class=ClassSpec,
					fieldname=FieldNames,
					type=Type};
	{typefieldreference,_} ->
	    case {catch get_unique_fieldname(#classdef{typespec=ClassSpec}),
		  asn1ct_gen:get_constraint(Constr,componentrelation)}of
		{Tuple,_} when tuple(Tuple) ->
		    OCFT#'ObjectClassFieldType'{class=ClassSpec,
						fieldname=FieldNames,
						type='ASN1_OPEN_TYPE'};
		{_,no} ->
		    OCFT#'ObjectClassFieldType'{class=ClassSpec,
						fieldname=FieldNames,
						type='ASN1_OPEN_TYPE'};
		_ ->
		    OCFT#'ObjectClassFieldType'{class=ClassSpec,
						fieldname=FieldNames,
						type=Type}
	    end
    end.

is_open_type(#'ObjectClassFieldType'{type='ASN1_OPEN_TYPE'}) ->
    true;
is_open_type(#'ObjectClassFieldType'{}) ->
    false.


notify_if_not_ptype(S,#pvaluesetdef{type=Type}) ->
    case Type#type.def of
	Ref when record(Ref,'Externaltypereference') ->
	    case get_referenced_type(S,Ref) of
		{_,#classdef{}} ->
		    throw(pobjectsetdef);
		{_,#typedef{}} ->
		    throw(pvalueset)
	    end;
	T when record(T,type) -> % this must be a value set
	    throw(pvalueset)
    end;
notify_if_not_ptype(_S,#ptypedef{}) ->
    ok.

% fix me
instantiate_ptype(S,Ptypedef,ParaList) ->
    #ptypedef{args=Args,typespec=Type} = Ptypedef,
%    Args = get_pt_args(Ptypedef),
%    Type = get_pt_spec(Ptypedef),
    MatchedArgs = match_args(Args, ParaList, []),
    NewS = S#state{type=Type,parameters=MatchedArgs,abscomppath=[]},
    %The abscomppath must be empty since a table constraint in a
    %parameterized type only can refer to components within the type
    check_type(NewS, Ptypedef, Type).

get_pt_args(#ptypedef{args=Args}) ->
    Args;
get_pt_args(#pvaluesetdef{args=Args}) ->
    Args;
get_pt_args(#pvaluedef{args=Args}) ->
    Args;
get_pt_args(#pobjectdef{args=Args}) ->
    Args;
get_pt_args(#pobjectsetdef{args=Args}) ->
    Args.

get_pt_spec(#ptypedef{typespec=Type}) ->
    Type;
get_pt_spec(#pvaluedef{value=Value}) ->
    Value;
get_pt_spec(#pvaluesetdef{valueset=VS}) ->
    VS;
get_pt_spec(#pobjectdef{def=Def}) ->
    Def;
get_pt_spec(#pobjectsetdef{def=Def}) ->
    Def.



match_args([FormArg|Ft], [ActArg|At], Acc) ->
    match_args(Ft, At, [{FormArg,ActArg}|Acc]);
match_args([], [], Acc) ->
    lists:reverse(Acc);
match_args(_, _, _) ->
    throw({error,{asn1,{wrong_number_of_arguments}}}).

check_constraints(S,C) when list(C) ->
    check_constraints(S, C, []);
check_constraints(S,C) when record(C,constraint) ->
    check_constraints(S, C#constraint.c, []).


resolv_tuple_or_list(S,List) when list(List) ->
    lists:map(fun(X)->resolv_value(S,X) end, List);
resolv_tuple_or_list(S,{Lb,Ub}) ->
    {resolv_value(S,Lb),resolv_value(S,Ub)}.

%%%-----------------------------------------
%% If the constraint value is a defined value the valuename
%% is replaced by the actual value
%%
resolv_value(S,Val) ->
    case match_parameters(Val, S#state.parameters) of
	Id -> % unchanged
	    resolv_value1(S,Id);
	Other ->
	    resolv_value(S,Other)
    end.

resolv_value1(S = #state{mname=M,inputmodules=InpMods},
	      V=#'Externalvaluereference'{pos=Pos,module=ExtM,value=Name}) ->
    case ExtM of
	M -> resolv_value2(S,M,Name,Pos);
	_ ->
	    case lists:member(ExtM,InpMods) of
		true ->
		    resolv_value2(S,M,Name,Pos);
		false ->
		    V
	    end
    end;
resolv_value1(S,{gt,V}) ->
    case V of
	Int when integer(Int) ->
	    V + 1;
	#valuedef{value=Int} ->
	    1 + resolv_value(S,Int);
	Other ->
	    throw({error,{asn1,{undefined_type_or_value,Other}}})
    end;
resolv_value1(S,{lt,V}) ->
    case V of
	Int when integer(Int) ->
	    V - 1;
	#valuedef{value=Int} ->
	    resolv_value(S,Int) - 1;
	Other ->
	    throw({error,{asn1,{undefined_type_or_value,Other}}})
    end;
resolv_value1(S,{'ValueFromObject',{object,Object},[{valuefieldreference,
						     FieldName}]}) ->
    %% FieldName can hold either a fixed-type value or a variable-type value
    %% Object is a DefinedObject, i.e. a #'Externaltypereference'
    {_,ObjTDef} = get_referenced_type(S,Object),
    TS = check_object(S,ObjTDef,ObjTDef#typedef.typespec),
    {_,_,Components} = TS#'Object'.def,
    case lists:keysearch(FieldName,1,Components) of
	{value,{_,#valuedef{value=Val}}} ->
	    Val;
	_ ->
	    error({value,"illegal value in constraint",S})
    end;
% resolv_value1(S,{'ValueFromObject',{po,Object,Params},FieldName}) ->
%     %% FieldName can hold either a fixed-type value or a variable-type value
%     %% Object is a ParameterizedObject
resolv_value1(_,V) ->
    V.

resolv_value2(S,ModuleName,Name,Pos) ->
    case asn1_db:dbget(ModuleName,Name) of
	undefined ->
	    case imported(S,Name) of
		{ok,Imodule} ->
		    {_,V2} = get_referenced(S,Imodule,Name,Pos),
		    V2#valuedef.value;
		_  ->
		    throw({error,{asn1,{undefined_type_or_value,Name}}})
	    end;
	Val ->
	    Val#valuedef.value
    end.

check_constraints(S,[{'ContainedSubtype',Type} | Rest], Acc) ->
    {_,CTDef} = get_referenced_type(S,Type#type.def),
    CType = check_type(S,S#state.tname,CTDef#typedef.typespec),
    check_constraints(S,Rest,CType#type.constraint ++ Acc);
check_constraints(S,[C | Rest], Acc) ->
    check_constraints(S,Rest,[check_constraint(S,C) | Acc]);
check_constraints(S,[],Acc) ->
%    io:format("Acc: ~p~n",[Acc]),
    C = constraint_merge(S,lists:reverse(Acc)),
%    io:format("C: ~p~n",[C]),
    lists:flatten(C).


range_check(F={FixV,FixV}) ->
%    FixV;
    F;
range_check(VR={Lb,Ub}) when Lb < Ub ->
    VR;
range_check(Err={_,_}) ->
    throw({error,{asn1,{illegal_size_constraint,Err}}});
range_check(Value) ->
    Value.

check_constraint(S,Ext) when record(Ext,'Externaltypereference') ->
    check_externaltypereference(S,Ext);


check_constraint(S,{'SizeConstraint',{Lb,Ub}})
  when list(Lb);tuple(Lb),size(Lb)==2 ->
    case Lb of
	#'Externalvaluereference'{} ->
	    check_constraint(S,{'SizeConstraint',{resolv_value(S,Lb),Ub}});
	_ ->
	    NewLb = range_check(resolv_tuple_or_list(S,Lb)),
	    NewUb = range_check(resolv_tuple_or_list(S,Ub)),
	    {'SizeConstraint',{NewLb,NewUb}}
    end;
check_constraint(S,{'SizeConstraint',{Lb,Ub}}) ->
    case {resolv_value(S,Lb),resolv_value(S,Ub)} of
	{FixV,FixV} ->
	    {'SizeConstraint',FixV};
	{Low,High} when Low < High ->
	    {'SizeConstraint',{Low,High}};
	Err ->
	    throw({error,{asn1,{illegal_size_constraint,Err}}})
    end;
check_constraint(S,{'SizeConstraint',Lb}) ->
    {'SizeConstraint',resolv_value(S,Lb)};

check_constraint(S,{'SingleValue', L}) when list(L) ->
    F = fun(A) -> resolv_value(S,A) end,
    {'SingleValue',lists:map(F,L)};

check_constraint(S,{'SingleValue', V}) when integer(V) ->
    Val = resolv_value(S,V),
%%    [{'SingleValue',Val},{'ValueRange',{Val,Val}}]; % Why adding value range?
    {'SingleValue',Val};
check_constraint(S,{'SingleValue', V}) ->
    {'SingleValue',resolv_value(S,V)};

check_constraint(S,{'ValueRange', {Lb, Ub}}) ->
    {'ValueRange',{resolv_value(S,Lb),resolv_value(S,Ub)}};

%%check_constraint(S,{'ContainedSubtype',Type}) ->
%%    #typedef{typespec=TSpec} =
%%	check_type(S,S#state.tname,get_referenced_type(S,Type#type.def)),
%%    [C] = TSpec#type.constraint,
%%    C;

check_constraint(S,{valueset,Type}) ->
    {valueset,check_type(S,S#state.tname,Type)};

check_constraint(S,{simpletable,Type}) ->
    OSName = (Type#type.def)#'Externaltypereference'.type,
    C = match_parameters(Type#type.def,S#state.parameters),
    case C of
	#'Externaltypereference'{} ->
	     Type#type{def=check_externaltypereference(S,C)},
	    {simpletable,OSName};
	_ ->
	    check_type(S,S#state.tname,Type),
	    {simpletable,OSName}
    end;

check_constraint(S,{componentrelation,{objectset,Opos,Objset},Id}) ->
    %% Objset is an 'Externaltypereference' record, since Objset is
    %% a DefinedObjectSet.
    RealObjset = match_parameters(Objset,S#state.parameters),
    Ext = check_externaltypereference(S,RealObjset),
    {componentrelation,{objectset,Opos,Ext},Id};

check_constraint(S,Type) when record(Type,type) ->
    #type{def=Def} = check_type(S,S#state.tname,Type),
    Def;

check_constraint(S,C) when list(C) ->
    lists:map(fun(X)->check_constraint(S,X) end,C);
% else keep the constraint unchanged
check_constraint(_S,Any) ->
%    io:format("Constraint = ~p~n",[Any]),
    Any.

%% constraint_merge/2
%% Compute the intersection of the outermost level of the constraint list.
%% See Dubuisson second paragraph and fotnote on page 285.
%% If constraints with extension are included in combined constraints. The
%% resulting combination will have the extension of the last constraint. Thus,
%% there will be no extension if the last constraint is without extension.
%% The rootset of all constraints are considered in the "outermoust
%% intersection". See section 13.1.2 in Dubuisson.
constraint_merge(_S,C=[H])when tuple(H) ->
    C;
constraint_merge(_S,[]) ->
    [];
constraint_merge(S,C) ->
    %% skip all extension but the last
    C1 = filter_extensions(C),
    %% perform all internal level intersections, intersections first
    %% since they have precedence over unions
    C2 = lists:map(fun(X)when list(X)->constraint_intersection(S,X);
		      (X) -> X end,
		   C1),
    %% perform all internal level unions
    C3 = lists:map(fun(X)when list(X)->constraint_union(S,X);
		      (X) -> X end,
		   C2),

    %% now get intersection of the outermost level
    %% get the least common single value constraint
    SVs = get_constraints(C3,'SingleValue'),
    CombSV = intersection_of_sv(S,SVs),
    %% get the least common value range constraint
    VRs = get_constraints(C3,'ValueRange'),
    CombVR = intersection_of_vr(S,VRs),
    %% get the least common size constraint
    SZs = get_constraints(C3,'SizeConstraint'),
    CombSZ = intersection_of_size(S,SZs),
    CminusSVs=ordsets:subtract(ordsets:from_list(C3),ordsets:from_list(SVs)),
    % CminusSVsVRs = ordsets:subtract(ordsets:from_list(CminusSVs),
% 				    ordsets:from_list(VRs)),
    RestC = ordsets:subtract(ordsets:from_list(CminusSVs),
			     ordsets:from_list(SZs)),
    %% get the least common combined constraint. That is the union of each
    %% deep costraint and merge of single value and value range constraints
    combine_constraints(S,CombSV,CombVR,CombSZ++RestC).

%% constraint_union(S,C) takes a list of constraints as input and
%% merge them to a union. Unions are performed when two
%% constraints is found with an atom union between.
%% The list may be nested. Fix that later !!!
constraint_union(_S,[]) ->
    [];
constraint_union(_S,C=[_E]) ->
    C;
constraint_union(S,C) when list(C) ->
    case lists:member(union,C) of
	true ->
	    constraint_union1(S,C,[]);
	_ ->
	    C
    end;
%     SV = get_constraints(C,'SingleValue'),
%     SV1 = constraint_union_sv(S,SV),
%     VR = get_constraints(C,'ValueRange'),
%     VR1 = constraint_union_vr(VR),
%     RestC = ordsets:filter(fun({'SingleValue',_})->false;
% 			      ({'ValueRange',_})->false;
% 			      (_) -> true end,ordsets:from_list(C)),
%     SV1++VR1++RestC;
constraint_union(_S,C) ->
    [C].

constraint_union1(S,[A={'ValueRange',_},union,B={'ValueRange',_}|Rest],Acc) ->
    AunionB = constraint_union_vr([A,B]),
    constraint_union1(S,Rest,AunionB++Acc);
constraint_union1(S,[A={'SingleValue',_},union,B={'SingleValue',_}|Rest],Acc) ->
    AunionB = constraint_union_sv(S,[A,B]),
    constraint_union1(S,Rest,AunionB++Acc);
constraint_union1(S,[A={'SingleValue',_},union,B={'ValueRange',_}|Rest],Acc) ->
    AunionB = union_sv_vr(S,A,B),
    constraint_union1(S,Rest,AunionB++Acc);
constraint_union1(S,[A={'ValueRange',_},union,B={'SingleValue',_}|Rest],Acc) ->
    AunionB = union_sv_vr(S,B,A),
    constraint_union1(S,Rest,AunionB++Acc);
constraint_union1(S,[union|Rest],Acc) -> %skip when unsupported constraints
    constraint_union1(S,Rest,Acc);
constraint_union1(S,[A|Rest],Acc) ->
    constraint_union1(S,Rest,[A|Acc]);
constraint_union1(_S,[],Acc) ->
    lists:reverse(Acc).

constraint_union_sv(_S,SV) ->
    Values=lists:map(fun({_,V})->V end,SV),
    case ordsets:from_list(Values) of
	[] -> [];
	[N] -> [{'SingleValue',N}];
	L -> [{'SingleValue',L}]
    end.

%% REMOVE????
%%constraint_union(S,VR,'ValueRange') ->
%%    constraint_union_vr(VR).

%% constraint_union_vr(VR)
%% VR = [{'ValueRange',{Lb,Ub}},...]
%% Lb = 'MIN' | integer()
%% Ub = 'MAX' | integer()
%% Returns if possible only one ValueRange tuple with a range that
%% is a union of all ranges in VR.
constraint_union_vr(VR) ->
    %% Sort VR by Lb in first hand and by Ub in second hand
    Fun=fun({_,{'MIN',_B1}},{_,{A2,_B2}}) when integer(A2)->true;
	   ({_,{A1,_B1}},{_,{'MAX',_B2}}) when integer(A1) -> true;
	   ({_,{A1,_B1}},{_,{A2,_B2}}) when integer(A1),integer(A2),A1<A2 -> true;
	   ({_,{A,B1}},{_,{A,B2}}) when B1=<B2->true;
	   (_,_)->false end,
    constraint_union_vr(lists:usort(Fun,VR),[]).

constraint_union_vr([],Acc) ->
    lists:reverse(Acc);
constraint_union_vr([C|Rest],[]) ->
    constraint_union_vr(Rest,[C]);
constraint_union_vr([{_,{Lb,Ub2}}|Rest],[{_,{Lb,_Ub1}}|Acc]) -> %Ub2 > Ub1
    constraint_union_vr(Rest,[{'ValueRange',{Lb,Ub2}}|Acc]);
constraint_union_vr([{_,{_,Ub}}|Rest],A=[{_,{_,Ub}}|_Acc]) ->
    constraint_union_vr(Rest,A);
constraint_union_vr([{_,{Lb2,Ub2}}|Rest],[{_,{Lb1,Ub1}}|Acc]) when Lb2=<Ub1,
								   Ub2>Ub1->
    constraint_union_vr(Rest,[{'ValueRange',{Lb1,Ub2}}|Acc]);
constraint_union_vr([{_,{_,Ub2}}|Rest],A=[{_,{_,Ub1}}|_Acc]) when Ub2=<Ub1->
    constraint_union_vr(Rest,A);
constraint_union_vr([VR|Rest],Acc) ->
    constraint_union_vr(Rest,[VR|Acc]).

union_sv_vr(_S,[],B) ->
    [B];
union_sv_vr(_S,A,[]) ->
    [A];
union_sv_vr(_S,C1={'SingleValue',SV},C2={'ValueRange',VR={Lb,Ub}})
  when integer(SV) ->
    case is_int_in_vr(SV,C2) of
	true -> [C2];
	_ ->
	    case VR of
		{'MIN',Ub} when SV==Ub+1 -> [{'ValueRange',{'MIN',SV}}];
		{Lb,'MAX'} when SV==Lb-1 -> [{'ValueRange',{SV,'MAX'}}];
		{Lb,Ub} when SV==Ub+1 -> [{'ValueRange',{Lb,SV}}];
		{Lb,Ub} when SV==Lb-1 -> [{'ValueRange',{SV,Ub}}];
		_ ->
		    [C1,C2]
	    end
    end;
union_sv_vr(_S,C1={'SingleValue',SV},C2={'ValueRange',{_Lb,_Ub}})
  when list(SV) ->
    case lists:filter(fun(X)->is_int_in_vr(X,C2) end,SV) of
	[] -> [C2];
	L ->
	    case expand_vr(L,C2) of
		{[],C3} -> [C3];
		{L,C2} -> [C1,C2];
		{[Val],C3} -> [{'SingleValue',Val},C3];
		{L2,C3} -> [{'SingleValue',L2},C3]
	    end
    end.

expand_vr(L,VR={_,{Lb,Ub}}) ->
    case lower_Lb(L,Lb) of
	false ->
	    case higher_Ub(L,Ub) of
		false ->
		    {L,VR};
		{L1,UbNew} ->
		    expand_vr(L1,{'ValueRange',{Lb,UbNew}})
	    end;
	{L1,LbNew} ->
	    expand_vr(L1,{'ValueRange',{LbNew,Ub}})
    end.

lower_Lb(_,'MIN') ->
    false;
lower_Lb(L,Lb) ->
    remove_val_from_list(Lb - 1,L).

higher_Ub(_,'MAX') ->
    false;
higher_Ub(L,Ub) ->
    remove_val_from_list(Ub + 1,L).

remove_val_from_list(List,Val) ->
    case lists:member(Val,List) of
	true ->
	    {lists:delete(Val,List),Val};
	false ->
	    false
    end.

%% get_constraints/2
%% Arguments are a list of constraints, which has the format {key,value},
%% and a constraint type
%% Returns a list of constraints only of the requested type or the atom
%% 'no' if no such constraints were found
get_constraints(L=[{CType,_}],CType) ->
    L;
get_constraints(C,CType) ->
   keysearch_allwithkey(CType,1,C).

%% keysearch_allwithkey(Key,Ix,L)
%% Types:
%% Key = atom()
%% Ix = integer()
%% L  = [TwoTuple]
%% TwoTuple = [{atom(),term()}|...]
%% Returns a List that contains all
%% elements from L that has a key Key as element Ix
keysearch_allwithkey(Key,Ix,L) ->
    lists:filter(fun(X) when tuple(X) ->
			 case element(Ix,X) of
			     Key -> true;
			     _ -> false
			 end;
		    (_) -> false
		 end, L).


%% filter_extensions(C)
%% takes a list of constraints as input and
%% returns a list with the intersection of all extension roots
%% and only the extension of the last constraint kept if any
%% extension in the last constraint
filter_extensions([]) ->
    [];
filter_extensions(C=[_H]) ->
    C;
filter_extensions(C) when list(C) ->
    filter_extensions(C,[]).

filter_extensions([C],Acc) ->
    lists:reverse([C|Acc]);
filter_extensions([{C,_E},H2|T],Acc) when tuple(C) ->
    filter_extensions([H2|T],[C|Acc]);
filter_extensions([{'SizeConstraint',{A,_B}},H2|T],Acc)
  when list(A);tuple(A) ->
    filter_extensions([H2|T],[{'SizeConstraint',A}|Acc]);
filter_extensions([H1,H2|T],Acc) ->
    filter_extensions([H2|T],[H1|Acc]).

%% constraint_intersection(S,C) takes a list of constraints as input and
%% performs intersections. Intersecions are performed when an
%% atom intersection is found between two constraints.
%% The list may be nested. Fix that later !!!
constraint_intersection(_S,[]) ->
    [];
constraint_intersection(_S,C=[_E]) ->
    C;
constraint_intersection(S,C) when list(C) ->
%    io:format("constraint_intersection: ~p~n",[C]),
    case lists:member(intersection,C) of
	true ->
	    constraint_intersection1(S,C,[]);
	_ ->
	    C
    end;
constraint_intersection(_S,C) ->
    [C].

constraint_intersection1(S,[A,intersection,B|Rest],Acc) ->
    AisecB = c_intersect(S,A,B),
    constraint_intersection1(S,Rest,AisecB++Acc);
constraint_intersection1(S,[A|Rest],Acc) ->
    constraint_intersection1(S,Rest,[A|Acc]);
constraint_intersection1(_,[],Acc) ->
    lists:reverse(Acc).

c_intersect(S,C1={'SingleValue',_},C2={'SingleValue',_}) ->
    intersection_of_sv(S,[C1,C2]);
c_intersect(S,C1={'ValueRange',_},C2={'ValueRange',_}) ->
    intersection_of_vr(S,[C1,C2]);
c_intersect(S,C1={'ValueRange',_},C2={'SingleValue',_}) ->
    intersection_sv_vr(S,[C2],[C1]);
c_intersect(S,C1={'SingleValue',_},C2={'ValueRange',_}) ->
    intersection_sv_vr(S,[C1],[C2]);
c_intersect(_S,C1,C2) ->
    [C1,C2].

%% combine_constraints(S,SV,VR,CComb)
%% Types:
%% S = record(state,S)
%% SV = [] | [SVC]
%% VR = [] | [VRC]
%% CComb = [] | [Lists]
%% SVC = {'SingleValue',integer()} | {'SingleValue',[integer(),...]}
%% VRC = {'ValueRange',{Lb,Ub}}
%% Lists = List of lists containing any constraint combination
%% Lb = 'MIN' | integer()
%% Ub = 'MAX' | integer()
%% Returns a combination of the least common constraint among SV,VR and all
%% elements in CComb
combine_constraints(_S,[],VR,CComb) ->
    VR ++ CComb;
%    combine_combined_cnstr(S,VR,CComb);
combine_constraints(_S,SV,[],CComb) ->
    SV ++ CComb;
%    combine_combined_cnstr(S,SV,CComb);
combine_constraints(S,SV,VR,CComb) ->
    C=intersection_sv_vr(S,SV,VR),
    C ++ CComb.
%    combine_combined_cnstr(S,C,CComb).

intersection_sv_vr(_,[],_VR) ->
    [];
intersection_sv_vr(_,_SV,[]) ->
    [];
intersection_sv_vr(_S,[C1={'SingleValue',SV}],[C2={'ValueRange',{_Lb,_Ub}}])
  when integer(SV) ->
    case is_int_in_vr(SV,C2) of
	true -> [C1];
	_ -> %%error({type,{"asn1 illegal constraint",C1,C2},S})
	    throw({error,{"asn1 illegal constraint",C1,C2}})
    end;
intersection_sv_vr(_S,[C1={'SingleValue',SV}],[C2])
  when list(SV) ->
    case lists:filter(fun(X)->is_int_in_vr(X,C2) end,SV) of
	[] ->
	    %%error({type,{"asn1 illegal constraint",C1,C2},S});
	    throw({error,{"asn1 illegal constraint",C1,C2}});
	[V] -> [{'SingleValue',V}];
	L -> [{'SingleValue',L}]
    end.



intersection_of_size(_,[]) ->
    [];
intersection_of_size(_,C=[_SZ]) ->
    C;
intersection_of_size(S,[SZ,SZ|Rest]) ->
    intersection_of_size(S,[SZ|Rest]);
intersection_of_size(S,C=[C1={_,Int},{_,Range}|Rest])
  when integer(Int),tuple(Range) ->
    case Range of
	{Lb,Ub} when Int >= Lb,
		     Int =< Ub ->
	    intersection_of_size(S,[C1|Rest]);
	_ ->
	    throw({error,{asn1,{illegal_size_constraint,C}}})
    end;
intersection_of_size(S,[C1={_,Range},C2={_,Int}|Rest])
  when integer(Int),tuple(Range) ->
    intersection_of_size(S,[C2,C1|Rest]);
intersection_of_size(S,[{_,{Lb1,Ub1}},{_,{Lb2,Ub2}}|Rest]) ->
    Lb=greatest_LB(ordsets:from_list([Lb1,Lb2])),
    Ub=smallest_UB(ordsets:from_list([Ub1,Ub2])),
    intersection_of_size(S,[{'SizeConstraint',{Lb,Ub}}|Rest]);
intersection_of_size(_,SZ) ->
    throw({error,{asn1,{illegal_size_constraint,SZ}}}).

intersection_of_vr(_,[]) ->
    [];
intersection_of_vr(_,VR=[_C]) ->
    VR;
intersection_of_vr(S,[{_,{Lb1,Ub1}},{_,{Lb2,Ub2}}|Rest]) ->
    Lb=greatest_LB(ordsets:from_list([Lb1,Lb2])),
    Ub=smallest_UB(ordsets:from_list([Ub1,Ub2])),
    intersection_of_vr(S,[{'ValueRange',{Lb,Ub}}|Rest]);
intersection_of_vr(_S,VR) ->
    %%error({type,{asn1,{illegal_value_range_constraint,VR}},S});
    throw({error,{asn1,{illegal_value_range_constraint,VR}}}).

intersection_of_sv(_,[]) ->
    [];
intersection_of_sv(_,SV=[_C]) ->
    SV;
intersection_of_sv(S,[SV,SV|Rest]) ->
    intersection_of_sv(S,[SV|Rest]);
intersection_of_sv(S,[{_,Int},{_,SV}|Rest]) when integer(Int),
						 list(SV) ->
    SV2=intersection_of_sv1(S,Int,SV),
    intersection_of_sv(S,[SV2|Rest]);
intersection_of_sv(S,[{_,SV},{_,Int}|Rest]) when integer(Int),
						 list(SV) ->
    SV2=intersection_of_sv1(S,Int,SV),
    intersection_of_sv(S,[SV2|Rest]);
intersection_of_sv(S,[{_,SV1},{_,SV2}|Rest]) when list(SV1),
						  list(SV2) ->
    SV3=common_set(SV1,SV2),
    intersection_of_sv(S,[SV3|Rest]);
intersection_of_sv(_S,SV) ->
    %%error({type,{asn1,{illegal_single_value_constraint,SV}},S}).
    throw({error,{asn1,{illegal_single_value_constraint,SV}}}).

intersection_of_sv1(_S,Int,SV) when integer(Int),list(SV) ->
    case lists:member(Int,SV) of
	true -> {'SingleValue',Int};
	_ ->
	    %%error({type,{asn1,{illegal_single_value_constraint,Int,SV}},S})
	    throw({error,{asn1,{illegal_single_value_constraint,Int,SV}}})
    end;
intersection_of_sv1(_S,SV1,SV2) ->
    %%error({type,{asn1,{illegal_single_value_constraint,SV1,SV2}},S}).
    throw({error,{asn1,{illegal_single_value_constraint,SV1,SV2}}}).

greatest_LB([H]) ->
    H;
greatest_LB(L) ->
    greatest_LB1(lists:reverse(L)).
greatest_LB1(['MIN',H2|_T])->
    H2;
greatest_LB1([H|_T]) ->
    H.
smallest_UB(L) ->
    hd(L).

common_set(SV1,SV2) ->
    lists:filter(fun(X)->lists:member(X,SV1) end,SV2).

is_int_in_vr(Int,{_,{'MIN','MAX'}}) when integer(Int) ->
    true;
is_int_in_vr(Int,{_,{'MIN',Ub}}) when integer(Int),Int =< Ub ->
    true;
is_int_in_vr(Int,{_,{Lb,'MAX'}}) when integer(Int),Int >= Lb ->
    true;
is_int_in_vr(Int,{_,{Lb,Ub}}) when integer(Int),Int >= Lb,Int =< Ub ->
    true;
is_int_in_vr(_,_) ->
    false.



check_imported(_S,Imodule,Name) ->
    case asn1_db:dbget(Imodule,'MODULE') of
	undefined ->
	    io:format("~s.asn1db not found~n",[Imodule]),
	    io:format("Type ~s imported from non existing module ~s~n",[Name,Imodule]);
	Im when record(Im,module) ->
	    case is_exported(Im,Name) of
		false ->
		    io:format("Imported type ~s not exported from module ~s~n",[Name,Imodule]);
		_ ->
		    ok
	    end
    end,
    ok.

is_exported(Module,Name) when record(Module,module) ->
    {exports,Exports} = Module#module.exports,
    case Exports of
	all ->
	    true;
	[] ->
	    false;
	L when list(L) ->
	    case lists:keysearch(Name,#'Externaltypereference'.type,Exports) of
		false -> false;
		_ -> true
	    end
    end.



check_externaltypereference(S,Etref=#'Externaltypereference'{module=Emod})->
    Currmod = S#state.mname,
    MergedMods = S#state.inputmodules,
    case Emod of
	Currmod ->
	    %% reference to current module or to imported reference
		check_reference(S,Etref);
	 _ ->
	    %% io:format("Type ~s IMPORTED FROM ~s~n",[Etype,Emod]),
	    case lists:member(Emod,MergedMods) of
		true ->
		    check_reference(S,Etref);
		false ->
		    Etref
	    end
    end.

check_reference(S,#'Externaltypereference'{pos=Pos,module=Emod,type=Name}) ->
    ModName = S#state.mname,
    case asn1_db:dbget(ModName,Name) of
	undefined ->
	    case imported(S,Name) of
		{ok,Imodule} ->
		    check_imported(S,Imodule,Name),
		    #'Externaltypereference'{module=Imodule,type=Name};
		_ ->
		    %may be a renamed type in multi file compiling!
		    {_,T}=renamed_reference(S,Name,Emod),
		    NewName = asn1ct:get_name_of_def(T),
		    NewPos = asn1ct:get_pos_of_def(T),
		    #'Externaltypereference'{pos=NewPos,
					     module=ModName,
					     type=NewName}
	    end;
	_ ->
	    %% cannot do check_type here due to recursive definitions, like
	    %% S ::= SEQUENCE {a INTEGER, b S}. This implies that references
	    %% that appear before the definition will be an
	    %% Externaltypereference in the abstract syntax tree
	    #'Externaltypereference'{pos=Pos,module=ModName,type=Name}
    end.


name2Extref(_Mod,Name) when record(Name,'Externaltypereference') ->
    Name;
name2Extref(Mod,Name) ->
    #'Externaltypereference'{module=Mod,type=Name}.

get_referenced_type(S,Ext) when record(Ext,'Externaltypereference') ->
    case match_parameters(Ext, S#state.parameters) of
	Ext ->
	    #'Externaltypereference'{pos=Pos,module=Emod,type=Etype} = Ext,
	    case S#state.mname of
		Emod -> % a local reference in this module
		    get_referenced1(S,Emod,Etype,Pos);
		_ ->% always when multi file compiling
		    case lists:member(Emod,S#state.inputmodules) of
			true ->
			    get_referenced1(S,Emod,Etype,Pos);
			false ->
			    get_referenced(S,Emod,Etype,Pos)
		    end
	    end;
	Other ->
	    {undefined,Other}
    end;
get_referenced_type(S=#state{mname=Emod},
		    ERef=#'Externalvaluereference'{pos=P,module=Emod,
						   value=Eval}) ->
    case match_parameters(ERef,S#state.parameters) of
	ERef ->
	    get_referenced1(S,Emod,Eval,P);
	OtherERef when record(OtherERef,'Externalvaluereference') ->
	    get_referenced_type(S,OtherERef);
	Value ->
	    {Emod,Value}
    end;
get_referenced_type(S,ERef=#'Externalvaluereference'{pos=Pos,module=Emod,
						value=Eval}) ->
    case match_parameters(ERef,S#state.parameters) of
	ERef ->
	    case lists:member(Emod,S#state.inputmodules) of
		true ->
		    get_referenced1(S,Emod,Eval,Pos);
		false ->
		    get_referenced(S,Emod,Eval,Pos)
	    end;
	OtherERef  ->
	    get_referenced_type(S,OtherERef)
    end;
get_referenced_type(S,#identifier{val=Name,pos=Pos}) ->
    get_referenced1(S,undefined,Name,Pos);
get_referenced_type(_S,Type) ->
    {undefined,Type}.

%% get_referenced/3
%% The referenced entity Ename may in case of an imported parameterized
%% type reference imported entities in the other module, which implies that
%% asn1_db:dbget will fail even though the referenced entity exists. Thus
%% Emod may be the module that imports the entity Ename and not holds the
%% data about Ename.
get_referenced(S,Emod,Ename,Pos) ->
    case asn1_db:dbget(Emod,Ename) of
	undefined ->
	    %% May be an imported entity in module Emod
%	    throw({error,{asn1,{undefined_type_or_value,{Emod,Ename}}}});
	    NewS = S#state{module=asn1_db:dbget(Emod,'MODULE')},
	    get_imported(NewS,Ename,Emod,Pos);
	T when record(T,typedef) ->
	    Spec = T#typedef.typespec,
	    case Spec#type.def of
		Tref when record(Tref,typereference) ->
		    Def = #'Externaltypereference'{module=Emod,
					     type=Tref#typereference.val,
					     pos=Tref#typereference.pos},


		    {Emod,T#typedef{typespec=Spec#type{def=Def}}};
		_ ->
		    {Emod,T} % should add check that T is exported here
	    end;
	V -> {Emod,V}
    end.

get_referenced1(S,ModuleName,Name,Pos) ->
    case asn1_db:dbget(S#state.mname,Name) of
	undefined ->
	    %% ModuleName may be other than S#state.mname when
	    %% multi file compiling is used.
	    get_imported(S,Name,ModuleName,Pos);
	T ->
	    {S#state.mname,T}
    end.

get_imported(S,Name,Module,Pos) ->
    case imported(S,Name) of
	{ok,Imodule} ->
	    case asn1_db:dbget(Imodule,'MODULE') of
		undefined ->
		    throw({error,{asn1,{module_not_found,Imodule}}});
		Im when record(Im,module) ->
		    case is_exported(Im,Name) of
			false ->
			    throw({error,
				   {asn1,{not_exported,{Im,Name}}}});
			_ ->
			    get_referenced_type(S,
						#'Externaltypereference'
						{module=Imodule,
						 type=Name,pos=Pos})
		    end
	    end;
	_ ->
	    renamed_reference(S,Name,Module)
    end.

renamed_reference(S,Name,Module) ->
    %% first check if there is a renamed type in this module
    %% second check if any type was imported with this name
    case ets:info(renamed_defs) of
	undefined -> throw({error,{asn1,{undefined_type,Name}}});
	_ ->
	    case ets:match(renamed_defs,{'$1',Name,Module}) of
		[] ->
		    case ets:info(original_imports) of
			undefined ->
			    throw({error,{asn1,{undefined_type,Name}}});
			_  ->
			    case ets:match(original_imports,{Module,'$1'}) of
				[] ->
				    throw({error,{asn1,{undefined_type,Name}}});
				[[ImportsList]] ->
				    case get_importmoduleoftype(ImportsList,Name) of
					undefined ->
					    throw({error,{asn1,{undefined_type,Name}}});
					NextMod ->
					    renamed_reference(S,Name,NextMod)
				    end
			    end
		    end;
		[[NewTypeName]] ->
		    get_referenced1(S,Module,NewTypeName,undefined)
	    end
    end.

get_importmoduleoftype([I|Is],Name) ->
    Index = #'Externaltypereference'.type,
    case lists:keysearch(Name,Index,I#'SymbolsFromModule'.symbols) of
	{value,_Ref} ->
	    (I#'SymbolsFromModule'.module)#'Externaltypereference'.type;
	_ ->
	    get_importmoduleoftype(Is,Name)
    end;
get_importmoduleoftype([],_) ->
    undefined.


match_parameters(Name,[]) ->
    Name;

match_parameters(#'Externaltypereference'{type=Name},[{#'Externaltypereference'{type=Name},NewName}|_T]) ->
    NewName;
match_parameters(#'Externaltypereference'{type=Name},[{{_,#'Externaltypereference'{type=Name}},NewName}|_T]) ->
    NewName;
% match_parameters(#'Externaltypereference'{type=Name},[{#typereference{val=Name},NewName}|T]) ->
%     NewName;
% match_parameters(#'Externaltypereference'{type=Name},[{{_,#typereference{val=Name}},NewName}|T]) ->
%     NewName;
%match_parameters(#typereference{val=Name},[{#typereference{val=Name},NewName}|T]) ->
%    NewName;
match_parameters(#'Externalvaluereference'{value=Name},[{#'Externalvaluereference'{value=Name},NewName}|_T]) ->
    NewName;
match_parameters(#'Externalvaluereference'{value=Name},[{{_,#'Externalvaluereference'{value=Name}},NewName}|_T]) ->
    NewName;
% match_parameters(#identifier{val=Name},[{#identifier{val=Name},NewName}|T]) ->
%     NewName;
% match_parameters(#identifier{val=Name},[{{_,#identifier{val=Name}},NewName}|T]) ->
%     NewName;
match_parameters({valueset,#type{def=#'Externaltypereference'{type=Name}}},
		 [{{_,#'Externaltypereference'{type=Name}},{valueset,#type{def=NewName}}}|_T]) ->
    NewName;
match_parameters({valueset,#type{def=#'Externaltypereference'{type=Name}}},
		 [{{_,#'Externaltypereference'{type=Name}},NewName}|_T]) ->
    NewName;
% match_parameters({valueset,#type{def=#'Externaltypereference'{type=Name}}},
% 		 [{{_,#typereference{val=Name}},{valueset,#type{def=NewName}}}|T]) ->
%     NewName;
% match_parameters({valueset,#type{def=#'Externaltypereference'{type=Name}}},
% 		 [{{_,#typereference{val=Name}},NewName}|T]) ->
%     NewName;

match_parameters(Name, [_H|T]) ->
    %%io:format("match_parameters(~p,~p)~n",[Name,[H|T]]),
    match_parameters(Name,T).

imported(S,Name) ->
    {imports,Ilist} = (S#state.module)#module.imports,
    imported1(Name,Ilist).

imported1(Name,
	  [#'SymbolsFromModule'{symbols=Symlist,
				module=#'Externaltypereference'{type=ModuleName}}|T]) ->
    case lists:keysearch(Name,#'Externaltypereference'.type,Symlist) of
	{value,_V} ->
	    {ok,ModuleName};
	_ ->
	    imported1(Name,T)
    end;
imported1(_Name,[]) ->
    false.


check_integer(_S,[],_C) ->
    ok;
check_integer(S,NamedNumberList,_C) ->
    case check_unique(NamedNumberList,2) of
	[] ->
	    check_int(S,NamedNumberList,[]);
	L when list(L) ->
	    error({type,{duplicates,L},S}),
	    unchanged

    end.

check_int(S,[{'NamedNumber',Id,Num}|T],Acc) when integer(Num) ->
    check_int(S,T,[{Id,Num}|Acc]);
check_int(S,[{'NamedNumber',Id,{identifier,_,Name}}|T],Acc) ->
    Val = dbget_ex(S,S#state.mname,Name),
    check_int(S,[{'NamedNumber',Id,Val#valuedef.value}|T],Acc);
check_int(_S,[],Acc) ->
    lists:keysort(2,Acc).



check_bitstring(_S,[],_Constr) ->
    [];
check_bitstring(S,NamedNumberList,_Constr) ->
    case check_unique(NamedNumberList,2) of
	[] ->
	    check_bitstr(S,NamedNumberList,[]);
	L when list(L) ->
	    error({type,{duplicates,L},S}),
	    unchanged
    end.

check_bitstr(S,[{'NamedNumber',Id,Num}|T],Acc)when integer(Num) ->
    check_bitstr(S,T,[{Id,Num}|Acc]);
check_bitstr(S,[{'NamedNumber',Id,Name}|T],Acc) when atom(Name) ->
%%check_bitstr(S,[{'NamedNumber',Id,{identifier,_,Name}}|T],Acc) ->
%%    io:format("asn1ct_check:check_bitstr/3 hej hop ~w~n",[Name]),
    Val = dbget_ex(S,S#state.mname,Name),
%%    io:format("asn1ct_check:check_bitstr/3: ~w~n",[Val]),
    check_bitstr(S,[{'NamedNumber',Id,Val#valuedef.value}|T],Acc);
check_bitstr(S,[],Acc) ->
    case check_unique(Acc,2) of
	[] ->
	    lists:keysort(2,Acc);
	L when list(L) ->
	    error({type,{duplicate_values,L},S}),
	    unchanged
    end.

%%check_bitstring(S,NamedNumberList,Constr) ->
%%    NamedNumberList.

%% Check INSTANCE OF
%% check that DefinedObjectClass is of TYPE-IDENTIFIER class
%% If Constraint is empty make it the general INSTANCE OF type
%% If Constraint is not empty make an inlined type
%% convert INSTANCE OF to the associated type
check_instance_of(S,DefinedObjectClass,Constraint) ->
    check_type_identifier(S,DefinedObjectClass),
    iof_associated_type(S,Constraint).


check_type_identifier(_S,'TYPE-IDENTIFIER') ->
    ok;
check_type_identifier(S,Eref=#'Externaltypereference'{}) ->
    case get_referenced_type(S,Eref) of
	{_,#classdef{name='TYPE-IDENTIFIER'}} -> ok;
	{_,TD=#typedef{typespec=#type{def=#'Externaltypereference'{}}}} ->
	    check_type_identifier(S,(TD#typedef.typespec)#type.def);
	_ ->
	    error({type,{"object set in type INSTANCE OF "
			 "not of class TYPE-IDENTIFIER",Eref},S})
    end.

iof_associated_type(S,[]) ->
    %% in this case encode/decode functions for INSTANCE OF must be
    %% generated
    case get(instance_of) of
	undefined ->
	    AssociateSeq = iof_associated_type1(S,[]),
	    Tag =
		case S#state.erule of
		    ber_bin_v2 ->
			[?TAG_CONSTRUCTED(?N_INSTANCE_OF)];
		    _ -> []
		end,
	    TypeDef=#typedef{checked=true,
			     name='INSTANCE OF',
			     typespec=#type{tag=Tag,
					    def=AssociateSeq}},
	    asn1_db:dbput(S#state.mname,'INSTANCE OF',TypeDef),
	    put(instance_of,generate);
	_ ->
	    ok
    end,
    #'Externaltypereference'{module=S#state.mname,type='INSTANCE OF'};
iof_associated_type(S,C) ->
    iof_associated_type1(S,C).

iof_associated_type1(S,C) ->
    {TableCInf,Comp1Cnstr,Comp2Cnstr,Comp2tablecinf}=
	instance_of_constraints(S,C),

    ModuleName = S#state.mname,
    Typefield_type=
	case C of
	    [] -> 'ASN1_OPEN_TYPE';
	    _ -> {typefield,'Type'}
	end,
    {ObjIdTag,C1TypeTag}=
	case S#state.erule of
	    ber_bin_v2 ->
		{[{'UNIVERSAL',8}],
		 [#tag{class='UNIVERSAL',
		       number=6,
		       type='IMPLICIT',
		       form=0}]};
	    _ -> {[{'UNIVERSAL','INTEGER'}],[]}
	end,
    TypeIdentifierRef=#'Externaltypereference'{module=ModuleName,
					       type='TYPE-IDENTIFIER'},
    ObjectIdentifier =
	#'ObjectClassFieldType'{classname=TypeIdentifierRef,
				class=[],
				fieldname={id,[]},
				type={fixedtypevaluefield,id,
				      #type{def='OBJECT IDENTIFIER'}}},
    Typefield =
	#'ObjectClassFieldType'{classname=TypeIdentifierRef,
				class=[],
				fieldname={'Type',[]},
				type=Typefield_type},
    IOFComponents =
	[#'ComponentType'{name='type-id',
			  typespec=#type{tag=C1TypeTag,
					 def=ObjectIdentifier,
					 constraint=Comp1Cnstr},
			  prop=mandatory,
			  tags=ObjIdTag},
	 #'ComponentType'{name=value,
			  typespec=#type{tag=[#tag{class='CONTEXT',
						   number=0,
						   type='EXPLICIT',
						   form=32}],
					 def=Typefield,
					 constraint=Comp2Cnstr,
					 tablecinf=Comp2tablecinf},
			  prop=mandatory,
			  tags=[{'CONTEXT',0}]}],
    #'SEQUENCE'{tablecinf=TableCInf,
		components=IOFComponents}.


%% returns the leading attribute, the constraint of the components and
%% the tablecinf value for the second component.
instance_of_constraints(_,[]) ->
    {false,[],[],[]};
instance_of_constraints(S,#constraint{c={simpletable,Type}}) ->
    #type{def=#'Externaltypereference'{type=Name}} = Type,
    ModuleName = S#state.mname,
    ObjectSetRef=#'Externaltypereference'{module=ModuleName,
					  type=Name},
    CRel=[{componentrelation,{objectset,
			      undefined, %% pos
			      ObjectSetRef},
			      [{innermost,
				[#'Externalvaluereference'{module=ModuleName,
							   value=type}]}]}],
    TableCInf=#simpletableattributes{objectsetname=Name,
				     c_name='type-id',
				     c_index=1,
				     usedclassfield=id,
				     uniqueclassfield=id,
				     valueindex=[]},
    {TableCInf,[{simpletable,Name}],CRel,[{objfun,ObjectSetRef}]}.

%% Check ENUMERATED
%% ****************************************
%% Check that all values are unique
%% assign values to un-numbered identifiers
%% check that the constraints are allowed and correct
%% put the updated info back into database
check_enumerated(_S,[{Name,Number}|Rest],_Constr) when atom(Name), integer(Number)->
    %% already checked , just return the same list
    [{Name,Number}|Rest];
check_enumerated(S,NamedNumberList,_Constr) ->
    check_enum(S,NamedNumberList,[],[]).

%% identifiers are put in Acc2
%% returns either [{Name,Number}] or {[{Name,Number}],[{ExtName,ExtNumber}]}
%% the latter is returned if the ENUMERATION contains EXTENSIONMARK
check_enum(S,[{'NamedNumber',Id,Num}|T],Acc1,Acc2) when integer(Num) ->
    check_enum(S,T,[{Id,Num}|Acc1],Acc2);
check_enum(S,[{'NamedNumber',Id,{identifier,_,Name}}|T],Acc1,Acc2) ->
    Val = dbget_ex(S,S#state.mname,Name),
    check_enum(S,[{'NamedNumber',Id,Val#valuedef.value}|T],Acc1,Acc2);
check_enum(S,['EXTENSIONMARK'|T],Acc1,Acc2) ->
    NewAcc2 = lists:keysort(2,Acc1),
    NewList = enum_number(lists:reverse(Acc2),NewAcc2,0,[]),
    { NewList, check_enum(S,T,[],[])};
check_enum(S,[Id|T],Acc1,Acc2) when atom(Id) ->
    check_enum(S,T,Acc1,[Id|Acc2]);
check_enum(_S,[],Acc1,Acc2) ->
    NewAcc2 = lists:keysort(2,Acc1),
    enum_number(lists:reverse(Acc2),NewAcc2,0,[]).


% assign numbers to identifiers , numbers from 0 ... but must not
% be the same as already assigned to NamedNumbers
enum_number([H|T],[{Id,Num}|T2],Cnt,Acc) when Num > Cnt ->
    enum_number(T,[{Id,Num}|T2],Cnt+1,[{H,Cnt}|Acc]);
enum_number([H|T],[{Id,Num}|T2],Cnt,Acc) when Num < Cnt -> % negative Num
    enum_number(T,T2,Cnt+1,[{H,Cnt},{Id,Num}|Acc]);
enum_number([],L2,_Cnt,Acc) ->
    lists:concat([lists:reverse(Acc),L2]);
enum_number(L,[{Id,Num}|T2],Cnt,Acc) -> % Num == Cnt
    enum_number(L,T2,Cnt+1,[{Id,Num}|Acc]);
enum_number([H|T],[],Cnt,Acc) ->
    enum_number(T,[],Cnt+1,[{H,Cnt}|Acc]).


check_boolean(_S,_Constr) ->
    ok.

check_octetstring(_S,_Constr) ->
    ok.

% check all aspects of a SEQUENCE
% - that all component names are unique
% - that all TAGS are ok (when TAG default is applied)
% - that each component is of a valid type
% - that the extension marks are valid

check_sequence(S,Type,Comps)  ->
    Components = expand_components(S,Comps),
    case check_unique([C||C <- Components ,record(C,'ComponentType')]
		      ,#'ComponentType'.name) of
	[] ->
	    %% sort_canonical(Components),
	    Components2 = maybe_automatic_tags(S,Components),
	    %% check the table constraints from here. The outermost type
	    %% is Type, the innermost is Comps (the list of components)
	    NewComps =
		case check_each_component(S,Type,Components2) of
		    NewComponents when list(NewComponents) ->
			check_unique_sequence_tags(S,NewComponents),
			NewComponents;
		    Ret = {NewComponents,NewEcomps} ->
			TagComps = NewComponents ++
			    [Comp#'ComponentType'{prop='OPTIONAL'}|| Comp <- NewEcomps],
			%% extension components are like optionals when it comes to tagging
			check_unique_sequence_tags(S,TagComps),
			Ret
		end,
	    %% CRelInf is the "leading attribute" information
	    %% necessary for code generating of the look up in the
	    %% object set table,
	    %% i.e. getenc_ObjectSet/getdec_ObjectSet.
	    %% {objfun,ERef} tuple added in NewComps2 in tablecinf
	    %% field in type record of component relation constrained
	    %% type
%	    io:format("NewComps: ~p~n",[NewComps]),
	    {CRelInf,NewComps2} = componentrelation_leadingattr(S,NewComps),
%	    io:format("CRelInf: ~p~n",[CRelInf]),
%	    io:format("NewComps2: ~p~n",[NewComps2]),
	    %% CompListWithTblInf has got a lot unecessary info about
	    %% the involved class removed, as the class of the object
	    %% set.
	    CompListWithTblInf = get_tableconstraint_info(S,Type,NewComps2),
%	    io:format("CompListWithTblInf: ~p~n",[CompListWithTblInf]),
	    {CRelInf,CompListWithTblInf};
	Dupl ->
		throw({error,{asn1,{duplicate_components,Dupl}}})
    end.

expand_components(S, [{'COMPONENTS OF',Type}|T]) ->
    CompList =
	case get_referenced_type(S,Type#type.def) of
	    {_,#typedef{typespec=#type{def=Seq}}} when record(Seq,'SEQUENCE') ->
		case Seq#'SEQUENCE'.components of
		    {Root,_Ext} -> Root;
		    Root -> Root
		end;
	    Err -> throw({error,{asn1,{illegal_COMPONENTS_OF,Err}}})
	end,
    expand_components(S,CompList) ++ expand_components(S,T);
expand_components(S,[H|T]) ->
    [H|expand_components(S,T)];
expand_components(_,[]) ->
    [].

check_unique_sequence_tags(S,[#'ComponentType'{prop=mandatory}|Rest]) ->
    check_unique_sequence_tags(S,Rest);
check_unique_sequence_tags(S,[C|Rest]) when record(C,'ComponentType') ->
    check_unique_sequence_tags1(S,Rest,[C]);% optional or default
check_unique_sequence_tags(S,[_ExtensionMarker|Rest]) ->
    check_unique_sequence_tags(S,Rest);
check_unique_sequence_tags(_S,[]) ->
    true.

check_unique_sequence_tags1(S,[C|Rest],Acc) when record(C,'ComponentType') ->
    case C#'ComponentType'.prop of
	mandatory ->
	    check_unique_tags(S,lists:reverse([C|Acc])),
	    check_unique_sequence_tags(S,Rest);
	_  ->
	    check_unique_sequence_tags1(S,Rest,[C|Acc]) % default or optional
    end;
check_unique_sequence_tags1(S,[H|Rest],Acc) ->
    check_unique_sequence_tags1(S,Rest,[H|Acc]);
check_unique_sequence_tags1(S,[],Acc) ->
    check_unique_tags(S,lists:reverse(Acc)).

check_sequenceof(S,Type,Component) when record(Component,type) ->
    check_type(S,Type,Component).

check_set(S,Type,Components) ->
    {TableCInf,NewComponents} = check_sequence(S,Type,Components),
    case lists:member(der,S#state.options) of
	true when S#state.erule == ber;
		  S#state.erule == ber_bin ->
	    {Sorted,SortedComponents} =
		sort_components(S#state.tname,
				(S#state.module)#module.tagdefault,
				NewComponents),
	    {Sorted,TableCInf,SortedComponents};
	_ ->
	    {false,TableCInf,NewComponents}
    end.

sort_components(_TypeName,'AUTOMATIC',Components) ->
    {true,Components};
sort_components(TypeName,_TagDefault,Components) ->
    case untagged_choice(Components) of
	false ->
	    {true,sort_components1(TypeName,Components,[],[],[],[])};
	true ->
	    {dynamic,Components} % sort in run-time
    end.

sort_components1(TypeName,[C=#'ComponentType'{tags=[{'UNIVERSAL',_}|_R]}|Cs],
		 UnivAcc,ApplAcc,ContAcc,PrivAcc) ->
    sort_components1(TypeName,Cs,[C|UnivAcc],ApplAcc,ContAcc,PrivAcc);
sort_components1(TypeName,[C=#'ComponentType'{tags=[{'APPLICATION',_}|_R]}|Cs],
		 UnivAcc,ApplAcc,ContAcc,PrivAcc) ->
    sort_components1(TypeName,Cs,UnivAcc,[C|ApplAcc],ContAcc,PrivAcc);
sort_components1(TypeName,[C=#'ComponentType'{tags=[{'CONTEXT',_}|_R]}|Cs],
		 UnivAcc,ApplAcc,ContAcc,PrivAcc) ->
    sort_components1(TypeName,Cs,UnivAcc,ApplAcc,[C|ContAcc],PrivAcc);
sort_components1(TypeName,[C=#'ComponentType'{tags=[{'PRIVATE',_}|_R]}|Cs],
		 UnivAcc,ApplAcc,ContAcc,PrivAcc) ->
    sort_components1(TypeName,Cs,UnivAcc,ApplAcc,ContAcc,[C|PrivAcc]);
sort_components1(TypeName,[],UnivAcc,ApplAcc,ContAcc,PrivAcc) ->
    I = #'ComponentType'.tags,
    ascending_order_check(TypeName,sort_universal_type(UnivAcc)) ++
	ascending_order_check(TypeName,lists:keysort(I,ApplAcc)) ++
	ascending_order_check(TypeName,lists:keysort(I,ContAcc)) ++
	ascending_order_check(TypeName,lists:keysort(I,PrivAcc)).

ascending_order_check(TypeName,Components) ->
    ascending_order_check1(TypeName,Components),
    Components.

ascending_order_check1(TypeName,
		       [C1 = #'ComponentType'{tags=[{_,T}|_]},
			C2 = #'ComponentType'{tags=[{_,T}|_]}|Rest]) ->
    io:format("WARNING: Indistinct tag ~p in SET ~p, components ~p and ~p~n",
	      [T,TypeName,C1#'ComponentType'.name,C2#'ComponentType'.name]),
    ascending_order_check1(TypeName,[C2|Rest]);
ascending_order_check1(TypeName,
		       [C1 = #'ComponentType'{tags=[{'UNIVERSAL',T1}|_]},
			C2 = #'ComponentType'{tags=[{'UNIVERSAL',T2}|_]}|Rest]) ->
    case (asn1ct_gen_ber:decode_type(T1) == asn1ct_gen_ber:decode_type(T2)) of
	true ->
	    io:format("WARNING: Indistinct tags ~p and ~p in"
		      " SET ~p, components ~p and ~p~n",
		      [T1,T2,TypeName,C1#'ComponentType'.name,
		       C2#'ComponentType'.name]),
	    ascending_order_check1(TypeName,[C2|Rest]);
	_ ->
	    ascending_order_check1(TypeName,[C2|Rest])
    end;
ascending_order_check1(N,[_|Rest]) ->
    ascending_order_check1(N,Rest);
ascending_order_check1(_,[_]) ->
    ok;
ascending_order_check1(_,[]) ->
    ok.

sort_universal_type(Components) ->
    List = lists:map(fun(C) ->
			     #'ComponentType'{tags=[{_,T}|_]} = C,
			     {asn1ct_gen_ber:decode_type(T),C}
		     end,
		     Components),
    SortedList = lists:keysort(1,List),
    lists:map(fun(X)->element(2,X) end,SortedList).

untagged_choice([#'ComponentType'{typespec=#type{tag=[],def={'CHOICE',_}}}|_Rest]) ->
    true;
untagged_choice([_|Rest]) ->
    untagged_choice(Rest);
untagged_choice([]) ->
    false.

check_setof(S,Type,Component) when record(Component,type) ->
    check_type(S,Type,Component).

check_restrictedstring(_S,_Def,_Constr) ->
    ok.

check_objectidentifier(_S,_Constr) ->
    ok.

% check all aspects of a CHOICE
% - that all alternative names are unique
% - that all TAGS are ok (when TAG default is applied)
% - that each alternative is of a valid type
% - that the extension marks are valid
check_choice(S,Type,Components) when list(Components) ->
    case check_unique([C||C <- Components,
			  record(C,'ComponentType')],#'ComponentType'.name) of
	[] ->
    %%    sort_canonical(Components),
	    Components2 = maybe_automatic_tags(S,Components),
	    %NewComps =
	    case check_each_alternative(S,Type,Components2) of
		{NewComponents,NewEcomps} ->
		    check_unique_tags(S,NewComponents ++ NewEcomps),
		    {NewComponents,NewEcomps};
		NewComponents ->
		    check_unique_tags(S,NewComponents),
		    NewComponents
	    end;
%%	    CompListWithTblInf = get_tableconstraint_info(S,Type,NewComps);
	Dupl ->
	    throw({error,{asn1,{duplicate_choice_alternatives,Dupl}}})
    end;
check_choice(_S,_,[]) ->
    [].

%% probably dead code that should be removed
%%maybe_automatic_tags(S,{Rc,Ec}) ->
%%    {maybe_automatic_tags1(S,Rc,0),maybe_automatic_tags1(S,Ec,length(Rc))};
maybe_automatic_tags(#state{erule=per},C) ->
    C;
maybe_automatic_tags(#state{erule=per_bin},C) ->
    C;
maybe_automatic_tags(S,C) ->
    maybe_automatic_tags1(S,C,0).

maybe_automatic_tags1(S,C,TagNo) ->
    case (S#state.module)#module.tagdefault of
	'AUTOMATIC' ->
	    generate_automatic_tags(S,C,TagNo);
	_ ->
	    %% maybe is the module a multi file module were only some of
	    %% the modules have defaulttag AUTOMATIC TAGS then the names
	    %% of those types are saved in the table automatic_tags
	    Name= S#state.tname,
	    case is_automatic_tagged_in_multi_file(Name) of
		true ->
		    generate_automatic_tags(S,C,TagNo);
		false ->
		    C
	    end
    end.

is_automatic_tagged_in_multi_file(Name) ->
    case ets:info(automatic_tags) of
	undefined ->
	    %% this case when not multifile compilation
	    false;
	_ ->
	    case ets:member(automatic_tags,Name) of
		true ->
		     true;
		_ ->
		    false
	    end
    end.

generate_automatic_tags(_S,C,TagNo) ->
    case any_manual_tag(C) of
	true ->
	    C;
	false ->
	    generate_automatic_tags1(C,TagNo)
    end.

generate_automatic_tags1([H|T],TagNo) when record(H,'ComponentType') ->
    #'ComponentType'{typespec=Ts} = H,
    NewTs = Ts#type{tag=[#tag{class='CONTEXT',
			     number=TagNo,
			     type={default,'IMPLICIT'},
			     form= 0 }]}, % PRIMITIVE
    [H#'ComponentType'{typespec=NewTs}|generate_automatic_tags1(T,TagNo+1)];
generate_automatic_tags1([ExtMark|T],TagNo) -> % EXTENSIONMARK
    [ExtMark | generate_automatic_tags1(T,TagNo)];
generate_automatic_tags1([],_) ->
    [].

any_manual_tag([#'ComponentType'{typespec=#type{tag=[]}}|Rest]) ->
    any_manual_tag(Rest);
any_manual_tag([{'EXTENSIONMARK',_,_}|Rest]) ->
    any_manual_tag(Rest);
any_manual_tag([_|_Rest]) ->
    true;
any_manual_tag([]) ->
    false.


check_unique_tags(S,C) ->
    case (S#state.module)#module.tagdefault of
	'AUTOMATIC' ->
	    case any_manual_tag(C) of
		false -> true;
		_ -> collect_and_sort_tags(C,[])
	    end;
	_ ->
	    collect_and_sort_tags(C,[])
    end.

collect_and_sort_tags([C|Rest],Acc) when record(C,'ComponentType') ->
    collect_and_sort_tags(Rest,C#'ComponentType'.tags ++ Acc);
collect_and_sort_tags([_|Rest],Acc) ->
    collect_and_sort_tags(Rest,Acc);
collect_and_sort_tags([],Acc) ->
    {Dupl,_}= lists:mapfoldl(fun(El,El)->{{dup,El},El};(El,_Prev)-> {El,El} end,notag,lists:sort(Acc)),
    Dupl2 = [Dup|| {dup,Dup} <- Dupl],
    if
	length(Dupl2) > 0 ->
	    throw({error,{asn1,{duplicates_of_the_tags,Dupl2}}});
	true ->
	    true
    end.

check_unique(L,Pos) ->
    Slist = lists:keysort(Pos,L),
    check_unique2(Slist,Pos,[]).

check_unique2([A,B|T],Pos,Acc) when element(Pos,A) == element(Pos,B) ->
    check_unique2([B|T],Pos,[element(Pos,B)|Acc]);
check_unique2([_|T],Pos,Acc) ->
    check_unique2(T,Pos,Acc);
check_unique2([],_,Acc) ->
    lists:reverse(Acc).

check_each_component(S,Type,{Rlist,ExtList}) ->
    {check_each_component(S,Type,Rlist),
     check_each_component(S,Type,ExtList)};
check_each_component(S,Type,Components) ->
    check_each_component(S,Type,Components,[],[],noext).

check_each_component(S = #state{abscomppath=Path,recordtopname=TopName},Type,
		     [C|Ct],Acc,Extacc,Ext) when record(C,'ComponentType') ->
    #'ComponentType'{name=Cname,typespec=Ts,prop=Prop} = C,
    NewAbsCPath =
	case Ts#type.def of
	    #'Externaltypereference'{} -> [];
	    _ -> [Cname|Path]
	end,
    CheckedTs = check_type(S#state{abscomppath=NewAbsCPath,
				   recordtopname=[Cname|TopName]},Type,Ts),
    NewTags = get_taglist(S,CheckedTs),

    NewProp =
%	case lists:member(der,S#state.options) of
%	    true ->
%	    True ->
	case normalize_value(S,CheckedTs,Prop,[Cname|TopName]) of
	    mandatory -> mandatory;
	    'OPTIONAL' -> 'OPTIONAL';
	    DefaultValue -> {'DEFAULT',DefaultValue}
	end,
%	    _ ->
%		Prop
%	end,
    NewC = C#'ComponentType'{typespec=CheckedTs,prop=NewProp,tags=NewTags},
    case Ext of
	noext ->
	    check_each_component(S,Type,Ct,[NewC|Acc],Extacc,Ext);
	ext ->
	    check_each_component(S,Type,Ct,Acc,[NewC|Extacc],Ext)
    end;
check_each_component(S,Type,[_|Ct],Acc,Extacc,noext) -> % skip 'EXTENSIONMARK'
    check_each_component(S,Type,Ct,Acc,Extacc,ext);
check_each_component(_S,_,[_C|_Ct],_,_,ext) -> % skip 'EXTENSIONMARK'
    throw({error,{asn1,{too_many_extension_marks}}});
check_each_component(_S,_,[],Acc,Extacc,ext) ->
    {lists:reverse(Acc),lists:reverse(Extacc)};
check_each_component(_S,_,[],Acc,_,noext) ->
    lists:reverse(Acc).

check_each_alternative(S,Type,{Rlist,ExtList}) ->
    {check_each_alternative(S,Type,Rlist),
     check_each_alternative(S,Type,ExtList)};
check_each_alternative(S,Type,[C|Ct]) ->
    check_each_alternative(S,Type,[C|Ct],[],[],noext).

check_each_alternative(S=#state{abscomppath=Path,recordtopname=TopName},Type,[C|Ct],
		       Acc,Extacc,Ext) when record(C,'ComponentType') ->
    #'ComponentType'{name=Cname,typespec=Ts,prop=_Prop} = C,
    NewAbsCPath =
	case Ts#type.def of
	    #'Externaltypereference'{} -> [];
	    _ -> [Cname|Path]
	end,
    NewState =
	S#state{abscomppath=NewAbsCPath,recordtopname=[Cname|TopName]},
    CheckedTs = check_type(NewState,Type,Ts),
    NewTags = get_taglist(S,CheckedTs),
    NewC = C#'ComponentType'{typespec=CheckedTs,tags=NewTags},
    case Ext of
	noext ->
	    check_each_alternative(S,Type,Ct,[NewC|Acc],Extacc,Ext);
	ext ->
	    check_each_alternative(S,Type,Ct,Acc,[NewC|Extacc],Ext)
    end;

check_each_alternative(S,Type,[_|Ct],Acc,Extacc,noext) -> % skip 'EXTENSIONMARK'
    check_each_alternative(S,Type,Ct,Acc,Extacc,ext);
check_each_alternative(_S,_,[_C|_Ct],_,_,ext) -> % skip 'EXTENSIONMARK'
    throw({error,{asn1,{too_many_extension_marks}}});
check_each_alternative(_S,_,[],Acc,Extacc,ext) ->
    {lists:reverse(Acc),lists:reverse(Extacc)};
check_each_alternative(_S,_,[],Acc,_,noext) ->
    lists:reverse(Acc).

%% componentrelation_leadingattr/2 searches the structure for table
%% constraints, if any is found componentrelation_leadingattr/5 is
%% called.
componentrelation_leadingattr(S,CompList) ->
%    {Cs1,Cs2} =
    Cs =
	case CompList of
	    {Components,EComponents} when list(Components) ->
%		{Components,Components};
		Components ++ EComponents;
	    CompList when list(CompList) ->
%		{CompList,CompList}
		CompList
	end,
%    case any_simple_table(S,Cs1,[]) of

    %% get_simple_table_if_used/2 should find out whether there are any
    %% component relation constraints in the entire tree of Cs1 that
    %% relates to this level. It returns information about the simple
    %% table constraint necessary for the the call to
    %% componentrelation_leadingattr/6. The step when the leading
    %% attribute and the syntax tree is modified to support the code
    %% generating.
    case get_simple_table_if_used(S,Cs) of
	[] -> {false,CompList};
	STList ->
%	    componentrelation_leadingattr(S,Cs1,Cs2,STList,[],[])
	    componentrelation_leadingattr(S,Cs,Cs,STList,[],[])
    end.

%% componentrelation_leadingattr/6 when all components are searched
%% the new modified components are returned together with the "leading
%% attribute" information, which later is stored in the tablecinf
%% field in the SEQUENCE/SET record. The "leading attribute"
%% information is used to generate the lookup in the object set
%% table. The other information gathered in the #type.tablecinf field
%% is used in code generating phase too, to recognice the proper
%% components for "open type" encoding and to propagate the result of
%% the object set lookup when needed.
componentrelation_leadingattr(_,[],_CompList,_,[],NewCompList) ->
    {false,lists:reverse(NewCompList)};
componentrelation_leadingattr(_,[],_CompList,_,LeadingAttr,NewCompList) ->
    {lists:last(LeadingAttr),lists:reverse(NewCompList)}; %send all info in Ts later
componentrelation_leadingattr(S,[C|Cs],CompList,STList,Acc,CompAcc) ->
    {LAAcc,NewC} =
	case catch componentrelation1(S,C#'ComponentType'.typespec,
				      [C#'ComponentType'.name]) of
	    {'EXIT',_} ->
		{[],C};
	    {CRI=[{_A1,_B1,_C1,_D1}|_Rest],NewTSpec} ->
		%% {ObjectSet,AtPath,ClassDef,Path}
		%% _A1 is a reference to the object set of the
		%% component relation constraint.
		%% _B1 is the path of names in the at-list of the
		%% component relation constraint.
		%% _C1 is the class definition of the
		%% ObjectClassFieldType.
		%% _D1 is the path of components that was traversed to
		%% find this constraint.
		case leading_attr_index(S,CompList,CRI,
					lists:reverse(S#state.abscomppath),[]) of
		    [] ->
			{[],C};
		    [{ObjSet,Attr,N,ClassDef,_Path,ValueIndex}|_NewRest] ->
			OS = object_set_mod_name(S,ObjSet),
			UniqueFieldName =
			    case (catch get_unique_fieldname(#classdef{typespec=ClassDef})) of
				{error,'__undefined_'} ->
				    no_unique;
				{asn1,Msg,_} ->
				    error({type,Msg,S});
				Other -> Other
			    end,
%			UsedFieldName = get_used_fieldname(S,Attr,STList),
			%% Res should be done differently: even though
			%% a unique field name exists it is not
			%% certain that the ObjectClassFieldType of
			%% the simple table constraint picks that
			%% class field.
			Res = #simpletableattributes{objectsetname=OS,
%%						     c_name=asn1ct_gen:un_hyphen_var(Attr),
						     c_name=Attr,
						     c_index=N,
						     usedclassfield=UniqueFieldName,
						     uniqueclassfield=UniqueFieldName,
						     valueindex=ValueIndex},
			{[Res],C#'ComponentType'{typespec=NewTSpec}}
		end;
	    _ ->
		%% no constraint was found
		{[],C}
	end,
    componentrelation_leadingattr(S,Cs,CompList,STList,LAAcc++Acc,
				  [NewC|CompAcc]).

object_set_mod_name(_S,ObjSet) when atom(ObjSet) ->
    ObjSet;
object_set_mod_name(#state{mname=M},
		    #'Externaltypereference'{module=M,type=T}) ->
    T;
object_set_mod_name(S,#'Externaltypereference'{module=M,type=T}) ->
    case lists:member(M,S#state.inputmodules) of
	true ->
	    T;
	false ->
	    {M,T}
    end.

%% get_used_fieldname gets the used field of the class referenced by
%% the ObjectClassFieldType construct in the simple table constraint
%% corresponding to the component relation constraint that depends on
%% it.
% get_used_fieldname(_S,CName,[{[CName|_Rest],_,ClFieldName}|_RestSimpleT]) ->
%     ClFieldName;
% get_used_fieldname(S,CName,[_SimpleTC|Rest]) ->
%     get_used_fieldname(S,CName,Rest);
% get_used_fieldname(S,_,[]) ->
%     error({type,"Error in Simple table constraint",S}).

%% any_simple_table/3 checks if any of the components on this level is
%% constrained by a simple table constraint. It returns a list of
%% tuples with three elements. It is a name path to the place in the
%% type structure where the constraint is, and the name of the object
%% set and the referenced field in the class.
% any_simple_table(S = #state{mname=M,abscomppath=Path},
% 		 [#'ComponentType'{name=Name,typespec=Type}|Cs],Acc) ->
%     Constraint = Type#type.constraint,
%     case lists:keysearch(simpletable,1,Constraint) of
% 	{value,{_,#type{def=Ref}}} ->
% 	    %% This ObjectClassFieldType, which has a simple table
% 	    %% constraint, must pick a fixed type value, mustn't it ?
% 	    {ClassDef,[{_,ClassFieldName}]} = Type#type.def,
% 	    ST =
% 		case Ref of
% 		    #'Externaltypereference'{module=M,type=ObjSetName} ->
% 			{[Name|Path],ObjSetName,ClassFieldName};
% 		    _ ->
% 			{[Name|Path],Ref,ClassFieldName}
% 		end,
% 	    any_simple_table(S,Cs,[ST|Acc]);
% 	false ->
% 	    any_simple_table(S,Cs,Acc)
%     end;
% any_simple_table(_,[],Acc) ->
%     lists:reverse(Acc);
% any_simple_table(S,[_|Cs],Acc) ->
%     any_simple_table(S,Cs,Acc).

%% get_simple_table_if_used/2 searches the structure of Cs for any
%% component relation constraints due to the present level of the
%% structure. If there are any, the necessary information for code
%% generation of the look up functionality in the object set table are
%% returned.
get_simple_table_if_used(S,Cs) ->
    CNames = lists:map(fun(#'ComponentType'{name=Name}) -> Name;
			  (_) -> [] %% in case of extension marks
		       end,
		       Cs),
    RefedSimpleTable=any_component_relation(S,Cs,CNames,[],[]),
    get_simple_table_info(S,Cs,remove_doubles(RefedSimpleTable)).

remove_doubles(L) ->
    remove_doubles(L,[]).
remove_doubles([H|T],Acc) ->
    NewT = remove_doubles1(H,T),
    remove_doubles(NewT,[H|Acc]);
remove_doubles([],Acc) ->
    Acc.

remove_doubles1(El,L) ->
    case lists:delete(El,L) of
	L -> L;
	NewL -> remove_doubles1(El,NewL)
    end.

%% get_simple_table_info searches the commponents Cs by the path from
%% an at-list (third argument), and follows into a component of it if
%% necessary, to get information needed for code generating.
%%
%% Returns a list of tuples with three elements. It holds a list of
%% atoms that is the path, the name of the field of the class that are
%% referred to in the ObjectClassFieldType, and the name of the unique
%% field of the class of the ObjectClassFieldType.
%%
% %% The level information outermost/innermost must be kept. There are
% %% at least two possibilities to cover here for an outermost case: 1)
% %% Both the simple table and the component relation have a common path
% %% at least one step below the outermost level, i.e. the leading
% %% information shall be on a sub level. 2) They don't have any common
% %% path.
get_simple_table_info(S,Cs,[AtList|Rest]) ->
%%    [get_simple_table_info1(S,Cs,AtList,S#state.abscomppath)|get_simple_table_info(S,Cs,Rest)];
    [get_simple_table_info1(S,Cs,AtList,[])|get_simple_table_info(S,Cs,Rest)];
get_simple_table_info(_,_,[]) ->
    [].
get_simple_table_info1(S,Cs,[Cname|Cnames],Path) when list(Cs) ->
    case lists:keysearch(Cname,#'ComponentType'.name,Cs) of
	{value,C} ->
	    get_simple_table_info1(S,C,Cnames,[Cname|Path]);
        _ ->
	    error({type,"Missing expected simple table constraint",S})
    end;
get_simple_table_info1(S,#'ComponentType'{typespec=TS},[],Path) ->
    %% In this component there must be a simple table constraint
    %% o.w. the asn1 code is wrong.
    #type{def=OCFT,constraint=Cnstr} = TS,
    case Cnstr of
	[{simpletable,_OSRef}]->
	    #'ObjectClassFieldType'{classname=ClRef,
				    class=ObjectClass,
				    fieldname=FieldName} = OCFT,
%	    #'ObjectClassFieldType'{ObjectClass,FieldType} = ObjectClassFieldType,
	    ObjectClassFieldName =
		case FieldName of
		    {LastFieldName,[]} -> LastFieldName;
		    {_FirstFieldName,FieldNames} ->
			lists:last(FieldNames)
		end,
	    %%ObjectClassFieldName is the last element in the dotted
	    %%list of the ObjectClassFieldType. The last element may
	    %%be of another class, that is referenced from the class
	    %%of the ObjectClassFieldType
	    ClassDef =
		case ObjectClass of
		    [] ->
			{_,CDef}=get_referenced_type(S,ClRef),
			CDef;
		    _ -> #classdef{typespec=ObjectClass}
		end,
	    UniqueName =
		case (catch get_unique_fieldname(ClassDef)) of
		    {error,'__undefined_'} -> no_unique;
		    {asn1,Msg,_} ->
			error({type,Msg,S});
		    Other -> Other
		end,
	    {lists:reverse(Path),ObjectClassFieldName,UniqueName};
	_ ->
	    error({type,{asn1,"missing expected simple table constraint",
			 Cnstr},S})
    end;
get_simple_table_info1(S,#'ComponentType'{typespec=TS},Cnames,Path) ->
    Components = get_atlist_components(TS#type.def),
    get_simple_table_info1(S,Components,Cnames,Path).

%% any_component_relation searches for all component relation
%% constraints that refers to the actual level and returns a list of
%% the "name path" in the at-list to the component relation constraint
%% that must refer to a simple table constraint. The list is empty if
%% no component relation constraints were found.
%%
%% NamePath has the names of all components that are followed from the
%% beginning of the search. CNames holds the names of all components
%% of the start level, this info is used if an outermost at-notation
%% is found to check the validity of the at-list.
any_component_relation(S,[C|Cs],CNames,NamePath,Acc) ->
    CName = C#'ComponentType'.name,
    Type = C#'ComponentType'.typespec,
    CRelPath =
	case Type#type.constraint of
	    [{componentrelation,_,AtNotation}] ->
		%% Found component relation constraint, now check
		%% whether this constraint is relevant for the level
		%% where the search started
		AtNot = extract_at_notation(AtNotation),
		%% evaluate_atpath returns the relative path to the
		%% simple table constraint from where the component
		%% relation is found.
		evaluate_atpath(S#state.abscomppath,NamePath,CNames,AtNot);
	    _ ->
		[]
	end,
    InnerAcc =
	case {Type#type.inlined,
	      asn1ct_gen:type(asn1ct_gen:get_inner(Type#type.def))} of
	    {no,{constructed,bif}} ->
		InnerCs =
		    case get_components(Type#type.def) of
			{IC1,_IC2} -> IC1 ++ IC1;
			IC -> IC
		    end,
		%% here we are interested in components of an
		%% SEQUENCE/SET OF as well as SEQUENCE, SET and CHOICE
		any_component_relation(S,InnerCs,CNames,[CName|NamePath],[]);
	    _ ->
		[]
	end,
    any_component_relation(S,Cs,CNames,NamePath,InnerAcc++CRelPath++Acc);
any_component_relation(_,[],_,_,Acc) ->
    Acc.

%% evaluate_atpath/4 finds out whether the at notation refers to the
%% search level. The list of referenced names in the AtNot list shall
%% begin with a name that exists on the level it refers to. If the
%% found AtPath is refering to the same sub-branch as the simple table
%% has, then there shall not be any leading attribute info on this
%% level.
evaluate_atpath(_,[],Cnames,{innermost,AtPath=[Ref|_Refs]}) ->
    %% any innermost constraint found deeper in the structure is
    %% ignored.
    case lists:member(Ref,Cnames) of
	true -> [AtPath];
	false -> []
    end;
%% In this case must check that the AtPath doesn't step any step of
%% the NamePath, in that case the constraint will be handled in an
%% inner level.
evaluate_atpath(TopPath,NamePath,Cnames,{outermost,AtPath=[_Ref|_Refs]}) ->
    AtPathBelowTop =
	case TopPath of
	    [] -> AtPath;
	    _ ->
		case lists:prefix(TopPath,AtPath) of
		    true ->
			lists:subtract(AtPath,TopPath);
		    _ -> []
		end
	end,
    case {NamePath,AtPathBelowTop} of
	{[H|_T1],[H|_T2]} -> []; % this must be handled in lower level
	{_,[]} -> [];% this must be handled in an above level
	{_,[H|_T]} ->
	    case lists:member(H,Cnames) of
		true -> [AtPathBelowTop];
		_ -> error({type,{asn1,"failed to analyze at-path",AtPath}})
	    end
    end;
evaluate_atpath(_,_,_,_) ->
    [].

%% Type may be any of SEQUENCE, SET, CHOICE, SEQUENCE OF, SET OF but
%% only the three first have valid components.
get_atlist_components(Def) ->
    get_components(atlist,Def).

get_components(Def) ->
    get_components(any,Def).

get_components(_,#'SEQUENCE'{components=Cs}) ->
    Cs;
get_components(_,#'SET'{components=Cs}) ->
    Cs;
get_components(_,{'CHOICE',Cs}) ->
    Cs;
get_components(any,{'SEQUENCE OF',#type{def=Def}}) ->
    get_components(any,Def);
get_components(any,{'SET OF',#type{def=Def}}) ->
    get_components(any,Def);
get_components(_,_) ->
    [].


extract_at_notation([{Level,[#'Externalvaluereference'{value=Name}|Rest]}]) ->
    {Level,[Name|extract_at_notation1(Rest)]};
extract_at_notation(At) ->
    exit({error,{asn1,{at_notation,At}}}).
extract_at_notation1([#'Externalvaluereference'{value=Name}|Rest]) ->
    [Name|extract_at_notation1(Rest)];
extract_at_notation1([]) ->
    [].

%% componentrelation1/1 identifies all componentrelation constraints
%% that exist in C or in the substructure of C. Info about the found
%% constraints are returned in a list. It is ObjectSet, the reference
%% to the object set, AttrPath, the name atoms extracted from the
%% at-list in the component relation constraint, ClassDef, the
%% objectclass record of the class of the ObjectClassFieldType, Path,
%% that is the component name "path" from the searched level to this
%% constraint.
%%
%% The function is called with one component of the type in turn and
%% with the component name in Path at the first call. When called from
%% within, the name of the inner component is added to Path.
componentrelation1(S,C = #type{def=Def,constraint=Constraint,tablecinf=TCI},
		   Path) ->
    Ret =
	case Constraint of
	    [{componentrelation,{_,_,ObjectSet},AtList}|_Rest] ->
		[{_,AL=[#'Externalvaluereference'{}|_R1]}|_R2] = AtList,
		%% Note: if Path is longer than one,i.e. it is within
		%% an inner type of the actual level, then the only
		%% relevant at-list is of "outermost" type.
%%		#'ObjectClassFieldType'{class=ClassDef} = Def,
		ClassDef = get_ObjectClassFieldType_classdef(S,Def),
		AtPath =
		    lists:map(fun(#'Externalvaluereference'{value=V})->V end,
			      AL),
		{[{ObjectSet,AtPath,ClassDef,Path}],Def};
	    _Other ->
		%% check the inner type of component
		innertype_comprel(S,Def,Path)
	end,
    case Ret of
	nofunobj ->
	    nofunobj; %% ignored by caller
	{CRelI=[{ObjSet,_,_,_}],NewDef} -> %%
	    TCItmp = lists:subtract(TCI,[{objfun,ObjSet}]),
	    {CRelI,C#type{tablecinf=[{objfun,ObjSet}|TCItmp],def=NewDef}};
	{CompRelInf,NewDef} -> %% more than one tuple in CompRelInf
	    TCItmp = lists:subtract(TCI,[{objfun,anyset}]),
	    {CompRelInf,C#type{tablecinf=[{objfun,anyset}|TCItmp],def=NewDef}}
    end.

innertype_comprel(S,{'SEQUENCE OF',Type},Path) ->
    case innertype_comprel1(S,Type,Path) of
	nofunobj ->
	    nofunobj;
	{CompRelInf,NewType} ->
	    {CompRelInf,{'SEQUENCE OF',NewType}}
    end;
innertype_comprel(S,{'SET OF',Type},Path) ->
    case innertype_comprel1(S,Type,Path) of
	nofunobj ->
	    nofunobj;
	{CompRelInf,NewType} ->
	    {CompRelInf,{'SET OF',NewType}}
    end;
innertype_comprel(S,{'CHOICE',CTypeList},Path) ->
    case componentlist_comprel(S,CTypeList,[],Path,[]) of
	nofunobj ->
	    nofunobj;
	{CompRelInf,NewCs} ->
	    {CompRelInf,{'CHOICE',NewCs}}
    end;
innertype_comprel(S,Seq = #'SEQUENCE'{components=Cs},Path) ->
    case componentlist_comprel(S,Cs,[],Path,[]) of
	nofunobj ->
	    nofunobj;
	{CompRelInf,NewCs} ->
	    {CompRelInf,Seq#'SEQUENCE'{components=NewCs}}
    end;
innertype_comprel(S,Set = #'SET'{components=Cs},Path) ->
    case componentlist_comprel(S,Cs,[],Path,[]) of
	nofunobj ->
	    nofunobj;
	{CompRelInf,NewCs} ->
	    {CompRelInf,Set#'SET'{components=NewCs}}
    end;
innertype_comprel(_,_,_) ->
    nofunobj.

componentlist_comprel(S,[C = #'ComponentType'{name=Name,typespec=Type}|Cs],
		      Acc,Path,NewCL) ->
    case catch componentrelation1(S,Type,Path++[Name]) of
	{'EXIT',_} ->
	    componentlist_comprel(S,Cs,Acc,Path,[C|NewCL]);
	nofunobj ->
	    componentlist_comprel(S,Cs,Acc,Path,[C|NewCL]);
	{CRelInf,NewType} ->
	    componentlist_comprel(S,Cs,CRelInf++Acc,Path,
				  [C#'ComponentType'{typespec=NewType}|NewCL])
    end;
componentlist_comprel(_,[],Acc,_,NewCL) ->
    case Acc of
	[] ->
	    nofunobj;
	_ ->
	    {Acc,lists:reverse(NewCL)}
    end.

innertype_comprel1(S,T = #type{def=Def,constraint=Cons,tablecinf=TCI},Path) ->
    Ret =
	case Cons of
	    [{componentrelation,{_,_,ObjectSet},AtList}|_Rest] ->
		%% This AtList must have an "outermost" at sign to be
		%% relevent here.
		[{_,AL=[#'Externalvaluereference'{value=_Attr}|_R1]}|_R2]
		    = AtList,
%%		#'ObjectClassFieldType'{class=ClassDef} = Def,
		ClassDef = get_ObjectClassFieldType_classdef(S,Def),
		AtPath =
		    lists:map(fun(#'Externalvaluereference'{value=V})->V end,
			      AL),
		[{ObjectSet,AtPath,ClassDef,Path}];
	    _ ->
		innertype_comprel(S,Def,Path)
	end,
    case Ret of
	nofunobj -> nofunobj;
	L = [{ObjSet,_,_,_}] ->
	    TCItmp = lists:subtract(TCI,[{objfun,ObjSet}]),
	    {L,T#type{tablecinf=[{objfun,ObjSet}|TCItmp]}};
	{CRelInf,NewDef} ->
	    TCItmp = lists:subtract(TCI,[{objfun,anyset}]),
	    {CRelInf,T#type{def=NewDef,tablecinf=[{objfun,anyset}|TCItmp]}}
    end.


%% leading_attr_index counts the index and picks the name of the
%% component that is at the actual level in the at-list of the
%% component relation constraint (AttrP).  AbsP is the path of
%% component names from the top type level to the actual level. AttrP
%% is a list with the atoms from the at-list.
leading_attr_index(S,Cs,[H={_,AttrP,_,_}|T],AbsP,Acc) ->
    AttrInfo =
	case lists:prefix(AbsP,AttrP) of
	    %% why this ?? It is necessary when in same situation as
	    %% TConstrChoice, there is an inner structure with an
	    %% outermost at-list and the "leading attribute" code gen
	    %% may be at a level some steps below the outermost level.
	    true ->
		RelativAttrP = lists:subtract(AttrP,AbsP),
		%% The header is used to calculate the index of the
		%% component and to give the fun, received from the
		%% object set look up, an unique name. The tail is
		%% used to match the proper value input to the fun.
		{hd(RelativAttrP),tl(RelativAttrP)};
	    false ->
		{hd(AttrP),tl(AttrP)}
	end,
    case leading_attr_index1(S,Cs,H,AttrInfo,1) of
	0 ->
	    leading_attr_index(S,Cs,T,AbsP,Acc);
	Res ->
	    leading_attr_index(S,Cs,T,AbsP,[Res|Acc])
    end;
leading_attr_index(_,_Cs,[],_,Acc) ->
    lists:reverse(Acc).

leading_attr_index1(_,[],_,_,_) ->
    0;
leading_attr_index1(S,[C|Cs],Arg={ObjectSet,_,CDef,P},
		    AttrInfo={Attr,SubAttr},N) ->
    case C#'ComponentType'.name of
	Attr ->
	    ValueMatch = value_match(S,C,Attr,SubAttr),
	    {ObjectSet,Attr,N,CDef,P,ValueMatch};
	_ ->
	    leading_attr_index1(S,Cs,Arg,AttrInfo,N+1)
    end.

%% value_math gathers information for a proper value match in the
%% generated encode function. For a SEQUENCE or a SET the index of the
%% component is counted. For a CHOICE the index is 2.
value_match(S,C,Name,SubAttr) ->
    value_match(S,C,Name,SubAttr,[]). % C has name Name
value_match(_S,#'ComponentType'{},_Name,[],Acc) ->
    Acc;% do not reverse, indexes in reverse order
value_match(S,#'ComponentType'{typespec=Type},Name,[At|Ats],Acc) ->
    InnerType = asn1ct_gen:get_inner(Type#type.def),
    Components =
	case get_atlist_components(Type#type.def) of
	    [] -> error({type,{asn1,"element in at list must be a "
			       "SEQUENCE, SET or CHOICE.",Name},S});
	    Comps -> Comps
	end,
    {Index,ValueIndex} = component_value_index(S,InnerType,At,Components),
    value_match(S,lists:nth(Index,Components),At,Ats,[ValueIndex|Acc]).

component_value_index(S,'CHOICE',At,Components) ->
    {component_index(S,At,Components),2};
component_value_index(S,_,At,Components) ->
    %% SEQUENCE or SET
    Index = component_index(S,At,Components),
    {Index,{Index+1,At}}.

component_index(S,Name,Components) ->
    component_index1(S,Name,Components,1).
component_index1(_S,Name,[#'ComponentType'{name=Name}|_Cs],N) ->
    N;
component_index1(S,Name,[_C|Cs],N) ->
    component_index1(S,Name,Cs,N+1);
component_index1(S,Name,[],_) ->
    error({type,{asn1,"component of at-list was not"
		 " found in substructure",Name},S}).

get_unique_fieldname(ClassDef) ->
%%    {_,Fields,_} = ClassDef#classdef.typespec,
    Fields = (ClassDef#classdef.typespec)#objectclass.fields,
    get_unique_fieldname(Fields,[]).

get_unique_fieldname([],[]) ->
    throw({error,'__undefined_'});
get_unique_fieldname([],[Name]) ->
    Name;
get_unique_fieldname([],Acc) ->
    throw({asn1,'only one UNIQUE field is allowed in CLASS',Acc});
get_unique_fieldname([{fixedtypevaluefield,Name,_,'UNIQUE',_}|Rest],Acc) ->
    get_unique_fieldname(Rest,[Name|Acc]);
get_unique_fieldname([_H|T],Acc) ->
    get_unique_fieldname(T,Acc).

get_tableconstraint_info(S,Type,{CheckedTs,EComps}) ->
    {get_tableconstraint_info(S,Type,CheckedTs,[]),
     get_tableconstraint_info(S,Type,EComps,[])};
get_tableconstraint_info(S,Type,CheckedTs) ->
    get_tableconstraint_info(S,Type,CheckedTs,[]).

get_tableconstraint_info(_S,_Type,[],Acc) ->
    lists:reverse(Acc);
get_tableconstraint_info(S,Type,[C|Cs],Acc) ->
    CheckedTs = C#'ComponentType'.typespec,
    AccComp =
	case CheckedTs#type.def of
	    %% ObjectClassFieldType
	    OCFT=#'ObjectClassFieldType'{class=#objectclass{},
					 type=_AType} ->
%		AType = get_ObjectClassFieldType(S,Fields,FieldRef),
%		RefedFieldName =
%		    get_referencedclassfield(CheckedTs#type.def),%is probably obsolete
		NewOCFT =
		    OCFT#'ObjectClassFieldType'{class=[]},
		C#'ComponentType'{typespec=
				  CheckedTs#type{
%				    def=AType,
				    def=NewOCFT
				    }};
%				    constraint=[{tableconstraint_info,
%						 FieldRef}]}};
	    {'SEQUENCE OF',SOType} when record(SOType,type),
					(element(1,SOType#type.def)=='CHOICE') ->
		CTypeList = element(2,SOType#type.def),
		NewInnerCList =
		    get_tableconstraint_info(S,Type,CTypeList,[]),
		C#'ComponentType'{typespec=
				  CheckedTs#type{
				    def={'SEQUENCE OF',
					 SOType#type{def={'CHOICE',
							  NewInnerCList}}}}};
	    {'SET OF',SOType} when record(SOType,type),
				   (element(1,SOType#type.def)=='CHOICE') ->
		CTypeList = element(2,SOType#type.def),
		NewInnerCList =
		    get_tableconstraint_info(S,Type,CTypeList,[]),
		C#'ComponentType'{typespec=
				  CheckedTs#type{
				    def={'SET OF',
					 SOType#type{def={'CHOICE',
							  NewInnerCList}}}}};
	    _ ->
		C
	end,
    get_tableconstraint_info(S,Type,Cs,[AccComp|Acc]).

get_referenced_fieldname([{_,FirstFieldname}]) ->
    {FirstFieldname,[]};
get_referenced_fieldname([{_,FirstFieldname}|Rest]) ->
    {FirstFieldname,lists:map(fun(X)->element(2,X) end,Rest)};
get_referenced_fieldname(Def) ->
    {no_type,Def}.

%% get_ObjectClassFieldType extracts the type from the chain of
%% objects that leads to a final type.
get_ObjectClassFieldType(S,ERef,PrimFieldNameList) when
  record(ERef,'Externaltypereference') ->
    {_,Type} = get_referenced_type(S,ERef),
    ClassSpec = check_class(S,Type),
    Fields = ClassSpec#objectclass.fields,
    get_ObjectClassFieldType(S,Fields,PrimFieldNameList);
get_ObjectClassFieldType(S,Fields,L=[_PrimFieldName1|_Rest]) ->
    check_PrimitiveFieldNames(S,Fields,L),
    get_OCFType(S,Fields,L).

check_PrimitiveFieldNames(_S,_Fields,_) ->
    ok.

%% get_ObjectClassFieldType_classdef gets the def of the class of the
%% ObjectClassFieldType, i.e. the objectclass record. If the type has
%% been checked (it may be a field type of an internal SEQUENCE) the
%% class field = [], then the classdef has to be fetched by help of
%% the class reference in the classname field.
get_ObjectClassFieldType_classdef(S,#'ObjectClassFieldType'{classname=Name,
							  class=[]}) ->
    {_,#classdef{typespec=TS}} = get_referenced_type(S,Name),
    TS;
get_ObjectClassFieldType_classdef(_,#'ObjectClassFieldType'{class=Cl}) ->
    Cl.

get_OCFType(S,Fields,[{_FieldType,PrimFieldName}|Rest]) ->
    case lists:keysearch(PrimFieldName,2,Fields) of
	{value,{fixedtypevaluefield,_,Type,_Unique,_OptSpec}} ->
	    {fixedtypevaluefield,PrimFieldName,Type};
	{value,{objectfield,_,Type,_Unique,_OptSpec}} ->
	    {_,ClassDef} = get_referenced_type(S,Type#type.def),
	    CheckedCDef = check_class(S#state{type=ClassDef,
					      tname=ClassDef#classdef.name},
				      ClassDef#classdef.typespec),
	    get_OCFType(S,CheckedCDef#objectclass.fields,Rest);
	{value,{objectsetfield,_,Type,_OptSpec}} ->
	    {_,ClassDef} = get_referenced_type(S,Type#type.def),
	    CheckedCDef = check_class(S#state{type=ClassDef,
					      tname=ClassDef#classdef.name},
				      ClassDef#classdef.typespec),
	    get_OCFType(S,CheckedCDef#objectclass.fields,Rest);

	{value,Other} ->
	    {element(1,Other),PrimFieldName};
	_  ->
	    error({type,"undefined FieldName in ObjectClassFieldType",S})
    end.

get_taglist(#state{erule=per},_) ->
    [];
get_taglist(#state{erule=per_bin},_) ->
    [];
get_taglist(S,Ext) when record(Ext,'Externaltypereference') ->
    {_,T} = get_referenced_type(S,Ext),
    get_taglist(S,T#typedef.typespec);
get_taglist(S,Tref) when record(Tref,typereference) ->
    {_,T} = get_referenced_type(S,Tref),
    get_taglist(S,T#typedef.typespec);
get_taglist(S,Type) when record(Type,type) ->
    case Type#type.tag of
	[] ->
	    get_taglist(S,Type#type.def);
	[Tag|_]  ->
% 	    case lists:member(S#state.erule,[ber,ber_bin]) of
% 		true ->
% 		   lists:map(fun(Tx) -> asn1ct_gen:def_to_tag(Tx) end,Type#type.tag);
% 		_ ->
	    [asn1ct_gen:def_to_tag(Tag)]
%	    end
    end;
get_taglist(S,{'CHOICE',{Rc,Ec}}) ->
    get_taglist(S,{'CHOICE',Rc ++ Ec});
get_taglist(S,{'CHOICE',Components}) ->
    get_taglist1(S,Components);
%% ObjectClassFieldType OTP-4390
get_taglist(_S,#'ObjectClassFieldType'{type={typefield,_}}) ->
    [];
get_taglist(S,#'ObjectClassFieldType'{type={fixedtypevaluefield,_,Type}}) ->
    get_taglist(S,Type);
get_taglist(S,{ERef=#'Externaltypereference'{},FieldNameList})
  when list(FieldNameList) ->
    case get_ObjectClassFieldType(S,ERef,FieldNameList) of
	Type when record(Type,type) ->
	    get_taglist(S,Type);
	{fixedtypevaluefield,_,Type} -> get_taglist(S,Type);
	{TypeFieldName,_} when atom(TypeFieldName) -> []%should check if allowed
    end;
get_taglist(S,{ObjCl,FieldNameList}) when record(ObjCl,objectclass),
					  list(FieldNameList) ->
    case get_ObjectClassFieldType(S,ObjCl#objectclass.fields,FieldNameList) of
	Type when record(Type,type) ->
	    get_taglist(S,Type);
	{fixedtypevaluefield,_,Type} -> get_taglist(S,Type);
	{TypeFieldName,_} when atom(TypeFieldName) -> []%should check if allowed
    end;
get_taglist(S,Def) ->
    case lists:member(S#state.erule,[ber_bin_v2]) of
	false ->
	    case Def of
		'ASN1_OPEN_TYPE' -> % open_type has no UNIVERSAL tag as such
		    [];
		_ ->
		    [asn1ct_gen:def_to_tag(Def)]
	    end;
	_ ->
	    []
    end.

get_taglist1(S,[#'ComponentType'{name=_Cname,tags=TagL}|Rest]) when list(TagL) ->
    %% tag_list has been here , just return TagL and continue with next alternative
    TagL ++ get_taglist1(S,Rest);
get_taglist1(S,[#'ComponentType'{typespec=Ts,tags=undefined}|Rest]) ->
    get_taglist(S,Ts) ++ get_taglist1(S,Rest);
get_taglist1(S,[_H|Rest]) -> % skip EXTENSIONMARK
    get_taglist1(S,Rest);
get_taglist1(_S,[]) ->
    [].

dbget_ex(_S,Module,Key) ->
    case asn1_db:dbget(Module,Key) of
	undefined ->

	    throw({error,{asn1,{undefined,{Module,Key}}}}); % this is catched on toplevel type or value
	T -> T
    end.

merge_tags(T1, T2) when list(T2) ->
    merge_tags2(T1 ++ T2, []);
merge_tags(T1, T2) ->
    merge_tags2(T1 ++ [T2], []).

merge_tags2([T1= #tag{type='IMPLICIT'}, T2 |Rest], Acc) ->
    merge_tags2([T1#tag{type=T2#tag.type, form=T2#tag.form}|Rest],Acc);
merge_tags2([T1= #tag{type={default,'IMPLICIT'}}, T2 |Rest], Acc) ->
    merge_tags2([T1#tag{type=T2#tag.type, form=T2#tag.form}|Rest],Acc);
merge_tags2([H|T],Acc) ->
    merge_tags2(T, [H|Acc]);
merge_tags2([], Acc) ->
    lists:reverse(Acc).

merge_constraints(C1, []) ->
    C1;
merge_constraints([], C2) ->
    C2;
merge_constraints(C1, C2) ->
    {SList,VList,PAList,Rest} = splitlist(C1++C2,[],[],[],[]),
    SizeC = merge_constraints(SList),
    ValueC = merge_constraints(VList),
    PermAlphaC = merge_constraints(PAList),
    case Rest of
        [] ->
            SizeC ++ ValueC ++ PermAlphaC;
        _ ->
            throw({error,{asn1,{not_implemented,{merge_constraints,Rest}}}})
    end.

merge_constraints([]) -> [];
merge_constraints([C1 = {_,{Low1,High1}},{_,{Low2,High2}}|Rest]) when Low1 >= Low2,
                                                                      High1 =< High2 ->
    merge_constraints([C1|Rest]);
merge_constraints([C1={'PermittedAlphabet',_},C2|Rest]) ->
    [C1|merge_constraints([C2|Rest])];
merge_constraints([C1 = {_,{_Low1,_High1}},C2 = {_,{_Low2,_High2}}|_Rest]) ->
    throw({error,asn1,{conflicting_constraints,{C1,C2}}});
merge_constraints([C]) ->
    [C].

splitlist([C={'SizeConstraint',_}|Rest],Sacc,Vacc,PAacc,Restacc) ->
    splitlist(Rest,[C|Sacc],Vacc,PAacc,Restacc);
splitlist([C={'ValueRange',_}|Rest],Sacc,Vacc,PAacc,Restacc) ->
    splitlist(Rest,Sacc,[C|Vacc],PAacc,Restacc);
splitlist([C={'PermittedAlphabet',_}|Rest],Sacc,Vacc,PAacc,Restacc) ->
    splitlist(Rest,Sacc,Vacc,[C|PAacc],Restacc);
splitlist([C|Rest],Sacc,Vacc,PAacc,Restacc) ->
    splitlist(Rest,Sacc,Vacc,PAacc,[C|Restacc]);
splitlist([],Sacc,Vacc,PAacc,Restacc) ->
    {lists:reverse(Sacc),
     lists:reverse(Vacc),
     lists:reverse(PAacc),
     lists:reverse(Restacc)}.



storeindb(M) when record(M,module) ->
    TVlist = M#module.typeorval,
    NewM = M#module{typeorval=findtypes_and_values(TVlist)},
    asn1_db:dbnew(NewM#module.name),
    asn1_db:dbput(NewM#module.name,'MODULE',  NewM),
    Res = storeindb(NewM#module.name,TVlist,[]),
    include_default_class(NewM#module.name),
    include_default_type(NewM#module.name),
    Res.

storeindb(Module,[H|T],ErrAcc) when record(H,typedef) ->
    storeindb(Module,H#typedef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,valuedef) ->
    storeindb(Module,H#valuedef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,ptypedef) ->
    storeindb(Module,H#ptypedef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,classdef) ->
    storeindb(Module,H#classdef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,pvaluesetdef) ->
    storeindb(Module,H#pvaluesetdef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,pobjectdef) ->
    storeindb(Module,H#pobjectdef.name,H,T,ErrAcc);
storeindb(Module,[H|T],ErrAcc) when record(H,pvaluedef) ->
    storeindb(Module,H#pvaluedef.name,H,T,ErrAcc);
storeindb(_,[],[]) -> ok;
storeindb(_,[],ErrAcc) ->
    {error,ErrAcc}.

storeindb(Module,Name,H,T,ErrAcc) ->
    case asn1_db:dbget(Module,Name) of
	undefined ->
	    asn1_db:dbput(Module,Name,H),
	    storeindb(Module,T,ErrAcc);
	_ ->
	    case H of
		_Type when record(H,typedef) ->
		    error({type,"already defined",
			   #state{mname=Module,type=H,tname=Name}});
		_Type when record(H,valuedef) ->
		    error({value,"already defined",
			   #state{mname=Module,value=H,vname=Name}});
		_Type when record(H,ptypedef) ->
		    error({ptype,"already defined",
			   #state{mname=Module,type=H,tname=Name}});
		_Type when record(H,pobjectdef) ->
		    error({ptype,"already defined",
			   #state{mname=Module,type=H,tname=Name}});
		_Type when record(H,pvaluesetdef) ->
		    error({ptype,"already defined",
			   #state{mname=Module,type=H,tname=Name}});
		_Type when record(H,pvaluedef) ->
		    error({ptype,"already defined",
			   #state{mname=Module,type=H,tname=Name}});
		_Type when record(H,classdef) ->
		    error({class,"already defined",
			   #state{mname=Module,value=H,vname=Name}})
	    end,
	    storeindb(Module,T,[H|ErrAcc])
    end.

findtypes_and_values(TVList) ->
    findtypes_and_values(TVList,[],[],[],[],[],[]).%% Types,Values,
%% Parameterizedtypes,Classes,Objects and ObjectSets

findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,typedef),record(H#typedef.typespec,'Object') ->
    findtypes_and_values(T,Tacc,Vacc,Pacc,Cacc,[H#typedef.name|Oacc],OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,typedef),record(H#typedef.typespec,'ObjectSet') ->
    findtypes_and_values(T,Tacc,Vacc,Pacc,Cacc,Oacc,[H#typedef.name|OSacc]);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,typedef) ->
    findtypes_and_values(T,[H#typedef.name|Tacc],Vacc,Pacc,Cacc,Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,valuedef) ->
    findtypes_and_values(T,Tacc,[H#valuedef.name|Vacc],Pacc,Cacc,Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,ptypedef) ->
    findtypes_and_values(T,Tacc,Vacc,[H#ptypedef.name|Pacc],Cacc,Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,classdef) ->
    findtypes_and_values(T,Tacc,Vacc,Pacc,[H#classdef.name|Cacc],Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,pvaluedef) ->
    findtypes_and_values(T,Tacc,[H#pvaluedef.name|Vacc],Pacc,Cacc,Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,pvaluesetdef) ->
    findtypes_and_values(T,Tacc,[H#pvaluesetdef.name|Vacc],Pacc,Cacc,Oacc,OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,pobjectdef) ->
    findtypes_and_values(T,Tacc,Vacc,Pacc,Cacc,[H#pobjectdef.name|Oacc],OSacc);
findtypes_and_values([H|T],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc)
  when record(H,pobjectsetdef) ->
    findtypes_and_values(T,Tacc,Vacc,Pacc,Cacc,Oacc,[H#pobjectsetdef.name|OSacc]);
findtypes_and_values([],Tacc,Vacc,Pacc,Cacc,Oacc,OSacc) ->
    {lists:reverse(Tacc),lists:reverse(Vacc),lists:reverse(Pacc),
     lists:reverse(Cacc),lists:reverse(Oacc),lists:reverse(OSacc)}.



error({export,Msg,#state{mname=Mname,type=Ref,tname=Typename}}) ->
    Pos = Ref#'Externaltypereference'.pos,
    io:format("asn1error:~p:~p:~p ~p~n",[Pos,Mname,Typename,Msg]),
    {error,{export,Pos,Mname,Typename,Msg}};
error({type,Msg,#state{mname=Mname,type=Type,tname=Typename}})
  when record(Type,typedef) ->
    io:format("asn1error:~p:~p:~p ~p~n",
	      [Type#typedef.pos,Mname,Typename,Msg]),
    {error,{type,Type#typedef.pos,Mname,Typename,Msg}};
error({type,Msg,#state{mname=Mname,type=Type,tname=Typename}})
  when record(Type,ptypedef) ->
    io:format("asn1error:~p:~p:~p ~p~n",
	      [Type#ptypedef.pos,Mname,Typename,Msg]),
    {error,{type,Type#ptypedef.pos,Mname,Typename,Msg}};
error({type,Msg,#state{mname=Mname,value=Value,vname=Valuename}})
  when record(Value,valuedef) ->
    io:format("asn1error:~p:~p:~p ~p~n",[Value#valuedef.pos,Mname,Valuename,Msg]),
    {error,{type,Value#valuedef.pos,Mname,Valuename,Msg}};
error({type,Msg,#state{mname=Mname,type=Type,tname=Typename}})
  when record(Type,pobjectdef) ->
    io:format("asn1error:~p:~p:~p ~p~n",
	      [Type#pobjectdef.pos,Mname,Typename,Msg]),
    {error,{type,Type#pobjectdef.pos,Mname,Typename,Msg}};
error({value,Msg,#state{mname=Mname,value=Value,vname=Valuename}}) ->
    io:format("asn1error:~p:~p:~p ~p~n",[Value#valuedef.pos,Mname,Valuename,Msg]),
    {error,{value,Value#valuedef.pos,Mname,Valuename,Msg}};
error({Other,Msg,#state{mname=Mname,value=#valuedef{pos=Pos},vname=Valuename}}) ->
    io:format("asn1error:~p:~p:~p ~p~n",[Pos,Mname,Valuename,Msg]),
    {error,{Other,Pos,Mname,Valuename,Msg}};
error({Other,Msg,#state{mname=Mname,type=#typedef{pos=Pos},tname=Typename}}) ->
    io:format("asn1error:~p:~p:~p ~p~n",[Pos,Mname,Typename,Msg]),
    {error,{Other,Pos,Mname,Typename,Msg}};
error({Other,Msg,#state{mname=Mname,type=#classdef{pos=Pos},tname=Typename}}) ->
    io:format("asn1error:~p:~p:~p ~p~n",[Pos,Mname,Typename,Msg]),
    {error,{Other,Pos,Mname,Typename,Msg}}.

include_default_type(Module) ->
    NameAbsList = default_type_list(),
    include_default_type1(Module,NameAbsList).

include_default_type1(_,[]) ->
    ok;
include_default_type1(Module,[{Name,TS}|Rest]) ->
    case asn1_db:dbget(Module,Name) of
	undefined ->
	    T = #typedef{name=Name,
			 typespec=TS},
		asn1_db:dbput(Module,Name,T);
	_ -> ok
    end,
    include_default_type1(Module,Rest).

default_type_list() ->
    %% The EXTERNAL type is represented, according to ASN.1 1997,
    %% as a SEQUENCE with components: identification, data-value-descriptor
    %% and data-value.
    Syntax =
	#'ComponentType'{name=syntax,
			 typespec=#type{def='OBJECT IDENTIFIER'},
			 prop=mandatory},
    Presentation_Cid =
	#'ComponentType'{name='presentation-context-id',
			 typespec=#type{def='INTEGER'},
			 prop=mandatory},
    Transfer_syntax =
	#'ComponentType'{name='transfer-syntax',
			 typespec=#type{def='OBJECT IDENTIFIER'},
			 prop=mandatory},
    Negotiation_items =
	#type{def=
	      #'SEQUENCE'{components=
			  [Presentation_Cid,
			   Transfer_syntax#'ComponentType'{prop=mandatory}]}},
    Context_negot =
	#'ComponentType'{name='context-negotiation',
			 typespec=Negotiation_items,
			 prop=mandatory},

    Data_value_descriptor =
	#'ComponentType'{name='data-value-descriptor',
			 typespec=#type{def='ObjectDescriptor'},
			 prop='OPTIONAL'},
    Data_value =
	#'ComponentType'{name='data-value',
			 typespec=#type{def='OCTET STRING'},
			 prop=mandatory},

    %% The EXTERNAL type is represented, according to ASN.1 1990,
    %% as a SEQUENCE with components: direct-reference, indirect-reference,
    %% data-value-descriptor and encoding.

    Direct_reference =
	#'ComponentType'{name='direct-reference',
			 typespec=#type{def='OBJECT IDENTIFIER'},
			 prop='OPTIONAL'},

    Indirect_reference =
	#'ComponentType'{name='indirect-reference',
			 typespec=#type{def='INTEGER'},
			 prop='OPTIONAL'},

    Single_ASN1_type =
	#'ComponentType'{name='single-ASN1-type',
			 typespec=#type{tag=[{tag,'CONTEXT',0,
					      'EXPLICIT',32}],
					def='ANY'},
			 prop=mandatory},

    Octet_aligned =
	#'ComponentType'{name='octet-aligned',
			 typespec=#type{tag=[{tag,'CONTEXT',1,
					      'IMPLICIT',32}],
					def='OCTET STRING'},
			 prop=mandatory},

    Arbitrary =
	#'ComponentType'{name=arbitrary,
			 typespec=#type{tag=[{tag,'CONTEXT',2,
					      'IMPLICIT',32}],
					def={'BIT STRING',[]}},
			 prop=mandatory},

    Encoding =
	#'ComponentType'{name=encoding,
			 typespec=#type{def={'CHOICE',
					     [Single_ASN1_type,Octet_aligned,
					      Arbitrary]}},
			 prop=mandatory},

    EXTERNAL_components1990 =
	[Direct_reference,Indirect_reference,Data_value_descriptor,Encoding],

    %% The EMBEDDED PDV type is represented by a SEQUENCE type
    %% with components: identification and data-value
    Abstract =
	#'ComponentType'{name=abstract,
			 typespec=#type{def='OBJECT IDENTIFIER'},
			 prop=mandatory},
    Transfer =
	#'ComponentType'{name=transfer,
			 typespec=#type{def='OBJECT IDENTIFIER'},
			 prop=mandatory},
    AbstractTrSeq =
	#'SEQUENCE'{components=[Abstract,Transfer]},
    Syntaxes =
	#'ComponentType'{name=syntaxes,
			 typespec=#type{def=AbstractTrSeq},
			 prop=mandatory},
    Fixed = #'ComponentType'{name=fixed,
			     typespec=#type{def='NULL'},
			     prop=mandatory},
    Negotiations =
	[Syntaxes,Syntax,Presentation_Cid,Context_negot,
	 Transfer_syntax,Fixed],
    Identification2 =
	#'ComponentType'{name=identification,
			 typespec=#type{def={'CHOICE',Negotiations}},
			 prop=mandatory},
    EmbeddedPdv_components =
	[Identification2,Data_value],

    %% The CHARACTER STRING type is represented by a SEQUENCE type
    %% with components: identification and string-value
    String_value =
	#'ComponentType'{name='string-value',
			 typespec=#type{def='OCTET STRING'},
			 prop=mandatory},
    CharacterString_components =
	[Identification2,String_value],

    [{'EXTERNAL',
      #type{tag=[#tag{class='UNIVERSAL',
		      number=8,
		      type='IMPLICIT',
		      form=32}],
	    def=#'SEQUENCE'{components=
			    EXTERNAL_components1990}}},
     {'EMBEDDED PDV',
      #type{tag=[#tag{class='UNIVERSAL',
		      number=11,
		      type='IMPLICIT',
		      form=32}],
	    def=#'SEQUENCE'{components=EmbeddedPdv_components}}},
     {'CHARACTER STRING',
      #type{tag=[#tag{class='UNIVERSAL',
		      number=29,
		      type='IMPLICIT',
		      form=32}],
	    def=#'SEQUENCE'{components=CharacterString_components}}}
     ].


include_default_class(Module) ->
    NameAbsList = default_class_list(),
    include_default_class1(Module,NameAbsList).

include_default_class1(_,[]) ->
    ok;
include_default_class1(Module,[{Name,TS}|_Rest]) ->
    case asn1_db:dbget(Module,Name) of
	undefined ->
	    C = #classdef{checked=true,name=Name,
			  typespec=TS},
	    asn1_db:dbput(Module,Name,C);
	_ -> ok
    end.

default_class_list() ->
    [{'TYPE-IDENTIFIER',
      {objectclass,
       [{fixedtypevaluefield,
	 id,
	 {type,[],'OBJECT IDENTIFIER',[]},
	 'UNIQUE',
	 'MANDATORY'},
	{typefield,'Type','MANDATORY'}],
       {'WITH SYNTAX',
	[{typefieldreference,'Type'},
	 'IDENTIFIED',
	 'BY',
	 {valuefieldreference,id}]}}},
     {'ABSTRACT-SYNTAX',
      {objectclass,
       [{fixedtypevaluefield,
	 id,
	 {type,[],'OBJECT IDENTIFIER',[]},
	 'UNIQUE',
	 'MANDATORY'},
	{typefield,'Type','MANDATORY'},
	{fixedtypevaluefield,
	 property,
	 {type,
	  [],
	  {'BIT STRING',[]},
	  []},
	 undefined,
	 {'DEFAULT',
	  [0,1,0]}}],
       {'WITH SYNTAX',
	[{typefieldreference,'Type'},
	 'IDENTIFIED',
	 'BY',
	 {valuefieldreference,id},
	 ['HAS',
	  'PROPERTY',
	  {valuefieldreference,property}]]}}}].