~jdpipe/ascend/trunk-old

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
/*	ASCEND modelling environment
	Copyright (C) 2006 Carnegie Mellon University
	Copyright (C) 1990, 1993, 1994 Thomas Guthrie Epperly
	Copyright (C) 1997 Benjamin Allan, Vicente Rico-Ramirez

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2, or (at your option)
	any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*//*
	@file
	Ascend Instantiator Implementation

	@TODO this file is enormous and should be broken into pieces! -- JP
*//*
	by Tom Epperly
	Created: 1/24/90
	Last in CVS: $Revision: 1.84 $ $Date: 2003/02/06 04:08:30 $ $Author: ballan $
*/

#include "instantiate.h"

#include <ascend/utilities/bit.h>

#include "vlist.h"
#include "initialize.h"
#include "watchpt.h"

#include "stattypes.h"
#include "statement.h"
#include "type_desc.h"
#include "type_descio.h"
#include "module.h"
#include "library.h"
#include "sets.h"
#include "setio.h"
#include "extfunc.h"
#include "extcall.h"
#include "forvars.h"
#include "exprs.h"
#include "nameio.h"
#include "evaluate.h"
#include "value_type.h"
#include "statio.h"
#include "pending.h"
#include "find.h"
#include "relation.h"
#include "logical_relation.h"
#include "logrelation.h"
#include "relation_util.h"
#include "rel_blackbox.h"
#include "logrel_util.h"
#include "instance_types.h"
#include "cmpfunc.h"
#include "instance_io.h"
#include "when.h"
#include "case.h"
#include "when_util.h"
#include "select.h"
#include "link.h"
/* new headers */
#include "atomvalue.h"
#include "arrayinst.h"
#include "copyinst.h"
#include "createinst.h"
#include "destroyinst.h"
#include "extinst.h"
#include "visitinst.h"
#include "instquery.h"
#include "mathinst.h"
#include "mergeinst.h"
#include "parentchild.h"
#include "refineinst.h"
#include "check.h"
#include "instance_name.h"
#include "setinstval.h"
#include "anontype.h"
#include "anoncopy.h"
#include "parpend.h"
#include "parpend.h"
#include "bintoken.h"
#include "relerr.h"

#include <stdarg.h>
#include <errno.h>

#include <ascend/utilities/config.h>
#include <ascend/general/platform.h>

#ifdef ASC_SIGNAL_TRAPS
# include <ascend/utilities/ascSignal.h>
#endif

/*#include <stdlib.h>*/
#include <ascend/general/ascMalloc.h>
#include <ascend/general/panic.h>
#include <ascend/utilities/error.h>
#include <ascend/general/pool.h>
#include <ascend/general/list.h>
#include <ascend/general/dstring.h>

#if TIMECOMPILER
#include <ascend/general/tm_time.h>
#endif

/* don't even THINK ABOUT adding instmacro.h to this list -- ...what the? */

#define MAXNUMBER 4		/* maximum number of iterations allowed
                                 * without change */
#define PASS2MAXNUMBER 1	/* maximum number of iterations allowed
                                 * without change doing relations. In
                                 * system where rels reference rels, > 1 */

#define PASS3MAXNUMBER 4	/* maximum number of iterations allowed
                                 * without change doing logical relations.
                                 * In system where logrels reference logrels,
                                 * > 1 */

#define PASS4MAXNUMBER 1	/* maximum number of iterations allowed
                                 * without change executing WHEN. In
                                 * system where WHEN reference WHEN, > 1 */

#define PASS5MAXNUMBER 1	/* maximum number of iterations allowed
                                 * without change executing LINK. In
                                 * system where LINK reference LINK, > 1 */

#define AVG_CASES 2L		/* size to which all cases lists are */
                                /* initialized (WHEN instance) */
#define AVG_REF 2L		/* size to which all list of references */
                                /* in a case are initialized (WHEN) */

#define NO_INCIDENCES 7         /* avg number of vars in a external reln */

static int g_iteration = 0;	/* the current iteration. */

/* moved from tcltk/generic/interface/SimsProc.c */
struct Instance *g_cursim;

#define NEW_ext 1
#define OLD_ext 0
/**<
	variable to check agreement in the number of boolean, integer or symbol
	variables in the WHEN/SELECT statement with the number of boolean, integer
	or symbol values in each of the CASEs
*/

#define MAX_VAR_IN_LIST  20
/**<
	Variables to switch old and new pass 2 instantiation.
	The condition for using new pass 2 (anonymous type-based
	relation copying) is g_use_copyanon != 0 || FORCE applied.
*/

int g_use_copyanon = 1;
/**
	the user switch for anonymous type based relation
	copying. if 0, no copying by that method is done.
*/

#if TIMECOMPILER
static
int g_ExecuteREL_CreateTokenRelation_calls = 0;
static
int g_ExecuteEXT_CreateBlackboxRelation_calls = 0;
/* count the number of calls to CreateTokenRelation from ExecuteREL */
int g_CopyAnonRelation = 0;
#endif

long int g_compiler_counter = 1;
/**<
	What: counter incremented every time a compiler action capable of
	     changing the instance tree is executed.
	     At present the compiler cares nothing about this counter,
	     but it is provided as a service to clients.

	Real applications:
	1) This variable is used for keeping track of calls to
	the compiler which will create the need for a total solver system
	rebuild.  This variable should be incremented anytime a function
	which changes the instance tree is called.
*/

#define DEBUG_RELS
/* undef DEBUG_RELS if you want less spew in pass 2 */
#undef DEBUG_RELS

#ifdef DEBUG_RELS
/* root of tree being visited in pass 2. */
struct Instance *debug_rels_work;
#endif /* dbgrels */

static unsigned
int g_instantiate_relns = ALLRELS;	/* default is to do all rels */

/* pointer to possible error message for child expansion.
 * messy way of error handling; do not imitate.
 */
static char *g_trychildexpansion_errmessage = NULL;
#define TCEM g_trychildexpansion_errmessage

/* error messages */
#define REDEFINE_CHILD_MESG "IS_A statement attempting to redefine child "
#define REDEFINE_CHILD_MESG2 "ALIASES statement attempting to redefine child "
#define UNDEFINED_TYPE_MESG "IS_A statement refers to undefined type "
#define IRT_UNDEFINED_TYPE "IS_REFINED_TO statement refers to undefined type "
#define REASSIGN_MESG1 "Attempt to reassign constant "
#define REASSIGN_MESG2 " value."

/*------------------------------------------------------------------------------
	forward declarations
*/

static void WriteForValueError(struct Statement *, struct value_t);
static void MakeInstance(CONST struct Name *, struct TypeDescription *, int,
                  struct Instance *, struct Statement *, struct Instance *);
static int CheckVarList(struct Instance *, struct Statement *);
static int CheckWhereStatements(struct Instance *,struct StatementList *);
static int ExecuteISA(struct Instance *, struct Statement *);
static int ExecuteCASGN(struct Instance *, struct Statement *);
static int DigestArguments(struct Instance *,
                    struct gl_list_t *, struct StatementList *,
                    struct StatementList *, struct Statement *);
static int DeriveSetType(CONST struct Set *, struct Instance *,CONST unsigned int);

static void MissingInsts(struct Instance *, CONST struct VariableList *,int);
static struct gl_list_t *FindArgInsts(struct Instance *, struct Set *,
                               rel_errorlist *);
static void AddIncompleteInst(struct Instance *);
static int CheckALIASES(struct Instance *, struct Statement *);
static int CheckARR(struct Instance *, struct Statement *);
static int CheckISA(struct Instance *, struct Statement *);
static int AssignStructuralValue(struct Instance *,struct value_t,struct Statement *);
static int  CheckSELECT(struct Instance *, struct Statement *);
static int  CheckWHEN(struct Instance *, struct Statement *);
static void MakeRealWhenCaseReferencesFOR(struct Instance *,
                                          struct Instance *,
                                          struct Statement *,
                                          struct gl_list_t *);
static void MakeWhenCaseReferencesFOR(struct Instance *,
                                      struct Instance *,
                                      struct Statement *,
                                      struct gl_list_t *);
static int  Pass1CheckFOR(struct Instance *, struct Statement *);
static int  Pass1ExecuteFOR(struct Instance *, struct Statement *);
#ifdef THIS_IS_AN_UNUSED_FUNCTION
static int  Pass1RealCheckFOR(struct Instance *, struct Statement *);
#endif /* THIS_IS_AN_UNUSED_FUNCTION */
static void Pass1RealExecuteFOR(struct Instance *, struct Statement *);
static int  Pass2CheckFOR(struct Instance *, struct Statement *);
static int  Pass2ExecuteFOR(struct Instance *, struct Statement *);
static void Pass2FORMarkCond(struct Instance *, struct Statement *);
static void Pass2FORMarkCondRelations(struct Instance *, struct Statement *);
static int  Pass2RealCheckFOR(struct Instance *, struct Statement *);
static int  Pass2RealExecuteFOR(struct Instance *, struct Statement *);
static int  Pass3CheckFOR(struct Instance *, struct Statement *);
static int  Pass3ExecuteFOR(struct Instance *, struct Statement *);
static int  Pass3RealCheckFOR (struct Instance *, struct Statement *);
static int  Pass3RealExecuteFOR(struct Instance *, struct Statement *);
static void Pass3FORMarkCond(struct Instance *, struct Statement *);
static void Pass3FORMarkCondLogRels(struct Instance *, struct Statement *);
static int  Pass4CheckFOR(struct Instance *, struct Statement *);
static int  Pass4ExecuteFOR(struct Instance *, struct Statement *);
static int  Pass4RealCheckFOR(struct Instance *, struct Statement *);
static int  Pass5ExecuteFOR(struct Instance *, struct Statement *);
static int  ExecuteUnSelectedForStatements(struct Instance *,
                                           struct StatementList *);
static void ExecuteDefault(struct Instance *, struct Statement *,
                           unsigned long int *);
static void RealDefaultFor(struct Instance *, struct Statement *,
                           unsigned long int *);
static void DefaultStatementList(struct Instance *, struct gl_list_t *,
                                 unsigned long int *);
static void ExecuteDefaultStatements(struct Instance *, struct gl_list_t *,
                                     unsigned long int *);
static int ExecuteSELECT(struct Instance *, unsigned long *,
                         struct Statement *);
static void ExecuteDefaultsInSELECT(struct Instance *, unsigned long *,
                                    struct Statement *, unsigned long int *);
static void RealExecuteWHEN(struct Instance *, struct Statement *);
static int  ExecuteUnSelectedSELECT(struct Instance *, unsigned long *,
                                    struct Statement *);
static void ExecuteUnSelectedStatements(struct Instance *i,unsigned long *,
                                        struct StatementList *);
static void ExecuteUnSelectedWhenStatements(struct Instance *,
                                            struct StatementList *);
static int ExecuteUnSelectedWHEN(struct Instance *, struct Statement *);
static void ReEvaluateSELECT(struct Instance *, unsigned long *,
                             struct Statement *, int, int *);
static int ExecuteLNK(struct Instance *inst, struct Statement *statement);

/*-----------------------------------------------------------------------------
	...
*/


static
void ClearIteration(void)
{
  g_iteration = 0;
}

static
void instantiation_error(error_severity_t sev
		, const struct Statement *stat, const char *fmt
		, ...
){
	va_list args,args2;
	va_start(args,fmt);
	va_copy(args2,args);
	if(stat!= NULL){
		va_error_reporter(sev
			, Asc_ModuleBestName(StatementModule(stat))
			, StatementLineNum(stat), NULL
			, fmt, &args2
		);
	}else{
		va_error_reporter(sev
			, NULL, 0, NULL
			, fmt, &args2
		);
	}
	va_end(args);
}

static void instantiation_name_error(error_severity_t sev
		, const struct Name *name,const char *msg
){
	ERROR_REPORTER_START_NOLINE(sev);
	FPRINTF(ASCERR,"%s: name '",msg);
	WriteName(ASCERR,name);
	FPRINTF(ASCERR,"'");
	error_reporter_end_flush();
}

static
void WriteSetError(struct Statement *statement, struct TypeDescription *def)
{
  STATEMENT_ERROR(statement, (GetBaseType(def) == set_type) ?
                             "No set type specified in IS_A statement"
                             : "Set type specified for a non-set type");
}

/**
	This code will emit error messages only on the last
	iteration when trying to clear pending statements.
	g_iteration is the global iteration counter, and MAXNUMBER
	is the number of times that the instantiator will try
	to clear the list, without change.
*/
static
void WriteUnexecutedMessage(FILE *f, struct Statement *stat, CONST char *msg)
{
  if (g_iteration>=(MAXNUMBER)) WSSM(f,stat,msg,0);
}


/**
	Write Unexecuted Error Message in Pass 3 WUEMPASS3

	This code will emit error messages only on the last
	iteration of pass3 when trying to clear pending statements.
	g_iteration is the global iteration counter, and PASS3MAXNUMBER
	is the number of times that the instantiator will try
	to clear the list, without change.
*/
static
void WUEMPASS3(FILE *f, struct Statement *stat, CONST char *msg)
{
  if (g_iteration>=(PASS3MAXNUMBER)) WSSM(f,stat,msg,0);
}

/*------------------------------------------------------------------------------
  DENSE ARRAY PROCESSING

	...mostly
*/

/**
	returns 0 if c is NULL, probably should be -1.
	-2 if c is illegal set type
	1 if c IS_A integer_constant set type
	0 if c IS_A symbol_constant set type
	@param statement is used only to issue error messages.
*/
static
int CalcSetType(symchar *c, struct Statement *statement)
{
  struct TypeDescription *desc;
  if (c==NULL) return 0;
  if ((desc = FindType(c)) != NULL){
    switch(GetBaseType(desc)){
    case integer_constant_type: return 1;
    case symbol_constant_type: return 0;
    default:
      STATEMENT_ERROR(statement, "Incorrect set type in IS_A");
      /* lint should keep us from ever getting here */
      return -2;
    }
  }else{
    STATEMENT_ERROR(statement, "Unable to determine type of set.");
    return -2;
  }
}

/**
	last minute check for set values that subscript arrays.
	probably should check constantness too but does not.
	return 0 if ok, 1 if not.
*/
static
int CheckSetVal(struct value_t setval)
{
  if (ValueKind(setval) != set_value) {
    switch (ValueKind(setval)) {
    case integer_value:
      TCEM = "Incorrectly integer-valued array range.";
      break;
    case symbol_value:
      TCEM = "Incorrect symbol-valued array range.";
      break;
    case real_value:
      TCEM = "Incorrect real-valued array subscript.";
      break;
    case boolean_value:
      TCEM = "Incorrect boolean-valued array subscript.";
      break;
    case list_value:
      TCEM = "Incorrect list-valued array subscript.";
      break;
    case error_value:
      switch (ErrorValue(setval)) {
      case type_conflict:
        TCEM = "Set expression type conflict in array subscript.";
        break;
      default:
        TCEM = "Generic error 1 in array subscript.";
        break;
      }
      break;
    case set_value: /* really weird if this happens, since if eliminated it */
      break;
    default:
      TCEM = "Generic error 2 in array subscript.";
      break;
    }
    return 1;
  }
  return 0;
}

/**
	This attempts to evaluate a the next undone subscript of the
	array and call ExpandArray with that set value.
	In the case of ALIAS arrays this must always succeed, because
	we have checked first that it will. If it did not we would
	be stuck because later calls to ExpandArray will not know
	the difference between the unexpanded alias array and the
	unexpanded IS_A array.

	Similarly, in the case of parameterized arrays this must
	always succeed, OTHERWISE ExpandArray will not know the
	arguments of the IS_A type, arginst next time around.

	In the event that the set given or set value expanded is bogus,
	returns 1 and statement from which this call was derived is
	semantically garbage.
*/
static
int ValueExpand(struct Instance *i, unsigned long int pos,
                 struct value_t value, int *changed,
                 struct Instance *rhsinst, struct Instance *arginst,
                 struct gl_list_t *rhslist)
{
  struct value_t setval;
  switch(ValueKind(value)){
  case list_value:
    setval = CreateSetFromList(value);
    if (CheckSetVal(setval)) {
      return 1;
    }
    ExpandArray(i,pos,SetValue(setval),rhsinst,arginst,rhslist);
    /* this may modify the pending instance list if
     * rhslist and rhsinst both == NULL.
     */
    *changed = 1;
    DestroyValue(&setval);
    break;
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      break;
    default:
      TCEM = "Array instance has incorrect index type.";
      return 1;
    }
    break;
  default:
    TCEM = "Array instance has incorrect index value type.";
    return 1;
  }
  return 0;
}

/**
	When an incorrect combination of sparse and dense indices is found,
	marks the statement wrong and whines. If the statement has already
	been marked wrong, does not whine.

	In FOR loops,
	this function warns  about a problem that the implementation really
	should allow. Alas, the fix is pending a complete rework of arrays.

	In user is idiot case,
	this really should have been ruled out by checkisa, which lets a little
	too much trash through. Our whole array implementation sucks.
*/
static
void SignalChildExpansionFailure(struct Instance *work,unsigned long cnum)
{
  struct TypeDescription *desc;
  ChildListPtr clp;
  struct Statement *statement;

  asc_assert(work!= NULL);
  asc_assert(cnum!= 0);
  asc_assert(InstanceKind(work)==MODEL_INST);
  desc = InstanceTypeDesc(work);
  clp = GetChildList(desc);
  statement = (struct Statement *)ChildStatement(clp,cnum);
  if ( StatWrong(statement) != 0) {
    return;
  }
  if (TCEM != NULL) {
    CONSOLE_DEBUG("TCEM = %s",TCEM);
    TCEM = NULL;
  }
  if (StatInFOR(statement)) {
    MarkStatContext(statement,context_WRONG);
    STATEMENT_ERROR(statement, "Add another FOR index. In FOR loops,"
         " all array subscripts must be scalar values, not sets.");
    WSS(ASCERR,statement);
  }else{
    MarkStatContext(statement,context_WRONG);
    STATEMENT_ERROR(statement, "Subscripts of conflicting or incorrect types"
         " in rectangular array.");
    WSS(ASCERR,statement);
  }
  return;
}

/**
	Should never be called with BOTH rhs(inst/list) and arginst != NULL,
	but one or both may be NULL depending on other circumstances.
	Should never be called on ALIASES/IS_A inside a for loop.
	Returns an error number other than 0 if called inside a for loop.
	If error, outer scope should mark statement incorrect.
*/
static
int TryChildExpansion(struct Instance *child,
                       struct Instance *parent,
                       int *changed,
                       struct Instance *rhsinst,
                       struct Instance *arginst,
                       struct gl_list_t *rhslist)
{
  unsigned long pos,oldpos=0;
  struct value_t value;
  CONST struct Set *setp;
  int error=0;
  asc_assert(arginst==NULL || (rhsinst==NULL && rhslist==NULL));
  /* one must be NULL as alii do not have args */
  while((pos=NextToExpand(child))>oldpos){
    oldpos=pos;
    setp = IndexSet(child,pos);
    if (GetEvaluationContext() != NULL) {
      error++;
      FPRINTF(ASCERR,"TryChildExpansion with mixed instance\n");
    }else{
      SetEvaluationContext(parent); /* could be wrong for mixed style arrays */
      value = EvaluateSet(setp,InstanceEvaluateName);
      SetEvaluationContext(NULL);
      if (ValueExpand(child,pos,value,changed,rhsinst,arginst,rhslist) != 0) {
        error++;
      }
      DestroyValue(&value);
    }
  }
  return error;
}

/**
	expands, if possible, children of nonrelation,
	nonalias, nonparameterized arrays.
*/
static
void TryArrayExpansion(struct Instance *work, int *changed)
{
  unsigned long c,len;
  struct Instance *child;
  struct TypeDescription *desc;
  len = NumberChildren(work);
  for(c=1;c<=len;c++){
    child = InstanceChild(work,c);
    if (child!=NULL){
      switch(InstanceKind(child)){
      case ARRAY_INT_INST:
      case ARRAY_ENUM_INST:
        desc = InstanceTypeDesc(child);
        /* no alii, no parameterized types, no for loops allowed. */
        if ((!GetArrayBaseIsRelation(desc))&&(!RectangleArrayExpanded(child)) &&
             (!GetArrayBaseIsLogRel(desc)) ) {
          if (TryChildExpansion(child,work,changed,NULL,NULL,NULL)!= 0) {
            SignalChildExpansionFailure(work,c);
          }
        }
        break;
      default:
#if 0 /* example of what not to do here */
        FPRINTF(ASCERR,"TryArrayExpansion called with non-array instance\n");
        /* calling with non array child is fairly common and unavoidable */
#endif
        break;
      }
    }
  }
}

static
void DestroyIndexList(struct gl_list_t *gl)
{
  struct IndexType *ptr;
  int c,len;
  if (gl!=NULL) {
    for (c=1,len = gl_length(gl);c <= len;c++) {
      ptr = (struct IndexType *)gl_fetch(gl,c);
      if (ptr) DestroyIndexType(ptr);
    }
    gl_destroy(gl);
  }
}

/**
	returns 1 if ex believed to be integer, 0 if symbol, and -1 if
	confused. if searchfor TRUE, includes fortable in search
*/
static
int FindExprType(CONST struct Expr *ex, struct Instance *parent,
                 CONST unsigned int searchfor
){
  struct Instance *i;
  struct gl_list_t *ilist;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  switch(ExprType(ex)){
  case e_var:
    ilist = FindInstances(parent,ExprName(ex),&err);
    if ((ilist!=NULL)&&(gl_length(ilist)>0)){
      i = (struct Instance *)gl_fetch(ilist,1);
      gl_destroy(ilist);
      switch(InstanceKind(i)){
      case INTEGER_ATOM_INST:
      case INTEGER_INST:
      case INTEGER_CONSTANT_INST:
        return 1;
      case SYMBOL_ATOM_INST:
      case SYMBOL_INST:
      case SYMBOL_CONSTANT_INST:
        return 0;
      case SET_ATOM_INST:
      case SET_INST:
        return IntegerSetInstance(i);
      default:
        FPRINTF(ASCERR,"Incorrect index type; guessing integer index.\n");
        return 1;
      }
    }else{
      if (ilist!=NULL) gl_destroy(ilist);
      if (GetEvaluationForTable()!=NULL) {
        symchar *name;
        struct for_var_t *ptr;
        AssertMemory(GetEvaluationForTable());
        name = SimpleNameIdPtr(ExprName(ex));
        if (name!=NULL) {
          ptr = FindForVar(GetEvaluationForTable(),name);
          if (ptr!=NULL) {
            switch(GetForKind(ptr)) {
            case f_integer:
              return 1;
            case f_symbol:
              return 0;
            default:
              FPRINTF(ASCERR,"Undefined FOR or indigestible variable.\n");
            }
          }
        }
      }
      return -1;
    }
  case e_int:
    return 1;
  case e_symbol:
    return 0;
  case e_set:
    return DeriveSetType(ExprSValue(ex),parent,searchfor);
  default:
    if (g_iteration>=(MAXNUMBER)) {
      /* referencing g_iteration sucks, but seeing spew sucks more.*/
      /* WUM, which we want, needs a statement ptr we can't supply. */
      ERROR_REPORTER_HERE(ASC_PROG_ERR,"Heuristic FindExprType failed. Check your indices. Assuming integer array index.");
    }
    return -1;
  }
}

/**
	returns -1 if has no clue,
	returns 1 if set appears to be int set
	returns 0 if apparently symbol_constant set.
*/
static
int DeriveSetType(CONST struct Set *sptr, struct Instance *parent,
                  CONST unsigned int searchfor
){
  register CONST struct Set *ptr;
  int result=-1;		/* -1 indicates a failure */
  ptr = sptr;
  /* if it contains a range it must be an integer set */
  while(ptr!=NULL){
    if (SetType(ptr)) return 1;
    ptr = NextSet(ptr);
  }
  ptr = sptr;
  /* try to find the type from the expressions */
  while(ptr!=NULL){
    if ((result = FindExprType(GetSingleExpr(ptr),parent,searchfor)) >= 0) {
      return result;
    }
    ptr = NextSet(ptr);
  }
  return -1;			/* undefined type */
}

/**
	Returns a gllist contain the string form (or forms) of array
	subscripts(s)
	e.g. Name a[1..2]['foo']
	will return a gllist containing something like:
	"1..2"
	"foo"
*/
static
struct gl_list_t *ArrayIndices(CONST struct Name *name,
                               struct Instance *parent)
{
  struct gl_list_t *result;
  int settype;
  CONST struct Set *sptr;

  if (!NameId(name)) return NULL;
  name = NextName(name);
  if (name == NULL) return NULL;
  result = gl_create(2L);
  while (name!=NULL){
    if (NameId(name)){
      DestroyIndexList(result);
      return NULL;
    }
    sptr = NameSetPtr(name);
    if ((settype = DeriveSetType(sptr,parent,0)) >= 0){
      gl_append_ptr(result,
                    (VOIDPTR)CreateIndexType(CopySetList(sptr),settype));
    }else{
      DestroyIndexList(result);
      return NULL;
    }
    name = NextName(name);
  }
  return result;
}

/*-----------------------------------------------------------------------------
  SPARSE AND DENSE ARRAY PROCESSING
*/

/* this function has been modified to handle list results when called
 * from check aliases and dense executearr.
 * The indices made here in the aliases case where the alias is NOT
 * inside a FOR loop are NOT for consumption by anyone because they
 * contain a dummy index type. They merely indicate that
 * indices can be made. They should be immediately destroyed.
 * DestroyIndexType is the only thing that groks the Dummy.
 * This should not be called on the final subscript of an ALIASES/IS_A
 * inside a FOR loop unless you can grok a dummy in last place.
 *
 * External relations (bbox) contain an innermost implicit for loop
 * in their arrayness over the outputs of the bbox, and this causes
 * us to have a bit of trickiness.
 */
static
struct IndexType *MakeIndex(struct Instance *inst,
                            CONST struct Set *sptr,
                            struct Statement *stat, int last)
{
  struct value_t value;
  struct value_t setval;
  int intset;
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  if (StatInFOR(stat) || StatementType(stat) == EXT) {
    if (sptr == NULL ||
        NextSet(sptr) != NULL ||
        SetType(sptr) != 0 ) {
      /* must be simple index */
      WriteUnexecutedMessage(ASCERR,stat,
        "Next subscript in FOR loop IS_A must be a scalar value,"
        " not a set value.");
      SetEvaluationContext(NULL);
      return NULL;
    }
    value = EvaluateExpr(GetSingleExpr(sptr),NULL,InstanceEvaluateName);
    SetEvaluationContext(NULL);
    switch(ValueKind(value)){
    case real_value:
    case boolean_value:
    case set_value:
    case list_value:
      if (last==0) {
        STATEMENT_ERROR(stat, "Index to sparse array is of an incorrect type");
        DestroyValue(&value);
        return NULL;
      }else{
        setval = CreateSetFromList(value);
        intset = (SetKind(SetValue(setval)) == integer_set);
        DestroyValue(&value);
        DestroyValue(&setval);
        return CreateDummyIndexType(intset);
        /* damn thing ends up in typedesc of arrays. */
      }
    case integer_value:
      DestroyValue(&value);
      return CreateIndexType(CopySetList(sptr),1);
    case symbol_value:
      DestroyValue(&value);
      return CreateIndexType(CopySetList(sptr),0);
    case error_value:
      switch(ErrorValue(value)){
      case undefined_value:
        if (StatementType(stat)==REL||StatementType(stat)==LOGREL) {
          WSSM(ASCERR,stat,"Undefined relation array indirect indices",3);
          /* don't want to warn about sparse IS_A/aliases here */
        }
        break;
      case name_unfound:
        break;
      default:
        WSSM(ASCERR,stat, "Error in sparse array indices",3);
        break;
      }
      DestroyValue(&value);
      return NULL;
    default:
      STATEMENT_ERROR(stat, "Unknown result value type in MakeIndex.\n");
      ASC_PANIC("Unknown result value type in MakeIndex.\n");
    }
  }else{ /* checking subscripts on dense ALIASES/param'd IS_A statement */
    if (sptr==NULL) {
      SetEvaluationContext(NULL);
      return NULL;
    }
    value = EvaluateSet(sptr,InstanceEvaluateName);
    SetEvaluationContext(NULL);
    switch(ValueKind(value)){
    case list_value:
      DestroyValue(&value);
      return CreateDummyIndexType(0 /* doesn't matter -- dense alias check */);
    case error_value:
      switch(ErrorValue(value)){
        case undefined_value:
        case name_unfound:
          DestroyValue(&value);
          return NULL;
      default:
        DestroyValue(&value);
        WSSM(ASCERR,stat, "Error evaluating index to dense array",3);
        return NULL;
      }
    default:
      DestroyValue(&value);
      STATEMENT_ERROR(stat, "Bad index to dense alias array");
      ASC_PANIC("Bad index to dense alias array");
    }
    /* return NULL; */  /* unreachable */
    /* FIXME add GCC flags to tell compiler that we never get here? */
  }
}

/**
	This function is used for making the indices of individual
	elements of sparse arrays (and for checking that it is possible)
	and for checking that the indices of dense alias arrays (a
	very wierd thing to have) and dense parameterized IS_A
	are fully defined so that aliases
	and parameterized/sparse IS_A can be fully constructed in 1 pass.
	paves over the last subscript on sparse ALIASES-IS_A.
*/
static
struct gl_list_t *MakeIndices(struct Instance *inst,
                              CONST struct Name *name,
                              struct Statement *stat)
{
  struct gl_list_t *result;
  CONST struct Set *sptr;
  struct IndexType *ptr;
  int last;


  result = gl_create((unsigned long)NameLength(name));
  while(name != NULL){
    if (NameId(name)){
      DestroyIndexList(result);
      return NULL;
    }
    sptr = NameSetPtr(name);
    last = (NextName(name)==NULL && StatementType(stat)==ARR);
    ptr = MakeIndex(inst,sptr,stat,last);
    if (ptr !=  NULL) {
      gl_append_ptr(result,(VOIDPTR)ptr);
    }else{
      DestroyIndexList(result);
      return NULL;
    }
    name = NextName(name);
  }
  return result;
}

static
void LinkToParentByName(struct Instance *inst,
                        struct Instance *child,
                        symchar *name)
{
  struct InstanceName rec;
  unsigned long pos;
  SetInstanceNameType(rec,StrName);
  SetInstanceNameStrPtr(rec,name);
  pos = ChildSearch(inst,&rec);
  LinkToParentByPos(inst,child,pos);
}

void LinkToParentByPos(struct Instance *inst,
                       struct Instance *child,
                       unsigned long pos)
{
  asc_assert(pos);
  asc_assert(child != NULL);
  asc_assert(inst != NULL);

  StoreChildPtr(inst,pos,child);
  AddParent(child,inst);
}

static
struct Instance *GetArrayHead(struct Instance *inst, CONST struct Name *name)
{
  struct InstanceName rec;
  unsigned long pos;
  if (NameId(name)){
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,NameIdPtr(name));
    pos=ChildSearch(inst,&rec);
    if (pos>0) {
      return InstanceChild(inst,pos);
    }else{
      return NULL;
    }
  }
  return NULL;
}

/**
	We are inside a FOR loop.
	If rhsinst is not null, we are in an alias statement and
	will use rhsinst as the child added instead of
	creating a new child.
	If arginst is not null, we will use it to aid in
	creating IS_A elements.
	at least one of arginst, rhsinst must be NULL.
	If last !=0, returns NULL naturally and ok.
*/
static
struct Instance *DoNextArray(struct Instance *parentofary, /* MODEL */
                             struct Instance *ptr, /* array layer */
                             CONST struct Name *name, /* subscript */
                             struct Statement *stat,
                             struct Instance *rhsinst, /*ALIASES*/
                             struct Instance *arginst, /* IS_A */
                             struct gl_list_t *rhslist, /*ARR*/
                             int last /* ARR */)
{
  CONST struct Set *sptr;
  struct value_t value;
  struct value_t setval;
  long i;
  symchar *sym;

  if (NameId(name) != 0) return NULL; /* must be subscript, i.e. set */
  sptr = NameSetPtr(name);
  if ((sptr==NULL)||(NextSet(sptr)!=NULL)||(SetType(sptr))) {
    return NULL;
  }
  asc_assert(GetEvaluationContext()==NULL);
  asc_assert(rhsinst==NULL || arginst==NULL);
  SetEvaluationContext(parentofary);
  value = EvaluateExpr(GetSingleExpr(sptr),NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case real_value:
  case set_value:
  case boolean_value:
  case list_value:
    if (last==0) {
      STATEMENT_ERROR(stat, "Index to array is of an incorrect type");
      DestroyValue(&value);
      return NULL;
    }else{
      /* we are at last subscript of ALIASES/IS_A in for loop. */
      /* expand using rhslist pretending dense array. */
      setval = CreateSetFromList(value);
      ExpandArray(ptr,1L,SetValue(setval),NULL,NULL,rhslist);
      DestroyValue(&setval);
      DestroyValue(&value);
      return NULL;
    }
  case integer_value:
    i = IntegerValue(value);
    DestroyValue(&value);
    return FindOrAddIntChild(ptr,i,rhsinst,arginst);
  case symbol_value:
    sym = SymbolValue(value);
    DestroyValue(&value);
    return FindOrAddStrChild(ptr,sym,rhsinst,arginst);
  case error_value:
    switch(ErrorValue(value)){
    case undefined_value:
      if (StatementType(stat)==REL||StatementType(stat)==LOGREL) {
        WSSM(ASCERR,stat, "Undefined relation array indirect indices",3);
      }
      break;
    case name_unfound:
      break;
    default:
      STATEMENT_ERROR(stat, "Error in array indices");
      break;
    }
    DestroyValue(&value);
    return NULL;
  default:
    ASC_PANIC("Unknown result value type.\n");

  }
}

/**
	We are inside a FOR loop.
	If rhsinst is not null, we are in an alias statement and
	will eventually use rhsinst as the child added instead of
	creating a new child.
	we expand each subscript individually here rahter than recursively.
	If we are on last subscript of an ALIASES/IS_A, we copy the
	layer in rhslist rather than expanding individually.
	rhslist and intset only make sense simultaneously.
*/
static
struct Instance *AddArrayChild(struct Instance *parentofary,
                               CONST struct Name *name,
                               struct Statement *stat,
                               struct Instance *rhsinst,
                               struct Instance *arginst,
                               struct gl_list_t *rhslist)
{
  struct Instance *ptr;
  int last;

  ptr = GetArrayHead(parentofary,name);
  if(ptr != NULL) {
    name = NextName(name);
    while(name!=NULL){
      last = (rhslist != NULL && NextName(name)==NULL);
      ptr = DoNextArray(parentofary,ptr,name,stat,
                        rhsinst,arginst,rhslist,last);
      if (ptr==NULL){
        return NULL;
      }
      name = NextName(name);
    }
    return ptr;
  }else{
    return NULL;
  }
}

/**
	Create the sparse array typedesc based on the statement kind
	and also add first child named. intset and def used for nonrelation types
	only.

	This function returns the child pointer because relation functions
	need it, not because the child is unconnected.

	If rhsinst is not NULL, uses rhsinst instead of creating new one.
	If rhslist is not NULL, uses rhslist instead of rhsinst or creating.

	It is expected that all subscripts will be evaluatable and that
	in the case of the ALIASES-IS_A statement, the IS_A part is done
	just before the ALIASES part.
*/
static
struct Instance *MakeSparseArray(struct Instance *parent,
                                 CONST struct Name *name,
                                 struct Statement *stat,
                                 struct TypeDescription *def,
                                 int intset,
                                 struct Instance *rhsinst,
                                 struct Instance *arginst,
                                 struct gl_list_t *rhslist)
{
  struct TypeDescription *desc = NULL;
  struct Instance *aryinst;
  struct gl_list_t *indices;
  indices = MakeIndices(parent,NextName(name),stat);
  if (indices != NULL) {
    switch (StatementType(stat)) {
    case REL:
      asc_assert(def==NULL && rhsinst==NULL && rhslist == NULL && arginst == NULL);
      desc = CreateArrayTypeDesc(StatementModule(stat),FindRelationType(),
                                 0,1,0,0,indices);
      break;
    case EXT:
      asc_assert(def==NULL && rhsinst==NULL && rhslist == NULL && arginst == NULL);
      desc = CreateArrayTypeDesc(StatementModule(stat),FindRelationType(),
                                 0,1,0,0,indices);
      break;
    case LOGREL:
      asc_assert(def==NULL && rhsinst==NULL && rhslist == NULL && arginst == NULL);
      desc = CreateArrayTypeDesc(StatementModule(stat),FindLogRelType(),
                                 0,0,1,0,indices);
      break;
    case WHEN:
      asc_assert(def==NULL && rhsinst==NULL && rhslist == NULL && arginst == NULL);
      desc = CreateArrayTypeDesc(StatementModule(stat),
                                 FindWhenType(),0,0,0,1,indices);
      break;
    case ISA:
    case ALIASES:
    case ARR:
      asc_assert(def!=NULL);
      desc = CreateArrayTypeDesc(StatementModule(stat),def,
                                 intset,0,0,0,indices);
      break;
    default:
      STATEMENT_ERROR(stat, "Utter screw-up in MakeSparseArray");
      ASC_PANIC("Utter screw-up in MakeSparseArray");
    }
    aryinst = CreateArrayInstance(desc,1);
    LinkToParentByName(parent,aryinst,NameIdPtr(name));
    return AddArrayChild(parent,name,stat,rhsinst,arginst,rhslist);
  }else{
    return NULL;
  }
}

/*------------------------------------------------------------------------------
	...
*/

/**
	handles construction of alias statements, allegedly, per lhs.
	parent function should find rhs and send it in as rhsinst.
	rhsinst == null should never be used with this function.
	currently, arrays ignored, fatally.
*/
static
void MakeAliasInstance(CONST struct Name *name,
                       CONST struct TypeDescription *basedef,
                       struct Instance *rhsinst,
                       struct gl_list_t *rhslist,
                       int intset,
                       struct Instance *parent,
                       struct Statement *statement)
{
  symchar *childname;
  int changed;
  unsigned long pos;
  struct Instance *inst;
  struct InstanceName rec;
  struct TypeDescription *arydef, *def;
  struct gl_list_t *indices;
  int tce;
  asc_assert(rhsinst != NULL || rhslist !=NULL); /* one required */
  asc_assert(rhsinst == NULL || rhslist ==NULL); /* only one allowed */
  childname = SimpleNameIdPtr(name);
  if (childname !=NULL){
    /* case of simple part name */
    if (StatInFOR(statement) && StatWrong(statement)==0) {
      MarkStatContext(statement,context_WRONG);
      STATEMENT_ERROR(statement,"Unindexed statement in FOR loop not allowed.");
      WSS(ASCERR,statement);
      return;
    }
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    pos = ChildSearch(parent,&rec);
    if (pos>0){
      /* case of part expected */
      if (InstanceChild(parent,pos)==NULL){
        /* case of part not there yet */
        inst = rhsinst;
        StoreChildPtr(parent,pos,inst);
        if (SearchForParent(inst,parent)==0) {
          /* case where we don't already have it at this scope */
          AddParent(inst,parent);
        }
      }else{			/* redefining instance */
        /* case of part already there and we barf */
        char *msg = ASC_NEW_ARRAY(char,SCLEN(childname)+strlen(REDEFINE_CHILD_MESG2)+1);
        strcpy(msg,REDEFINE_CHILD_MESG2);
        strcat(msg,SCP(childname));
        STATEMENT_ERROR(statement,msg);
        ascfree(msg);
      }
    }else{			/* unknown child name */
      /* case of part not expected */
      STATEMENT_ERROR(statement, "Unknown child name.  Never should happen");
      ASC_PANIC("Unknown child name.  Never should happen");
    }
  }else{
    /* if reach the else, means compound identifier or garbage */
    indices = ArrayIndices(name,parent);
    if (rhsinst != NULL) {
      def = InstanceTypeDesc(rhsinst);
    }else{
      def = (struct TypeDescription *)basedef;
    }
    if (indices!=NULL){ /* array of some sort */
      childname = NameIdPtr(name);
      SetInstanceNameType(rec,StrName);
      SetInstanceNameStrPtr(rec,childname);
      pos = ChildSearch(parent,&rec);
      if (!StatInFOR(statement)) {
        /* rectangle arrays */
        arydef = CreateArrayTypeDesc(StatementModule(statement),
                                     def,intset,0,0,0,indices);
        if (pos>0) {
          inst = CreateArrayInstance(arydef,1);
          if (inst!=NULL){
            changed = 0;
            tce = TryChildExpansion(inst,parent,&changed,rhsinst,NULL,rhslist);
            /* we're not in a for loop, so can't fail unless user is idiot. */
            LinkToParentByPos(parent,inst,pos); /* don't want to lose memory */
            /* if user is idiot, whine. */
            if (tce != 0) {
              SignalChildExpansionFailure(parent,pos);
            }
          }else{
            STATEMENT_ERROR(statement, "Unable to create alias array instance");
            ASC_PANIC("Unable to create alias array instance");
          }
        }else{
          DeleteTypeDesc(arydef);
          STATEMENT_ERROR(statement,
               "Unknown array child name. Never should happen");
          ASC_PANIC("Unknown array child name. Never should happen");
        }
      }else{
        /* sparse array */
        DestroyIndexList(indices);
        if (pos>0) {
          if (InstanceChild(parent,pos)==NULL) {
            /* need to make alias array */
            /* should check for NULL return here */
            (void)
            MakeSparseArray(parent,name,statement,def,
                            intset,rhsinst,NULL,rhslist);
          }else{
            /* need to add alias array element */
            /* should check for NULL return here */
            (void) AddArrayChild(parent,name,statement,
                                 rhsinst,NULL,rhslist);
          }
        }else{
          STATEMENT_ERROR(statement,
            "Unknown array child name. Never should happen");
          ASC_PANIC("Unknown array child name. Never should happen");
        }
      }
    }else{
      /* bad child name. cannot create parts of parts. should never
       * happen, being trapped out in typelint.
       */
      STATEMENT_ERROR(statement,"Bad ALIASES child name.");
    }
  }
}

/**
	@return 1 if concluded with statement, 0 if might try later.
*/
static
int ExecuteALIASES(struct Instance *inst, struct Statement *statement)
{
  CONST struct VariableList *vlist;
  struct gl_list_t *rhslist;
  struct Instance *rhsinst;
  CONST struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  int intset;

  asc_assert(StatementType(statement)==ALIASES);
  if (StatWrong(statement)) {
    /* incorrect statements should be warned about when they are
     * marked wrong, so we just ignore them here.
     */
    return 1;
  }
  if (!CheckALIASES(inst,statement)) {
    WriteUnexecutedMessage(ASCERR,statement,
      "Possibly undefined sets/ranges in ALIASES statement.");
    return 0;
  }
  name = AliasStatName(statement);
  rhslist = FindInstances(inst,name,&err);
  if (rhslist == NULL) {
    WriteUnexecutedMessage(ASCERR,statement,
      "Possibly undefined right hand side in ALIASES statement.");
    return 0; /* rhs not compiled yet */
  }
  if (gl_length(rhslist)>1) {
    STATEMENT_ERROR(statement,"ALIASES needs exactly 1 RHS");
    gl_destroy(rhslist);
    return 1; /* rhs not unique for current values of sets */
  }
  rhsinst = (struct Instance *)gl_fetch(rhslist,1);
  gl_destroy(rhslist);
  if (InstanceKind(rhsinst)==REL_INST || LREL_INST ==InstanceKind(rhsinst)) {
    STATEMENT_ERROR(statement,"Direct ALIASES of relations are not permitted");
    MarkStatContext(statement,context_WRONG);
    WSS(ASCERR,statement);
    return 1; /* relations only aliased through models */
  }
  intset = ( (InstanceKind(rhsinst)==SET_ATOM_INST) &&
             (IntegerSetInstance(rhsinst)) );
  vlist = GetStatVarList(statement);
  while (vlist!=NULL){
    MakeAliasInstance(NamePointer(vlist),NULL,rhsinst,
                      NULL,intset,inst,statement);
    vlist = NextVariableNode(vlist);
  }
  return 1;
}


/*------------------------------------------------------------------------------
  SUPPORT FOR ALIASES-IS_A STATEMENTS
*/

/**
	enforce max len and no-apostrope (') rules for subscripts. string returned
	may not be string sent.
*/
static
char *DeSingleQuote(char *s)
{
  char *old;
  int len;
  if (s==NULL) {
    return s;
  }
  len = strlen(s);
  if (len > 40) {
    old = s;
    s = ASC_NEW_ARRAY(char,41);
    strncpy(s,old,17);
    s[17] = '.';
    s[18] = '.';
    s[19] = '.';
    s[20] = '\0';
    strcat(s,(old+len-20));
    ascfree(old);
  }
  old = s;
  while (*s != '\0') {
    if (*s =='\'') {
      *s = '_';
    }
    s++;
  }

  return old;
}

/**
	returns a symchar based on but not in strset,
	and adds original and results to sym table.
	destroys the s given.
*/
static
symchar *UniquifyString(char *s, struct set_t *strset)
{
  int oldlen, maxlen, c;
  char *new;
  symchar *tmp;

  tmp = AddSymbol(s);
  if (StrMember(tmp,strset)!=0) {
    oldlen = strlen(s);
    maxlen = oldlen+12;
    new = ascrealloc(s,oldlen+14);
    asc_assert(new!=NULL);
    while ( (oldlen+1) < maxlen) {
      new[oldlen+1] = '\0';
      for(c = 'a'; c <= 'z'; c++){
        new[oldlen] = (char)c;
        tmp = AddSymbol(new);
        if (StrMember(tmp,strset)==0) {
          ascfree(new);
          return tmp;
        }
      }
      oldlen++;
    }
    Asc_Panic(2, NULL,
              "Unable to generate unique compound alias subscript.\n");

  }else{
    ascfree(s);
    return tmp;
  }
}

static
struct value_t GenerateSubscripts(struct Instance *iref,
                                  struct gl_list_t *rhslist,
                                  int intset)
{
  struct set_t *setinstval;
  unsigned long c,len;
  char *str;
  symchar *sym;

  setinstval = CreateEmptySet();
  len = gl_length(rhslist);
  if (intset!=0) {
    /* create subscripts 1..rhslistlen */
    for (c=1;c<=len; c++) {
      AppendIntegerElement(setinstval,c);
    }
    return CreateSetValue(setinstval);
  }
  /* create string subscripts */
  for (c=1; c<= len; c++) {
    str = WriteInstanceNameString((struct Instance *)gl_fetch(rhslist,c),iref);
    str = DeSingleQuote(str); /* transmogrify for length and ' marks */
    sym = UniquifyString(str,setinstval); /* convert to symbol and free str */
    AppendStringElement(setinstval,sym);
  }
  return CreateSetValue(setinstval);
}

static
void DestroyArrayElements(struct gl_list_t *rhslist)
{
  unsigned long c,len;
  if (rhslist==NULL){
    return;
  }
  for (c=1, len = gl_length(rhslist); c <= len; c++) {
    FREEPOOLAC(gl_fetch(rhslist,c));
  }
  gl_destroy(rhslist);
}

/**
	this function computes the subscript set (or generates it if
	needed) and checks it for matching against the instance list
	and whines when things aren't kosher.
	When things are kosher, creates a gl_list of array children.
	This list is returned through rhslist.
*/
static
struct value_t ComputeArrayElements(struct Instance *inst,
                                    struct Statement *statement,
                                    struct gl_list_t *rhsinstlist,
                                    struct gl_list_t **rhslist)
{
  struct value_t subslist;
  struct value_t subscripts;
  struct value_t result; /* return value is the expanded subscript set */
  CONST struct Set *setp;
  struct set_t *sip;
  int intset;
  unsigned long c, len;
  struct ArrayChild *ptr;

  asc_assert((*rhslist)==NULL && rhsinstlist != NULL && rhslist != NULL);

  intset = ArrayStatIntSet(statement);
  len = gl_length(rhsinstlist);
  setp = ArrayStatSetValues(statement);
  if (setp==NULL) {
    /* value generated is a set and automatically is of correct CARD() */
    result = GenerateSubscripts(inst,rhsinstlist,intset);
    /* fill up rhslist and return */
    *rhslist = gl_create(len);
    sip = SetValue(result);
    if (intset != 0) {
      for (c = 1; c <= len; c++) {
        ptr = MALLOCPOOLAC;
        ptr->inst = gl_fetch(rhsinstlist,c);
        ptr->name.index = FetchIntMember(sip,c);
        gl_append_ptr(*rhslist,(VOIDPTR)ptr);
      }
    }else{
      for (c = 1; c <= len; c++) {
        ptr = MALLOCPOOLAC;
        ptr->inst = gl_fetch(rhsinstlist,c);
        ptr->name.str = FetchStrMember(sip,c);
        gl_append_ptr(*rhslist,(VOIDPTR)ptr);
      }
    }
    return result;
  }else{
    /* cook up the users list */
    asc_assert(GetEvaluationContext()==NULL);
    SetEvaluationContext(inst);
    subslist = EvaluateSet(setp,InstanceEvaluateName);
    SetEvaluationContext(NULL);
    /* check that it evaluates */
    if (ValueKind(subslist)==error_value) {
      switch(ErrorValue(subslist)) {
      case name_unfound:
      case undefined_value:
        DestroyValue(&subslist);
        WriteUnexecutedMessage(ASCERR,statement,
          "Undefined values in WITH_VALUE () list");
        return CreateErrorValue(undefined_value);
      default:
        STATEMENT_ERROR(statement,"Bad result in evaluating WITH_VALUE list\n");
        MarkStatContext(statement,context_WRONG);
        WSS(ASCERR,statement);
        DestroyValue(&subslist);
      }
    }
    /* collect sets to assign later */
    result = CreateSetFromList(subslist); /* unique list */
    ListMode=1;
    subscripts = CreateOrderedSetFromList(subslist); /* as ordered to insts */
    ListMode=0;
    DestroyValue(&subslist); /* done with it */
    /* check everything dumb that can happen */
    if ( ValueKind(result) != set_value ||
         Cardinality(SetValue(subscripts)) != Cardinality(SetValue(result))
       ) {
      DestroyValue(&result);
      DestroyValue(&subscripts);
      STATEMENT_ERROR(statement,
        "WITH_VALUE list does not form a proper subscript set.\n");
      MarkStatContext(statement,context_WRONG);
      WSS(ASCERR,statement);
      return CreateErrorValue(type_conflict);
    }
    /* check sanity of values. may need fixing around empty set. */
    if ( (SetKind(SetValue(subscripts))==integer_set) != (intset!=0)) {
      STATEMENT_ERROR(statement,
        "Unable to construct set. Values and set type mismatched\n");
      DestroyValue(&result);
      DestroyValue(&subscripts);
      MarkStatContext(statement,context_WRONG);
      WSS(ASCERR,statement);
      return CreateErrorValue(type_conflict);
    }
    /* check set size == instances to alias */
    if (Cardinality(SetValue(subscripts)) != len) {
      STATEMENT_ERROR(statement,"In: ");
      FPRINTF(ASCERR,
        "WITH_VALUE list length (%lu) != number of instances given (%lu)\n",
        Cardinality(SetValue(subscripts)),len);
      DestroyValue(&result);
      DestroyValue(&subscripts);
      MarkStatContext(statement,context_WRONG);
      WSS(ASCERR,statement);
      return CreateErrorValue(type_conflict);
    }
    /* fill up rhslist and return */
    *rhslist = gl_create(len);
    sip = SetValue(subscripts);
    if (intset != 0) {
      for (c = 1; c <= len; c++) {
        ptr = MALLOCPOOLAC;
        ptr->inst = gl_fetch(rhsinstlist,c);
        ptr->name.index = FetchIntMember(sip,c);
        gl_append_ptr(*rhslist,(VOIDPTR)ptr);
      }
    }else{
      for (c = 1; c <= len; c++) {
        ptr = MALLOCPOOLAC;
        ptr->inst = gl_fetch(rhsinstlist,c);
        ptr->name.str = FetchStrMember(sip,c);
        gl_append_ptr(*rhslist,(VOIDPTR)ptr);
      }
    }
    DestroyValue(&subscripts);
    return result;
  }
}

/**
	@return 1 if concluded with statement, 0 if might try later.
*/
static
int ExecuteARR(struct Instance *inst, struct Statement *statement)
{
  CONST struct VariableList *vlist;
  struct gl_list_t *rhsinstlist; /* list of instances found to alias */
  struct gl_list_t *setinstl; /* instance found searching for IS_A'd set */
  struct gl_list_t *rhslist=NULL; /* list of arraychild structures */
  struct value_t subsset;
#ifndef NDEBUG
  struct Instance *rhsinst;
#endif
  struct Instance *setinst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  CONST struct TypeDescription *basedef;
  ChildListPtr icl;
  int intset;

  asc_assert(StatementType(statement)==ARR);
  if (StatWrong(statement)) {
    /* incorrect statements should be warned about when they are
     * marked wrong, so we just ignore them here.
     */
    return 1;
  }
  if (!CheckARR(inst,statement)) {
    WriteUnexecutedMessage(ASCERR,statement,
      "Possibly undefined instances/sets/ranges in ALIASES-IS_A statement.");
    return 0;
  }
  rhsinstlist = FindInsts(inst,GetStatVarList(statement),&err);
  if (rhsinstlist == NULL) {
    MissingInsts(inst,GetStatVarList(statement),0);
    WriteUnexecutedMessage(ASCERR,statement,
      "Incompletely defined source instance list in ALIASES-IS_A statement.");
    return 0; /* rhs's not compiled yet */
  }
  /* check for illegal rhs types. parser normally bars this. */
#ifndef NDEBUG
  if (gl_length(rhsinstlist) >0) {
    rhsinst = (struct Instance *)gl_fetch(rhsinstlist,1);
    if (BaseTypeIsEquation(InstanceTypeDesc(rhsinst))) {
      STATEMENT_ERROR(statement,
        "Direct ALIASES of rels/lrels/whens are not permitted");
      MarkStatContext(statement,context_WRONG);
      WSS(ASCERR,statement);
      gl_destroy(rhsinstlist);
      return 1; /* (log)relations/whens only aliased through models */
    }
  }
#endif
  /* evaluate name list, if given, OTHERWISE generate it, and check CARD.
   * issues warnings as needed
   */
  subsset = ComputeArrayElements(inst,statement,rhsinstlist,&rhslist);
  gl_destroy(rhsinstlist);
  /* check return values of subsset and rhslist here */
  if (ValueKind(subsset)== error_value) {
    if (ErrorValue(subsset) == undefined_value) {
      DestroyValue(&subsset);
      return 0;
    }else{
      DestroyValue(&subsset);
      return 1;
    }
  }
  asc_assert(rhslist!=NULL); /* might be empty, but not NULL */
  /* make set ATOM */
  vlist = ArrayStatSetName(statement);
  intset = ArrayStatIntSet(statement);
  MakeInstance(NamePointer(vlist),FindSetType(),intset,inst,statement,NULL);
  /* get instance  and assign. */
  setinstl = FindInstances(inst,NamePointer(vlist),&err);
  if (setinstl == NULL || gl_length(setinstl) != 1L) {
    ERROR_REPORTER_HERE(ASC_PROG_ERR,"Unable to construct set. Bizarre error in ALIASES-IS_A.");
    if (setinstl!=NULL) {
      gl_destroy(setinstl);
    }
    DestroyArrayElements(rhslist);
    DestroyValue(&subsset);
    MarkStatContext(statement,context_WRONG);
    WSS(ASCERR,statement);
    /* should nuke entire compound ALIASES/IS_A array pair already built */
    return 1;
  }else{
    setinst = (struct Instance *)gl_fetch(setinstl,1);
    gl_destroy(setinstl);
    AssignSetAtomList(setinst,CopySet(SetValue(subsset)));
    DestroyValue(&subsset);
  }

  /* create  ALIASES-IS_A array */
  /* recycle the local pointer to our set ATOM to check base type of rhslist */
  setinst = CAC(gl_fetch(rhslist,1))->inst;
  intset = ( InstanceKind(setinst)==SET_ATOM_INST &&
             IntegerSetInstance(setinst)!=0 );
  /* the real question is does anyone downstream care if intset correct?
   * probably not since its an alias anyway.
   */
  vlist = ArrayStatAvlNames(statement);
  icl = GetChildList(InstanceTypeDesc(inst));
  basedef = ChildBaseTypePtr(icl,ChildPos(icl,NameIdPtr(NamePointer(vlist))));
  while (vlist!=NULL){
    /* fix me for sparse case. dense ok. */
    MakeAliasInstance(NamePointer(vlist), basedef,NULL,
                      rhslist, intset, inst, statement);
    vlist = NextVariableNode(vlist);
  }
  /* clean up memory */
  DestroyArrayElements(rhslist);

  return 1;
}

/*------------------------------------------------------------------------------
	...
*/
/**
	Makes a single instance of the type given,which must not be array
	or relation of any kind or when.

	If type is a MODEL, adds the MODEL to pending list.

	The argument intset is only used if type is set, then
	if intset==1, set ATOM made will be integer set.

	Attempts to find a UNIVERSAL before making the instance.

	@param statement only used for error messages.
*/
static
struct Instance *MakeSimpleInstance(struct TypeDescription *def,
                                    int intset,
                                    struct Statement *statement,
                                    struct Instance *arginst)
{
  struct Instance *inst;

  inst = ShortCutMakeUniversalInstance(def);
  if (inst==NULL) {
    switch(GetBaseType(def)){
    case model_type:
      inst = CreateModelInstance(def);  /* if we are here - build one */
      if (!GetUniversalFlag(def)||!InstanceInList(inst)) {
        /* add PENDING model if not UNIVERSAL, or UNIVERSAL and
         * this is the very first time seen - don't ever want an instance
         * in the pending list twice.
         */
        /*
         * here we need to shuffle in info from arginst.
         * note that because this is inside the UNIVERSAL check,
         * only the first set of arguments to a UNIVERSAL type will
         * ever apply.
         */
        ConfigureInstFromArgs(inst,arginst);
        AddBelow(NULL,inst);
      }
      break;
    case real_type:
    case real_constant_type:
      inst = CreateRealInstance(def);
      break;
    case boolean_type:
    case boolean_constant_type:
      inst = CreateBooleanInstance(def);
      break;
    case integer_type:
    case integer_constant_type:
      inst = CreateIntegerInstance(def);
      break;
    case set_type:
      inst = CreateSetInstance(def,intset);
      break;
    case symbol_type:
    case symbol_constant_type:
      inst = CreateSymbolInstance(def);
      break;
    case relation_type:
      inst = NULL;
      FPRINTF(ASCERR,"Type '%s' is not allowed in IS_A.\n",
              SCP(GetBaseTypeName(relation_type)));
    case logrel_type:
      inst = NULL;
      FPRINTF(ASCERR,"Type '%s' is not allowed in IS_A.\n",
              SCP(GetBaseTypeName(logrel_type)));
      break;
    case when_type:
      inst = NULL;
      FPRINTF(ASCERR,"Type '%s' is not allowed in IS_A.\n",
              SCP(GetBaseTypeName(when_type)));
      break;
    case array_type:
    default: /* picks up patch_type */
      STATEMENT_ERROR(statement, "MakeSimpleInstance error. PATCH/ARRAY found.\n");
      ASC_PANIC("MakeSimpleInstance error. PATCH/ARRAY found.\n");
    }
  }
  return inst;
}

static unsigned long g_unasscon_count = 0L;
/* counter for the following functions */
static
void CountUnassignedConst(struct Instance *i)
{
  if (i!=NULL && (IsConstantInstance(i) || InstanceKind(i)==SET_ATOM_INST) ) {
    if (AtomAssigned(i)==0) {
      g_unasscon_count++;
    }
  }
}
/**
	Returns 0 if all constant scalars in ipass are assigned,
	for ipass that are of set/scalar array/scalar type.
	Handles null input gracefully, as if there is something
	unassigned in it.
	Variable types are considered permanently assigned, since
	we are checking for constants being unassigned.
	Assumes arrays, if passed in, are fully expanded.
*/
static
int ArgValuesUnassigned(struct Instance *ipass)
{
  struct TypeDescription *abd;
  if (ipass==NULL) return 1;
  switch (InstanceKind(ipass)) {
  case ERROR_INST:
   return 1;
  case SIM_INST:
  case MODEL_INST:
  case REL_INST:
  case LREL_INST:
  case WHEN_INST:
    return 0;
  case ARRAY_INT_INST:
  case ARRAY_ENUM_INST:
    abd = GetArrayBaseType(InstanceTypeDesc(ipass));
    if (BaseTypeIsConstant(abd)==0 && BaseTypeIsSet(abd)==0) {
      return 0;
    }
    g_unasscon_count = 0;
    SilentVisitInstanceTree(ipass,CountUnassignedConst,0,0);
    if (g_unasscon_count != 0) {
      return 1;
    }else{
      return 0;
    }
  case REAL_INST:
  case INTEGER_INST:
  case BOOLEAN_INST:
  case SYMBOL_INST:
  case SET_INST:
  case REAL_ATOM_INST:
  case INTEGER_ATOM_INST:
  case BOOLEAN_ATOM_INST:
  case SYMBOL_ATOM_INST:
    return 0;
  case SET_ATOM_INST:
  case REAL_CONSTANT_INST:
  case BOOLEAN_CONSTANT_INST:
  case INTEGER_CONSTANT_INST:
  case SYMBOL_CONSTANT_INST:
    return (AtomAssigned(ipass)==0); /* return 0 if assigned, 1 not */
  default:
    return 1; /* NOTREACHED */
  }
}
/**
	Appends the pointers in the set chain s
	into the list given args. args must not be NULL unless s is.

	If needed, args will be expanded, but if you know the length
	to expect, make args of that size before calling and this
	will be faster.

	This does not go into the expressions (which may contain other
	sets themselves) of the set nodes and disassemble them.
	The list may be safely destroyed, but its contents should not
	be destroyed with it as they belong to something else in all
	likelihood.

	@TODO This function should be moved into a set header someplace.
*/
static
void SplitArgumentSet(CONST struct Set *s, struct gl_list_t *args)
{
  struct Set *sp;
  if (s==NULL) return;
  asc_assert(args !=NULL); /* debug WriteSet(ASCERR,s); FPRINTF(ASCERR,"\n"); */
  while (s!=NULL) {
    sp = CopySetNode(s);
    gl_append_ptr(args,(VOIDPTR)sp);
    s = NextSet(s);
  }
}

#define GETARG(l,n) ((struct Set *)gl_fetch((l),(n)))

/**
	Check compatibility of array elements? -- JP

	@return 1 if all ok, 0 if any array child is < type required,
		-1 if some array child is type incompatible with ptype/stype.

	Does some optimization around arrays of sets and array basetypes.
	Doesn't check names.
*/
static
int ArrayElementsTypeCompatible(CONST struct Instance *ipass,
                                CONST struct TypeDescription *ptype,
                                symchar *stype)
{
  struct gl_list_t *achildren=NULL;
  CONST struct TypeDescription *atype;
  CONST struct TypeDescription *mrtype;
  unsigned long c,len,lessrefined=0L;
  struct Instance *i;

  if (ipass==NULL || ptype == NULL) {
    return -1; /* hosed input */
  }
  asc_assert(IsArrayInstance(ipass) != 0);
  atype = GetArrayBaseType(InstanceTypeDesc(ipass));
  if (BaseTypeIsSet(atype)==0 && MoreRefined(atype,ptype)==atype) {
      /* if not set and if array base is good enough */
    return 1;
  }
  achildren = CollectArrayInstances(ipass,NULL);
  len = gl_length(achildren);
  for (c = 1; c <= len; c++) {
    i = (struct Instance *)gl_fetch(achildren,c);
    atype = InstanceTypeDesc(i);
    if (InstanceKind(i) == SET_ATOM_INST) {
      /* both should be of same type "set" */
      if (atype!=ptype ||
          (IntegerSetInstance(i)==0 &&
           stype == GetBaseTypeName(integer_constant_type))
          || (IntegerSetInstance(i)==1 &&
              stype == GetBaseTypeName(symbol_constant_type))
         ) {
        /* set type mismatch */
        gl_destroy(achildren);
        return -1;
      }else{
        /* assumption about arrays of sets being sane, if 1 element is. */
        gl_destroy(achildren);
        return 1;
      }
    }
    if (ptype==atype) {
      continue;
    }
    mrtype = MoreRefined(ptype,atype);
    if (mrtype == NULL) {
      gl_destroy(achildren);
      return -1;
    }
    if (mrtype == ptype) {
      lessrefined++;
    }
  }
  gl_destroy(achildren);
  return (lessrefined==0L); /* if any elements are inadequately refined, 0 */
}

/**
	returns a value_t, but the real result is learned by consulting err.
	err == 0 means some interesting value found.
	err == 1 means try again later
	err == -1 means things are hopeless.
*/
static
struct value_t FindArgValue(struct Instance *parent,
                            struct Set *argset,
                            int *err)
{
  int previous_context;
  struct value_t value;

  asc_assert(err!=NULL);
  *err=0;
  previous_context = GetDeclarativeContext();
  SetDeclarativeContext(0);
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(parent);
  value = EvaluateExpr(GetSingleExpr(argset),
                       NULL,
                       InstanceEvaluateName);
  SetEvaluationContext(NULL);
  SetDeclarativeContext(previous_context);
  if (ValueKind(value)==error_value) {
    switch(ErrorValue(value)){
    case name_unfound:
      *err = 1;
      DestroyValue(&value);
      return CreateErrorValue(undefined_value);
    case undefined_value:
      *err = 1;
      return value;
    default:
      *err = -1;
    }
  }
  if (IsConstantValue(value)==0){
    *err = -1;
    DestroyValue(&value);
    return CreateErrorValue(type_conflict);
  }
  return value;
}

/* return codes and message handling for MakeParameterInst */
#define MPIOK 1
#define MPIWAIT 0
#define MPIINPUT -1
#define MPIARGTYPE -2
#define MPIARRINC -3
#define MPIBADASS -4
#define MPIARRRNG -5
#define MPIINSMEM -6
#define MPIBADARG -7
#define MPIMULTI -8
#define MPIBADVAL -9
#define MPIWEIRD -10
#define MPIUNMADE -11
#define MPIWEAKTYPE -12
#define MPIUNASSD -13
#define MPIARGVAL -14
#define MPIARGSIZ -15
#define MPIBADWBTS -16
#define MPIBADWNBTS -17
#define MPIBADMERGE -18
#define MPIREASGN -19
#define MPIREDEF -20
#define MPIFOR -21
#define MPIBADREL -22
#define MPIEXCEP -23
#define MPIVARREL -24
#define MPINOTBOOL -25
static
char *g_mpi_message[] = {
/* 0 */  "Nothing wrong with parameter",
/* -1 */ "Bad input statement or parent or arginstptr.",
/* -2 */ "Incompatible argument type.",
/* -3 */ "Incomplete assignment of absorbed pass-by-value array.",
/* -4 */ "Error in absorbed assignment RHS.",
/* -5 */ "Mismatch in range of array subscripts.",
/* -6 */ "Insufficient memory - crashing soon",
/* -7 */ "Nonexistent argument. (bad set in array expression, probably)",
/* -8 */ "Too many instances named for 1 parameter slot",
/* -9 */ "Bad expression passed to IS_A",
/* -10 */ "Something rotten in lint",
/* -11 */ "Instance doesn't yet exist",
/* -12 */ "Instance not sufficiently refined",
/* -13 */ "Argument value not assigned",
/* -14 */ "Argument value != required value",
/* -15 */ "Array object given has with too many/too few subscripts.",
/* -16 */ "Incorrect instance named in WILL_BE_THE_SAME.",
/* -17 */ "Nonexistent instance named in WILL_NOT_BE_THE_SAME.",
/* -18 */ "Merged instances found in WILL_NOT_BE_THE_SAME.",
/* -19 */ "Refinement cannot reassign constant value.",
/* -20 */ "Refinement must pass in same objects used in IS_A.",
/* -21 */ "Improper FOR loop in WHERE statements",
/* -22 */ "WHERE condition unsatisfied",
/* -23 */ "WHERE condition incorrect (system exception occurred)",
/* -24 */ "WHERE condition incorrect (nonconstant value)",
/* -25 */ "WHERE condition incorrect (nonboolean value)"
};

/**
	Returns MPIOK if value in ipass matches WITH_VALUE field of
	statement, or if the test is silly beacause ipass isn't
	a set/constant or if statement does not constrain value.
	Returns MPIWAIT if statement truth cannot be tested because
	WITH_VALUE clause is not yet evaluatable.
	Returns MPIARGVAL if WITH_VALUE is provably unsatisfied.
	On truly garbage input, unlikely to return.
*/
static
int ArgValueCorrect(struct Instance *inst,
                    struct Instance *tmpinst,
                    CONST struct Statement *statement)
{
  CONST struct Expr *check;
  int previous_context;
  struct value_t value;

  asc_assert(inst!=NULL);
  asc_assert(tmpinst!=NULL);
  asc_assert(statement!=NULL);

  if ( StatementType(statement)!= WILLBE ||
       (check = GetStatCheckValue(statement)) == NULL ||
       ( IsConstantInstance(inst) ==0 &&
         InstanceKind(inst) != SET_ATOM_INST)
     ) {
    return MPIOK;
  }
  if (!AtomAssigned(inst)) {
    return MPIWAIT;
  }
  previous_context = GetDeclarativeContext();
  SetDeclarativeContext(0);
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(tmpinst);
  value = EvaluateExpr(check, NULL, InstanceEvaluateName);
  SetEvaluationContext(NULL);
  SetDeclarativeContext(previous_context);
  if (ValueKind(value)==error_value) {
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      return MPIWAIT;
    default:
      DestroyValue(&value);
      return MPIARGVAL;
    }
  }
  if (IsConstantValue(value)==0){
    DestroyValue(&value);
    FPRINTF(ASCERR,"Variable value found where constant required");
    return MPIARGVAL;
  }
  /* ok, so we have a reasonable inst type and a constant value */
  switch(InstanceKind(inst)){
  case REAL_CONSTANT_INST:
    switch(ValueKind(value)){
    case real_value:
      if ( ( RealValue(value) != RealAtomValue(inst) ||
             !SameDimen(RealValueDimensions(value),RealAtomDims(inst)) )
         ) {
        DestroyValue(&value);
        return MPIARGVAL;
      }
      break;
    case integer_value:
      if ( ( (double)IntegerValue(value) != RealAtomValue(inst) ||
             !SameDimen(Dimensionless(),RealAtomDims(inst)) )
         ) {
        DestroyValue(&value);
        return MPIARGVAL;
      }
      break;
    default:
      DestroyValue(&value);
      return MPIARGVAL;
    }
    break;
  case BOOLEAN_CONSTANT_INST:
    if (ValueKind(value)!=boolean_value ||
        BooleanValue(value) != GetBooleanAtomValue(inst) ) {
      DestroyValue(&value);
      return MPIARGVAL;
    }
    break;
  case INTEGER_CONSTANT_INST:
    switch(ValueKind(value)){
    case integer_value:
      if (GetIntegerAtomValue(inst)!=IntegerValue(value)) {
        DestroyValue(&value);
        return MPIARGVAL;
      }
      break;
    case real_value: /* case which is parser artifact: real, wild 0 */
      if ( RealValue(value)==0.0 &&
           IsWild(RealValueDimensions(value)) &&
           GetIntegerAtomValue(inst) != 0) {
        DestroyValue(&value);
        return MPIARGVAL;
      }
      break;
    default:
      DestroyValue(&value);
      return MPIARGVAL;
    }
    break;
  case SET_ATOM_INST:
    if (ValueKind(value)!=set_value ||
        !SetsEqual(SetValue(value),SetAtomList(inst))) {
      DestroyValue(&value);
      return MPIARGVAL;
    }
    break;
  case SYMBOL_CONSTANT_INST:
    if (ValueKind(value) != symbol_value ||
         SymbolValue(value) != GetSymbolAtomValue(inst)) {
      asc_assert(AscFindSymbol(SymbolValue(value))!=NULL);
      DestroyValue(&value);
      return MPIARGVAL;
    }
    break;
  default:
    DestroyValue(&value);
    return MPIARGVAL;
  }
  DestroyValue(&value);
  return MPIOK;
}

/**
	evaluate a logical or real relation and see that it is satisfied.

	@BUG baa. needs to be exception safe and is not.

	returns MPIOK (satisfied)
	returns MPIBADREL (dissatisified)
	returns MPIVARREL (dissatisified - variable result)
	returns MPIWAIT (not yet determinable)
	returns MPIEXCEP (evaluation is impossible due to float/other error)
	returns MPINOTBOOL (dissatisfied- nonboolean result)

	@param statement should be a rel or logrel.
*/
static
int MPICheckConstraint(struct Instance *tmpinst, struct Statement *statement)
{
  struct value_t value;

  IVAL(value);

  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(tmpinst);
  switch (StatementType(statement)){
  case REL: /* note EXT not allowed in constraint list */
    value = EvaluateExpr(RelationStatExpr(statement),NULL,
                         InstanceEvaluateName);
    break;
  case LOGREL:
    value = EvaluateExpr(LogicalRelStatExpr(statement),NULL,
                         InstanceEvaluateName);
    break;
  default:
    SetEvaluationContext(NULL);
    return MPIWEIRD;
  }
  SetEvaluationContext(NULL);
  switch (ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case undefined_value:
      DestroyValue(&value);
      WriteUnexecutedMessage(ASCERR,statement,
        "Incomplete expression (value undefined) in argument condition.");
      return MPIWAIT;
    case name_unfound:
      DestroyValue(&value);
      WriteUnexecutedMessage(ASCERR,statement,
        "Incomplete expression (name unfound) in argument condition.");
      return MPIWAIT;
    default:
      /* it questionable whether this is a correct action in all cases*/
      /* we could probably turn out more useful error messages here */
      STATEMENT_ERROR(statement, "Condition doesn't make sense.");
      DestroyValue(&value);
      return MPIBADREL;
    }
  case boolean_value:
    if (IsConstantValue(value)!=0) {
      if (BooleanValue(value) != FALSE) {
        DestroyValue(&value);
        return MPIOK;
      }else{
        DestroyValue(&value);
        STATEMENT_ERROR(statement, "Arguments do not conform to requirements");
        return MPIBADREL;
      }
    }else{
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Requirements cannot be satisfied by variables");
      return MPIVARREL;
    }
  default:
    DestroyValue(&value);
    STATEMENT_ERROR(statement, "Constraint does not evaluate to boolean result.");
    return MPINOTBOOL;
  }
}

/**
	returns MPIOK if subscripts match declarations,
	MPIWAIT if declarations cannot yet be interpretted,
	or some other error if there is a mismatch.

	So far only the square version. Should have a forvar
	capable recursive version sometime when we allow
	passage of sparse arrays.

	Assumes the array given has proper number of
	subscripts to match name and is fully expanded.
*/
static
int MPICheckSubscripts(struct Instance *tmpinst,
                       struct Instance *aryinst,
                       struct Statement *s)
{
  CONST struct Name *nptr;

  nptr = NextName(NamePointer(GetStatVarList(s)));
  switch (RectangleSubscriptsMatch(tmpinst,aryinst,nptr)) {
  case -2:
    return MPIWAIT;
  case 1:
    return MPIOK;
  case 0:
  default:
    return MPIARRRNG;
  }
}

#define NOIPICHECK 0
#define IPICHECK 1
/**
	links parent and child. if checkdup != 0,
	it will check child to see if it already has this parent.
*/
static
int InsertParameterInst(struct Instance *parent,
                        struct Instance *child,
                        CONST struct Name *name,
                        CONST struct Statement *statement,
                        int checkdup)
{
  symchar *childname;
  struct InstanceName rec;
  unsigned long pos;

  childname = NameIdPtr(name);
  SetInstanceNameType(rec,StrName);
  SetInstanceNameStrPtr(rec,childname);
  pos = ChildSearch(parent,&rec);
  if (pos>0) {
    if (InstanceChild(parent,pos)==NULL) {
      StoreChildPtr(parent,pos,child);
      if (checkdup == 0 || SearchForParent(child,parent)==0) {
          /* case where we don't already have it at this scope */
        AddParent(child,parent);
      }
      return 1;
    }else{			/* redefining instance */
      char *msg = ASC_NEW_ARRAY(char,SCLEN(childname)+strlen(REDEFINE_CHILD_MESG)+1);
      strcpy(msg,REDEFINE_CHILD_MESG);
      strcat(msg,SCP(childname));
      STATEMENT_ERROR(statement,msg);
      ascfree(msg);
      return 0;
    }
  }else{			/* unknown name */
    STATEMENT_ERROR(statement, "Unknown parameter name.  Never should happen");
    ASC_PANIC("Unknown parameter name.  Never should happen");

  }
}

/**
	The instance this is called with should not have
	any parents whatsoever. The instance this is called
	with will be completely destroyed including any parts
	of the instance that do not have other parents.
*/
static
void DestroyParameterInst(struct Instance *i)
{
  DestroyInstance(i,NULL);
}

/**
	destroys everything you send it. If you send some arguments in
	as null, we don't mind.
*/
static
void ClearMPImem(
  struct gl_list_t *args,
  struct gl_list_t *il,
  struct Instance *tmpinst,
  struct Instance *ipass,
  struct value_t *valp
)
{
  if (args!=NULL) {
    gl_iterate(args,(void (*)(VOIDPTR))DestroySetNode);
    gl_destroy(args);
  }
  if (il!=NULL) {
    gl_destroy(il);
  }
  if (tmpinst!=NULL) {
    DestroyParameterInst(tmpinst);
  }
  if (ipass!=NULL) {
    DestroyParameterInst(ipass);
  }
  if (valp!=NULL) {
    DestroyValue(valp);
  }
}

/**
	 Error reporting for 'MakeParameterInstance'
*/
static
void mpierror(struct Set *argset,
              unsigned long argn,
              struct Statement *statement,
              int errcode)
{
  int arrloc;
  if (errcode<0) {
    arrloc = (-errcode);
  }else{
    return;
    /* why are we here? */
  }
  FPRINTF(ASCERR,"Parameter passing error: %s\n",g_mpi_message[arrloc]);
  if (argset !=NULL && argn >0) {
    FPRINTF(ASCERR,"  Argument %lu:",argn);
    WriteSet(ASCERR,argset);
  }
  STATEMENT_ERROR(statement,"Error in executing statement:");
  MarkStatContext(statement,context_WRONG);
  WSS(ASCERR,statement);
}

static
void MPIwum(struct Set *argset,
            unsigned long argn,
            struct Statement *statement,
            int msgcode)
{
  int arrloc;
  if (g_iteration < MAXNUMBER) {
    return;
  }
  if (msgcode<0) {
    arrloc = (-msgcode);
  }else{
    return;
    /* why are we here? */
  }
  ERROR_REPORTER_START_NOLINE(ASC_USER_ERROR);
  FPRINTF(ASCERR,"Parameter list waiting on sufficient type or value of:\n");
  if (argset !=NULL && argn >0) {
    FPRINTF(ASCERR,"  Argument %lu:",argn);
    WriteSetNode(ASCERR,argset);
  }
  error_reporter_end_flush();
  WriteUnexecutedMessage(ASCERR,statement,g_mpi_message[arrloc]);
}

/**
	process pass by value scalar: evaluate and make it, or return
	appropriate whine if not possible.
	If this returns anything other than mpiok, the user may
	wish to dispose of tmpinst, args as we do not here.
	We do issue whines here, however.
*/
static
int MPIMakeSimple(struct Instance *parent,
                  struct Instance *tmpinst,
                  struct Set *argset,
                  unsigned long argn,
                  CONST struct Name *nptr,
                  struct TypeDescription *ptype,
                  int intset,
                  struct Statement *ps,
                  struct Statement *statement
)
{
  int tverr;	/* error return from checking array elt type, or value */
  struct Instance *ipass;
  struct value_t vpass;

  vpass = FindArgValue(parent,argset,&tverr);
  if (tverr != 0) {
    if (tverr == 1) { /* try later */
      MPIwum(argset,argn,statement,MPIUNASSD);
      return MPIWAIT;
    }else{ /* hopeless */
      mpierror(argset,argn,statement,MPIBADVAL);
      return MPIBADVAL;
    }
  }
  /* don't forget to dispose of vpass if exiting err after here */
  ipass = MakeSimpleInstance(ptype,intset,ps,NULL);
  if (ipass==NULL) {
    DestroyValue(&vpass);
    return MPIINSMEM;
  }
  /* don't forget to dispose of vpass if exiting err after here */
  if (AssignStructuralValue(ipass,vpass,statement)!=1) {
    mpierror(argset,argn,statement,MPIARGTYPE);
    DestroyParameterInst(ipass);
    DestroyValue(&vpass);
    return MPIARGTYPE;
  }
  DestroyValue(&vpass);
  /* install ipass in tmpinst */
  if ( InsertParameterInst(tmpinst,ipass,nptr,ps,IPICHECK) != 1) {
    /* noipicheck because var just created has no parents at all,
     * unless of course var is UNIVERSAL... so ipicheck */
    mpierror(argset,argn,statement,MPIMULTI);
    DestroyParameterInst(ipass);
    return MPIMULTI;
  }
  return MPIOK;
}
#define NOKEEPARGINST 0
#define KEEPARGINST 1
/**
	Check and assemble the arguments of the parameterized type referenced in
	statement, using information derived from the parent instance.

	If the type found in the statement given is not a MODEL type,
	we will immediately return 1 and *arginstptr will be set NULL.

	In general, we are trying to check and assemble enough information
	to prove that a parameterized IS_A can be executed or proved wrong
	once ExecuteISA sees it.

	If keepargs ==KEEPARGINST, then on a successful return,
	*arginstptr will be to a MODEL instance (with no parents)
	with its children derived via parameter list filled in and
	all other children NULL.
	If there are NO children derived via parameter list or
	the reductions list, then *arginstptr will be NULL.
	If keepargs != KEEPARGINST, then arginstptr will not be
	used/set in any way, OTHERWISE it should be NULL on entry.
	If keepargs != KEEPARGINST, then we will do only the minimal
	necessary work to check that the arginst could be created.
	At present, we can't tell what this last ambition amounts to -
	we do the same amount of work regardless, though we try to put
	the more likely to fail steps first.

	A successful return value is 1.

	A failure possibly to succeed later is 0.
	Possible causes will be detailed via the WriteUnexecutedMessage
	facility.

	A permanent failure is any value < 0.
	Causes will be detailed via the WSEM facility, in addition return
	values < 0 have the interpretations given in g_mpi_message[-value]
	above.

	@NOTE assumes statement is well formed, in terms of
	arglist of IS_A/IS_REFINED_TO (if there is one) being of correct length.
	returns fairly quickly for nonmodel and nonparametric
	MODEL types.
*/
static
int MakeParameterInst(struct Instance *parent,
                      struct Statement *statement,
                      struct Instance **arginstptr,
                      int keepargs)
{
  struct TypeDescription *d; /* the type we are constructing or checking */
  struct TypeDescription *atype; /* the type we are being passed */
  struct TypeDescription *ptype; /* the type we are expecting */
  struct TypeDescription *mrtype; /* the more refined of two types */
  symchar *stype;		/* the set type we are expecting */
  struct gl_list_t *args; /* parameter Set given split for easy access */
  struct gl_list_t *il;   /* instance(s) required to digest a parameter */
  struct Instance *ipass; /* instance being passed into type */
  struct Instance *tmpinst; /* holding instance for derivation work. */
  struct StatementList *psl; /* list of parameters the type requires */
  struct StatementList *absorbed; /* list of absorbed isas and casgns */
  struct Statement *ps;      /* a statement from psl */
  struct Set *argset;		/* set element extracted from arglist */
  CONST struct VariableList *vl;
  struct for_table_t *SavedForTable;
  unsigned long slen,c,argn;
  int tverr;	/* error return from checking array elt type, or value */
  int suberr;	/* error return from other routine */
  int intset;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  unsigned int pc;	     /* number of parameters the type requires */

  if (StatWrong(statement)) {
    /* incorrect statements should be warned about when they are
     * marked wrong, so we just ignore them here.
     */
    return MPIOK;
  }
  d = FindType(GetStatType(statement));
  if (d==NULL) {
    /* lint should make this impossible */
    mpierror(NULL,0L,statement,MPIINPUT);
    return MPIINPUT;
  }
  if (keepargs == KEEPARGINST && arginstptr == NULL) {
    /* someone screwed up the call, but maybe they get it right later. */
    FPRINTF(ASCERR," *** MakeParameterInst miscalled *** \n");
    return MPIWAIT;
  }
  if (keepargs == KEEPARGINST) {
    /* init arginstptr */
    *arginstptr = NULL;
  }
  if ( GetBaseType(d)!=model_type) {
    return MPIOK;
  }
  pc = GetModelParameterCount(d);
  absorbed = GetModelAbsorbedParameters(d);
  if (pc==0 && StatementListLength(absorbed)==0L) {
    /* no parameters in this type or its ancestors */
    return MPIOK;
  }
  /* init tmpinst, which we must remember to punt before
   * error returns or nokeep returns.
   */
  /* may want an SCMUI here, not sure. */
  tmpinst = CreateModelInstance(d);
  if (tmpinst==NULL) {
    mpierror(NULL,0L,statement,MPIINPUT);
    return MPIINSMEM;
  }
  args = gl_create((unsigned long)pc);
  if (args == NULL) {
    mpierror(NULL,0L,statement,MPIINPUT);
    ClearMPImem(NULL,NULL,tmpinst,NULL,NULL);
    return MPIINSMEM;
  }
  SplitArgumentSet(GetStatTypeArgs(statement),args);
  /* due to typelint, the following assertion should pass. fix lint if not. */
  asc_assert(gl_length(args)==(unsigned long)pc);
  psl = GetModelParameterList(d);
  slen = StatementListLength(psl);
  argn = 1L;
  for (c = 1; c <= slen; c++) {
    ps = GetStatement(psl,c);
    vl = GetStatVarList(ps); /* move inside switch if allow FOR later */
    ptype = FindType(GetStatType(ps));
    stype = GetStatSetType(ps);
    intset = CalcSetType(stype,ps);
    if (intset <0 || intset >1) {
      /* shouldn't be possible -- typelint trapped */
      mpierror(NULL,0L,statement,MPIARGTYPE);
      ClearMPImem(args,NULL,tmpinst,NULL,NULL);
      return MPIARGTYPE;
    }
    switch (StatementType(ps)) {
    case WILLBE:
      while (vl != NULL) {
        argset = GETARG(args,argn);
        il = FindArgInsts(parent,argset,&err);
        if (il == NULL) {
          switch(rel_errorlist_get_find_error(&err)) {
          case unmade_instance:
          case undefined_instance: /* this case ought to be separable */
            MPIwum(argset,argn,statement,MPIUNMADE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          case impossible_instance:
            mpierror(argset,argn,statement,MPIBADARG);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIBADARG;
          case correct_instance:
            mpierror(argset,argn,statement,MPIWEIRD);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWEIRD;
          }
        }
        if (gl_length(il)!=1L) {
          mpierror(argset,argn,statement,MPIMULTI);
          ClearMPImem(args,il,tmpinst,NULL,NULL);
          return MPIMULTI;
        }
        ipass = (struct Instance *)gl_fetch(il,1L);
        gl_destroy(il);
        il = NULL;
        if (SimpleNameIdPtr(NamePointer(vl))==NULL) {
          /* arg required is an array, check this.
           * check complete expansion of arg, constant type or not.
           * check compatible base type of all elements with spec-
           * note we haven't checked subscript ranges at this point.
           */
          if (IsArrayInstance(ipass)==0) {
            mpierror(argset,argn,statement,MPIARGTYPE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIARGTYPE;
          }
          if (RectangleArrayExpanded(ipass)==0) {
            /* this works for sparse or dense because sparse won't
             * exist except in the fully expanded state due to
             * the construction all at once.
             */
            MPIwum(argset,argn,statement,MPIUNMADE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          }
          if (NumberofDereferences(ipass) !=
              (unsigned long)(NameLength(NamePointer(vl)) - 1)) {
            /* I may need an offset other than -1 here */
            mpierror(argset,argn,statement,MPIARGSIZ);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIARGTYPE;
          }
          tverr = ArrayElementsTypeCompatible(ipass,ptype,stype);
          switch (tverr) {
          case 1:
           /* happy happy joy joy */
            break;
          case 0:
            MPIwum(argset,argn,statement,MPIWEAKTYPE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          default:
            mpierror(argset,argn,statement,MPIARGTYPE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIARGTYPE;
          }
          if (ArgValuesUnassigned(ipass)!=0) {
            MPIwum(argset,argn,statement,MPIUNASSD);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          }
        }else{
          /* arg must be scalar/set/MODEL */
          atype = InstanceTypeDesc(ipass);
          if (atype==ptype) {
            /* we're happy unless sets of mismatched base */
            if (stype!=NULL) {
              if ((IntegerSetInstance(ipass)!=0 && intset==0) ||
                  (IntegerSetInstance(ipass)==0 && intset==1)) {
                mpierror(argset,argn,statement,MPIARGTYPE);
                ClearMPImem(args,NULL,tmpinst,NULL,NULL);
                return MPIARGTYPE;
              }
            }
          }else{
            mrtype = MoreRefined(atype,ptype);
            if (mrtype==NULL) {
              mpierror(argset,argn,statement,MPIARGTYPE);
              ClearMPImem(args,NULL,tmpinst,NULL,NULL);
              return MPIARGTYPE;
            }
            if (mrtype==ptype) {
              /* arg is less refined than param spec. maybe better later */
              MPIwum(argset,argn,statement,MPIWEAKTYPE);
              ClearMPImem(args,NULL,tmpinst,NULL,NULL);
              return MPIWAIT;
            }
          }
          if (ArgValuesUnassigned(ipass)!=0) {
            MPIwum(argset,argn,statement,MPIUNASSD);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          }
          /* here we check against WITH_VALUE clause, if one in ps */
          suberr = ArgValueCorrect(ipass,tmpinst,ps);
          switch(suberr) {
          case MPIOK:
            break;
          case MPIWAIT:
            /* can only occur if other portions of tmpinst needed to compute
             * check value are not in place yet. no wum here because
             * Digest below will catch it if it's broken.
             */
            break;
          /* may need additional cases depending on argval implementation */
          default:
            mpierror(argset,argn,statement,MPIARGVAL);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          }
        }
        /* install ipass in tmpinst */
        if ( InsertParameterInst(tmpinst,ipass,NamePointer(vl),ps,IPICHECK)
            !=1) {
          /* ipicheck because we might be passed same instance in 2 slots */
          mpierror(argset,argn,statement,MPIMULTI);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIMULTI;
        }
        argn++;
        vl = NextVariableNode(vl);
      }
      break;
    case ISA:
      argset = GETARG(args,argn);
      if (SimpleNameIdPtr(NamePointer(vl))!=NULL) {
        /* scalar: evaluate and make it */
        suberr = MPIMakeSimple(parent,tmpinst,argset,argn,
                               NamePointer(vl),ptype,intset,ps,statement);
        if (suberr!=MPIOK) {
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return suberr;
        }
      }else{
        /* check completedness, assignedness, base type of array-by-value
         * and copy. Note that what we copy may prove to be incompatible
         * later when we check the names of subscripts.
         */
        il = FindArgInsts(parent,argset,&err);
        if (il == NULL) {
          switch(rel_errorlist_get_find_error(&err)) {
          case unmade_instance:
          case undefined_instance: /* this case ought to be separable */
            MPIwum(argset,argn,statement,MPIUNMADE);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWAIT;
          case impossible_instance:
            mpierror(argset,argn,statement,MPIBADARG);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIBADARG;
          case correct_instance:
            mpierror(argset,argn,statement,MPIWEIRD);
            ClearMPImem(args,NULL,tmpinst,NULL,NULL);
            return MPIWEIRD;
          }
        }
        if (gl_length(il)!=1L) {
          mpierror(argset,argn,statement,MPIMULTI);
          ClearMPImem(args,il,tmpinst,NULL,NULL);
          return MPIMULTI;
        }
        ipass = (struct Instance *)gl_fetch(il,1L);
        gl_destroy(il);
        il = NULL;
        /* arg required is an array, check this.
         * check complete expansion of arg, constant type or not.
         * check compatible base type of all elements with spec-
         * note we haven't checked subscript ranges at this point.
         */
        if (IsArrayInstance(ipass)==0) {
          mpierror(argset,argn,statement,MPIARGTYPE);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIARGTYPE;
        }
        if (RectangleArrayExpanded(ipass)==0) {
          /* this works for spare or dense because sparse won't
           * exist except in the fully expanded state due to
           * the construction all at once.
           */
          MPIwum(argset,argn,statement,MPIUNMADE);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIWAIT;
        }
        if (NumberofDereferences(ipass) !=
            (unsigned long)(NameLength(NamePointer(vl)) - 1)) {
          /* I may need an offset other than -1 here */
          mpierror(argset,argn,statement,MPIARGSIZ);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIARGTYPE;
        }
        tverr = ArrayElementsTypeCompatible(ipass,ptype,stype);
        switch (tverr) {
        case 1:
         /* happy happy joy joy */
          break;
        case 0:
          /* wum here */
          MPIwum(argset,argn,statement,MPIWEAKTYPE);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIWAIT;
        default:
          mpierror(argset,argn,statement,MPIARGTYPE);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIARGTYPE;
        }
        if (ArgValuesUnassigned(ipass)!=0) {
          MPIwum(argset,argn,statement,MPIUNASSD);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIWAIT;
        }
        /* this copy will mess up tmpnums in old ipass. */
        ipass = CopyInstance(ipass);
        /* note the copy has only been verified to work for completed
         * arrays of constants, not models.
         */
        /* we don't care about the old ipass any more. check new one. */
        if (ipass==NULL) {
          mpierror(argset,argn,statement,MPIINSMEM);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIMULTI;
        }
        /* install ipass in tmpinst */
        if ( InsertParameterInst(tmpinst,ipass,NamePointer(vl),ps,NOIPICHECK)
            !=1 /* arrays cannot be UNIVERSAL */ ) {
          mpierror(argset,argn,statement,MPIMULTI);
          ClearMPImem(args,NULL,tmpinst,NULL,NULL);
          return MPIMULTI;
        }
        /* we still need to check the subscripts for compatibility with
         * arg description. can't do yet.
         */
      }
      argn++;
      break;
    default:
      ASC_PANIC("how the hell did typelint let that through?");
      /* how the hell did typelint let that through? */
      break;
    }
  }
  /* ok, so now we have everything passed (which might be nothing)
   * in place. We need to check WITH_VALUE's, subscript ranges,
   * and insist all scalars end up assigned while processing
   * the absorbed statements. Possibly may still find undefined
   * values in rhs of assignments or in subscript ranges, drat.
   * May take several passes.
   */

  suberr = DigestArguments(tmpinst,args,psl,absorbed,statement); /*1*/
  switch(suberr) {
  case MPIOK:
    break;
  case MPIWAIT:
    ClearMPImem(args,NULL,tmpinst,NULL,NULL);
    return MPIWAIT;
  default:
    /* anything else is an error. mpierror will have been called. */
    ClearMPImem(args,NULL,tmpinst,NULL,NULL);
    return MPIINPUT;
  }

  /* ok, now we need to check where statement list. */
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  suberr = CheckWhereStatements(tmpinst,GetModelParameterWheres(d));
  DestroyForTable(GetEvaluationForTable());
  SetEvaluationForTable(SavedForTable);
  switch(suberr) {
  case MPIOK:
    break;
  case MPIWAIT:
    ClearMPImem(args,NULL,tmpinst,NULL,NULL);
    return MPIWAIT;
  default:
    /* anything else is an error */
    ClearMPImem(args,NULL,tmpinst,NULL,NULL);
    mpierror(NULL,0,statement,suberr);
    return suberr;
  }

  ClearMPImem(args,NULL,NULL,NULL,NULL);
  if (keepargs == KEEPARGINST) {
    *arginstptr = tmpinst;
  }else{
    DestroyParameterInst(tmpinst);
  }
  return MPIOK;
}

static int MPICheckWBTS(struct Instance *tmpinst, struct Statement *statement){
  struct gl_list_t *instances;
  unsigned long c,len;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct Instance *head = NULL;

  instances = FindInsts(tmpinst,GetStatVarList(statement),&err);
  if (instances==NULL) {
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance:
      MissingInsts(tmpinst,GetStatVarList(statement),1);
      STATEMENT_ERROR(statement,
        "WILL_BE_THE_SAME statement contains an impossible instance name");
      return MPIBADWBTS;
    default:
      MissingInsts(tmpinst,GetStatVarList(statement),0);
      WriteUnexecutedMessage(ASCERR,statement,
        "Incomplete instances in WILL_BE_THE_SAME");
      return MPIWAIT; /* statement is not ready to be executed */
    }
  }
  len = gl_length(instances);
  if (len >0 ) {
    head = gl_fetch(instances,1);
  }
  for (c=2; c<=len; c++) {
    if (((struct Instance *)gl_fetch(instances,c)) != head) {
      if (IsArrayInstance(head)==0 &&
          MoreRefined(InstanceTypeDesc(gl_fetch(instances,c)),
                      InstanceTypeDesc(head))==NULL) {
        /* can't be merged later */
        STATEMENT_ERROR(statement,
          "WILL_BE_THE_SAME statement contains incompatible instances");
        gl_destroy(instances);
        return MPIBADWBTS;
      }else{
        /* maybe merge later */
        WriteUnexecutedMessage(ASCERR,statement,
          "Unmerged instances in WILL_BE_THE_SAME");
        gl_destroy(instances);
        return MPIWAIT;
      }
    }
  }
  gl_destroy(instances);
  return MPIOK;
}

#define MPICheckWB(a,b) MPIWEIRD
/* WILL_BE not yet legal in where section. implement later if req'd */

/**
	verifies that all the instances found, if any, are different.
	uses an nlogn (n = # of instance) algorithm, which
	could be made order n using the interface pointer protocol,
	but the additional overhead makes the multiplier for
	o(n) probably not worth the trouble.
*/
static
int MPICheckWNBTS(struct Instance *tmpinst, struct Statement *statement)
{
  struct gl_list_t *instances;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  instances = FindInsts(tmpinst,GetStatVarList(statement),&err);
  if (instances==NULL) {
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance:
      MissingInsts(tmpinst,GetStatVarList(statement),1);
      STATEMENT_ERROR(statement,
        "WILL_NOT_BE_THE_SAME statement contains an impossible instance name");
      return MPIBADWNBTS;
    default:
      MissingInsts(tmpinst,GetStatVarList(statement),0);
      WriteUnexecutedMessage(ASCERR,statement,
        "Incomplete instances in WILL_NOT_BE_THE_SAME");
      return MPIWAIT; /* statement is not ready to be executed */
    }
  }
  if (gl_unique_list(instances)==0) {
    STATEMENT_ERROR(statement,
          "WILL_NOT_BE_THE_SAME statement contains"
         " identical/merged instances");
    gl_destroy(instances);
    return MPIBADMERGE;
  }
  gl_destroy(instances);
  return MPIOK;
}

/**
	Checks the for statements, along with all the horrid machinery needed
	to make a for loop go.
*/
static
int CheckWhereFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  int code=MPIOK;

  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return MPIFOR;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "FOR has undefined values");
      return MPIFOR; /* this maybe should be mpiwait? */
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return MPIFOR;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    instantiation_error(ASC_USER_ERROR,statement
  		,"FOR expression returns the wrong type."
  	);
    DestroyValue(&value);
    return MPIFOR;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        code = CheckWhereStatements(inst,sl);
        if (code != MPIOK) {
          break;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        code = CheckWhereStatements(inst,sl);
        if (code != MPIOK) {
          break;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
  return code;
}

/**
	checks that all conditions are satisfied, else returns a whine.
	does not call mpierror, so caller ought to if needed.
	returns one of the defined MPI codes.
*/
static
int CheckWhereStatements(struct Instance *tmpinst, struct StatementList *sl)
{
  unsigned long c,len;
  struct Statement *s;
  int code=MPIOK;

  if (tmpinst ==NULL) {
    return MPIWEIRD;
  }
  len = StatementListLength(sl);
  for (c=1;c <= len && code == MPIOK; c++) {
    s = GetStatement(sl,c);
    switch (StatementType(s)) {
    case WBTS:
      code = MPICheckWBTS(tmpinst,s);
      break;
    case WNBTS:
      code = MPICheckWNBTS(tmpinst,s);
      break;
    case WILLBE:
      code = MPICheckWB(tmpinst,s);
      break;
    case LOGREL:
    case REL: /* note EXT not allowed in constraint list */
        /* baa. fix me. bug. need to evaluate rules in a way which is
         * exception-safe. EvaluateExpr currently isn't
         */
      code = MPICheckConstraint(tmpinst,s);
      break;
    case FOR:
      code = CheckWhereFOR(tmpinst,s);
      break;
    default:
      code = MPIWEIRD;
      break;
    }
  }
  return code;
}

#if 0 /* migrating, or migraining, depending on your viewpoint, to parpend.h */
enum ppstatus {
  pp_ERR =0,
  pp_ISA,	/* IS_A of simple to be done, from absorbed. */
  pp_ISAARR,	/* IS_A of array to do, from absorbed and
                 * gets converted to asar during processing.
                 */
  pp_ARR,	/* array that's constructed but requires range checking */
  pp_ASGN,	/* assignment to do in absorbed objects */
  pp_ASSC,	/* scalar assignment to check in absorbed objects */
  pp_ASAR,	/* Array to be checked for being completely assigned,
                 * but its subscript range is presumed right.
                 */
  pp_WV,	/* WITH_VALUE to be checked */
  pp_DONE	/* finished statement */
};

struct parpendingentry {
  struct Set *arg;	/* parameter given in user's IS_A statement */
  struct Statement *s;
  struct Instance *inst;
  struct parpendingentry *next;
  enum ppstatus status;
  int argn; /* the psl position if >0,  or -(the absorbed position) if <0 */
  /* argn==0 is an error */
};

#endif /* 0 migraining */

/**
	returns a single instance, if such can be properly derived
	from the name given.

	Returns NULL if too many or no instances are found.
	Probably ought to have a return code, but doesn't.
*/
static
struct Instance *GetNamedInstance(CONST struct Name *nptr,
                                  CONST struct Instance *tmpinst)
{
  struct Instance *i=NULL;
  struct gl_list_t *insts;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  asc_assert(nptr!=NULL);
  asc_assert(tmpinst!=NULL);
  insts = FindInstances(tmpinst,nptr,&err);
  if (insts==NULL) {
    return NULL;
  }
  if (gl_length(insts) == 1L) {
    i = (struct Instance *)gl_fetch(insts,1);
  }
  gl_destroy(insts);
  return i;
}

/*
	put the parameters open (if any) and absorbed statements into the
	pending list we're creating.
*/
static
struct parpendingentry *
CreateParameterPendings(struct Instance *tmpinst,
                        struct gl_list_t *args,
                        struct StatementList *psl,
                        struct StatementList *absorbed)
{
  unsigned long c,len;
  struct parpendingentry *new, *list=NULL;
  CONST struct Expr *ex;
  struct gl_list_t *nlist=NULL;

  asc_assert(args!=NULL);

  len = gl_length(args);
  for (c=len; c >= 1; c--) {
    new = CreatePPE();
    /* Create must not return NULL */
    new->arg = gl_fetch(args,c);
    new->s = GetStatement(psl,c);
    new->inst = NULL;
    new->argn = c;
    switch (StatementType(new->s)) {
    case WILLBE:
      /* assumes lint did it's job */
      if (NameLength(NamePointer(GetStatVarList(new->s))) > 1) {
        /* arrays were connected already, but no subscript check */
        new->inst = GetArrayHead(tmpinst,NamePointer(GetStatVarList(new->s)));
        new->status = pp_ARR;
      }else{
        /* scalar */
        ex = GetStatCheckValue(new->s);
        if (ex != NULL) {
          nlist = EvaluateNamesNeededShallow(ex,NULL,NULL);
          asc_assert(nlist!=NULL);
          if (gl_length(nlist) != 0L) {
            new->status = pp_WV;
            new->inst =
              GetNamedInstance(NamePointer(GetStatVarList(new->s)),tmpinst);
          }else{
            /* nothing further to check. done already */
            DestroyPPE(new);
            new = NULL;
          }
          gl_destroy(nlist);
        }else{
          DestroyPPE(new);
          new = NULL;
        }
      }
      break;
    case ISA:
      if (NameLength(NamePointer(GetStatVarList(new->s))) > 1) {
        /* subscript check */
        new->inst = GetArrayHead(tmpinst,NamePointer(GetStatVarList(new->s)));
        new->status = pp_ARR;
      }else{
        /* nothing further to check. assumed done already */
        DestroyPPE(new);
        new = NULL;
      }
      break;
    default:
      Asc_Panic(2, "CreateParameterPendings",
                "Unknown statement type in CreateParameterPendings!\n");
      break;
    }
    if (new != NULL) {
      /* insert at head, but completed statements don't get added */
      new->next = list;
      list = new;
    }
  }
  len = StatementListLength(absorbed);
  for (c=len; c >= 1; c--) {
    new = CreatePPE();
    /* Create must not return NULL */
    new->arg = NULL;
    new->s = GetStatement(absorbed,c);
    new->inst = NULL;
    new->argn =0; new->argn -= c;
    switch (StatementType(new->s)) {
    case ISA:
      if (NameLength(NamePointer(GetStatVarList(new->s))) > 1) {
        /* array needed and subscript check */
        new->status = pp_ISAARR;
        /* after construction, no check until fully assigned at end */
      }else{
        /* simplename */
        new->status = pp_ISA;
      }
      break;
    case CASGN:
      new->status = pp_ASGN;
      break;
    default:
      Asc_Panic(2, "CreateParameterPendings",
                "Unknown statement type in CreateParameterPendings!\n");
      break;
    }
    new->next = list;
    list = new;
  }
  return list;
}
/* destroy a list of pending parameter items.
 */
static
void DestroyParameterPendings( struct parpendingentry *pp)
{
  struct parpendingentry *old;
  while (pp!=NULL) {
    old = pp;
    pp = pp->next;
    DestroyPPE(old);
  }
}

/*
	this function should not be entered until all WB arguments have
	been installed in tmpinst.
*/
static
int DigestArguments(
                    struct Instance *tmpinst,
                    struct gl_list_t *args,
                    struct StatementList *psl,
                    struct StatementList *absorbed,
                    struct Statement *statement)
{
  struct parpendingentry *pp,	/* current work */
                         *pphead, /* first in work list */
                         *pplast; /* just prior work, so can delete current */
  int change = 1;
  int suberr = MPIOK; /* maybe mpi enum */

  pphead = pp = CreateParameterPendings(tmpinst,args,psl,absorbed);
  while (change && pphead!=NULL && suberr ==MPIOK) {
    pplast = NULL;
    pp = pphead;
    change = 0;
    while (pp != NULL && suberr ==MPIOK) {
      switch (pp->status) {
      case pp_ISA:
        /* building a scalar! OTHERWISE recursion could bite us.
         * We don't use mpimakesimpleinstance because no argval.
         */
        suberr = ExecuteISA(tmpinst,pp->s);
        if (suberr!=1) {
          suberr = MPIWEIRD;
          pp->status = pp_ERR;
          FPRINTF(ASCERR,"While executing (1) absorbed statement in %s:\n",
            SCP(GetName(InstanceTypeDesc(tmpinst))));
          WriteStatement(ASCERR,pp->s,2);
          mpierror(NULL,0,statement,suberr);
        }else{
          pp->inst =
            GetNamedInstance(NamePointer(GetStatVarList(pp->s)),tmpinst);
          if (pp->inst != NULL) {
            suberr = MPIOK;
            pp->status = pp_ASSC;
          }else{
            suberr = MPIWEIRD;
            pp->status = pp_ERR;
            FPRINTF(ASCERR,"While executing (2) absorbed statement in %s:\n",
              SCP(GetName(InstanceTypeDesc(tmpinst))));
            WriteStatement(ASCERR,pp->s,2);
            mpierror(NULL,0,statement,suberr);
          }
        }
        change++;
        break;
        /* done case */
      case pp_ISAARR:
        /* IS_A of array that needs doing, range, args assignment */
        if (CheckISA(tmpinst,pp->s) == 1) {
          /* Must have subscripts defined first, because we do not
           * want the array to be put on the global pending list as
           * that would be algorithmic suicide. The whole point of
           * parameters is reducing a set of operations to a point
           * in the ProcessPending execution cycle.
           */
          suberr = ExecuteISA(tmpinst,pp->s);
          /* so the array should be completely expanded now. */
          /* we won't check unless problems start to show up,
           * since we believe the array code to be correct.
           */
          if (suberr!=1) {
            suberr = MPIWEIRD;
            pp->status = pp_ERR;
            FPRINTF(ASCERR,"While executing (3) absorbed statement in %s:\n",
              SCP(GetName(InstanceTypeDesc(tmpinst))));
            WriteStatement(ASCERR,pp->s,2);
            mpierror(NULL,0,statement,suberr);
          }else{
            pp->inst =GetArrayHead(tmpinst,NamePointer(GetStatVarList(pp->s)));
            if (pp->inst == NULL) {
              suberr = MPIWEIRD;
              pp->status = pp_ERR;
              FPRINTF(ASCERR,"While executing (4) absorbed statement in %s:\n",
                SCP(GetName(InstanceTypeDesc(tmpinst))));
              WriteStatement(ASCERR,pp->s,2);
              mpierror(NULL,0,statement,suberr);
            }else{
              suberr = MPIOK;
              pp->status = pp_ASAR; /* needs assigning */
            }
          }
          change++;
        }
        /* done case */
        break;
      case pp_ARR:
        /* someone will have init'd pp->inst */
        /* checking whether sets in pp->s expand to match sets
         * in pp->inst, the array head and child of tmpinst.
         * Must accomodate FOR loops in future.
         */
        suberr = MPICheckSubscripts(tmpinst,pp->inst,pp->s);
        switch(suberr) {
        case MPIOK:
          pp->status = pp_DONE;
          change++;
          break;
        case MPIWAIT:
          suberr = MPIOK;
          break;
        default:
          pp->status = pp_ERR;
          WriteInstance(ASCERR,tmpinst);
          WriteInstance(ASCERR,pp->inst);
          mpierror(pp->arg,pp->argn,statement,suberr);
          change++;
          break;
        }
        break;
        /* done case */
      case pp_ASGN:
        if (ExecuteCASGN(tmpinst,pp->s) == 1) {
          pp->status = pp_DONE;
          change++;
        }
        /* done case */
        break;
      case pp_WV:	/* WITH_VALUE that needs checking */
        if (ArgValueCorrect(pp->inst,tmpinst,pp->s)==MPIOK) {
          pp->status = pp_DONE;
          change++;
        }
        /* done case */
        break;
      case pp_ASAR:
      case pp_ASSC:
        if (ArgValuesUnassigned(pp->inst)==0) {
          pp->status = pp_DONE;
          change++;
        }
        /* done case */
        break;
      case pp_DONE:
        FPRINTF(ASCERR,"Unexpected pp_DONE in DigestParameters!\n");
        break;
        /* say what? should have been deleted already. */
        /* done case */
      case pp_ERR:
        /* shouldn't have gone through the loop to reach an err marked pp */
      default:
        ASC_PANIC("Unexpected status in DigestParameters!\n");
        break;
      }
      /* delete if we finished it, then advance counter. */
      if (pp->status == pp_DONE) {
        /* delete pp, but pplast cannot change */
        if (pplast != NULL) { /* we're somewhere in the middle */
          pplast->next = pp->next;
          DestroyPPE(pp);
          pp = pplast->next; /* could be null */
        }else{
          /* we're at the top */
          pphead = pp->next;
          DestroyPPE(pp);
          pp = pphead; /* could be null */
        }
      }else{
        /* just advance the list, even if pperr. */
        pplast = pp;
        pp = pplast->next;
        /* if pp --> NULL, inner while will fail, outer may */
      }
    }
  }
  /* either fell out on error, in which case it is in pplast and the
   * error whine already was done,
   * or pphead !=NULL, but changed didn't move, in which case we
   * need to look for unexecuted assignments, unchecked WITH_VALUE's,
   * and unverified array subscripts and wum about them,
   * or pphead == NULL and we're done and can get out.
   */
  if (suberr!= MPIOK) {
    DestroyParameterPendings(pphead);
    return suberr;
  }
  if (pphead == NULL) {
    return suberr; /* the normal exit */
  }
  pp = pphead;
  while (pp!=NULL) {
    char *msg;
    //CONST struct Statement *stat;
    switch (pp->status) {
    case pp_ISA:
      msg = "Oddly unable to construct parameter scalar";
      //stat = pp->s;
      break;
    case pp_ISAARR:
      msg = "Unable to construct array parameter. Probably missing subscripts";
      //stat = pp->s;
      break;
    case pp_ARR:
      msg = "Unable to check parameter array subscripts.";
      //stat = pp->s;
      break;
    case pp_ASGN:
      msg = "Unable to execute assigment: LHS unmade or RHS not evaluatable";
      //stat = pp->s;
      break;
    case pp_ASSC:
      msg ="Unable to set scalar param: RHS not evaluatable or incorrect type";
      //stat = pp->s;
      break;
    case pp_ASAR:
      msg = "Parameters: Not all array elements assigned during refinement";
      //stat = pp->s;
      break;
    case pp_WV:
      msg = "Unable to verify parameter value: probably bad WITH_VALUE RHS";
      //stat = pp->s;
      break;
    case pp_ERR:
      //stat = statement;
      msg = "Unexpected pp_ERR pending in parameters";
      break;
    case pp_DONE:
      msg = NULL;
      break;
    default:
	  msg = NULL;
    }
    if (msg != NULL) {
      WriteUnexecutedMessage(ASCERR,statement,msg);
    }
    pp = pp->next;
  }
  DestroyParameterPendings(pphead);
  return MPIWAIT;
}

static
void ConfigureCopy(struct Instance *inst,
                   CONST struct Instance *arginst,
                   unsigned long cnum)
{
  struct Instance *src,*copy;

  src = InstanceChild(arginst,cnum);
  asc_assert(src!=NULL);
  copy = CopyInstance(src);
  asc_assert(copy!=NULL);
  StoreChildPtr(inst,cnum,copy);
  /* hunting out UNIVERSAL/arrays we could make this check much
   * less needed.
   */
  if (SearchForParent(copy,inst)==0) {
    AddParent(copy,inst);
  }
}

/* assumes inst, arginst of same type. copies reference
 * children of arginst to same slots in inst.
 */
static
void ConfigureReference(struct Instance *inst,
                        CONST struct Instance *arginst,
                        unsigned long cnum)
{
  struct Instance *src;

  src = InstanceChild(arginst,cnum);
  asc_assert(src!=NULL);
  StoreChildPtr(inst,cnum,src);
  /* hunting out UNIVERSAL/arrays we could make this check much
   * less needed.
   */
  if (SearchForParent(src,inst)==0) {
    AddParent(src,inst);
  }
}

/**
	Connect WILL_BE'd children from arginst to inst.
	Copy IS_A'd children from arginst to inst.
	At this point there can be no alias children -- all
	are either WILL_BE or IS_A of constants/arrays.
	This must only be called with models when arginst !=NULL.
	arginst == NULL --> immediate, no action return.
	inst and arginst are assumed to be the same type.
*/
void ConfigureInstFromArgs(struct Instance *inst,
                           CONST struct Instance *arginst)
{
  ChildListPtr clist;
  unsigned long c,len;

  if (arginst == NULL) {
    return;
  }
  asc_assert(InstanceKind(inst)==MODEL_INST);
  asc_assert(InstanceTypeDesc(inst)==InstanceTypeDesc(arginst));
  clist = GetChildList(InstanceTypeDesc(inst));
  len = ChildListLen(clist);
  for (c=1; c <= len; c++) {
    switch(ChildOrigin(clist,c)) {
    case origin_ALI:
    case origin_ARR:
    case origin_ISA:
    case origin_WB:
    case origin_PALI:
    case origin_PARR:
      if (InstanceChild(arginst,c)!=NULL) {
        ASC_PANIC("arginst caught with illegitimate child. Bye!");
      }
      break;
    case origin_PISA:
      ConfigureCopy(inst,arginst,c);
      break;
    case origin_PWB:
      ConfigureReference(inst,arginst,c);
      break;
    case origin_ERR:
    default:
      ASC_PANIC("arginst caught with alien child. Bye!");
    }
  }
}

/**
	For Those children not already present in inst,
	which must be of the same type as arginst.
	Connect WILL_BE'd children from arginst to inst.
	Copy IS_A'd children from arginst to inst.
	At this point there can be no alias children -- all
	are either WILL_BE or IS_A of constants/arrays, so far as
	arginst is concerned.

	This must only be called with models when arginst !=NULL.
	arginst == NULL --> immediate, no action return.
	inst is expected to be of same type as arginst.
*/
void ReConfigureInstFromArgs(struct Instance *inst,
                             CONST struct Instance *arginst)
{
  ChildListPtr clist;
  unsigned long c,len;

  if (arginst == NULL) {
    return;
  }
  asc_assert(InstanceKind(inst)==MODEL_INST);
  asc_assert(InstanceTypeDesc(inst)==InstanceTypeDesc(arginst));
  clist = GetChildList(InstanceTypeDesc(arginst));
  len = ChildListLen(clist);
  for (c=1; c <= len; c++) {
    switch(ChildOrigin(clist,c)) {
    case origin_ALI:
    case origin_ARR:
    case origin_ISA:
    case origin_WB:
    case origin_PALI:
    case origin_PARR:
      if (InstanceChild(arginst,c)!=NULL) {
        ASC_PANIC("arginst caught with illegitimate child. Bye!");
      }
      break;
    case origin_PISA:
      if (InstanceChild(inst,c)==NULL) {
        /* child that didn't exist in the less refined type. */
        ConfigureCopy(inst,arginst,c);
      }
      break;
    case origin_PWB:
      if (InstanceChild(inst,c)==NULL) {
        /* child that didn't exist in the less refined type. */
        ConfigureReference(inst,arginst,c);
      }
      break;
    case origin_ERR:
    default:
      ASC_PANIC("arginst caught with alien child. Bye!");
    }
  }
}

static
int EqualChildInsts(struct Instance *i1, struct Instance *i2,
                    unsigned long c1, unsigned long c2)
{
  if (c1==0 || c2==0 || i1 == NULL || i2 == NULL ||
      InstanceChild(i1,c1) != InstanceChild(i2,c2)) {
    return 1;
  }
  return 0;
}

/**
	On proper types returns 0 if the inst values are ==
	for the c1th child of i1 and c2th child of i2. OTHERWISE nonzero.

	@BUG
	do not call this with instances other than variables/constants
	or arrays of same. relations, models, etc make it barf or lie.
*/
static
int CompareChildInsts(struct Instance *i1, struct Instance *i2,
                      unsigned long c1, unsigned long c2)
{
  struct Instance *ch1,* ch2;
  asc_assert(i1!=NULL);
  asc_assert(i2!=NULL);
  ch1 = InstanceChild(i1,c1);
  ch2 = InstanceChild(i2,c2);
  asc_assert(ch1!=NULL);
  asc_assert(ch2!=NULL);
  if (InstanceKind(ch1) != InstanceKind(ch2)) {
    return 1;
  }
  if (IsArrayInstance(ch1)) {
    return CmpArrayInsts(ch1,ch2);
  }else{
    return CmpAtomValues(ch1,ch2);
  }
}

/**
	Needs to see that all nonnull children in inst are compatible
	with corresponding children in mpi if such exist.
	arginst must be as or morerefined than inst.

	In particular, needs to be damned picky about where's being met
	and types matching exactly because we won't refine up stuff
	by passing it through a parameter list.
	WILL_BE child pointers of the arginst must = those in inst
	when the inst has a child of that name.
	IS_A child pointers of the arginst must have same value as
	those in inst when the inst has a child of that name.
	When inst has no child of that name, must eventually copy it
	to the expanded instance.

	This has to check that absolutely everything is correct
	because RefineClique/RefineInstance asks no questions.
	This itself assume arginst has been correctly constructed.
*/
static
int CheckParamRefinement(struct Instance *parent,
                         struct Instance *inst,
                         struct Instance *arginst,
                         struct Statement *statement)
{
  ChildListPtr icl, aicl;
  unsigned long oldlen, newlen, c,pos;
  symchar *childname;

  asc_assert(MoreRefined(InstanceTypeDesc(inst),InstanceTypeDesc(arginst))==
         InstanceTypeDesc(arginst));
  icl = GetChildList(InstanceTypeDesc(inst));
  aicl = GetChildList(InstanceTypeDesc(arginst));
  oldlen = ChildListLen(icl);
  newlen = ChildListLen(aicl);
  if (newlen == oldlen) {
    /* very common case, just upgrading types by assigning constants
     * in REFINES clause, though things may have been constructed
     * with those constants earlier.
     */
    for (c=1; c <= newlen; c++) {
      switch(ChildOrigin(aicl,c)) {
      case origin_ALI:
      case origin_ARR:
      case origin_ISA:
      case origin_WB:
      case origin_PALI:
      case origin_PARR:
        if (InstanceChild(arginst,c)!=NULL) {
          ASC_PANIC("arginst caught with illegitimate child. Bye!");
        }
        break;
      case origin_PISA:
        /* both must be assigned, and to the same values */
        if (CompareChildInsts(inst,arginst,c,c)!=0) {
          FPRINTF(ASCERR,"Incompatible constants: ");
          WriteInstanceName(ASCERR,InstanceChild(inst,c),parent);
          mpierror(NULL,0,statement,MPIREASGN);
          return MPIREASGN;
        }
        break;
      case origin_PWB:
        if (EqualChildInsts(inst,arginst,c,c)!=0) {
          FPRINTF(ASCERR,"Different object passed for: ");
          WriteInstanceName(ASCERR,InstanceChild(inst,c),parent);
          mpierror(NULL,0,statement,MPIREDEF);
          return MPIREDEF;
        }
        break;
      case origin_ERR:
      default:
        ASC_PANIC("arginst caught with alien child. Bye!");
      }
    }
  }else{
    /* increased child list */
    for (c=1; c <= newlen; c++) {
      switch(ChildOrigin(aicl,c)) {
      case origin_ALI:
      case origin_ARR:
      case origin_ISA:
      case origin_WB:
      case origin_PALI:
      case origin_PARR:
        if (InstanceChild(arginst,c)!=NULL) {
          ASC_PANIC("arginst caught with illegitimate child. Bye!");
        }
        break;
      case origin_PISA:
        /* both must be assigned, and to the same values, if inst has it */
        childname = ChildStrPtr(aicl,c);
        pos = ChildPos(icl,childname);
        if (pos > 0 && CompareChildInsts(inst,arginst,pos,c)!=0) {
          FPRINTF(ASCERR,"Incompatible constants: ");
          WriteInstanceName(ASCERR,InstanceChild(inst,pos),parent);
          mpierror(NULL,0,statement,MPIREASGN);
          return MPIREASGN;
        }
        break;
      case origin_PWB:
        childname = ChildStrPtr(aicl,c);
        pos = ChildPos(icl,childname);
        if (pos > 0 && EqualChildInsts(inst,arginst,pos,c)!=0) {
          FPRINTF(ASCERR,"Different object passed for: ");
          WriteInstanceName(ASCERR,InstanceChild(inst,pos),parent);
          mpierror(NULL,0,statement,MPIREDEF);
          return MPIREDEF;
        }
        break;
      case origin_ERR:
      default:
        ASC_PANIC("arginst caught with alien child. Bye!");
      }
    }
  }
  return MPIOK;
}

/*------------------------------------------------------------------------------
	...
*/

/**
	handles construction of IS_A statements.
	MakeInstance and its subsidiaries must not cannibalize
	parts from arginst, because it may be used again on
	subsequent calls when the IS_A has several lhs.
*/
static
void MakeInstance(CONST struct Name *name,
                  struct TypeDescription *def,
                  int intset,
                  struct Instance *parent,
                  struct Statement *statement,
                  struct Instance *arginst)
{
  symchar *childname;
  int changed;
  unsigned long pos;
  struct Instance *inst;
  struct InstanceName rec;
  struct TypeDescription *arydef;
  struct gl_list_t *indices;
  int tce;
  /*char *nstr;
  nstr = WriteNameString(name);
  CONSOLE_DEBUG(nstr);
  ascfree(nstr); */
  if ((childname = SimpleNameIdPtr(name))!=NULL){ /* simple 1 element name */
    if (StatInFOR(statement) && StatWrong(statement)==0) {
      MarkStatContext(statement,context_WRONG);
      STATEMENT_ERROR(statement,"Unindexed statement in FOR loop not allowed.");
      WSS(ASCERR,statement);
      return;
    }
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    pos = ChildSearch(parent,&rec);
    if (pos>0) {
      if (InstanceChild(parent,pos)==NULL){
        inst = MakeSimpleInstance(def,intset,statement,arginst);
        LinkToParentByPos(parent,inst,pos);
      }else{			/* redefining instance */
        char *msg = ASC_NEW_ARRAY(char,SCLEN(childname)+strlen(REDEFINE_CHILD_MESG)+1);
        strcpy(msg,REDEFINE_CHILD_MESG);
        strcat(msg,SCP(childname));
        STATEMENT_ERROR(statement,msg);
        ascfree(msg);
      }
    }else{			/* unknown child name */
      STATEMENT_ERROR(statement, "Unknown child name.  Never should happen");
      ASC_PANIC("Unknown child name.  Never should happen");
    }
  }else{
    /* if reach the else, means compound identifier or garbage */
    indices = ArrayIndices(name,parent);
    if (indices!=NULL){ /* array of some sort */
      childname = NameIdPtr(name);
      SetInstanceNameType(rec,StrName);
      SetInstanceNameStrPtr(rec,childname);
      pos = ChildSearch(parent,&rec);
      if (!StatInFOR(statement)) { /* rectangle arrays */
        arydef = CreateArrayTypeDesc(StatementModule(statement),
                                     def,intset,0,0,0,indices);
        if (pos>0) {
          inst = CreateArrayInstance(arydef,1);
          if (inst!=NULL){
            changed = 0;
            tce = TryChildExpansion(inst,parent,&changed,NULL,arginst,NULL);
            /* we're not in a for loop, so can't fail unless user is idiot. */
            LinkToParentByPos(parent,inst,pos);
            /* if user is idiot, whine. */
            if (tce != 0) {
              SignalChildExpansionFailure(parent,pos);
            }
          }else{
            STATEMENT_ERROR(statement, "Unable to create array instance");
            ASC_PANIC("Unable to create array instance");
          }
        }else{
          DeleteTypeDesc(arydef);
          STATEMENT_ERROR(statement,
               "Unknown array child name. Never should happen");
          ASC_PANIC("Unknown array child name. Never should happen");
        }
      }else{
        DestroyIndexList(indices);
        if (pos>0) {
          if (InstanceChild(parent,pos)==NULL) {
            /* must make IS_A array */
            (void) /* should check for NULL return here */
            MakeSparseArray(parent,name,statement,
                            def,intset,NULL,arginst,NULL);
          }else{
            /* must add array element */ /* should check for NULL return here */
            (void)AddArrayChild(parent,name,statement,NULL,arginst,NULL);
          }
        }else{
          STATEMENT_ERROR(statement,
            "Unknown array child name. Never should happen");
          ASC_PANIC("Unknown array child name. Never should happen");
        }
      }
    }else{
      /* bad child name. cannot create parts of parts.  should never
       * happen, being trapped out in typelint.
       */
      STATEMENT_ERROR(statement,"Bad IS_A child name.");
    }
  }
}

static
int ExecuteISA(struct Instance *inst, struct Statement *statement)
{
  struct TypeDescription *def;
  CONST struct VariableList *vlist;
  struct Instance *arginst = NULL;
  int mpi;
  int intset;

  asc_assert(StatementType(statement)==ISA);
  if (StatWrong(statement)) {
    /* incorrect statements should be warned about when they were
     * marked wrong, so we just ignore them here.
     */
    return 1;
  }
  if ((def = FindType(GetStatType(statement)))!=NULL){
    if ((GetStatSetType(statement)!=NULL) != (GetBaseType(def)==set_type)){
      WriteSetError(statement,def);
      return 1;
    }
    if (!CheckISA(inst,statement)) {
      /* last pass whine */
      WriteUnexecutedMessage(ASCERR,statement,
        "Possibly undefined indices in IS_A statement.");
      return 0;
    }
    mpi = MakeParameterInst(inst,statement,&arginst,KEEPARGINST);/*3*/
    if (mpi != MPIOK) {
      if (mpi == MPIWAIT) {
        WriteUnexecutedMessage(ASCERR,statement,
          "Possibly undefined arguments in IS_A statement.");
        return 0;
      }else{
        /* bogus args or definition. punt IS_A permanently. */
        MarkStatContext(statement,context_WRONG);
        WSS(ASCERR,statement);
        return 1;
      }
    }
    intset = CalcSetType(GetStatSetType(statement),statement);
    if (intset < 0) { /* incorrect set type */
      STATEMENT_ERROR(statement,"Illegal set type encountered.");
      /* should never happen due to lint */
      return 0;
    }
    vlist = GetStatVarList(statement);
    while (vlist!=NULL){
      MakeInstance(NamePointer(vlist),def,intset,inst,statement,arginst);
      vlist = NextVariableNode(vlist);
    }
    if (arginst != NULL) {
      DestroyParameterInst(arginst);
    }
    return 1;
  }else{
    /*
     * Should never happen, due to lint.
     */
    char *msg = ASC_NEW_ARRAY(char,strlen(UNDEFINED_TYPE_MESG)+SCLEN(GetStatType(statement))+1);
    strcpy(msg,UNDEFINED_TYPE_MESG);
    strcat(msg,SCP(GetStatType(statement)));
    STATEMENT_ERROR(statement,msg); /* added print. baa. string was here already*/
    ascfree(msg);
    return 1;
  }
}

/**
	handles construction of Dummy Instance
	A dummy instance is universal.
*/
static
void MakeDummyInstance(CONST struct Name *name,
                       struct TypeDescription *def,
                       struct Instance *parent,
                       struct Statement *statement)
{
  symchar *childname;
  unsigned long pos;
  struct Instance *inst;
  struct InstanceName rec;

  childname = SimpleNameIdPtr(name);
  if (childname==NULL) {
    childname = NameIdPtr(name);
  }
  SetInstanceNameType(rec,StrName);
  SetInstanceNameStrPtr(rec,childname);
  pos = ChildSearch(parent,&rec);
  if (pos>0) {
    if (InstanceChild(parent,pos)==NULL){
      inst = ShortCutMakeUniversalInstance(def);
      if (inst==NULL) {
        inst = CreateDummyInstance(def);
      }
      LinkToParentByPos(parent,inst,pos);
    }else{			/* redefining instance */
      char *msg = ASC_NEW_ARRAY(char,SCLEN(childname) + strlen(REDEFINE_CHILD_MESG)+1);
      strcpy(msg,REDEFINE_CHILD_MESG);
      strcat(msg,SCP(childname));
      STATEMENT_ERROR(statement,msg);
      ascfree(msg);
    }
  }else{			/* unknown child name */
      STATEMENT_ERROR(statement, "Unknown child name.  Never should happen");
      ASC_PANIC("Unknown child name.  Never should happen");
  }
}


/**
	Used for IS_A statement inside a non-matching CASE of a
	SELECT statement.

	Make a dummy instance for each name in vlisti, but arrays are not expanded
	over subscripts. The dummy instance is UNIVERSAL.
*/
static
int ExecuteUnSelectedISA( struct Instance *inst, struct Statement *statement)
{
  struct TypeDescription *def;
  CONST struct VariableList *vlist;
  asc_assert(StatementType(statement)==ISA);
  if ((def = FindDummyType())!=NULL){
    vlist = GetStatVarList(statement);
    while (vlist!=NULL){
      MakeDummyInstance(NamePointer(vlist),def,inst,statement);
      vlist = NextVariableNode(vlist);
    }
    return 1;
  }else{
    /*
     * Should never happen, due to lint.
     */
    char *msg = ASC_NEW_ARRAY(char,strlen(UNDEFINED_TYPE_MESG)+11);
    strcpy(msg,UNDEFINED_TYPE_MESG);
    strcat(msg,"dummy_type");
    STATEMENT_ERROR(statement,msg);
    ascfree(msg);
    return 1;
  }
}


/**
	For ALIASES inside a non matching CASEs of a SELECT statement, we
	do not even have to care about the rhs. Similar to ISAs, we only
	take the list of variables and create the dummy instance
*/
static
int ExecuteUnSelectedALIASES(struct Instance *inst,
                             struct Statement *statement)
{
  CONST struct VariableList *vlist;

  asc_assert(StatementType(statement)==ALIASES);
  vlist = GetStatVarList(statement);
  while (vlist!=NULL){
    MakeDummyInstance(NamePointer(vlist),FindDummyType(),inst,statement);
    vlist = NextVariableNode(vlist);
  }
  return 1;
}

/*------------------------------------------------------------------------------
	REFERENCE STATEMENT PROCESSING

	"Highly incomplete		KAA_DEBUG"
*/

#ifdef THIS_IS_AN_UNUSED_FUNCTION
static
struct Instance *RealExecuteRef(struct Name *name,
                                struct TypeDescription *def,
                                int intset,
                                struct Instance *parent,
                                struct Statement *statement)
{
  struct Instance *result = NULL;

  return result;
}
#endif  /* THIS_IS_AN_UNUSED_FUNCTION */

static
int ExecuteREF(struct Instance *inst, struct Statement *statement)
{
  (void)inst;       /*  stop gcc whine about unused parameter */
  (void)statement;  /*  stop gcc whine about unused parameter */
  return 1;
}

/**
	Finds all the instances required to evaluate set element given.
	If problem, returns NULL and err should be consulted.
	Note this may have some angst around FOR vars, as it
	should since forvars are not instances.

	Lint is precluding passing a forvar where an instance is required.
	err should only be consulted if result comes back NULL.

	@NOTE that we will ignore any sets chained on to the end of s.
*/
static struct gl_list_t *FindArgInsts(struct Instance *parent,
	struct Set *s, rel_errorlist *err
){
  struct gl_list_t *result,*temp; /* instance lists */
  struct gl_list_t *nl=NULL; /* name list */
  unsigned nc,nlen;

  result = gl_create(2L);
  nl = EvaluateSetNamesNeededShallow(s,nl);
  nlen = gl_length(nl);
  for (nc=1; nc <= nlen; nc++) {
    temp = FindInstances(parent,(struct Name *)gl_fetch(nl,nc),err);
    if (temp==NULL){
      gl_destroy(nl);
      gl_destroy(result);
      return NULL;
    }
    gl_append_list(result,temp);
    gl_destroy(temp);
  }
  gl_destroy(nl);
  return result;
}


/**
   Missing instances: makes sure at least one thing is found for
   each name item on list (else prints the name with a little message)
   if noisy != 0 || on last iteration, does the printing, OTHERWISE
   returns immediately.
*/
static
void MissingInsts(struct Instance *inst,
                  CONST struct VariableList *list,
                  int noisy)
{
  struct gl_list_t *temp;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  if (g_iteration >= (MAXNUMBER-1) || noisy != 0) {
    while(list!=NULL){
      temp = FindInstances(inst,NamePointer(list),&err);
      if (temp==NULL){
        instantiation_name_error(ASC_USER_ERROR,NamePointer(list),
			"Instance not found"
		);
		error_reporter_end_flush();
      }else{
        gl_destroy(temp);
      }
      list = NextVariableNode(list);
    }
  }
}

/**
   Verify instances: Makes sure at least one thing is found for
   each name item on list. Returns 1 if so, or 0 if not.
   Does not return the collected instances.
*/
static
int VerifyInsts(struct Instance *inst,
	CONST struct VariableList *list, rel_errorlist *err
){
  struct gl_list_t *temp;
  while(list!=NULL){
    temp = FindInstances(inst,NamePointer(list),err);
    if (temp==NULL){
      gl_destroy(temp);
      return 0;
    }
    gl_destroy(temp);
    list = NextVariableNode(list);
  }
  return 1;
}

static
int SameClique(struct Instance *i1, struct Instance *i2)
{
  register struct Instance *i=i1;
  do {
    if (i==i2) return 1;
    i = NextCliqueMember(i);
  } while(i!=i1);
  return 0;
}

static
int InPrecedingClique(struct gl_list_t *list, unsigned long int pos,
                      struct Instance *inst)
{
  unsigned long c;
  struct Instance *i;
  asc_assert(pos<=gl_length(list));
  for(c=1;c<pos;c++){
    i = (struct Instance *)gl_fetch(list,c);
    if (SameClique(i,inst)) return 1;
  }
  return 0;
}

/**
	This procedure takes time proportion to n^2.
*/
static
void RemoveExtras(struct gl_list_t *list){
  unsigned long c=1;
  struct Instance *inst;
  while(c<=gl_length(list)){
    inst = (struct Instance *)gl_fetch(list,c);
    if (InPrecedingClique(list,c,inst)) gl_delete(list,c,0);
    else c++;
  }
}

static
int ListContainsFundamental(struct gl_list_t *list)
{
  unsigned long c=1;
  CONST struct Instance *inst;
  while(c <= gl_length(list)){
    inst = (CONST struct Instance *)gl_fetch(list,c);
    if ( IsFundamentalInstance(inst) ){
      return 1;
    }
    c++;
  }
  return 0;
}

static
int ListContainsParameterized(struct gl_list_t *list)
{
  unsigned long c,len;
  CONST struct Instance *inst;
  CONST struct TypeDescription *d;

  len = gl_length(list);
  for (c=1; c <= len; c++) {
    inst = (CONST struct Instance *)gl_fetch(list,c);
    if (inst != NULL) {
      d = InstanceTypeDesc(inst);
      if (d != NULL) {
        if (TypeHasParameterizedInsts(d)!=0) {
          return 1;
        }
      }else{
        FPRINTF(ASCERR,"NULL TypeDescription in ExecuteAA\n");
        return 1;
      }
    }else{
      FPRINTF(ASCERR,"NULL instance in ExecuteAA\n");
      return 1;
    }
  }
  return 0;
}

static
int ExecuteIRT(struct Instance *work, struct Statement *statement)
{
  struct TypeDescription *def, *more_refined;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct gl_list_t *instances; /* presently leaking ? */
  struct Instance *inst, *arginst;
  unsigned long c,len;
  int suberr;

  asc_assert(StatementType(statement)==IRT);

  def = FindType(GetStatType(statement)); /* sort of redundant, but safe */
  if(def!=NULL) {
    instances = FindInsts(work,GetStatVarList(statement),&err);
    if(instances != NULL){
      if (ListContainsFundamental(instances)){
        STATEMENT_ERROR(statement,
              "IS_REFINED_TO statement affects a part of an atom");
        gl_destroy(instances);
        MarkStatContext(statement,context_WRONG);
        WSS(ASCERR,statement);
        return 1;
      }
      RemoveExtras(instances);	/* slow process to make sure each clique is */
                                /* only represented once in the list */
      suberr = MakeParameterInst(work,statement,&arginst,KEEPARGINST);/*2*/
      if (suberr != MPIOK) {
        gl_destroy(instances);
        if (suberr == MPIWAIT) {
          WriteUnexecutedMessage(ASCERR,statement,
            "Possibly undefined arguments in IS_REFINED_TO statement.");
          return 0;
        }else{
          /* bogus args or definition. punt IRT permanently. */
          MarkStatContext(statement,context_WRONG);
          WSS(ASCERR,statement);
          return 1;
        }
      }
      len = gl_length(instances);
      /* first we check compatibility -
       * no half executed statements and no parameterized cliques.
       */
      for(c=1;c<=len;c++){
        inst = (struct Instance *)gl_fetch(instances,c);
        more_refined = MoreRefined(def,InstanceTypeDesc(inst));
        if ( more_refined == NULL){
          FPRINTF(ASCERR,"Incompatible instance: ");
          WriteInstanceName(ASCERR,inst,work);
          STATEMENT_ERROR(statement,
               "Unconformable refinement in IS_REFINED_TO statement");
          gl_destroy(instances);
          MarkStatContext(statement,context_WRONG);
          WSS(ASCERR,statement);
          if (arginst!=NULL) {
            DestroyParameterInst(arginst);
          }
          return 1;
        }
        if (arginst!=NULL) {
          if (inst != NextCliqueMember(inst)) {
            FPRINTF(ASCERR,"ARE_ALIKE'd instance: ");
            WriteInstanceName(ASCERR,inst,work);
            STATEMENT_ERROR(statement,
              "Refinement of clique to parameterized type family disallowed");
            gl_destroy(instances);
            MarkStatContext(statement,context_WRONG);
            WSS(ASCERR,statement);
            DestroyParameterInst(arginst);
            return 1;
          }
          suberr = CheckParamRefinement(work,inst,arginst,statement);
          /* CheckParamRefinement is responsible for mpierrors wums */
          switch (suberr) {
          case MPIOK:
            break;
          case MPIWAIT:
            gl_destroy(instances);
            DestroyParameterInst(arginst);
            return 0;
          default:
            MarkStatContext(statement,context_WRONG);
            WSS(ASCERR,statement);
            DestroyParameterInst(arginst);
            return 1;
          }
        }
      }
      /* ok, so we're going to repeat a little list/type lookups */
      for(c=1;c<=len;c++){
        inst = (struct Instance *)gl_fetch(instances,c);
        more_refined = MoreRefined(def,InstanceTypeDesc(inst));
        if (more_refined == def) {
          /* whole set will need refining. */
          inst = RefineClique(inst,def,arginst);
        }
      }
      DestroyParameterInst(arginst);
      gl_destroy(instances);
      return 1;
    }else{
      switch(rel_errorlist_get_find_error(&err)){
      case impossible_instance:
        STATEMENT_ERROR(statement,
          "IS_REFINED_TO statement contains an impossible instance name");
        MissingInsts(work,GetStatVarList(statement),1);
        return 1;
      default:
        MissingInsts(work,GetStatVarList(statement),0);
        WriteUnexecutedMessage(ASCERR,statement,
                               "Could not execute IS_REFINED_TO");
        return 0; /* statement is not ready to be executed */
      }
    }
  }else{
    char *msg = ASC_NEW_ARRAY(char,strlen(IRT_UNDEFINED_TYPE)+SCLEN(GetStatType(statement))+1);
    strcpy(msg,IRT_UNDEFINED_TYPE);
    strcat(msg,SCP(GetStatType(statement)));
    STATEMENT_ERROR(statement,msg);
    ascfree(msg);
    return 1;
  }
}

/**
	This assumes that NULL is not in the list.
*/
static
void RemoveDuplicates(struct gl_list_t *list)
{
  VOIDPTR ptr=NULL;
  unsigned c=1;
  gl_sort(list,(CmpFunc)CmpPtrs);
  while(c<=gl_length(list)){
    if (ptr == gl_fetch(list,c)) {
      gl_delete(list,c,0);
    }else{
      ptr = gl_fetch(list,c);
      c++;
    }
  }
}

/**
	Return NULL if the list is not conformable or empty.  Otherwise,
	return the type description of the most refined instance.
*/
static
struct TypeDescription *MostRefined(struct gl_list_t *list)
{
  struct TypeDescription *mostrefined;
  struct Instance *inst;
  unsigned long c,len;
  asc_assert(list!=NULL);
  len = gl_length(list);
  if (len==0) return NULL;
  inst = (struct Instance  *)gl_fetch(list,1);
  mostrefined = InstanceTypeDesc(inst);
  for(c=2;c<=len;c++){
    inst = (struct Instance *)gl_fetch(list,c);
    mostrefined = MoreRefined(mostrefined,InstanceTypeDesc(inst));
    if (mostrefined==NULL) return NULL;
  }
  return mostrefined;
}


static int ExecuteATS(struct Instance *inst, struct Statement *statement){
  struct gl_list_t *instances;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  unsigned long c,len;
  struct Instance *inst1,*inst2;

  instances = FindInsts(inst,GetStatVarList(statement),&err);
  if (instances != NULL){
    if (ListContainsFundamental(instances)){
      STATEMENT_ERROR(statement,
        "ARE_THE_SAME statement affects a part of an atom");
      gl_destroy(instances);
      return 1;
    }
    RemoveDuplicates(instances); /* make sure that no instances occurs */
                                 /* multiple times */
    if ((gl_length(instances)==0)||(MostRefined(instances)!=NULL)){
      len = gl_length(instances);
      if (len>1){
        inst1 = (struct Instance *)gl_fetch(instances,1);
        for(c=2;c<=len;c++){
          inst2 = (struct Instance *)gl_fetch(instances,c);
          inst1 = MergeInstances(inst1,inst2);
          if (inst1==NULL){
            STATEMENT_ERROR(statement, "Fatal ARE_THE_SAME error");
            ASC_PANIC("Fatal ARE_THE_SAME error");
            /*NOTREACHED Wanna bet? ! */
          }
        }
        PostMergeCheck(inst1);
      }
    }else{
      STATEMENT_ERROR(statement,
           "ARE_THE_SAME statement contains unconformable instances");
    }
    gl_destroy(instances);
    return 1;
  }else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance:
      MissingInsts(inst,GetStatVarList(statement),1);
      WriteStatementError(ASC_USER_ERROR,statement,1,"ARE_THE_SAME contains impossible instance");
      return 1;
    default:
      MissingInsts(inst,GetStatVarList(statement),0);
      WriteUnexecutedMessage(ASCERR,statement,
                             "Could not execute ARE_THE_SAME");
      return 0; /* statement is not ready to be executed */
    }
  }
}


/**
	disallows parameterized objects from being added to cliques.
*/
static int ExecuteAA(struct Instance *inst, struct Statement *statement){
  struct gl_list_t *instances;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct TypeDescription *mostrefined = NULL;
  unsigned long c,len;
  struct Instance *inst1,*inst2;
  instances = FindInsts(inst,GetStatVarList(statement),&err);
  if (instances != NULL){
    if (ListContainsFundamental(instances)){
      STATEMENT_ERROR(statement, "ARE_ALIKE statement affects a part of an atom");
      gl_destroy(instances);
      return 1;
    }
    if (ListContainsParameterized(instances)){
      STATEMENT_ERROR(statement, "ARE_ALIKE statement affects parameterized type");
      gl_destroy(instances);
      return 1;
    }
    if ((gl_length(instances)==0) ||
        ((mostrefined = MostRefined(instances))!=NULL)){
      RemoveExtras(instances);	/* slow process to make sure each clique is */
                                /* only represented once in the list */
      len = gl_length(instances);
      /* refine instances */
      for(c=1;c<=len;c++){
        inst1 = (struct Instance *)gl_fetch(instances,c);
        inst2 = RefineClique(inst1,mostrefined,NULL);
        if (inst2!=inst1) {
          gl_store(instances,c,(char *)inst2);
        }
      }
      /* merge cliques */
      if (len>1){
        inst1 = (struct Instance *)gl_fetch(instances,1);
        for(c=2;c<=len;c++){
          inst2 = (struct Instance *)gl_fetch(instances,c);
          MergeCliques(inst1,inst2);
        }
      }
    }else{
      STATEMENT_ERROR(statement,
                    "ARE_ALIKE statement contains unconformable instances");
    }
    gl_destroy(instances);
    return 1;
  }else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance:
      MissingInsts(inst,GetStatVarList(statement),1);
      STATEMENT_ERROR(statement, "ARE_ALIKE contains impossible instance");
      return 1;
    default:
      MissingInsts(inst,GetStatVarList(statement),0);
      WriteUnexecutedMessage(ASCERR,statement,
                             "Could not execute ARE_ALIKE");
      return 0;
    }
  }
}


static int ExecuteLNK(struct Instance *inst, struct Statement *statement){
	struct TypeDescription *def_inst;
	REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
	struct gl_list_t *instances;
	symchar *key;

	asc_assert(StatementType(statement)==LNK);

	def_inst = InstanceTypeDesc(inst);
	instances = FindInsts(inst,LINKStatVlist(statement),&err);
	key = LINKStatKey(statement);

	if((instances != NULL) && (key != NULL)){
		switch (def_inst->t) {
		case model_type:
			if(statement->v.lnk.key_type == 2) {/* in case the LINK entry has the 'ignore' key */
				CONSOLE_DEBUG("Ignore declarative link");
				ignoreDeclLinkEntry(inst,key,LINKStatVlist(statement));
			}else{
				CONSOLE_DEBUG("Adding declarative link");
				addLinkEntry(inst,key,instances,statement,1);
			}
			return 1;
		default:
			STATEMENT_ERROR(statement, "LINK is not called by a model");
			return 1;
		}
	}else if(key == NULL){
		STATEMENT_ERROR(statement, "declarative LINK contains impossible key");
		return 1;
	}else{
		switch(rel_errorlist_get_find_error(&err)){
		case impossible_instance:
			MissingInsts(inst,LINKStatVlist(statement),1);
			STATEMENT_ERROR(statement, "LINK contains impossible instance");
			return 1;
		default:
			MissingInsts(inst,LINKStatVlist(statement),0);
			WriteUnexecutedMessage(ASCERR,statement, "Could not execute LINK");
			return 0;
		}
	}
}
/*------------------------------------------------------------------------------
	RELATION PROCESSING
*/

static
struct Instance *MakeRelationInstance(struct Name *name,
                                      struct TypeDescription *def,
                                      struct Instance *parent,
                                      struct Statement *stat,
                                      enum Expr_enum type)
{
  /* CONSOLE_DEBUG("..."); */
  symchar *childname;
  struct Instance *child;
  struct InstanceName rec;
  unsigned long pos;
  childname = SimpleNameIdPtr(name);
  if (childname!=NULL){
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    pos = ChildSearch(parent,&rec);
    if(pos>0){
      /* following assertion should be true */
      asc_assert(InstanceChild(parent,pos)==NULL);
      child = CreateRelationInstance(def,type);	/* token, bbox relation so far */
      LinkToParentByPos(parent,child,pos);
      return child;
    }else{
      return NULL;
    }
  }else{				/* sparse array of relations */
    childname = NameIdPtr(name);
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    pos = ChildSearch(parent,&rec);
    if (pos>0) {
      if (InstanceChild(parent,pos)==NULL){
        /* must make array */
        child = MakeSparseArray(parent,name,stat,NULL,0,NULL,NULL,NULL);
      }else{
      	/* must add array element */
        child = AddArrayChild(parent,name,stat,NULL,NULL,NULL);
      }
      return child;
    }else{
      return NULL;
    }
  }
}


/**
	ok, now we can whine real loud about what's missing.
	even in relations referencing relations, because they
	should have been added to pendings in dependency order. (hah!)
*/
static int ExecuteREL(struct Instance *inst, struct Statement *statement){
	struct Name *name;
	REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
	struct relation *reln;
	struct Instance *child;
	struct gl_list_t *instances;
	enum Expr_enum reltype;
	//char *iname;

	char *iname;

#ifdef DEBUG_RELS
	CONSOLE_DEBUG("ENTERED ExecuteREL");
#endif

	name = RelationStatName(statement);
	instances = FindInstances(inst,name,&err);
	/* see if the relation is there already */
	if(instances==NULL){
		if(rel_errorlist_get_find_error(&err) == unmade_instance){		/* make a reln head */
			child = MakeRelationInstance(name,FindRelationType(),
                                   inst,statement,e_token);
			if(child==NULL){
				STATEMENT_ERROR(statement, "Unable to create expression structure");
				/* print a better message here if needed. maybe an if!makeindices moan*/
				return 1;
			}
		}else{
			/* undefined instances in the relation name, or out of memory */
			WSSM(ASCERR,statement, "Unable to execute relation label",3);
			return 1;
		}
	}else{
		if(gl_length(instances)==1){
			child = (struct Instance *)gl_fetch(instances,1);
			asc_assert((InstanceKind(child)==REL_INST)||(InstanceKind(child)==DUMMY_INST));
			gl_destroy(instances);
			if (InstanceKind(child)==DUMMY_INST) {
#ifdef DEBUG_RELS
				STATEMENT_ERROR(statement, "DUMMY_INST foundin compiling relation.");
#endif
				return 1;
			}
#ifdef DEBUG_RELS
			STATEMENT_ERROR(statement, "REL_INST found in compiling relation.");
#endif
		}else{
			STATEMENT_ERROR(statement, "Expression name refers to more than one object");
			gl_destroy(instances);	/* bizarre! */
			return 1;
		}
	}

	/* child now contains the pointer to the relation instance.
	We should perhaps double check that the reltype
	has not been set or has been set to e_undefined. */
	if(GetInstanceRelation(child,&reltype)==NULL){
		if((g_instantiate_relns & TOKRELS) ==0){
#ifdef DEBUG_RELS
			STATEMENT_NOTE(statement, "TOKRELS 0 found in compiling relation.");
#endif
			return 1;
		}
#if TIMECOMPILER
		g_ExecuteREL_CreateTokenRelation_calls++;
#endif
		reln = CreateTokenRelation(inst,child,RelationStatExpr(statement),&err);
		if(reln != NULL){
			SetInstanceRelation(child,reln,e_token);
#ifdef DEBUG_RELS
			STATEMENT_NOTE(statement, "Created relation");
#endif
			return 1;
		}else{
			SetInstanceRelation(child,NULL,e_token);
            rel_errorlist_report_error(&err,statement);
		}
#ifdef DEBUG_RELS
		STATEMENT_NOTE(statement, "   Failed relation -- unexpected scenario.");
#endif
	}else{
		/*  Do nothing, somebody already completed the relation.  */
#ifdef DEBUG_RELS
		STATEMENT_NOTE(statement, "Already compiled in compiling relation?!.");
#endif
		return 1;
	}
#ifdef DEBUG_RELS
	STATEMENT_NOTE(statement, "End of ExecuteREL. huh?");
#endif
}

/**
	set a relation instance as Conditional. This is done by activating
	a bit ( relinst_set_conditional(rel,TRUE) ) and by using a flag
	SetRelationIsCond(reln). Only one of these two would be strictly
	required
*/
static
void MarkREL(struct Instance *inst, struct Statement *statement)
{
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct relation *reln;
  struct Instance *rel;
  struct gl_list_t *instances;
  enum Expr_enum reltype;

  name = RelationStatName(statement);
  instances = FindInstances(inst,name,&err);
  if (instances==NULL){
    gl_destroy(instances);
    return;
  }
  else{
    if(gl_length(instances)==1){
      rel = (struct Instance *)gl_fetch(instances,1);
      gl_destroy(instances);
      asc_assert(InstanceKind(rel)==REL_INST);
      relinst_set_conditional(rel,TRUE);
      reln = GetInstanceRelToModify(rel,&reltype);
      if (reln == NULL) {
        return ;
      }
      SetRelationIsCond(reln);
    }else{         /* expression name refers to more than one object */
      gl_destroy(instances);
      return;
    }
  }
}

/**
	set a relation instance as Conditional. This is done by activating
	a bit ( relinst_set_conditional(rel,TRUE) ) and by using a flag
	SetRelationIsCond(reln). Only one of these two would be strictly
	required

	@TODO FIXME. probably should look similar to MarkREL.
	Remember that the compiled instance of an EXT statement
	is still a Relation instance.
*/
static void MarkEXT(struct Instance *inst, struct Statement *statement){
	(void)inst; (void)statement;

        FPRINTF(stderr,"MarkEXT: external rels in conditional statements not fully supported yet.\n");
}

/**
	set a logical relation instance as Conditional. This is done by activating
	a bit ( logrelinst_set_conditional(lrel,TRUE) ) and by using a flag
	SetLogRelIsCond(reln). Only one of these two would be strictly
	required
*/
static
void MarkLOGREL(struct Instance *inst, struct Statement *statement)
{
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct logrelation *lreln;
  struct Instance *lrel;
  struct gl_list_t *instances;

  name = LogicalRelStatName(statement);
  instances = FindInstances(inst,name,&err);
  if (instances==NULL){
    gl_destroy(instances);
    return;
  }
  else{
    if(gl_length(instances)==1){
      lrel = (struct Instance *)gl_fetch(instances,1);
      gl_destroy(instances);
      asc_assert(InstanceKind(lrel)==LREL_INST);
      logrelinst_set_conditional(lrel,TRUE);
      lreln = GetInstanceLogRelToModify(lrel);
      if (lreln == NULL) {
        return;
      }
      SetLogRelIsCond(lreln);
    }else{          /* expression name refers to more than one object */
      gl_destroy(instances);
      return;
    }
  }
}


/**
	For its use in ExecuteUnSelectedStatements.
	Execute the REL or LOGREL statements inside those cases of a SELECT
	which do not match the selection variables
*/
static
int ExecuteUnSelectedEQN(struct Instance *inst, struct Statement *statement)
{
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct Instance *child;
  struct gl_list_t *instances;

  switch(StatementType(statement)) {
  case REL:
    name = RelationStatName(statement);
    break;
  case EXT:
    name = ExternalStatNameRelation(statement);
    break;
  case LOGREL:
    name = LogicalRelStatName(statement);
    break;
  default:
    ASC_PANIC("Incorrect argument passed to ExecuteUnSelectedEQN\n");
	name = NULL;
  }
  instances = FindInstances(inst,name,&err);
  /* see if the relation is there already */
  if (instances==NULL) {
    MakeDummyInstance(name,FindDummyType(),inst,statement);
  }else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      asc_assert(InstanceKind(child)==DUMMY_INST);
      gl_destroy(instances);
    }else{
      STATEMENT_ERROR(statement, "Expression name refers to more than one object");
      gl_destroy(instances);
      ASC_PANIC("Expression name refers to more than one object");
    }
  }
  return 1;
}

/*------------------------------------------------------------------------------
  LOGICAL RELATIONS PROCESSING

  Making instances of logical relations or arrays of instances of
  logical relations.
*/

static
struct Instance *MakeLogRelInstance(struct Name *name,
                                    struct TypeDescription *def,
                                    struct Instance *parent,
                                    struct Statement *stat)
{
  symchar *childname;
  struct Instance *child;
  struct InstanceName rec;
  unsigned long pos;
  if ((childname=SimpleNameIdPtr(name))!=NULL){ /* simple name */
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    if(0 != (pos = ChildSearch(parent,&rec))){
      /* following assertion should be true */
      asc_assert(InstanceChild(parent,pos)==NULL);
      child = CreateLogRelInstance(def);
      LinkToParentByPos(parent,child,pos);
      return child;
    }else{
      return NULL;
    }
  }else{				/* sparse array of logical relations */
    childname = NameIdPtr(name);
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,childname);
    if(0 != (pos = ChildSearch(parent,&rec))){
      if (InstanceChild(parent,pos)==NULL){ /* need to make array */
        child = MakeSparseArray(parent,name,stat,NULL,0,NULL,NULL,NULL);
      }else{			/* need to add array element */
        child = AddArrayChild(parent,name,stat,NULL,NULL,NULL);
      }
      return child;
    }else{
      return NULL;
    }
  }
}

static
int ExecuteLOGREL(struct Instance *inst, struct Statement *statement)
{
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct logrelation *lreln;
  struct Instance *child;
  struct gl_list_t *instances;

  name = LogicalRelStatName(statement);
  instances = FindInstances(inst,name,&err);
  /* see if the logical relation is there already */
  if (instances==NULL){
    gl_destroy(instances);
    if(rel_errorlist_get_find_error(&err) == unmade_instance){
      child = MakeLogRelInstance(name,FindLogRelType(),inst,statement);
      if (child==NULL){
        WUEMPASS3(ASCERR,statement, "Unable to create logical expression structure");
        /* print a better message here if needed */
        return 1;
      }
    }
    else {
      WUEMPASS3(ASCERR,statement, "Unable to execute expression");
      return 1;
    }
  }
  else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(child)==LREL_INST)||(InstanceKind(child)==DUMMY_INST));
      gl_destroy(instances);
      if (InstanceKind(child)==DUMMY_INST) {
        return 1;
      }
    }else{
      WUEMPASS3(ASCERR,statement,
                           "Expression name refers to more than one object");
      gl_destroy(instances);
      return 1;
    }
  }

  /*
   * child now contains the pointer to the logical relation.
   */
  if (GetInstanceLogRel(child)==NULL){
    /*    if ( (g_instantiate_relns & TOKRELS) ==0) {
      return 1;
    }  */
    if(NULL!=(lreln = CreateLogicalRelation(
		inst,child,LogicalRelStatExpr(statement),&err)
	)){
      SetInstanceLogRel(child,lreln);
      return 1;
    }else{
      SetInstanceLogRel(child,NULL);
      switch(rel_errorlist_get_lrcode(&err)){
      case incorrect_logstructure:
        WUEMPASS3(ASCERR,statement,
                       "Bad logical relation expression in ExecuteLOGREL\n");
        return 0;
      case incorrect_linst_type:
        WUEMPASS3(ASCERR,statement,
                             "Incorrect instance types in logical relation");
        return 0;
      case incorrect_boolean_linst_type:
        WUEMPASS3(ASCERR,statement,
             "Incorrect boolean child of atom instance in logical relation");
        return 0;
      case incorrect_integer_linst_type:
        WUEMPASS3(ASCERR,statement,
                           "Incorrect integer instance in logical relation");
        return 0;
      case incorrect_symbol_linst_type:
        WUEMPASS3(ASCERR,statement,
                            "Incorrect symbol instance in logical relation");
        return 0;
      case incorrect_real_linst_type:
        WUEMPASS3(ASCERR,statement,
                              "Incorrect real instance in logical relation");
        return 0;
      case find_logerror:
        switch(rel_errorlist_get_find_error(&err)){
        case unmade_instance:
        case undefined_instance:
          WUEMPASS3(ASCERR,statement,
                       "Unmade or Undefined instances in logical relation");
          return 0;
        case impossible_instance:
          WUEMPASS3(ASCERR,statement,
                        "Logical Relation contains an impossible instance");
          return 0;
        case correct_instance:
          ASC_PANIC("Incorrect error response.\n");/*NOTREACHED*/
        default:
          ASC_PANIC("Unknown error response.\n");/*NOTREACHED*/
        }
      case boolean_value_undefined:
        WUEMPASS3(ASCERR,statement,
                                "Unassigned constants in logical relation");
          return 0;
      case lokay:
        ASC_PANIC("Incorrect error response.\n");/*NOTREACHED*/

      default:
        ASC_PANIC("Unknown error response.\n");/*NOTREACHED*/

      }
    }
  }else{
    /* do nothing. someone already completed the logrelation */
    return 1;
  }
}

/*==============================================================================
  EXTERNAL CALL PROCESSING
*/

/*------------------------------------------------------------------------------
  BLACK BOX RELATIONS PROCESSING
*/

/**
	Verify that all instances named in the arglist of lists are real_atoms.
*/
static
int CheckExtCallArgTypes(struct gl_list_t *arglist)
{
  unsigned long len1,c1;
  unsigned long len2,c2;
  struct gl_list_t *branch;
  struct Instance *arg;

  len1 = gl_length(arglist);
  for (c1=1;c1<=len1;c1++){
    branch = (struct gl_list_t *)gl_fetch(arglist,c1);
    if (!branch) return 1;
    len2 = gl_length(branch);
    for(c2=1;c2<=len2;c2++){
      arg = (struct Instance *)gl_fetch(branch,c2);
      if ((InstanceKind(arg)) != REAL_ATOM_INST) {
        return 1;
      }
    }
  }
  return 0;
}

/*
 @param names a pointer address that will be set to a list or null
  to provide the names result.
 */
static /* blackbox only */
struct gl_list_t *GetExtCallArgs(struct Instance *inst, struct Statement *stat
	,rel_errorlist *err, struct gl_list_t **names
){
  CONST struct VariableList *vl;
  struct gl_list_t *result;
  REL_ERRORLIST err2 = REL_ERRORLIST_EMPTY;

  /* the two process calls could be merged if we change findpaths
     to return instance/name pairs rather than just names. it does
     know the instances.
   */

  vl = ExternalStatVlistRelation(stat);
  result = ProcessExtRelArgs(inst,vl,err);

  /* FIXME is it OK to set *names=NULL? memory leak? */
  *names = NULL;
  if (result != NULL) {
    *names = ProcessExtRelArgNames(inst,vl,&err2);
    asc_assert(rel_errorlist_get_find_error(err) == rel_errorlist_get_find_error(&err2));
  }
  return result;
}

static /* blackbox only */
struct Instance *CheckExtCallData(struct Instance *inst, struct Statement *stat,
	rel_errorlist *err, struct Name **name
){
  struct Name *n;
  struct Instance *result;
  /* we need a second error list here, since we need a separate check */
  REL_ERRORLIST err2 = REL_ERRORLIST_EMPTY;

  n = ExternalStatDataBlackBox(stat);
  result = ProcessExtRelData(inst, n, err);

  *name = NULL;
  if (result != NULL) {
    *name = ProcessExtRelDataName(inst, n, &err2);
    asc_assert(rel_errorlist_get_find_error(err)==rel_errorlist_get_find_error(&err2));
  }
  return result;
}


static int Pass2ExecuteBlackBoxEXTLoop(struct Instance *inst, struct Statement *statement);

int ExecuteBBOXElement(struct Instance *inst, struct Statement *statement, struct Instance *subject, struct gl_list_t *inputs,  struct BlackBoxCache * common, long c, CONST char *context);

/**
	This function does the job of creating an instance of a 'black box' external
	relation or set of relations. It does it by working as if the user wrote a 
	for loop over the outputs. While managing this for loop, we have to make
	sure that if we are already inside a for loop we don't mess that one up.
	The role of savedfortable is to manage the change of model context when one
	model instantiates another inside a for loop. For relations in particular, 
	the saved for table will always be null unless we drop the multipass
	instantiation scheme.
*/
static int ExecuteBlackBoxEXT(struct Instance *inst
	,struct Statement *statement
){
  int alreadyInFor = 0;
  int executeStatus = 0;
  struct for_table_t *SavedForTable;

  if(GetEvaluationForTable() != NULL){
	/* is this the right test? FIXME if not multipass instantiation. */
	/* as written, this might see a fortable from elsewhere */
    alreadyInFor = 1;
  }

  if(!alreadyInFor){ /* pushing/popping null table...*/
    SavedForTable = GetEvaluationForTable();
    SetEvaluationForTable(CreateForTable());
  }
  executeStatus = Pass2ExecuteBlackBoxEXTLoop(inst,statement);
  if(!alreadyInFor){
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
  }
  if(executeStatus){
	/* don't report an error here, because return 1 is possible even with
	eventual success at later compiler passes. */
	//ERROR_REPORTER_HERE(ASC_USER_ERROR,"Failed to execute blackbox statement");
    return 1;
  }else{
    return 0;
  }
}

/* This looks a lot like a FOR loop, since we're building an array,
but is very specialized to eliminate the user trying to declare
the for loop of an external relation correctly. Basically they
would have to write the output index expression identically twice, which
apparently is too hard for some.
@param instance: the enclosing model.
@param statement: the EXT bbox statement.
*/
int Pass2ExecuteBlackBoxEXTLoop(struct Instance *inst, struct Statement *statement){
  symchar *name;
  struct Expr *ex, *one, *en;
  unsigned long c,len;
  long aindex;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;

  struct BlackBoxCache * common;
  ExtBBoxInitFunc * init;
  char *context;
  struct Instance *data=NULL, *subject = NULL;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct gl_list_t *arglist=NULL;
  struct ExternalFunc *efunc = NULL;
  CONST char *funcname = NULL;
  unsigned long n_input_args=0L, n_output_args=0L; /* formal arg counts */
  unsigned long n_inputs_actual=0L, n_outputs_actual=0L; /* atomic arg counts */
  struct gl_list_t *inputs, *outputs, *argListNames;
  struct Name *dataName = NULL;
  unsigned long start,end;
  struct Set *extrange= NULL;

  /* common stuff do once ------------ */

  /*
	note ignoring return codes as all is guaranteed to work by passing
	the checks done before this statement was attempted.
  */
  if (ExternalStatDataBlackBox(statement) != NULL) {
    data = CheckExtCallData(inst, statement, &err, &dataName);
    /* should never be here, if checkext were being used properly somewhere. it isn't */
    if (data==NULL && rel_errorlist_get_find_error(&err) != correct_instance){
      /* should never be here, if checkext were being used properly somewhere. it isn't */
      switch(rel_errorlist_get_find_error(&err)){
      case unmade_instance:
		STATEMENT_ERROR(statement,"Statement contains unmade data instance");
        return 1;
      case undefined_instance:
        STATEMENT_ERROR(statement,"Statement contains undefined data instance\n");
        return 1; /* for the time being give another crack */
      case impossible_instance:
        STATEMENT_ERROR(statement,"Statement contains impossible data instance\n");
        return 1;
      default:
        STATEMENT_ERROR(statement,"Unhandled case!");
        return 1;
      }
    }
  }

  /* expand the formal args into a list of lists of realatom args. */
  arglist = GetExtCallArgs(inst, statement, &err, &argListNames);
  if (arglist==NULL){
    /* should never be here, if checkext were being used properly somewhere. it isn't */
    switch(rel_errorlist_get_find_error(&err)){
    case unmade_instance:
      STATEMENT_ERROR(statement,"Statement contains unmade argument instance\n");
      return 1;
    case undefined_instance:
      STATEMENT_ERROR(statement,"Statement contains undefined argument instance\n");
      return 1;
    case impossible_instance:
      instantiation_error(ASC_USER_ERROR,statement,"Statement contains impossible instance\n");
      return 1;
    default:
      instantiation_error(ASC_PROG_ERR,statement,"Unhandled case!");
      return 1;
    }
  }
  funcname = ExternalStatFuncName(statement);
  efunc = LookupExtFunc(funcname);
  if (efunc == NULL) {
    return 1;
  }
/*
  n_input_args = NumberInputArgs(efunc);
  n_output_args = NumberOutputArgs(efunc);
 */
  //so lets see if getting i and o works better than commented code above
  n_input_args = statement->v.ext.u.black.n_inputs;
  n_output_args = statement->v.ext.u.black.n_outputs;

  if ((len =gl_length(arglist)) != (n_input_args + n_output_args)) {
    instantiation_error(ASC_PROG_ERR,statement
		,"Unable to create external expression structure."
	);
    return 1;
  }

  /* we should have a valid arglist at this stage */
  if (CheckExtCallArgTypes(arglist)) {
    instantiation_error(ASC_USER_ERROR,statement,"Wrong type of args to external statement");
    DestroySpecialList(arglist);
    return 1;
  }
  start = 1L;
  end = n_input_args;
  inputs = LinearizeArgList(arglist,start,end);
  n_inputs_actual = gl_length(inputs);

  /* Now process the outputs */
  start = n_input_args+1;
  end = n_input_args + n_output_args;
  outputs = LinearizeArgList(arglist,start,end);
  n_outputs_actual = gl_length(outputs);

/*
  char *tempnamestr = WriteNameString(dataName);
  CONSOLE_DEBUG("dataName = %s", tempnamestr);
  ASC_FREE(tempnamestr);
*/

  /* Now create the relations, all with the same common. */
  common = CreateBlackBoxCache(n_inputs_actual,n_outputs_actual, argListNames, dataName, efunc);
  common->interp.task = bb_first_call;
  context = WriteInstanceNameString(inst, NULL);

  /* now set up the for loop index --------------------------------*/
  name = AddSymbol(BBOX_RESERVED_INDEX);
  /* using a reserved character not legal in user level modeling. */
  asc_assert(FindForVar(GetEvaluationForTable(),name) == NULL);
  /* cannot happen as bbox definitions don't nest as statements and	user identifiers cannot contain ?. */

  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  /* construct a set value of 1..bbox_arraysize */
  one = CreateIntExpr(1L); /* destroyed with set. */
  en = CreateIntExpr(n_outputs_actual); /* destroyed with set. */
  extrange = CreateRangeSet(one,en);
  ex = CreateSetExpr(extrange);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);

  ASC_ASSERT_EQ(ValueKind(value),set_value);
  sptr = SetValue(value);
  ASC_ASSERT_EQ(SetKind(sptr),integer_set);
  fv = CreateForVar(name);
  SetForVarType(fv,f_integer);
  AddLoopVariable(GetEvaluationForTable(),fv);
  len = Cardinality(sptr);
  #ifdef DEBUG_RELS
  ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Pass2RealExecuteFOR integer_set %lu.\n",len);
  #endif
  for(c=1;c<=len;c++){
    aindex = FetchIntMember(sptr,c);
    SetForInteger(fv,aindex);
    subject = (struct Instance *)gl_fetch(outputs,aindex);
    ExecuteBBOXElement(inst, statement, subject, inputs, common, aindex, context);
    /*  currently designed to always succeed or fail permanently */
  }
  RemoveForVariable(GetEvaluationForTable());
  DestroyValue(&value);
  DestroySetNode(extrange);

/* ------------ */ /* ------------ */
  /* and now for cleaning up shared data. */
  init = GetInitFunc(efunc);
  if(init){
    if( (*init)( &(common->interp), data, arglist) ){
      ERROR_REPORTER_HERE(ASC_PROG_ERR,"Error in blackbox initfn");
    }
  }
  common->interp.task = bb_none;
  ascfree(context);
  DeleteRefBlackBoxCache(NULL, &common);
  gl_destroy(inputs);
  gl_destroy(outputs);
  DestroySpecialList(arglist);
  DeepDestroySpecialList(argListNames,(DestroyFunc)DestroyName);
  DestroyName(dataName);
/* ------------ */ /* ------------ */

  /*  currently designed to always succeed or fail permanently.
   *  We reached this point meaning we've processed everything.
   *  Therefore the statment returns 1 and becomes no longer pending.
   */
  return 1;
}

int ExecuteBBOXElement(struct Instance *inst
	, struct Statement *statement, struct Instance *subject
	, struct gl_list_t *inputs,  struct BlackBoxCache * common, long c
	, CONST char *context
){
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct gl_list_t *instances = NULL;
  struct Instance *child = NULL;
  struct relation *reln  = NULL;
  enum Expr_enum reltype;

#ifdef DEBUG_RELS
  CONSOLE_DEBUG("ENTERED ExecuteBBOXElement\n");
#endif

  /* make or find the instance */
  name = ExternalStatNameRelation(statement);
  instances = FindInstances(inst, name, &err);
  /* see if the relation is there already. If it is, we're really hosed. */
  if(instances==NULL){
    if(rel_errorlist_get_find_error(&err) == unmade_instance){		/* make a reln head */
      child = MakeRelationInstance(name,FindRelationType(),
                                   inst,statement,e_blackbox);
      if (child==NULL){
        STATEMENT_ERROR(statement, "Unable to create external black-box expression structure (unmade instance)");
       /* print a better message here if needed. maybe an if!makeindices moan*/
        return 1;
      }
    }else{
      /* undefined instances in the relation name, or out of memory */
      WSSM(ASCERR,statement, "Unable to execute blackbox label",3);
      return 1;
    }
  }else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(child)==REL_INST) || (InstanceKind(child)==DUMMY_INST));
      gl_destroy(instances);
      if (InstanceKind(child)==DUMMY_INST) {
#ifdef DEBUG_RELS
        STATEMENT_ERROR(statement, "DUMMY_INST found in compiling blackbox.");
#endif
        return 1;
      }
#ifdef DEBUG_RELS
      STATEMENT_ERROR(statement, "REL_INST found in compiling blackbox.");
#endif
    }else{
      STATEMENT_ERROR(statement, "Expression name refers to more than one object");
      gl_destroy(instances);	/* bizarre! */
      return 1;
    }
  }

  /*
   * child now contains the pointer to the relation instance.
   * We should perhaps double check that the reltype
   * has not been set or has been set to e_undefined.
   */
  if (GetInstanceRelation(child,&reltype)==NULL) {
    if ( (g_instantiate_relns & BBOXRELS) ==0) {
#ifdef DEBUG_RELS
      STATEMENT_NOTE(statement, "BBOXRELS 0 found in compiling bbox.");
#endif
      return 1;
    }
#if TIMECOMPILER
    g_ExecuteEXT_CreateBlackboxRelation_calls++;
#endif
    reln = CreateBlackBoxRelation(child,
				subject, inputs,
				common, c-1, context);
    asc_assert(reln != NULL); /* cbbr does not return null */
    SetInstanceRelation(child,reln,e_blackbox);
#ifdef DEBUG_RELS
    STATEMENT_NOTE(statement, "Created bbox relation.");
#endif
    return 1;
  }else{
    /*  Do nothing, somebody already completed the relation.  */
#ifdef DEBUG_RELS
        STATEMENT_NOTE(statement, "Already compiled element in blackbox?!.");
#endif
    return 1;
  }
#ifdef DEBUG_RELS
  STATEMENT_NOTE(statement, "End of ExecuteBBOX. huh?");
  /* not reached */
#endif
}

/*------------------------------------------------------------------------------
  GLASS BOX RELATIONS PROCESSING

	GlassBox relations processing. As is to be expected, this code
	is a hybrid between TRUE ascend relations and blackbox relations.
*/

#if 0

static struct gl_list_t *CheckGlassBoxArgs(struct Instance *inst
	,struct Statement *stat,rel_errorlist *err
){
  struct Instance *var;
  CONST struct VariableList *vl;
  struct gl_list_t *varlist = NULL, *tmp = NULL;
  unsigned long len,c;
  int error = 0;

  vl = ExternalStatVlistRelation(stat);
  if (!vl) {
    rel_errorlist_set_find_error(err,impossible_instance); /* a relation with no incidence ! */
    return NULL;
  }

  ListMode = 1; /* order is very important */
  varlist = gl_create(NO_INCIDENCES); /* could be fine tuned */
  while (vl!=NULL) {
    tmp = FindInstances(inst,NamePointer(vl),err);
    if (tmp) {
      len = gl_length(tmp);
      for (c=1;c<=len;c++) {
        var = (struct Instance *)gl_fetch(tmp,c);
        if (InstanceKind(var) != REAL_ATOM_INST) {
          error++;
          rel_errorlist_set_code(err,incorrect_inst_type);
          //rel_errorlist_add(err,incorrect_inst_type,var,stat);
          rel_errorlist_set_find_error(err,correct_instance);
          gl_destroy(tmp);
          goto cleanup;
        }
        gl_append_ptr(varlist,(VOIDPTR)var);
      }
      gl_destroy(tmp);
    }else{ /* ferr will be already be set */
      error++;
      goto cleanup;
    }
    vl = NextVariableNode(vl);
  }

cleanup:
  ListMode = 0;
  if (error) {
    gl_destroy(varlist);
    return NULL;
  }else{
    return varlist;
  }
}


static int CheckGlassBoxIndex(struct Instance *inst
	, struct Statement *stat, rel_errorlist *err
){
  int result;
  long int iresult;
  char *tail;
  CONST struct Name *n;
  symchar *str;		   /* a string representation of the index */

  (void)inst;  /*  stop gcc whine about unused parameter  */

  n = ExternalStatDataGlassBox(stat);
  if(!n){
    rel_errorlist_set_code(err,incorrect_num_args);
	//rel_errorlist_add(err,incorrect_num_args,inst,stat);/* we must have an index */
    return -1;
  }

  str = SimpleNameIdPtr(n);
  if(str){
#if 0
    result = atoi(SCP(str));	/* convert to integer. use strtol */
#endif
    errno = 0;
    iresult = strtol(SCP(str),&tail,0);
    if (errno != 0 || (iresult == 0 && tail == SCP(str))) {
      rel_errorlist_set_code(err,incorrect_structure);
      //rel_errorlist_add(err,incorrect_structure,inst,stat);
      return -1;
    }
    result = iresult; /* range errror possible. */
    rel_errorlist_set_code(err,okay);
    return result;
  }else{
	rel_errorlist_set_code(err,incorrect_structure);
    //rel_errorlist_add(err,incorrect_structure,inst,stat);		/* we really need to expand */
    return -1;				/* the relation_error types. !! */
  }
}

static int ExecuteGlassBoxEXT(struct Instance *inst
	, struct Statement *statement
){
  struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct Instance *child;
  struct gl_list_t *instances;
  struct gl_list_t *varlist;
  struct relation *reln;
  struct ExternalFunc *efunc;
  CONST char *funcname;
  enum Expr_enum type;
  int gbindex;

  /*
   * Get function call details. The external function had better
   * loaded at this stage or report an error. No point in wasting
   * time.
   */
  funcname = ExternalStatFuncName(statement);
  efunc = LookupExtFunc(funcname);
  if (!efunc) {
    FPRINTF(ASCERR,"External function %s was not loaded\n",funcname);
    return 1;
  }

  name = ExternalStatNameRelation(statement);
  instances = FindInstances(inst,name,&err);
  if(instances==NULL){
    if(rel_errorlist_get_find_error(&err) == unmade_instance){			/* glassbox reln */
      child = MakeRelationInstance(name,FindRelationType(),inst,statement,e_glassbox);
      if (child==NULL){
        STATEMENT_ERROR(statement, "Unable to create glass box expression structure");
        return 1;
      }
    }else{
      STATEMENT_ERROR(statement, "Unable to execute expression");
      return 1;
    }
  }else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      ASC_ASSERT_EQ(InstanceKind(child), REL_INST);
      gl_destroy(instances);
    }else{
      STATEMENT_ERROR(statement, "Expression name refers to more than one object");
      gl_destroy(instances);
      return 1;
    }
  }

  /*
   * child now contains the pointer to the relation instance;
   * Ensure that the variable list is ready.
   */
  /* FIX FIX FIX -- give some more error diagnostics for err and ferr */
  varlist = CheckGlassBoxArgs(inst,statement,&err);
  if (varlist==NULL){
    switch(rel_errorlist_get_find_error(&err)){
    case unmade_instance:
      return 0;
    case undefined_instance:
      return 0; /* for the time being give another crack */
    case impossible_instance:
      instantiation_error(ASC_PROG_ERROR,statement
			,"Statement contains impossible instance\n");
      return 1;
    default:
      instantiation_error(ASC_PROG_ERROR,statement
			,"Something really wrong in ExecuteGlassEXT routine\n");
      return 1;
    }
  }

  /*
   * Get the gbindex of the relation for mapping into the external
   * call. An gbindex < 0 is invalid.
   */
  gbindex = CheckGlassBoxIndex(inst,statement,&err);
  if (gbindex < 0) {
    instantiation_error(ASC_USER_ERROR,statement
	    ,"Invalid index in external relation statement");
    return 1;
  }

  /*
   * All should be ok at this stage. Create the relation
   * structure and attach it to the relation instance.
   * CreateGlassBoxRelation makes a copy of the varlist.
   * But before we go through the trouble of making the
   * relation, we will check that none exists already. If
   * one has been created we cleanup and return 1.
   */
  if (GetInstanceRelation(child,&type)!=NULL) {
    goto error;
  }
  reln = CreateGlassBoxRelation(child,efunc,varlist,gbindex,e_equal);
  if (!reln) {
    Asc_Panic(2, __FUNCTION__,
      "Major error: Unable to create external relation structure."
    );
  }
  SetInstanceRelation(child,reln,e_glassbox);

 error:
  if (varlist) gl_destroy(varlist);
  return 1;
}
#endif


static int ExecuteEXT(struct Instance *inst, struct Statement *statement){
  int mode;

  /* CONSOLE_DEBUG("..."); */
  mode = ExternalStatMode(statement);
  switch(mode) {
  case ek_method:
    instantiation_error(ASC_USER_ERROR,statement
			,"Invalid external statement in declarative section. \n");
    return 1;
#if 0
  case ek_glass:
    return ExecuteGlassBoxEXT(inst,statement);
#endif
  case ek_black:
    return ExecuteBlackBoxEXT(inst,statement);
  default:
    instantiation_error(ASC_USER_ERROR,statement
			,"Invalid external statement in declarative section. \n");
    return 1;
  }
}

/*------------------------------------------------------------------------------
  ASSIGNMENT PROCESSING
*/

static void StructuralAsgnErrorReport(struct Statement *statement
	, struct value_t *value
){
  STATEMENT_ERROR(statement,
    "Structural assignment right hand side is not constant");
  DestroyValue(value);
}


/*
 * returns 1 if error will be persistent, or 0 if error may
 * go away later when more compiling is done.
 * Issues some sort of message in the case of persistent errors.
 */
static int AsgnErrorReport(struct Statement *statement, struct value_t *value){
  switch(ErrorValue(*value)){
  case undefined_value:
  case name_unfound: DestroyValue(value); return 0;
  case incorrect_name:
    STATEMENT_ERROR(statement,
         "Assignment right hand side contains non-existent instance");
    DestroyValue(value);
    return 1;
  case temporary_variable_reused:
    STATEMENT_ERROR(statement, "Assignment re-used temporary variable");
    DestroyValue(value);
    return 1;
  case dimension_conflict:
    STATEMENT_ERROR(statement,
          "Assignment right hand side is dimensionally inconsistent");
    DestroyValue(value);
    return 1;
  case incorrect_such_that:
    STATEMENT_ERROR(statement, "Assignment uses incorrect such that expression");
    DestroyValue(value);
    return 1;
  case empty_choice:
    STATEMENT_ERROR(statement, "Assignment has CHOICE of an empty set");
    DestroyValue(value);
    return 1;
  case empty_intersection:
    STATEMENT_ERROR(statement,
      "Assignment has an empty INTERSECTION() construct which is undefined");
    DestroyValue(value);
    return 1;
  case type_conflict:
    STATEMENT_ERROR(statement,
         "Assignment right hand side contains a type conflict");
    DestroyValue(value);
    return 1;
  default:
    STATEMENT_ERROR(statement, "Assignment contains strange error");
    DestroyValue(value);
    return 1;
  }
}


static void ReAssignmentError(CONST char *str, struct Statement *statement){
  char *msg = ASC_NEW_ARRAY(char,strlen(REASSIGN_MESG1)+strlen(REASSIGN_MESG2)+strlen(str)+1);
  strcpy(msg,REASSIGN_MESG1);
  strcat(msg,str);
  strcat(msg,REASSIGN_MESG2);
  STATEMENT_ERROR(statement,msg);
  ascfree(msg);
}


/**
	returns 1 if ok, 0 if unhappy.
	for any given statement, once unhappy = always unhappy.
*/
static int AssignStructuralValue(struct Instance *inst
	,struct value_t value,struct Statement *statement
){
  switch(InstanceKind(inst)){
  case MODEL_INST:
  case ARRAY_INT_INST:
  case ARRAY_ENUM_INST:
  case REL_INST:
  case LREL_INST:
    STATEMENT_ERROR(statement, "Arg!  Attempt to assign to a non-scalar");
    return 0;
  case REAL_ATOM_INST:
  case REAL_INST:
  case BOOLEAN_ATOM_INST:
  case BOOLEAN_INST:
  case INTEGER_ATOM_INST:
  case INTEGER_INST:
  case SYMBOL_ATOM_INST:
  case SYMBOL_INST:
    STATEMENT_ERROR(statement, "Assignment to non-constant LHS ignored");
    return 0;
  case REAL_CONSTANT_INST:
    switch(ValueKind(value)){
    case real_value:
      if ( AtomAssigned(inst) &&
           ( RealValue(value) != RealAtomValue(inst) ||
             !SameDimen(RealValueDimensions(value),RealAtomDims(inst)) )
         ) {
        ReAssignmentError(SCP(GetBaseTypeName(real_constant_type)),statement);
        return 0;
      }else{
        if (!AtomAssigned(inst)) {
          if ( !IsWild(RealAtomDims(inst)) &&
               !SameDimen(RealValueDimensions(value),RealAtomDims(inst)) ) {
            STATEMENT_ERROR(statement, "Dimensionally inconsistent assignment");
            return 0;
          }else{
      	    if (IsWild(RealAtomDims(inst))) {
              SetRealAtomDims(inst,RealValueDimensions(value));
            }
            SetRealAtomValue(inst,RealValue(value),0);
          }
        }
      }
      /* case of same value,dimen reassigned is silently ignored */
      return 1;
    case integer_value:
      if ( AtomAssigned(inst) &&
           ( (double)IntegerValue(value) != RealAtomValue(inst) ||
             !SameDimen(Dimensionless(),RealAtomDims(inst)) )
         ) {
        ReAssignmentError(SCP(GetBaseTypeName(real_constant_type)),
                          statement);
        return 0;
      }else{
        if (!AtomAssigned(inst)) {
          if ( !IsWild(RealAtomDims(inst)) &&
               !SameDimen(Dimensionless(),RealAtomDims(inst)) ) {
            STATEMENT_ERROR(statement, "Dimensionally inconsistent assignment");
            return 0;
          }else{
      	    if (IsWild(RealAtomDims(inst))) {
              SetRealAtomDims(inst,Dimensionless());
            }
            SetRealAtomValue(inst,(double)IntegerValue(value),0);
          }
        }
      }
      /* case of same value,dimen reassigned is silently ignored */
      return 1;
    default:
      STATEMENT_ERROR(statement,
           "Attempt to assign non-real value to a real instance");
    }
    return 0;
  case BOOLEAN_CONSTANT_INST:
    if (ValueKind(value)!=boolean_value){
      STATEMENT_ERROR(statement,
      "Attempt to assign a non-boolean value to a boolean instance");
      return 0;
    }else{
      if ( AtomAssigned(inst) &&
           BooleanValue(value) != GetBooleanAtomValue(inst) ) {
        ReAssignmentError(SCP(GetBaseTypeName(boolean_constant_type)),
                          statement);
        return 0;
      }else{
        if (!AtomAssigned(inst)) {
          SetBooleanAtomValue(inst,BooleanValue(value),0);
        }
      }
    }
    return 1;
  case INTEGER_CONSTANT_INST:
    switch(ValueKind(value)){
    case integer_value:
      if (AtomAssigned(inst)
          && (GetIntegerAtomValue(inst)!=IntegerValue(value))) {
        ReAssignmentError(SCP(GetBaseTypeName(integer_constant_type)),
                          statement);
        return 0;
      }else{
        if (!AtomAssigned(inst)) {
          SetIntegerAtomValue(inst,IntegerValue(value),0);
        }
      }
      return 1;
    case real_value: /* case which is parser artifact: real, wild 0 */
      if ( RealValue(value)==0.0 && IsWild(RealValueDimensions(value)) ) {
        if (!AtomAssigned(inst)) {
          SetIntegerAtomValue(inst,(long)0,0);
        }else{
          if (AtomAssigned(inst) && (GetIntegerAtomValue(inst)!=0)) {
            ReAssignmentError(SCP(GetBaseTypeName(integer_constant_type)),
                              statement);
            return 0;
          }
        }
        return 1;
      }
      /* intended to fall through to default if not wild real or not 0 */
    default:
      STATEMENT_ERROR(statement,
           "Attempt to assign a non-integer value to an integer instance");
    }
    return 0;
  case SET_ATOM_INST:
  case SET_INST:
    if (ValueKind(value)==set_value){
      if (AtomAssigned(inst)&&
          !SetsEqual(SetValue(value),SetAtomList(inst))) {
        ReAssignmentError(SCP(GetBaseTypeName(set_type)),
                          statement);
        return 0;
      }else{
        if(!AtomAssigned(inst)) {
          struct set_t *cslist;
          cslist = CopySet(SetValue(value));
          if (!AssignSetAtomList(inst,cslist)) {
            DestroySet(cslist);
            return 0;
          }
        }
        /* quietly ignore benign reassignment */
      }
      return 1;
    }else{
      STATEMENT_ERROR(statement,
           "Attempt to assign a non-set value to a set instance");
      return 0;
    }
  case SYMBOL_CONSTANT_INST:
    if (ValueKind(value)==symbol_value){
      asc_assert(AscFindSymbol(SymbolValue(value))!=NULL);
      if (AtomAssigned(inst) &&
          (SymbolValue(value) != GetSymbolAtomValue(inst))) {
        ReAssignmentError(SCP(GetBaseTypeName(symbol_constant_type)),
                          statement);
        return 0;
      }else{
        if (!AtomAssigned(inst)) {
          SetSymbolAtomValue(inst,SymbolValue(value));
        }
      }
      return 1;
    }else{
      STATEMENT_ERROR(statement,
              "Attempt to assign a non-symbol value to a symbol instance");
    }
    return 0;
  default:
    STATEMENT_ERROR(statement, "Error: Unknown value type");
    return 0;
  }
}


/**
	Execute structural and dimensional assignments.
	This is called by execute statements and exec for statements.
	Assignments to variable types are ignored.
	Variable defaults expressions are done in executedefaults.
	rhs expressions must yield constant value_t.
	Incorrect statements will be marked context_WRONG where possible.
*/
static int ExecuteCASGN(struct Instance *work, struct Statement *statement){
  struct gl_list_t *instances;
  struct Instance *inst;
  unsigned long c,len;
  struct value_t value;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  int previous_context;
  int rval;

  if (StatWrong(statement)) return 1; /* if we'll never execute it, it's ok */

  previous_context = GetDeclarativeContext();
  SetDeclarativeContext(0);
  instances = FindInstances(work,AssignStatVar(statement),&err);
  if (instances != NULL){
    asc_assert(GetEvaluationContext()==NULL);
    SetEvaluationContext(work);

#ifdef ASC_SIGNAL_TRAPS
	Asc_SignalHandlerPushDefault(SIGFPE);
	if(SETJMP(g_fpe_env)==0){
#endif

	value = EvaluateExpr(AssignStatRHS(statement),NULL,InstanceEvaluateName);

#ifdef ASC_SIGNAL_TRAPS
	}else{
		STATEMENT_ERROR(statement, "Floating-point error while evaluating assignment statement");
        MarkStatContext(statement,context_WRONG);
		SetDeclarativeContext(previous_context);
		return 1;
	}
	Asc_SignalHandlerPopDefault(SIGFPE);
#endif

    SetEvaluationContext(NULL);


    if (ValueKind(value)==error_value || !IsConstantValue(value) ){
      if (ValueKind(value)==error_value) {
        gl_destroy(instances);
        SetDeclarativeContext(previous_context);
        rval = AsgnErrorReport(statement,&value);
        if (rval) {
          MarkStatContext(statement,context_WRONG);
          WSS(ASCERR,statement);
        }
        return rval;
      }else{
        gl_destroy(instances);
        SetDeclarativeContext(previous_context);
        StructuralAsgnErrorReport(statement,&value);
        STATEMENT_ERROR(statement, "Assignment is impossible");
        MarkStatContext(statement,context_WRONG);
        WSS(ASCERR,statement);
        return 1;
      }
    }else{
      /* good rhs value, but may be mismatched to set ATOM */
      len = gl_length(instances);
      for(c=1;c<=len;c++){
        inst = (struct Instance *)gl_fetch(instances,c);
        if (!AssignStructuralValue(inst,value,statement)) {
          MarkStatContext(statement,context_WRONG);
          STATEMENT_ERROR(statement, "Assignment is impossible (wrong set type)");
          WSS(ASCERR,statement);
        }
      }
      DestroyValue(&value);
      gl_destroy(instances);
      SetDeclarativeContext(previous_context);
      return 1;
    }
  }else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance:
      STATEMENT_ERROR(statement, "Left hand side of assignment statement"
            " contains an impossible instance");
      SetDeclarativeContext(previous_context);
      return 1;
    default:			/* unmade instances or something */
      SetDeclarativeContext(previous_context);
      return 0;
    }
  }
}

/*------------------------------------------------------------------------------
  CHECK ROUTINES
*/

/**
	Returns 1 if name can be found in name, or 0 OTHERWISE.
	only deals well with n and sub being Id names.
*/
static int NameContainsName(CONST struct Name *n,CONST struct Name *sub){
  struct gl_list_t *nl;
  unsigned long c,len;
  struct Expr *en;

  asc_assert(n!=NULL);
  asc_assert(sub!=NULL);
  en = ASC_NEW(struct Expr);
  InitVarExpr(en,n);
  nl = EvaluateNamesNeededShallow(en,NULL,NULL);
  /* should this function be checking deep instead? can't tell yet. */
  if (nl==NULL || gl_length(nl)==0) {
    return 0; /* should never happen */
  }
  for (c=1, len = gl_length(nl); c <= len; c++) {
    if (CompareNames((struct Name *)gl_fetch(nl,c),sub)==0) {
      gl_destroy(nl);
      return 1;
    }
  }
  gl_destroy(nl);
  ascfree(en);
  return 0;
}

/**
	Checks that the namelist, less any components that contain arrsetname,
	can be evaluated to constant values.
	Returns 1 if it can be evaluated.

	This is heuristic. It can fail in very very twisty circumstances.
	What saves the heuristic is that usually all the other conditions
	on the compound ALIASES (that rhs's must exist and so forth) will
	be satisfied before this check is performed and that that will mean
	enough structure to do the job at Execute time will be in place even
	if this returns a FALSE positive.

	Basically to trick this thing you have to do indirect addressing with
	the set elements of the IS_A set in declaring the lhs of the ALIASES
	part. Of course if you really do that sort of thing, you should be
	coding in C++ or F90 anyway.

	What it comes down to is that this array constructor from diverse
	elements really sucks -- but so does varargs and that's what we're
	using the compound alias array constructor to implement.

	There is an extremely expensive alternative that is not heuristic --
	create the IS_A set (which might be a sparse array) during the
	check process and blow it away when the check fails. This is an
	utter nuisance and a cost absurdity.
	--baa 1/97.
*/
static int ArrayCheckNameList(struct Instance *inst
	, struct Statement *statement, struct gl_list_t *nl
	, CONST struct Name *arrsetname
){
  unsigned long c,len,i,ilen;
  struct Instance *fi;
  CONST struct Name *n;
  struct gl_list_t *il;
  symchar *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  len = gl_length(nl);
  if (len==0) {
    return 1;
  }
  for (c=1; c <= len; c++) {
    n = (struct Name *)gl_fetch(nl,c);
    if (NameContainsName(n,arrsetname) == 0 ) {
      name = SimpleNameIdPtr(n);
      if (name !=NULL && StatInFOR(statement) &&
          FindForVar(GetEvaluationForTable(),name)!=NULL) {
        continue;
      }
      /* else hunt up the instances */
      il = FindInstances(inst,n,&err);
      if (il == NULL) {
        return 0;
      }
      for (i=1, ilen=gl_length(il); i <=ilen; i++) {
        fi = (struct Instance *)gl_fetch(il,i);
        switch(InstanceKind(fi)) {
        case SET_ATOM_INST:
        case INTEGER_CONSTANT_INST:
        case SYMBOL_CONSTANT_INST:
          if (AtomAssigned(fi)==0) {
            gl_destroy(il);
            return 0;
          }
          break;
        case MODEL_INST:
        case ARRAY_INT_INST:
        case ARRAY_ENUM_INST:
          /* ok, it was found. odd, that, but it might be ok */
          break;
        /* fundamental, variable, relation, when, logrel, realcon, boolcon
         * can none of them figure in the definition of valid set.
         * so we exit early and execution will fail as required.
         */
        default:
          gl_destroy(il);
          return 1;
        }
      }
    }
  }
  return 1;
}
/*
	check the subscripts for definedness, including FOR table checks and
	checks for the special name in the compound ALIASES-IS_A statement.
	Assumes it is going to be handed a name consisting entirely of
	subscripts.
*/
static int FailsCompoundArrayCheck(struct Instance *inst
	,CONST struct Name *name, struct Statement *statement
	,CONST struct Name *arrsetname
){
  struct gl_list_t *nl;
  CONST struct Set *sptr;
  int ok;

  while(name != NULL){
    /* foreach subscript */
    if (NameId(name)!=0){ /* what's a . doing in the name? */
      return 1;
    }
    sptr = NameSetPtr(name);
    nl = EvaluateSetNamesNeeded(sptr,NULL);
    if (nl !=  NULL) {
      ok = ArrayCheckNameList(inst,statement,nl,arrsetname);
      gl_destroy(nl);
      if (ok == 0 ) {
        return 1;
      }
    }else{
      return 1;
    }
    name = NextName(name);
  }
  return 0;
}

/**
	The name pointer is known to be an array, so now it is checked to make
	sure that each index type can be determined.
	It is not a . qualified name.

	With searchfor == 0:
	This routine deliberately lets some errors through because the will
	be trapped elsewhere.  Its *only* job is to detect undefined index
	types. (defined indices simply missing values will merely be done
	in a later array expansion.
	Returns 1 if set type indeterminate.

	With searchfor != 0:
	Tries to expand the indices completely and returns 1 if fails.
	arrset name is a special name that may be used in indices when
	creating compound ALIASES-IS_A -- it is the name the IS_A will create.
	It is only considered if searchfor != 0.
*/
static
int FailsIndexCheck(CONST struct Name *name, struct Statement *statement,
                    struct Instance *inst, CONST unsigned int searchfor,
                    CONST struct Name *arrsetname)
{
  CONST struct Set *sptr;
  struct gl_list_t *indices;
  if (!NameId(name)) {
     return 0;	/* this is a different type of error */
  }
  /* hunt the subscripts */
  name = NextName(name);
  if (name == NULL) {
    return 0;	/* this is a different type of error */
  }
  if (searchfor == 0) { /* not in FOR loop and not ALIASES of either sort */
    while (name != NULL){
      if (NameId(name) !=0 ) {
        /* what's a . doing here? */
        return 0;
      }
      sptr = NameSetPtr(name);
      if (DeriveSetType(sptr,inst,0) < 0) {
        return 1; /* confusion reigns */
      }
      name = NextName(name);
    }
  }else{
    asc_assert(statement!=NULL);
    if (arrsetname == NULL) {
      /* sparse IS_A or ALIASES but not ALIASES/IS_A */
      indices = MakeIndices(inst,name,statement);
      if (indices != NULL) {
        DestroyIndexList(indices);
        return 0;
      }else{
        return 1;
      }
    }else{
      /* sparse or dense ALIASES-IS_A where we have to handle a
       * special name we
       * can't tell the value of yet because the IS_A hasn't been
       * compiled.
       */
      return FailsCompoundArrayCheck(inst,name,statement,arrsetname);
    }
  }
  return 0;
}

/**
	This has to check this member of the variable list for unknown
	array indices.  It returns TRUE iff it contains an unknown index;
	otherwise, it returns FALSE.
	If searchfor !=0, include for indices in list of valid things,
	and insist that values actually have been assigned as well.
*/
static
int ContainsUnknownArrayIndex(struct Instance *inst,
                              struct Statement *stat,
                              CONST struct Name *name,
                              CONST unsigned int searchfor,
                              CONST struct Name *arrsetname)
{
  if (!SimpleNameIdPtr(name)){ /* simple names never miss indices */
    if (FailsIndexCheck(name,stat,inst,searchfor,arrsetname)) return 1;
  }
  return 0;
}

/**
	If there are no array instances, this should always return TRUE.  When
	there are array instances to be created, it has to check to make sure
	that all of the index types can be determined and their values are
	defined!

	aliases always appears to be in for loop because we must always have
	a definition of all the sets because an alias array can't be finished
	up later.
*/
static int CheckALIASES(struct Instance *inst, struct Statement *stat){
  CONST struct VariableList *vlist;
  int cu;
  struct gl_list_t *rhslist;
  CONST struct Name *name;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  vlist = GetStatVarList(stat);
  while (vlist != NULL){
    cu = ContainsUnknownArrayIndex(inst,stat,NamePointer(vlist),1,NULL);
    if (cu) {
      return 0;
    }
    vlist = NextVariableNode(vlist);
  }

  /*
   * Checking the existence of the rhs in the aliases statement
   */
  name = AliasStatName(stat);
  rhslist = FindInstances(inst,name,&err);
  if (rhslist == NULL) {
    WriteUnexecutedMessage(ASCERR,stat,
      "Possibly undefined right hand side in ALIASES statement.");
    return 0; /* rhs not compiled yet */
  }
  if (gl_length(rhslist)>1) {
    STATEMENT_ERROR(stat,"ALIASES needs exactly 1 RHS");
  }
  gl_destroy(rhslist);

  return 1;
}

/**
	This has to make sure the RHS list of the ALIASES and the WITH_VALUE
	of the IS_A are both satisfied.

	When the statement is in a FOR loop, this has to check to make sure
	that all of the LHS index types can be determined and their values are
	defined!
	ALIASES always appears to be in for loop because we must always have
	a definition of all the sets because an alias array can't be finished
	up later.
*/
static int CheckARR(struct Instance *inst, struct Statement *stat){
  CONST struct VariableList *vlist;
  struct value_t value;
  int cu;

  asc_assert(StatementType(stat)==ARR);

  /* check subscripts on IS_A portion lhs. all mess should be in fortable */
  cu = ContainsUnknownArrayIndex(inst,
                                 stat,
                                 NamePointer( ArrayStatSetName(stat)),
                                 1,
                                 NULL);
  if(cu != 0){
    return 0;
  }
  /* check ALIASES portion lhs list */
  vlist = ArrayStatAvlNames(stat);
  while(vlist != NULL){
    cu = ContainsUnknownArrayIndex(inst,
                                   stat,
                                   NamePointer(vlist),
                                   1,
                                   NamePointer(ArrayStatSetName(stat)));
    if(cu != 0){
      return 0;
    }
    vlist = NextVariableNode(vlist);
  }
  /* check ALIASES portion rhs (list of instances collecting to an array) */
  if(CheckVarList(inst,stat)==0){
    return 0;
  }
  /* check IS_A WITH_VALUE list */
  if(ArrayStatSetValues(stat)!=NULL){
    asc_assert(GetEvaluationContext()==NULL);
    SetEvaluationContext(inst);
    value = EvaluateSet(ArrayStatSetValues(stat),InstanceEvaluateName);
    SetEvaluationContext(NULL);
    switch(ValueKind(value)){
    case list_value:
      /* set may be garbage, in which case execute will whine */
      break;
    case error_value:
      switch(ErrorValue(value)){
      case name_unfound:
      case undefined_value:
        DestroyValue(&value);
        return 0;
      default:
        instantiation_error(ASC_USER_ERROR,stat
			,"Compound alias instance has incorrect index type.\n"
		);
        break;
      }
      break;
    default:
      instantiation_error(ASC_USER_ERROR,stat
			,"Compound alias instance has incorrect index value type."
	  );
      break;
    }
    DestroyValue(&value);
  }
  return 1;
}

/**
	If there are no array instances, this should always return TRUE.  When
	there are array instances to be created, it has to check to make sure
	that all of the index types can be determined.
	If statement requires type args, also checks that all array indices
	can be evaluated.

	Currently, this can handle checking for completable sets in any
	statement's var list, not just ISAs.

	It does not at present check arguments of IS_A's.
*/
static int CheckISA(struct Instance *inst, struct Statement *stat){
  CONST struct VariableList *vlist;
  int cu;
  unsigned int searchfor;
  if (StatWrong(stat)) return 1; /* if we'll never execute it, it's ok */
  searchfor = ( StatInFOR(stat)!=0 ||
                GetStatNeedsArgs(stat) > 0 ||
                StatModelParameter(stat)!=0 );
  vlist = GetStatVarList(stat);
  while(vlist != NULL){
    cu =
      ContainsUnknownArrayIndex(inst,stat,NamePointer(vlist),searchfor,NULL);
    if(cu){
      return 0;
    }
    vlist = NextVariableNode(vlist);
  }
  return 1;
}

/**
	checks that all the names in a varlist exist as instances.
	returns 1 if TRUE, 0 if not.
*/
static int CheckVarList(struct Instance *inst, struct Statement *statement){
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  int instances;
  instances = VerifyInsts(inst,GetStatVarList(statement),&err);
  if(instances){
    return 1;
  }else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance: return 1;
    default: return 0;
    }
  }
}

static int CheckIRT(struct Instance *inst, struct Statement *statement){
  if (FindType(GetStatType(statement))==NULL) return 1;
  return CheckVarList(inst,statement);
}

static int CheckATS(struct Instance *inst, struct Statement *statement){
  return CheckVarList(inst,statement);
}

static int CheckAA(struct Instance *inst, struct Statement *statement){
  return CheckVarList(inst,statement);
}

static int CheckLNK(struct Instance *inst, struct Statement *statement){
  return CheckVarList(inst,statement);
}

/**
	Checks that the lhs of an assignment statement expands into
	a complete set of instances.
	Not check that the first of those instances is type compatible with
	the value being assigned.
*/
static int CheckCASGN(struct Instance *inst, struct Statement *statement){
  struct gl_list_t *instances;
  struct value_t value;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  instances = FindInstances(inst,AssignStatVar(statement),&err);
  if (instances != NULL){
    gl_destroy(instances);
    asc_assert(GetEvaluationContext()==NULL);
    SetEvaluationContext(inst);
    value = EvaluateExpr(AssignStatRHS(statement),NULL,
                         InstanceEvaluateName);
    SetEvaluationContext(NULL);
    if (ValueKind(value)==error_value){
      switch(ErrorValue(value)){
      case undefined_value:
      case name_unfound:
        DestroyValue(&value);
        return 0;
      default: /* it is a question whether this is a correct action */
        break; /* should we handle other error classes? */
      }
    }
    DestroyValue(&value);
    return 1; /* everything is okay */
  }else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance: return 1;
    default:
      return 0;
    }
  }
}

#ifdef THIS_IS_AN_UNUSED_FUNCTION
static
int CheckASGN(struct Instance *inst, struct Statement *statement)
{
  struct gl_list_t *instances;
  struct value_t value;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  instances = FindInstances(inst,DefaultStatVar(statement),&err);
  if (instances != NULL){
    gl_destroy(instances);
    asc_assert(GetEvaluationContext()==NULL);
    SetEvaluationContext(inst);
    value = EvaluateExpr(DefaultStatRHS(statement),NULL,
                         InstanceEvaluateName);
    SetEvaluationContext(NULL);
    if (ValueKind(value)==error_value){
      switch(ErrorValue(value)){
      case undefined_value:
      case name_unfound:
        DestroyValue(&value);
        return 0;
      default: /* it is a question whether this is a correct action */
        break; /* should we handle other error classes? */
      }
    }
    DestroyValue(&value);
    return 1;			/* everything is okay */
  }
  else{
    switch(rel_errorlist_get_find_error(&err)){
    case impossible_instance: return 1;
    default:
      return 0;
    }
  }
}
#endif   /* THIS_IS_AN_UNUSED_FUNCTION */


/**
	Check if the relation exists, also, if it exists as relation or as a
	dummy instance. return -1 for DUMMY. 1 for relation. 0 if the checking
	fails.
*/
static int CheckRelName(struct Instance *work, struct Name *name){
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  instances = FindInstances(work,name,&err);
  if(instances==NULL){
    return 1;
  }else{
    if (gl_length(instances)==1){
      inst = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(inst)==REL_INST) || (InstanceKind(inst)==DUMMY_INST));
      gl_destroy(instances);
      if (InstanceKind(inst)==DUMMY_INST) {
        return -1;
      }
      return 1;
    }else{
      gl_destroy(instances);
      return 0;
    }
  }
}

/*
 * If the relation is already there, it may be a dummy instance. In
 * such a case, do not check the expression.
 */
static int CheckREL(struct Instance *inst, struct Statement *statement){
  int status;
  status = CheckRelName(inst,RelationStatName(statement));
  if (status == 0) {
    return 0;
  }
  if ( status == -1) {
    return 1;
  }
  return CheckRelation(inst,RelationStatExpr(statement));
}
/*
 * If the external relation is already there,
 * it may be a dummy instance. In
 * such a case, do not check the args.
 */
static int CheckEXT(struct Instance *inst, struct Statement *statement){
  int status;
  status = CheckRelName(inst,ExternalStatNameRelation(statement));
  if (status == 0) {
    return 0;
  }
  if ( status == -1) {
    return 1;
  }
  return CheckExternal(inst,
                       ExternalStatVlistRelation(statement),
                       ExternalStatDataBlackBox(statement));
}

/***********************************************************************/

/* Check that the logical relation instance of some name has not been
 * previously created, or if it has, the instance is unique and
 * corresponds to a logical relation or to a dummy.
 * return -1 for DUMMY. 1 for log relation. 0 if the checking fails.
 */
static int CheckLogRelName(struct Instance *work, struct Name *name){
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  instances = FindInstances(work,name,&err);
  if (instances==NULL){
    return 1;
  }else{
    if (gl_length(instances)==1){
      inst = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(inst)==LREL_INST) || (InstanceKind(inst)==DUMMY_INST));
      gl_destroy(instances);
      if (InstanceKind(inst)==DUMMY_INST) {
        return -1;
      }
      return 1;
    }else {
      gl_destroy(instances);
      return 0;
    }
  }
}

/**
	Checking of Logical relation. First the name, then the expression.
	If the logrel exists as a dummy, then do not check the expression.
	Currently not in use.
*/
static int CheckLOGREL(struct Instance *inst, struct Statement *statement){
  if (!CheckLogRelName(inst,LogicalRelStatName(statement)))
    return 0;
  if ( CheckLogRelName(inst,LogicalRelStatName(statement)) == -1)
    return 1;
  return CheckLogRel(inst,LogicalRelStatExpr(statement));
}


/**
	Checking FNAME statement (1)

	["The following two functions..." -- ed] Check that the FNAME inside a WHEN
	make reference to instance of models, relations, or arrays of
	models or relations previously created.
*/
static int CheckArrayRelMod(struct Instance *child){
  struct Instance *arraychild;
  unsigned long len,c;
  switch (InstanceKind(child)) {
    case REL_INST:
    case LREL_INST:
    case MODEL_INST:
      return 1;
    case ARRAY_INT_INST:
    case ARRAY_ENUM_INST:
      len = NumberChildren(child);
      for(c=1;c<=len;c++){
        arraychild = InstanceChild(child,c);
        if (!CheckArrayRelMod(arraychild)){
          return 0;
        }
      }
      return 1;
    default:
      FPRINTF(ASCERR,
      "Incorrect array instance name inside a WHEN statement\n");
      return 0;
  }
}

/**
	Checking FNAME statement (2)

	Check that the FNAME inside a WHEN
	make reference to instance of models, relations, or arrays of
	models or relations previously created.
*/
static int CheckRelModName(struct Instance *work, struct Name *name){
  struct gl_list_t *instances;
  struct Instance *inst, *child;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  unsigned long len,c;
  instances = FindInstances(work,name,&err);
  if (instances==NULL){
    instantiation_name_error(ASC_USER_ERROR,name,
		"Un-made Relation/Model instance inside a 'WHEN':"
	);
    gl_destroy(instances);
    return 0;
  }else{
    if (gl_length(instances)==1){
     inst = (struct Instance *)gl_fetch(instances,1);
     switch (InstanceKind(inst)) {
     case REL_INST:
     case LREL_INST:
     case MODEL_INST:
       gl_destroy(instances);
       return 1;
     case ARRAY_INT_INST:
     case ARRAY_ENUM_INST:
      len = NumberChildren(inst);
      for(c=1;c<=len;c++){
        child = InstanceChild(inst,c);
        if (!CheckArrayRelMod(child)){
          gl_destroy(instances);
          return 0;
        }
      }
      gl_destroy(instances);
      return 1;
     default:
       instantiation_name_error(ASC_USER_ERROR,name
			,"Incorrect instance name (no Model/Relation) inside 'WHEN'"
	   );
       gl_destroy(instances);
       return 0;
     }
    }else{
    instantiation_name_error(ASC_USER_ERROR,name
		,"Error in 'WHEN'. Name assigned to more than one instance type"
	);
    gl_destroy(instances);
    return 0;
    }
  }
}

/**
	A FNAME statement stands for a relation, model, or an array of models
	or relations. This checking is to make sure that those instance
	were already created
*/
static int CheckFNAME(struct Instance *inst, struct Statement *statement){
  if(!CheckRelModName(inst,FnameStat(statement))){
    return 0;
  }else{
    return 1;
  }
}

/**
	Only logrelations and FOR loops of logrelations are allowed inside a
	conditional statement in Pass3. This function ask for recursively
	checking these statements
*/
static int Pass3CheckCondStatements(struct Instance *inst
	, struct Statement *statement
){
  asc_assert(inst&&statement);
  switch(StatementType(statement)){
    case LOGREL:
      return CheckLOGREL(inst,statement);
    case FOR:
      return Pass3RealCheckFOR(inst,statement);
    case REL:
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case LNK:
    case UNLNK:
    case CALL:
    case EXT:
    case ASGN:
    case CASGN:
    case COND:
    case WHEN:
    case FNAME:
    case SELECT:
      STATEMENT_ERROR(statement,
        "Statement not allowed inside a CONDITIONAL statement\n");
      return 0;
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      return 1;
    }
}

/**
	Checking the statement list inside a CONDITIONAL statement in Pass3
*/
static int Pass3CheckCOND(struct Instance *inst, struct Statement *statement){
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
     stat = (struct Statement *)gl_fetch(list,c);
     if (!Pass3CheckCondStatements(inst,stat)) return 0;
  }
  return 1;
}


/**
	Only relations and FOR loops of relations are allowed inside a
	conditional statement in Pass2. This function ask for recursively
	checking these statements
*/
static int Pass2CheckCondStatements(struct Instance *inst
	,struct Statement *statement
){
  asc_assert(inst&&statement);
  switch(StatementType(statement)){
    case REL:
      return CheckREL(inst,statement);
    case EXT:
      return CheckEXT(inst,statement);
    case FOR:
      return Pass2RealCheckFOR(inst,statement);
    case LOGREL:
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case LNK:
    case UNLNK:
    case CALL:
    case ASGN:
    case CASGN:
    case COND:
    case WHEN:
    case FNAME:
    case SELECT:
         STATEMENT_ERROR(statement,
               "Statement not allowed inside a CONDITIONAL statement\n");
         return 0;
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      return 1;
    }
}

/**
	Checking the statement list inside a CONDITIONAL statement in Pass2
*/
static int Pass2CheckCOND(struct Instance *inst, struct Statement *statement){
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
     stat = (struct Statement *)gl_fetch(list,c);
     if (!Pass2CheckCondStatements(inst,stat)) return 0;
  }
  return 1;
}

/**
	Checking that not other instance has been created with the same
	name of the current WHEN. If it has, it has to be a WHEN or a
	DUMMY. return -1 for DUMMY. 1 for WHEN. 0 if the checking fails.
*/
static int CheckWhenName(struct Instance *work, struct Name *name){
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  instances = FindInstances(work,name,&err);
  if (instances==NULL){
    return 1;
  }else{
    if (gl_length(instances)==1){
      inst = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(inst)==WHEN_INST)||(InstanceKind(inst)==DUMMY_INST) );
      gl_destroy(instances);
      if (InstanceKind(inst)==DUMMY_INST) {
        return -1;
      }
      return 1;
    }else {
      gl_destroy(instances);
      return 0;
    }
  }
}

/**
	p1 and p2 are pointers to arrays of integers. Here we are checking
	that the type (integer, boolean, symbol) of each variable in the
	variable list of a WHEN (or a SELECT) is the same as the type of
	each value in the list of values a CASE
*/
static int CompListInArray(unsigned long numvar, int *p1, int *p2){
  unsigned long c;
  for (c=1;c<=numvar;c++) {
    if (*p2 != 3) { /* To account for ANY */
      if (*p1 != *p2) return 0;
    }
    if (c < numvar) {
      p1++;
      p2++;
    }
  }
  return 1;
}


/**
	Checking that the values of the set of values of each CASE of a
	WHEN statement are appropriate. This is, they
	are symbol, integer or boolean. The first part of the
	function was written for the case of WHEN statement
	inside a FOR loop. This function also sorts
	the kinds of values in the set by assigning a value
	to the integer *p2
*/
static int CheckWhenSetNode(struct Instance *ref
	,CONST struct Expr *expr, int *p2
){
  symchar *str;
  struct for_var_t *fvp;
  struct Set *set;
  CONST struct Expr *es;
  switch (ExprType(expr)) {
  case e_boolean:
    if (ExprBValue(expr)==2) {
      *p2 = 3;  /*  ANY */
    }else{
      *p2=1;
    }
    return 1;
  case e_int:
    *p2=0;
    return 1;
  case e_symbol:
    *p2=2;
    return 1;
  case e_var:
    if ((GetEvaluationForTable() != NULL) &&
        (NULL != (str = SimpleNameIdPtr(ExprName(expr)))) &&
        (NULL != (fvp=FindForVar(GetEvaluationForTable(),str)))) {
      if (GetForKind(fvp)==f_integer){
        *p2=0;
        return 1;
      }else{
        if (GetForKind(fvp)==f_symbol){
          *p2=2;
          return 1;
        }else{
	  	  instantiation_name_error(ASC_USER_ERROR,ExprName(expr)
			,"Inappropriate index in the list of values of a CASE in a 'WHEN'\n"
			"(only symbols or integers are allowed)"
		  );
	  return 0;
	}
      }
    }else{
		instantiation_name_error(ASC_USER_ERROR,ExprName(expr),
			"Inappropriate value type in the list of values of a CASE of a 'WHEN'\n"
			"(index has not been created)"
		);
        return 0;
    }
  case e_set:
    set = expr->v.s;
    if (set->range) {
      return 0;
    }
    es = GetSingleExpr(set);
    return CheckWhenSetNode(ref,es,p2);
  default:
    FPRINTF(ASCERR,"Innapropriate value type in the list of %s\n",
	    "values of a CASE of a WHEN statement");
    FPRINTF(ASCERR,"Only symbols or integers and booleans are allowed\n");
    return 0;
  }
}


/**
	Checking that the variables of the list of variables of a
	WHEN statement are appropriate. This is, they
	are boolean, integer or symbol instances. The first part of the
	function was written for the case of WHEN statement
	inside a FOR loop. This function also sorts
	the kinds of variables in the list by assigning a value
	to the integer *p1
*/
static int CheckWhenVariableNode(struct Instance *ref
	, CONST struct Name *name, int *p1
){
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  symchar *str;
  struct for_var_t *fvp;
  str = SimpleNameIdPtr(name);
  if(str!=NULL &&
      GetEvaluationForTable()!=NULL &&
      (fvp=FindForVar(GetEvaluationForTable(),str))!=NULL) {
    switch (GetForKind(fvp)) {
    case f_integer:
      *p1=0;
      return 1;
    case f_symbol:
      *p1=2;
      return 1;
    default:
      FPRINTF(ASCERR,"Innapropriate index in the list of %s\n",
	      "variables of a WHEN statement");
      FPRINTF(ASCERR,"only symbol or integer allowed\n");
      return 0;
    }
  }
  instances = FindInstances(ref,name,&err);
  if (instances == NULL){
    switch(rel_errorlist_get_find_error(&err)){
    case unmade_instance:
    case undefined_instance:
      FPRINTF(ASCERR,"Unmade instance in the list of %s\n",
	      "variables of a WHEN statement");
      WriteName(ASCERR,name);
      return 0;
    default:
      FPRINTF(ASCERR,"Unmade instance in the list of %s\n",
	      "variables of a WHEN statement");
      WriteName(ASCERR,name);
      return 0;
    }
  }else{
    if (gl_length(instances)==1) {
      inst = (struct Instance *)gl_fetch(instances,1);
      gl_destroy(instances);
      switch(InstanceKind(inst)){
      case BOOLEAN_ATOM_INST:
        *p1=1;
        return 1;
      case BOOLEAN_CONSTANT_INST:
        if (AtomAssigned(inst)) {
          *p1=1;
          return 1;
        }else{
          FPRINTF(ASCERR,"Undefined constant in the list of %s\n",
	          "variables of a WHEN statement");
          WriteName(ASCERR,name);
          return 0;
        }
      case INTEGER_ATOM_INST:
        *p1=0;
        return 1;
      case INTEGER_CONSTANT_INST:
        if (AtomAssigned(inst)) {
           *p1=0;
           return 1;
        }else{
          FPRINTF(ASCERR,"Undefined constant in the list of %s\n",
	          "variables of a WHEN statement");
          WriteName(ASCERR,name);
          return 0;
        }
      case SYMBOL_ATOM_INST:
        *p1=2;
        return 1;
      case SYMBOL_CONSTANT_INST:
        if (AtomAssigned(inst)) {
          *p1=2;
          return 1;
        }else{
          FPRINTF(ASCERR,"Undefined constant in the list of %s\n",
	          "variables of a WHEN statement");
          WriteName(ASCERR,name);
          return 0;
        }
      default:
        FPRINTF(ASCERR,"Inappropriate instance in the list of %s\n",
		"variables of a WHEN statement");
        FPRINTF(ASCERR,"Only boolean, integer and symbols are allowed\n");
        WriteName(ASCERR,name);
        return 0;
      }
    }else{
      gl_destroy(instances);
      FPRINTF(ASCERR,"Inappropriate instance in the list of %s\n",
	      "variables of a WHEN statement");
      FPRINTF(ASCERR,"Multiple instances of\n");
      WriteName(ASCERR,name);
      return 0;
    }
  }
}


/**
	Inside a WHEN, only FNAMEs (name of models, relations or array of)
	and nested WHENs ( and FOR loops of them) are allowed. This function
	asks for the checking of these statements.
*/
static
int CheckWhenStatements(struct Instance *inst, struct Statement *statement){
  asc_assert(inst&&statement);
  switch(StatementType(statement)){
    case WHEN:
      return CheckWHEN(inst,statement);
    case FNAME:
      return CheckFNAME(inst,statement);
    case FOR:
      return Pass4RealCheckFOR(inst,statement);
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case LNK:
    case UNLNK:
    case REL:
    case LOGREL:
    case EXT:
    case CALL:
    case ASGN:
    case SELECT:
         STATEMENT_ERROR(statement,
              "Statement not allowed inside a WHEN statement\n");
         return 0;
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      return 1;
    }
}

/**
	Call CheckWhenSetNode for each value in the set of values included
	in the CASE of a WHEN statement
*/
static
int CheckWhenSetList(struct Instance *inst, struct Set *s, int *p2)
{
  struct Set *set;
  CONST struct  Expr *expr;
  set = s;
  while (set!=NULL) {
    expr = GetSingleExpr(set);
    if (!CheckWhenSetNode(inst,expr,p2)) return 0;
    set = NextSet(set);
    p2++;
  }
  return 1;
}

/**
	Call CheckWhenVariableNode for each variable vl in the variable
	list of a WHEN statement
*/
static
int CheckWhenVariableList(struct Instance *inst, struct VariableList *vlist,
                          int *p1)
{
  CONST struct Name *name;
  CONST struct VariableList *vl;
  vl = vlist;
  while (vl!=NULL) {
    name = NamePointer(vl);
    if (!CheckWhenVariableNode(inst,name,p1)) return 0;
    vl = NextVariableNode(vl);
    p1++;
  }
  return 1;
}

/**
	Checking the list statements of statements inside each CASE of the
	WHEN statement by calling CheckWhenStatements
*/
static
int CheckWhenStatementList(struct Instance *inst, struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  struct gl_list_t *list;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
     statement = (struct Statement *)gl_fetch(list,c);
     if (!CheckWhenStatements(inst,statement)) return 0;
  }
  return 1;
}


/**
	Checking of the Select statements. It checks that:
	1) The name of the WHEN. If it was already created. It has to be
	   a WHEN or a DUMMY. If a Dummy (case -1 of CheckWhenName),
	   do not check the structure of the WHEN statement, return 1.
	2) The number of conditional variables is equal to the number
	   of values in each of the CASEs.
	3) That the conditional variables exist, and are boolean
	   integer or symbol.
	4) The number and the type  of conditional variables is the same
	   as the number of values in each of the CASEs.
	5) Only one OTHERWISE case is present.
	6) The statements inside a WHEN are only a FNAME or a nested WHEN,
	   and ask for the chcking of these interior statements.
*/
static
int CheckWHEN(struct Instance *inst, struct Statement *statement)
{
  struct Name *wname;
  struct VariableList *vlist;
  struct WhenList *w1;
  struct Set *s;
  struct StatementList *sl;
  unsigned long numother;
  unsigned long numvar;
  unsigned long numset;
  int vl[MAX_VAR_IN_LIST],*p1;
  int casel[MAX_VAR_IN_LIST],*p2;
  wname = WhenStatName(statement);
  if (wname!=NULL) {
    if (!CheckWhenName(inst,wname)) {
    FPRINTF(ASCERR,"Name of a WHEN already exits in\n");
    WriteInstanceName(ASCERR,inst,NULL);
    STATEMENT_ERROR(statement,"The following statement will not be executed: \n");
      return 0;
    }
    if ( CheckWhenName(inst,wname) == -1) return 1;
  }
  vlist = WhenStatVL(statement);
  numvar = VariableListLength(vlist);
  asc_assert(numvar<=MAX_VAR_IN_LIST);
  p1 = &vl[0];
  p2 = &casel[0];
  numother=0;
  if (!CheckWhenVariableList(inst,vlist,p1)) {
    FPRINTF(ASCERR,"In ");
    WriteInstanceName(ASCERR,inst,NULL);
    STATEMENT_ERROR(statement," the following statement will not be executed:\n");
    return 0;
  }
  w1 = WhenStatCases(statement);
  while (w1!=NULL){
      s = WhenSetList(w1);
      if (s!=NULL) {
          numset = SetLength(s);
          if (numvar != numset) {
            FPRINTF(ASCERR,"Number of variables different from %s\n",
		    "number of values in a CASE");
            FPRINTF(ASCERR,"In ");
            WriteInstanceName(ASCERR,inst,NULL);
            STATEMENT_ERROR(statement,
		 " the following statement will not be executed: \n");
	    return 0;
	  }
          if (!CheckWhenSetList(inst,s,p2)) {
            FPRINTF(ASCERR,"In ");
            WriteInstanceName(ASCERR,inst,NULL);
            STATEMENT_ERROR(statement,
		 " the following statement will not be executed: \n");
	    return 0;
	  }
          p1 = &vl[0];
          p2 = &casel[0];
          if (!CompListInArray(numvar,p1,p2)) {
            FPRINTF(ASCERR,"Type of variables different from type %s\n",
		    "of values in a CASE");
            FPRINTF(ASCERR,"In ");
            WriteInstanceName(ASCERR,inst,NULL);
            STATEMENT_ERROR(statement,
		 " the following statement will not be executed: \n");
	    return 0;
	  }
      }else{
          numother++;
          if (numother>1) {
            FPRINTF(ASCERR,"More than one default case in a WHEN\n");
            FPRINTF(ASCERR,"In ");
            WriteInstanceName(ASCERR,inst,NULL);
            STATEMENT_ERROR(statement,
		 " the following statement will not be executed: \n");
	    return 0;
	  }
      }
      sl = WhenStatementList(w1);
      if (!CheckWhenStatementList(inst,sl)) {
        FPRINTF(ASCERR,"In ");
        WriteInstanceName(ASCERR,inst,NULL);
        STATEMENT_ERROR(statement,
	     " the following statement will not be executed: \n");
	return 0;
      }
      w1 = NextWhenCase(w1); }
  return 1;
}


/* - - - - - - - - - - - - -
	Check SELECT Functions
*/

#ifdef THIS_IS_AN_UNUSED_FUNCTION
/**
	Code curently not in use. It would be used in case that we want to do
	the checking of all of the statement list in all of the cases of a
	SELECT simultaneously, previous to execution.
	Actually, the code is in disrepair, particularly around what is
	allowed in SELECT. We surely need to create a CheckSelectStatement
	function specific for each pass of instantiation.
*/
static
int CheckSelectStatements(struct Instance *inst, struct Statement *statement)
{
  asc_assert(inst&&statement);
  switch(StatementType(statement)){
  case ALIASES:
  case ISA:
  case IRT:
  case ATS:
  case AA:
  case LNK:
  case UNLNK:
  case ARR:
    return 1;
  case FOR:
    return Pass1RealCheckFOR(inst,statement);
  case ASGN:
    return CheckASGN(inst,statement);
  case CASGN:
    return CheckCASGN(inst,statement);
  case SELECT:
    return CheckSELECT(inst,statement);
  case REL: /* not broken. equations disallowed. */
  case LOGREL:
  case EXT:
  case CALL:
  case WHEN:
  case FNAME:
    if (g_iteration>=MAXNUMBER) { /* see WriteUnexecutedMessage */
       STATEMENT_ERROR(statement,
              "Statement not allowed inside a SELECT statement\n"); }
    /** AND WHY NOT? fix me. **/
    return 0;
  default:
    STATEMENT_ERROR(statement,"Inappropriate statement type");
	ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    return 1;
  }
}
#endif  /*  THIS_IS_AN_UNUSED_FUNCTION  */


#ifdef THIS_IS_AN_UNUSED_FUNCTION
/**
	Currently not in use
*/
static
int CheckSelectStatementList(struct Instance *inst, struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  struct gl_list_t *list;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    if (!CheckSelectStatements(inst,statement)) return 0;
  }
  return 1;
}
#endif  /* THIS_IS_AN_UNUSED_FUNCTION */


/**
	Current checking of the Select statement starts here.

	Checking that the values of the set of values of each CASE of a
	SELECT statement are appropriate. This is, they
	are symbol, integer or boolean. The first part of the
	function was written for the case of SELECT statement
	inside a FOR loop. Therefore, it is going to be there,
	but not used at the moment.This function also sorts
	the kinds of values in the set by assigning a value
	to the integer *p2
*/
static
int CheckSelectSetNode(struct Instance *ref, CONST struct Expr *expr,
                       int *p2 )
{
  symchar *str;
  struct for_var_t *fvp;
  struct Set *set;
  CONST struct Expr *es;
  switch (ExprType(expr)) {
    case e_boolean:
      if (ExprBValue(expr)==2) {
       *p2 = 3;  /*  ANY */
      }else{
       *p2=1;
      }
       return 1;
    case e_int:
       *p2=0;
       return 1;
    case e_symbol:
       *p2=2;
       return 1;
    case e_var:
      if ((NULL != GetEvaluationForTable()) &&
          (NULL != (str = SimpleNameIdPtr(ExprName(expr)))) &&
          (NULL != (fvp=FindForVar(GetEvaluationForTable(),str)))) {
        if (GetForKind(fvp)==f_integer){
          *p2=0;
          return 1;
        }else{
          if(GetForKind(fvp)==f_symbol){
            *p2=2;
            return 1;
          }
          return 0;
        }
      }else{
        return 0;
      }
    case e_set:
      set = expr->v.s;
      if (set->range) {
        return 0;
      }
      es = GetSingleExpr(set);
      return CheckSelectSetNode(ref,es,p2);
    default:
       return 0;
  }
}

/**
	Checking that the variables of the list of variables of a
	SELECT statement are appropriate. This is, they
	are constant and are assigned. The first part of the
	function was written for the case of SELECT statement
	inside a FOR loop. Therefore, it is going to be there,
	but not used at the moment.This function also sorts
	the kinds of variables in the list by assigning a value
	to the integer *p1
*/
static
int CheckSelectVariableNode(struct Instance *ref,
                            CONST struct Name *name,
                            int *p1)
{
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  symchar *str;
  struct for_var_t *fvp;

  str = SimpleNameIdPtr(name);
  if( str!=NULL &&
      GetEvaluationForTable() != NULL &&
      (fvp=FindForVar(GetEvaluationForTable(),str))!=NULL) {

    switch (GetForKind(fvp)) {
    case f_integer:
      *p1=0;
      return 1;
    case f_symbol:
      *p1=2;
      return 1;
    default:
      return 0;
    }
  }

  instances = FindInstances(ref,name,&err);
  if (instances == NULL){
    switch(rel_errorlist_get_find_error(&err)){
    case unmade_instance:
    case undefined_instance: return 0;
    default:
      return 0;
    }
  }else{
    if (gl_length(instances)==1) {
      inst = (struct Instance *)gl_fetch(instances,1);
      gl_destroy(instances);
      switch(InstanceKind(inst)){
        case BOOLEAN_CONSTANT_INST:
          if (AtomAssigned(inst)) {
            *p1 = 1;
            return 1;
          }else{
            return 0;
          }
        case INTEGER_CONSTANT_INST:
          if (AtomAssigned(inst)) {
            *p1 = 0;
            return 1;
          }else{
            return 0;
          }
        case SYMBOL_CONSTANT_INST:
          if (AtomAssigned(inst)) {
            *p1 = 2;
            return 1;
          }else{
            return 0;
          }
        default:
          return 0;
      }
    }else{
      gl_destroy(instances);
      return 0;
    }
  }
}

/**
	Call CheckSelectSetNode for each set member of the set of
	values of each CASE of a SELECT statement
*/
static
int CheckSelectSetList(struct Instance *inst, struct Set *s, int *p2 )
{
  struct Set *set;
  CONST struct  Expr *expr;
  set = s;
  while (set!=NULL) {
    expr = GetSingleExpr(set);
    if (!CheckSelectSetNode(inst,expr,p2)) return 0;
    set = NextSet(set);
    p2++;
  }
  return 1;
}

/**
	Call CheckSelectVariableNode for each variable vl in the variable
	list of a SELECT statement
*/
static
int CheckSelectVariableList(struct Instance *inst, struct VariableList *vlist,
                            int *p1)
{
  CONST struct Name *name;
  CONST struct VariableList *vl;
  vl = vlist;
  while (vl!=NULL) {
    name = NamePointer(vl);
    if (!CheckSelectVariableNode(inst,name,p1)) return 0;
    vl = NextVariableNode(vl);
    p1++;
  }
  return 1;
}


/**
	The conditions for checkselect is that
	1) The number of selection variables is equal to the number
	   of values in each of the CASEs.
	2) That the selection variables exist, are constant and
	   are assigned.
	3) Only one OTHERWISE case is present.
*/
static
int CheckSELECT(struct Instance *inst, struct Statement *statement)
{
  struct VariableList *vlist;
  struct SelectList *sel1;
  struct Set *set;
  unsigned long numother;
  unsigned long numsvar;
  unsigned long numsset;
  int vl[MAX_VAR_IN_LIST], *p1;
  int casel[MAX_VAR_IN_LIST], *p2;

  vlist = SelectStatVL(statement);
  numsvar = VariableListLength(vlist);
  asc_assert(numsvar<=MAX_VAR_IN_LIST);
  p1 = &vl[0];
  p2 = &casel[0];
  numother = 0;

  if (!CheckSelectVariableList(inst,vlist,p1)) return 0;
  sel1 = SelectStatCases(statement);
  while (sel1!=NULL){
    set = SelectSetList(sel1);
    if (set!=NULL) {
      numsset = SetLength(set);
      if (numsvar != numsset) return 0;
      if (!CheckSelectSetList(inst,set,p2)) return 0;
      p1 = &vl[0];
      p2 = &casel[0];
      if (!CompListInArray(numsvar,p1,p2)) return 0;
    }else{
      numother++;
      if (numother>1) return 0;
    }
    sel1 = NextSelectCase(sel1);
  }
  return 1;
}


/*==============================================================================
	PASS-BY-PASS CHECKING
*/


static
int Pass4CheckStatement(struct Instance *inst, struct Statement *stat)
{
  asc_assert(stat&&inst);
  switch(StatementType(stat)){
  case WHEN:
    return CheckWHEN(inst,stat);
  case FNAME:
    return CheckFNAME(inst,stat);
  case FOR:
    return Pass4CheckFOR(inst,stat);
  case UNLNK:
    STATEMENT_ERROR(stat,"Inappropriate UNLINK statement in the declarative part");
    ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    return 0;
  case COND:
  case SELECT:
  case REL:
  case EXT:
  case LOGREL:
  case ISA:
  case ARR:
  case ALIASES:
  case IRT:
  case ATS:
  case AA:
  case LNK:
  case CASGN:
  case ASGN:
  default:
    return 1; /* ignore all in phase 4.*/
  }
}


static
int Pass3CheckStatement(struct Instance *inst, struct Statement *stat)
{
  asc_assert(stat&&inst);
  switch(StatementType(stat)){
  case FOR:
    return Pass3RealCheckFOR(inst,stat);
  case LOGREL:
    return CheckLOGREL(inst,stat);
  case COND:
    return Pass3CheckCOND(inst,stat);
  case REL:
  case EXT:
  case ALIASES:
  case ARR:
  case ISA:
  case IRT:
  case ATS:
  case AA:
  case LNK:
  case UNLNK:
  case CASGN:
  case ASGN:
  case WHEN:
  case SELECT:
  case FNAME:
  default:
    return 1; /* ignore all in phase 3. nondeclarative flagged in pass1 */
  }
}


static
int Pass2CheckStatement(struct Instance *inst, struct Statement *stat)
{
  asc_assert(stat&&inst);
  switch(StatementType(stat)){
  case FOR:
    return Pass2RealCheckFOR(inst,stat);
  case EXT:
    return CheckEXT(inst,stat);
  case REL:
    return CheckREL(inst,stat);
  case COND:
    return Pass2CheckCOND(inst,stat);
  case LOGREL:
  case ALIASES:
  case ARR:
  case ISA:
  case IRT:
  case ATS:
  case AA:
  case LNK:
  case UNLNK:
  case CASGN:
  case ASGN:
  case WHEN:
  case SELECT:
  case FNAME:
  default:
    return 1; /* ignore all in phase 2. nondeclarative flagged in pass1 */
  }
}

/**
	checking statementlist, as in a FOR loop check.
	relations are not handled in pass 1
*/
static
int Pass1CheckStatement(struct Instance *inst, struct Statement *stat)
{
  asc_assert(stat&&inst);
  switch(StatementType(stat)){
  case ALIASES:
    return CheckALIASES(inst,stat);
  case ARR:
    return CheckARR(inst,stat);
  case ISA:
    if ( CheckISA(inst,stat) == 0 ) {
      return 0;
    }
    return MakeParameterInst(inst,stat,NULL,NOKEEPARGINST); /*1*/
  case IRT:
    if ( CheckIRT(inst,stat) == 0 ) {
      return 0;
    }
    return MakeParameterInst(inst,stat,NULL,NOKEEPARGINST); /*1b*/
  case ATS:
    return CheckATS(inst,stat);
  case AA:
    return CheckAA(inst,stat);
  case LNK:
    return CheckLNK(inst,stat);
  case UNLNK:
   	FPRINTF(ASCERR,"UNLINK are only allowed inside a non-declarative part.\n");
   	return 0;
  case FOR:
    return Pass1CheckFOR(inst,stat);
  case REL:
    return 1; /* ignore'm in phase 1 */
  case EXT:
    return 1; /* ignore'm in phase 1 */
  case COND:
    return 1; /* ignore'm in phase 1 */
  case LOGREL:
    return 1; /* ignore'm in phase 1 */
  case CASGN:
    return CheckCASGN(inst,stat);
  case ASGN:
    return 1; /* ignore'm in phase 1 */
  case WHEN:
    return 1; /* ignore'm in phase 1 */
  case SELECT:
    return CheckSELECT(inst,stat);
  case FNAME:
    FPRINTF(ASCERR,"FNAME are only allowed inside a WHEN Statement\n");
    return 0;
  default:
    STATEMENT_ERROR(stat,"Inappropriate statement type");
    ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    return 1;
  }
}

static
int Pass4CheckStatementList(struct Instance *inst, struct StatementList *sl)
{
  unsigned long c,len;
  struct gl_list_t *list;
  struct Statement *stat;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (!Pass4CheckStatement(inst,stat)) return 0;
  }
  return 1;
}

static
int Pass3CheckStatementList(struct Instance *inst, struct StatementList *sl)
{
  unsigned long c,len;
  struct gl_list_t *list;
  struct Statement *stat;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (!Pass3CheckStatement(inst,stat)) return 0;
  }
  return 1;
}

static
int Pass2CheckStatementList(struct Instance *inst, struct StatementList *sl)
{
  unsigned long c,len;
  struct gl_list_t *list;
  struct Statement *stat;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (Pass2CheckStatement(inst,stat)==0) return 0;
  }
  return 1;
}

static
int Pass1CheckStatementList(struct Instance *inst, struct StatementList *sl)
{
  unsigned long c,len;
  struct gl_list_t *list;
  struct Statement *stat;
  asc_assert(inst&&sl);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (Pass1CheckStatement(inst,stat)==0) return 0;
  }
  return 1;
}


/*------------------------------------------------------------------------------
  'FNAME' STATEMENT PROCESSING
*/

/**
	The FNAME statement is just used to stand for the model relations or
	arrays inside the CASES of a WHEN statement. Actually, this
	statement does not need to be executed. It is required only
	for checking and for avoiding conflicts in the semantics.
*/
static
int ExecuteFNAME(struct Instance *inst, struct Statement *statement)
{
  (void)inst;       /*  stop gcc whine about unused parameter */
  (void)statement;  /*  stop gcc whine about unused parameter */
  return 1;
}

/*------------------------------------------------------------------------------
  CONDITIONAL Statement Processing
*/

/**
	The logical relations inside a conditional statement do not have
	to be satisified. They are going to be used to check conditions in
	the solution of other logical relations. So, we need something to
	distinguish a conditional logrelation from a non-conditional
	logrelation. The next three functions "Mark" those log relations
	inside a CONDITIONAL statement as Conditional logrelations.
	Right now we not only set a bit indicating
	that the logrelation is conditional, but also set a flag equal to 1.
	This is done in MarkLOGREL above. The flag could be eliminated, but
	we need to fix some places in which it is used, and to use the
	bit instead.
*/
static
void Pass3MarkCondLogRels(struct Instance *inst, struct Statement *statement)
{
  switch(StatementType(statement)){
    case LOGREL:
      MarkLOGREL(inst,statement);
      break;
    case FOR:
      if ( ForContainsLogRelations(statement) ) {
        Pass3FORMarkCond(inst,statement);
      }
      break;
    case REL:
      break;
    case EXT:
      break;
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
  }
}

static
void Pass3MarkCondLogRelStatList(struct Instance *inst,
                                 struct StatementList *sl)
{
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(stat)){
      case LOGREL:
        MarkLOGREL(inst,stat);
        break;
      case FOR:
        if ( ForContainsLogRelations(stat) ) {
        Pass3FORMarkCondLogRels(inst,stat);
        }
        break;
      case EXT:
        break;
      case REL:
        break;
      default:
        STATEMENT_ERROR(stat,"Inappropriate statement type");
        ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    }
  }
}

static
void Pass3MarkCondLogRelStat(struct Instance *inst,
                             struct Statement *statement)
{
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    Pass3MarkCondLogRels(inst,stat);
  }
}


/**
	Execution of the statements allowed inside a CONDITIONAL
	statement. Only log/relations and FOR loops containing only
	log/relations are allowed.
*/
static
int Pass3ExecuteCondStatements(struct Instance *inst,
                               struct Statement *statement)
{
  switch(StatementType(statement)){
    case LOGREL:
      return ExecuteLOGREL(inst,statement);
    case FOR:
      if ( ForContainsLogRelations(statement) ) {
        return Pass3ExecuteFOR(inst,statement);
      }else{
        return 1;
      }
    case EXT:
      return 1; /* assume done */
    case REL:
      return 1; /* assume done */
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      return 0;
  }
}

static
int Pass3RealExecuteCOND(struct Instance *inst, struct Statement *statement)
{
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (!Pass3ExecuteCondStatements(inst,stat)) return 0;
  }
  return 1;
}

/**
	Execution of the Conditional statements. In pass3 we consider only
	logrelations (or FOR loops of logrelations),so  the checking is not
	done at all. After execution, the logrelations are set as conditional
	by means of a bit and a flag
*/
static
int Pass3ExecuteCOND(struct Instance *inst, struct Statement *statement)
{
  int return_value;

  if (Pass3RealExecuteCOND(inst,statement)) {
    return_value = 1;
  }else{
    return_value = 0;
  }
  Pass3MarkCondLogRelStat(inst,statement);
  return return_value;
}

/**
	The relations inside a conditional statement do not have to be
	solved. They are going to be used as boundaries in conditional
	programming. So, we need something to distinguish a conditional
	relation from a non-conditional relation. The next three functions
	"Mark" those relations inside a CONDITIONAL statement as
	Conditional relations. Right now we not only set a bit indicating
	that the relation is conditional, but also set a flag equal to 1.
	This is done in MarkREL above. The flag could be eliminated, but
	we need to fix some places in which it is used, and to use the
	bit instead.
*/
static
void Pass2MarkCondRelations(struct Instance *inst, struct Statement *statement)
{
  switch(StatementType(statement)){
    case REL:
      MarkREL(inst,statement);
      break;
    case EXT:
      MarkEXT(inst,statement);
      break;
    case FOR:
      if ( ForContainsRelations(statement) ||
           ForContainsExternal(statement)
         ) {
        Pass2FORMarkCond(inst,statement);
      }
      break;
    case LOGREL:
      break;
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
  }
}

static
void Pass2MarkCondRelStatList(struct Instance *inst, struct StatementList *sl)
{
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(stat)){
      case EXT:
        MarkEXT(inst,stat);
        break;
      case REL:
        MarkREL(inst,stat); /* MarkEXT is MarkREL exactly */
        break;
      case FOR:
        if ( ForContainsRelations(stat) ||
             ForContainsExternal(stat)
           ) {
          Pass2FORMarkCondRelations(inst,stat);
        }
        break;
      case LOGREL:
        break;
      default:
        STATEMENT_ERROR(stat,"Inappropriate statement type");
        ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    }
  }
}

static
void Pass2MarkCondRelStat(struct Instance *inst, struct Statement *statement)
{
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    Pass2MarkCondRelations(inst,stat);
  }
}

/**
	Execution of the statements allowed inside a CONDITIONAL
	statement. Only relations and FOR loops containing only
	relations are considered in Pass2.
*/
static
int Pass2ExecuteCondStatements(struct Instance *inst,
                               struct Statement *statement)
{
  switch(StatementType(statement)){
    case REL:
#ifdef DEBUG_RELS
    ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
    FPRINTF(stderr,"Pass2ExecuteCondStatements: case REL");
    WriteStatement(stderr, statement, 3);
    error_reporter_end_flush();
#endif
      return ExecuteREL(inst,statement);
    case EXT:
#ifdef DEBUG_RELS
    ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
    FPRINTF(stderr,"Pass2ExecuteCondStatements: case EXT");
    WriteStatement(stderr, statement, 3);
    error_reporter_end_flush();
#endif
      return ExecuteEXT(inst,statement);
    case FOR:
      if ( ForContainsRelations(statement) ) {
#ifdef DEBUG_RELS
        ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
        FPRINTF(stderr,"Pass2ExecuteCondStatements: case FOR");
        WriteStatement(stderr, statement, 3);
        error_reporter_end_flush();
#endif
        return Pass2ExecuteFOR(inst,statement);
      }
      return 1;
    case LOGREL:
      return 1; /* Ignore */
    default:
      STATEMENT_ERROR(statement,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      return 0;
  }
}

static
int Pass2RealExecuteCOND(struct Instance *inst, struct Statement *statement)
{
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  sl = CondStatList(statement);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    if (!Pass2ExecuteCondStatements(inst,stat)) return 0;
  }
  return 1;
}

/**
	Execution of the Conditional statements. In pass2 we consider only
	relations (or FOR loops of relations),so  the checking is not
	done at all. After execution, the relations are set as conditional
	by means of a bit and a flag
*/
static
int Pass2ExecuteCOND(struct Instance *inst, struct Statement *statement)
{
  int return_value;

  if (Pass2RealExecuteCOND(inst,statement)) {
    return_value = 1;
  }else{
    return_value = 0;
  }
  Pass2MarkCondRelStat(inst,statement);
  return return_value;
}


/**
	For its use in ExecuteUnSelectedStatements.
	Execute the  statements of a CONDITIONAL statement which is inside
	a CASE not matching the selection variables.

	Only FOR loops containing log/relations or log/relations are allowed
	inside CONDITIONAL statements. This function ultimately call
	the function ExecuteUnSelectedEQN, to create Dummy instances
	for the relations inside CONDITIONAL
*/
static
int ExecuteUnSelectedCOND(struct Instance *inst, struct Statement *statement)
{
  struct StatementList *sl;
  struct Statement *stat;
  unsigned long c,len;
  struct gl_list_t *list;
  int return_value = 0;

  sl = CondStatList(statement);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    stat = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(stat)){
    case FOR:
      return_value = ExecuteUnSelectedForStatements(inst,ForStatStmts(stat));
      break;
    case REL:
    case EXT:
    case LOGREL:
      return_value = ExecuteUnSelectedEQN(inst,stat);
      break;
    default:
      STATEMENT_ERROR(stat,"Inappropriate statement type");
	  ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
      Asc_Panic(2, NULL,
                "Inappropriate statement type in CONDITIONAL Statement");
    }
    asc_assert(return_value);
  }
  return 1;
}

/*------------------------------------------------------------------------------
  'WHEN' STATEMENT PROCESSING
*/

/**
	Find the instances corresponding to the list of conditional
	variables of a WHEN, and append ther pointers in a gl_list.
	This gl_list becomes part of the WHEN instance.
	Also, this function notify those instances that the WHEN is
	pointing to them, so that their list of whens is updated.
*/
static
struct gl_list_t *MakeWhenVarList(struct Instance *inst,
                                  struct Instance *child,
                                  CONST struct VariableList *vlist)
{
  CONST struct Name *name;
  struct Instance *var;
  struct gl_list_t *instances;
  struct gl_list_t *whenvars;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  unsigned long numvar;

  numvar = VariableListLength(vlist);
  whenvars = gl_create(numvar);

  while(vlist != NULL){
    name = NamePointer(vlist);
    instances = FindInstances(inst,name,&err);
    if (instances == NULL){
      ASC_PANIC("Instance not found in MakeWhenVarList \n");
    }else{
      if (gl_length(instances)==1) {
        var = (struct Instance *)gl_fetch(instances,1);
        gl_destroy(instances);
        switch(InstanceKind(var)){
          case BOOLEAN_ATOM_INST:
          case INTEGER_ATOM_INST:
          case SYMBOL_ATOM_INST:
          case BOOLEAN_CONSTANT_INST:
          case INTEGER_CONSTANT_INST:
          case SYMBOL_CONSTANT_INST:
            gl_append_ptr(whenvars,(VOIDPTR)var);
            AddWhen(var,child);
            break;
          default:
            Asc_Panic(2, NULL,
                      "Incorrect instance type in MakeWhenVarList \n");
        }
      }else{
        gl_destroy(instances);
        Asc_Panic(2, NULL,
                  "Variable name assigned to more than one instance \n");
      }
    }
    vlist = NextVariableNode(vlist);
  }
  return whenvars;
}

/*- - - - - - - - - -  -  - - - - - - - - -
	The following four functions create the gl_list of references of
	each CASE of a WHEN instance. By list of references I mean the
	list of pointers to relations, models or arrays which will become
	active if such a CASE applies.
*/

/**
	creating list of reference for each CASE in a WHEN: (1) dealing with arrays
*/
static
void MakeWhenArrayReference(struct Instance *when,
                            struct Instance *child,
                            struct gl_list_t *listref)
{
  struct Instance *arraychild;
  unsigned long len,c;
  switch (InstanceKind(child)) {
  case REL_INST:
    gl_append_ptr(listref,(VOIDPTR)child);
    AddWhen(child,when);
    relinst_set_in_when(child,TRUE);
    return;
  case LREL_INST:
    gl_append_ptr(listref,(VOIDPTR)child);
    AddWhen(child,when);
    logrelinst_set_in_when(child,TRUE);
    return;
  case MODEL_INST:
    gl_append_ptr(listref,(VOIDPTR)child);
    AddWhen(child,when);
    model_set_in_when(child,TRUE);
    return;
  case WHEN_INST:
    gl_append_ptr(listref,(VOIDPTR)child);
    AddWhen(child,when);
    return;
  case ARRAY_INT_INST:
  case ARRAY_ENUM_INST:
    len = NumberChildren(child);
    for(c=1;c<=len;c++){
      arraychild = InstanceChild(child,c);
      MakeWhenArrayReference(when,arraychild,listref);
    }
    return;
  default:
    Asc_Panic(2, NULL,
              "Incorrect array instance name inside a WHEN statement\n");
  }
}

/**
	creating list of reference for each CASE in a WHEN: (2)
*/
static
void MakeWhenReference(struct Instance *ref,
                       struct Instance *child,
                       struct Name *name,
                       struct gl_list_t *listref)
{
  struct Instance *inst,*arraychild;
  struct gl_list_t *instances;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  unsigned long len,c;

  instances = FindInstances(ref,name,&err);
  if (instances==NULL){
    gl_destroy(instances);
    WriteName(ASCERR,name);
    Asc_Panic(2, NULL,
              "Name of an unmade instance (Relation-Model)"
              " inside a WHEN statement \n");
  }else{
    if (gl_length(instances)==1){
      inst = (struct Instance *)gl_fetch(instances,1);
      gl_destroy(instances);
      switch (InstanceKind(inst)) {
        case REL_INST:
          gl_append_ptr(listref,(VOIDPTR)inst);
          AddWhen(inst,child);
          relinst_set_in_when(inst,TRUE);
          return;
        case LREL_INST:
          gl_append_ptr(listref,(VOIDPTR)inst);
          AddWhen(inst,child);
          logrelinst_set_in_when(inst,TRUE);
          return;
        case MODEL_INST:
          gl_append_ptr(listref,(VOIDPTR)inst);
          AddWhen(inst,child);
          model_set_in_when(inst,TRUE);
          return;
        case WHEN_INST:
          gl_append_ptr(listref,(VOIDPTR)inst);
          AddWhen(inst,child);
          return;
        case ARRAY_INT_INST:
        case ARRAY_ENUM_INST:
          len = NumberChildren(inst);
          for(c=1;c<=len;c++){
            arraychild = InstanceChild(inst,c);
            MakeWhenArrayReference(child,arraychild,listref);
          }
          return;
        default:
          gl_destroy(instances);
          WriteName(ASCERR,name);
          Asc_Panic(2, NULL,
                    "Incorrect instance name inside a WHEN statement\n");
          break;
      }
    }else{
      gl_destroy(instances);
      WriteName(ASCERR,name);
      Asc_Panic(2, NULL,
                "Error in WHEN statement. Name assigned"
                " to more than one instance type\n");
    }
  }
}

/**
	creating list of reference for each CASE in a WHEN: (3) nested WHENs,
	nested FOR loops etc.
*/
static
void MakeWhenCaseReferences(struct Instance *inst,
                            struct Instance *child,
                            struct StatementList *sl,
                            struct gl_list_t *listref)
{
  struct Statement *statement;
  struct Name *name;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case WHEN:
      name = WhenStatName(statement);
      MakeWhenReference(inst,child,name,listref);
      break;
    case FNAME:
      name = FnameStat(statement);
      MakeWhenReference(inst,child,name,listref);
      break;
    case FOR:
      MakeWhenCaseReferencesFOR(inst,child,statement,listref);
      break;
    default:
      WSEM(stderr,statement,
                      "Inappropriate statement type in WHEN Statement");
      ASC_PANIC("Inappropriate statement type in WHEN Statement");
    }
  }
}

/**
	creating list of reference for each CASE in a WHEN: (4) almost identical
	to the previous one.
	They differ only in the case of a FOR loop. This function is
	required to appropriately deal with nested FOR loops which
	contain FNAMEs or WHENs
*/
static
void MakeRealWhenCaseReferencesList(struct Instance *inst,
                                    struct Instance *child,
                                    struct StatementList *sl,
                                    struct gl_list_t *listref)
{
  struct Statement *statement;
  struct Name *name;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case WHEN:
      name = WhenStatName(statement);
      MakeWhenReference(inst,child,name,listref);
      break;
    case FNAME:
      name = FnameStat(statement);
      MakeWhenReference(inst,child,name,listref);
      break;
    case FOR:
      MakeRealWhenCaseReferencesFOR(inst,child,statement,listref);
      break;
    default:
      STATEMENT_ERROR(statement,
                      "Inappropriate statement type in declarative section");
      ASC_PANIC("Inappropriate statement type in declarative section");
      break;
    }
  }
  return ;
}

/*-  - - - - - - - - - -- - - - - -  - - */

/**
	Make a WHEN instance or an array of WHEN instances by calling
	CreateWhenInstance. It does not create the lists of pointers
	to the conditional variables or the models or relations.
*/

static
struct Instance *MakeWhenInstance(struct Instance *parent,
                                  struct Name *name,
                                  struct Statement *stat)
{
  symchar *when_name;
  struct TypeDescription *desc;
  struct Instance *child;
  struct InstanceName rec;
  unsigned long pos;
  if ((when_name=SimpleNameIdPtr(name))!=NULL){
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,when_name);
    if(0 != (pos = ChildSearch(parent,&rec))){
      asc_assert(InstanceChild(parent,pos)==NULL);
      desc = FindWhenType();
      child = CreateWhenInstance(desc);
      LinkToParentByPos(parent,child,pos);
      return child;
    }else{
      return NULL;
    }
  }else{				/* sparse array of when */
    when_name = NameIdPtr(name);
    SetInstanceNameType(rec,StrName);
    SetInstanceNameStrPtr(rec,when_name);
    if(0 != (pos = ChildSearch(parent,&rec))){
      if (InstanceChild(parent,pos)==NULL){ /* need to make array */
        child = MakeSparseArray(parent,name,stat,NULL,0,NULL,NULL,NULL);
      }else{			/* need to add array element */
        child = AddArrayChild(parent,name,stat,NULL,NULL,NULL);
      }
      return child;
    }else{
      return NULL;
    }
  }
}

/**
	Executing the possible kind of statements inside a WHEN. It
	consider the existence of FOR loops and nested WHENs
*/
static
void ExecuteWhenStatements(struct Instance *inst,
                           struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value = 0;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case WHEN:
      return_value = 1;
      RealExecuteWHEN(inst,statement);
      break;
    case FNAME:
      return_value = ExecuteFNAME(inst,statement);
      break;
    case FOR:
      return_value = 1;
      Pass4ExecuteFOR(inst,statement);
      break;
    default:
      WSEM(stderr,statement,
                      "Inappropriate statement type in WHEN Statement");
      ASC_PANIC("Inappropriate statement type in WHEN Statement");
    }
    asc_assert(return_value);
  }
}


/**
	Creates a CASE included in a WHEN statement. It involves the
	allocation of memory of the CASE and the creation of the
	gl_list of references (pointer to models, arrays, relations)
	which will be contained in such a case.
*/
static
struct Case *RealExecuteWhenStatements(struct Instance *inst,
                                       struct Instance *child,
                                       struct WhenList *w1)
{
  struct StatementList *sl;
  struct Case *cur_case;
  struct gl_list_t *listref;
  struct Set *set;

  listref = gl_create(AVG_REF);

  set = WhenSetList(w1);
  cur_case = CreateCase(CopySetByReference(set),NULL);
  sl = WhenStatementList(w1);
  ExecuteWhenStatements(inst,sl);
  MakeWhenCaseReferences(inst,child,sl,listref);
  SetCaseReferences(cur_case,listref);
  return cur_case;
}


/**
	Call the Creation of a WHEN instance. This function is also in charge
	of filling the gl_list of conditional variables and the gl_list of
	CASEs contained in the WHEN instance
*/
static void RealExecuteWHEN(struct Instance *inst, struct Statement *statement){
  struct VariableList *vlist;
  struct WhenList *w1;
  struct Instance *child;
  struct Name *wname;
  struct Case *cur_case;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct gl_list_t *instances;
  struct gl_list_t *whenvars;
  struct gl_list_t *whencases;

  wname = WhenStatName(statement);
  instances = FindInstances(inst,wname,&err);
  if (instances==NULL) {
    /* if (ferr == unmade_instance) { */
      child = MakeWhenInstance(inst,wname,statement);
      if (child == NULL) {
        STATEMENT_ERROR(statement,"Unable to create when instance");
        ASC_PANIC("Unable to create when instance");
      }
      /*    }
    else {
      STATEMENT_ERROR(statement,"Unable to execute statement");
      ASC_PANIC("Unable to execute statement");
    }  */
  }else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      asc_assert((InstanceKind(child)==WHEN_INST) || (InstanceKind(child)==DUMMY_INST));
      gl_destroy(instances);
      if (InstanceKind(child)==DUMMY_INST) {
        return;
      }
    }else{
      STATEMENT_ERROR(statement, "Expression name refers to more than one object");
      gl_destroy(instances);
      ASC_PANIC("Expression name refers to more than one object");
	  child = NULL;
    }
  }
  vlist = WhenStatVL(statement);
  whenvars = MakeWhenVarList(inst,child,vlist);
  SetWhenVarList(child,whenvars);
  whencases = gl_create(AVG_CASES);
  w1 = WhenStatCases(statement);
  while (w1!=NULL){
    cur_case = RealExecuteWhenStatements(inst,child,w1);
    gl_append_ptr(whencases,(VOIDPTR)cur_case);
    w1 = NextWhenCase(w1);
  }
  SetWhenCases(child,whencases);
}


/**
	After Checking the WHEN statement, it calls for its  execution
*/
static
int ExecuteWHEN(struct Instance *inst, struct Statement *statement)
{
  if (CheckWHEN(inst,statement)){
    RealExecuteWHEN(inst,statement);
    return 1;
  }else{
    return 0;
  }
}


/**
	Written because of the possiblity of nested WHEN and
	Nested WHEN inside a FOR loop in an unselected case of
	SELECT statement
*/
static
void ExecuteUnSelectedWhenStatements(struct Instance *inst,
                                     struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value = 0;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case WHEN:
      return_value = ExecuteUnSelectedWHEN(inst,statement);
      break;
    case FNAME:
      return_value = 1;
      break;
    case FOR:
      return_value = ExecuteUnSelectedForStatements(inst,
                                                    ForStatStmts(statement));
      break;
    default:
      WSEM(stderr,statement,
                      "Inappropriate statement type in WHEN Statement");
      ASC_PANIC("Inappropriate statement type in WHEN Statement");
    }
    asc_assert(return_value);
  }
}

/*
	For its use in ExecuteUnSelectedStatements.
	Execute the WHEN statements inside those cases of a SELECT
	which do not match the selection variables
*/
static
int ExecuteUnSelectedWHEN(struct Instance *inst, struct Statement *statement)
{
  struct WhenList *w1;
  struct Instance *child;
  struct Name *wname;
  struct StatementList *sl;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct gl_list_t *instances;
  struct TypeDescription *def;

  wname = WhenStatName(statement);
  instances = FindInstances(inst,wname,&err);
  if (instances==NULL) {
    def = FindDummyType();
    MakeDummyInstance(wname,def,inst,statement);
  }else{
    if(gl_length(instances)==1){
      child = (struct Instance *)gl_fetch(instances,1);
      asc_assert(InstanceKind(child)==DUMMY_INST);
      gl_destroy(instances);
    }else{
      STATEMENT_ERROR(statement, "Expression name refers to more than one object");
      gl_destroy(instances);
      ASC_PANIC("Expression name refers to more than one object");
    }
  }

  w1 = WhenStatCases(statement);
  while (w1!=NULL){
    sl = WhenStatementList(w1);
    ExecuteUnSelectedWhenStatements(inst,sl);
    w1 = NextWhenCase(w1);
  }
  return 1;
}

/*------------------------------------------------------------------------------
  'SELECT' STATEMENT PROCESSING
*/

/**
	Execution of the Statements inside the case that
	matches the selection variables
*/
static
void ExecuteSelectStatements(struct Instance *inst, unsigned long *count,
                             struct StatementList *sl)
{
  struct BitList *blist;
  struct Statement *statement;
  unsigned long c,len;
  int return_value;
  struct gl_list_t *list;

  blist = InstanceBitList(inst);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    (*count)++;
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
      case ALIASES:
        return_value = ExecuteALIASES(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case CASGN:
        return_value =  ExecuteCASGN(inst,statement);
        if (return_value) {
          ClearBit(blist,*count);
        }
        break;
      case ARR:
        return_value = ExecuteISA(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case ISA:
        return_value = ExecuteISA(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case IRT:
        return_value = ExecuteIRT(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case ATS:
        return_value = ExecuteATS(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case AA:
        return_value = ExecuteAA(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case LNK:
        return_value = ExecuteLNK(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case UNLNK:
        FPRINTF(ASCERR,"UNLINK are only allowed inside a non-declarative part of the \n");
        break;
      case FOR:
        return_value = Pass1ExecuteFOR(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case ASGN:
      case REL:
      case EXT:
      case LOGREL:
      case COND:
      case CALL:
      case WHEN:
        return_value = 1;  /* ignore'm */
        ClearBit(blist,*count);
        break;
      case FNAME:
        if (g_iteration>=MAXNUMBER) {
          STATEMENT_ERROR(statement,
              "FNAME not allowed inside a SELECT Statement");
        }
        return_value = 1; /* Ignore it */
        ClearBit(blist,*count);
        break;
      case SELECT:
        return_value = ExecuteSELECT(inst,count,statement);
        break;
      default:
        WSEM(stderr,statement,
           "Inappropriate statement type in declarative section SELECT\n");
        Asc_Panic(2, NULL,
                  "Inappropriate statement type"
                  " in declarative section SELECT");
    }
  }
}


/**
	Execution of the UnSelected Statements inside those cases of the
	SELECT that do not match match the selection variables
*/
static
void ExecuteUnSelectedStatements(struct Instance *inst,unsigned long *count,
                                 struct StatementList *sl)
{
  struct BitList *blist;
  struct Statement *statement;
  unsigned long c,len;
  int return_value;
  struct gl_list_t *list;

  blist = InstanceBitList(inst);
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    (*count)++;
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
      case ARR:
      case IRT:
      case ATS:
      case AA:
      case LNK:
      case UNLNK:
      case CALL:
      case CASGN:
      case ASGN:
        ClearBit(blist,*count);
        break;
      case FNAME:
        if (g_iteration>=MAXNUMBER) {
          STATEMENT_ERROR(statement,"FNAME not allowed inside a SELECT Statement");
        }
        return_value = 1; /*ignore it */
        ClearBit(blist,*count);
        break;
      case ALIASES:
        return_value = ExecuteUnSelectedALIASES(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case ISA:
        return_value = ExecuteUnSelectedISA(inst,statement);
        if (return_value) ClearBit(blist,*count);
        break;
      case FOR:
        return_value = ExecuteUnSelectedForStatements(inst,
                       ForStatStmts(statement));
        if (return_value) ClearBit(blist,*count);
        break;
      case REL:
      case EXT:
      case LOGREL:
        return_value = ExecuteUnSelectedEQN(inst,statement);
        ClearBit(blist,*count);
        break;
      case COND:
        return_value = ExecuteUnSelectedCOND(inst,statement);
        ClearBit(blist,*count);
        break;
      case WHEN:
        return_value = ExecuteUnSelectedWHEN(inst,statement);
        ClearBit(blist,*count);
        break;
      case SELECT:
        return_value = ExecuteUnSelectedSELECT(inst,count,statement);
        break;
      default:
        WSEM(stderr,statement,
          "Inappropriate statement type in declarative section unSELECTed\n");
        ASC_PANIC("Inappropriate statement type"
                  " in declarative section unSELECTed\n");
    }
  }
}

/**
	Execution of the SELECT statement inside a case that does not
	match the selection variables
*/
static
int ExecuteUnSelectedSELECT(struct Instance *inst, unsigned long *c,
                            struct Statement *statement)
{
  struct BitList *blist;
  struct SelectList *sel1;
  struct StatementList *sl;

  blist = InstanceBitList(inst);
  ClearBit(blist,*c);
  sel1 = SelectStatCases(statement);
  while (sel1!=NULL){
    sl = SelectStatementList(sel1);
    ExecuteUnSelectedStatements(inst,c,sl);
    sel1 = NextSelectCase(sel1);
  }
  return 1;
}


/**
	Compare current values of the selection variables with
	the set of values in a CASE of a SELECT statement, and try to find
	is such values are the same. If they are, the function will return 1,
	else, it will return 0.
*/
static
int AnalyzeSelectCase(struct Instance *ref, struct VariableList *vlist,
                      struct Set *s)
{
  CONST struct Expr *expr;
  CONST struct Name *name;
  symchar *value;
  symchar *symvar;
  CONST struct VariableList *vl;
  CONST struct Set *values;
  int val;
  int valvar;
  struct gl_list_t *instances;
  struct Instance *inst;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;

  asc_assert(s!= NULL);
  asc_assert(vlist != NULL);
  values = s;
  vl = vlist;

  while (vl!=NULL) {
    name = NamePointer(vl);
    expr = GetSingleExpr(values);
    instances = FindInstances(ref,name,&err);
    asc_assert(gl_length(instances)==1);
    inst = (struct Instance *)gl_fetch(instances,1);
    gl_destroy(instances);
    switch(ExprType(expr)) {
      case e_boolean:
        val =  ExprBValue(expr);
        if (val == 2) { /* ANY */
          break;
        }
        valvar = GetBooleanAtomValue(inst);
        if (val != valvar) return 0;
        break;
      case e_int:
        asc_assert(InstanceKind(inst)==INTEGER_CONSTANT_INST);
        val =  ExprIValue(expr);
        valvar = GetIntegerAtomValue(inst);
        if (val != valvar) return 0;
        break;
      case e_symbol:
        asc_assert(InstanceKind(inst)==SYMBOL_CONSTANT_INST);
        symvar = ExprSymValue(expr);
        value = GetSymbolAtomValue(inst);
        if (symvar != value) {
          asc_assert(AscFindSymbol(symvar)!=NULL);
          return 0;
        }
        break;
      default:
        FPRINTF(stderr,"Something wrong happens in AnalyzeSelectCase \n");
        return 0;
    }
    vl = NextVariableNode(vl);
    values = NextSet(values);
  }

  return 1;
}


/**
	This function will determine which case of a SELECT statement
	applies for the current values of the selection variables.
	this function  will call for the execution of the case which
	matches. It handles OTHERWISE properly (case when set == NULL).
	At most one case is going to be executed.
*/
static
void RealExecuteSELECT(struct Instance *inst, unsigned long *c,
                       struct Statement *statement)
{
  struct VariableList *vlist;
  struct SelectList *sel1;
  struct Set *set;
  struct StatementList *sl;
  int case_match;

  vlist = SelectStatVL(statement);
  sel1 = SelectStatCases(statement);
  case_match =0;

  while (sel1!=NULL){
    set = SelectSetList(sel1);
    sl = SelectStatementList(sel1);
    if (case_match==0) {
      if (set != NULL) {
        case_match = AnalyzeSelectCase(inst,vlist,set);
        if (case_match==1) {
          ExecuteSelectStatements(inst,c,sl);
        }else{
          ExecuteUnSelectedStatements(inst,c,sl);
        }
      }else{
        ExecuteSelectStatements(inst,c,sl);
        case_match = 1;
      }
    }else{
      ExecuteUnSelectedStatements(inst,c,sl);
    }
    sel1 = NextSelectCase(sel1);
  }

  if (case_match == 0) {
    FPRINTF(ASCERR,"No case matched in SELECT statement\n");
  }
}


/**
	If A SELECT statement passess its checking, this function
	will ask for its execution, otherwise the SELECT and all
	the other statements inside of it, will not be touched.
	The counter in the bitlist is increased properly.
	NOTE for efficiency: Maybe we should integrate the
	Check function of the SELECT together with the analysis
	of the CASEs to see which of them matches.We are doing
	twice the execution of some C functions.
*/
static
int ExecuteSELECT(struct Instance *inst, unsigned long *c,
                  struct Statement *statement)
{
  unsigned long tmp;
  struct BitList *blist;

  blist = InstanceBitList(inst);
  if (CheckSELECT(inst,statement)){
    ClearBit(blist,*c);
    RealExecuteSELECT(inst,c,statement);
    return 1;
  }else{
    tmp = SelectStatNumberStats(statement);
    *c = (*c) + tmp;
    return 0;
  }
}


/**
	This function jumps the statements inside non-matching
	cases of a SELECT statement, so that they are not analyzed
	in compilation passes > 1.
	If there is a SELECT inside a SELECT,
	the function uses the number of statements in the nested
	SELECTs
*/
static
void JumpSELECTStats(unsigned long *count,struct StatementList *sl)
{
  unsigned long c,length;
  int tmp;
  struct Statement *s;

  length = StatementListLength(sl);
  *count = (*count) + length;
  for(c=1;c<=length;c++){
    tmp = 0;
    s = GetStatement(sl,c);
    asc_assert(s!=NULL);
    switch(StatementType(s)) {
      case SELECT:
        tmp = SelectStatNumberStats(s);
        break;
      default:
        break;
    }
    *count = (*count) + tmp;
  }
  return;
}

/**
	This function is used only for setting  the
	bits ON for some statements in the matching case of a
	SELECT statement. Only these statements will be
	analyzed in Pass > 1. The conditions to set a bit ON
	depend on the number of pass.
*/
static
void SetBitsOnOfSELECTStats(struct Instance *inst, unsigned long *count,
                            struct StatementList *sl, int pass, int *changed)
{
  unsigned long c,length;
  struct Statement *s;
  struct BitList *blist;

  blist = InstanceBitList(inst);
  length = StatementListLength(sl);
  for(c=1;c<=length;c++){
    s = GetStatement(sl,c);
    asc_assert(s!=NULL);
    (*count)++;
    switch (pass) {
      case 2:
        switch(StatementType(s)) {
          case REL:
            SetBit(blist,*count);
            (*changed)++;
            break;
          case EXT:
            SetBit(blist,*count);
            (*changed)++;
            break;
          case COND:
            if (CondContainsRelations(s)) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case FOR:
            if ( ForContainsRelations(s) ) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case SELECT:
            if (SelectContainsRelations(s)) {
              ReEvaluateSELECT(inst,count,s,pass,changed);
            }else{
              *count = *count + SelectStatNumberStats(s);
            }
            break;
          default:
            break;
        }
        break;
      case 3:
        switch(StatementType(s)) {
          case LOGREL:
            SetBit(blist,*count);
            (*changed)++;
            break;
          case COND:
            if (CondContainsLogRelations(s)) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case FOR:
            if ( ForContainsLogRelations(s) ) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case SELECT:
            if (SelectContainsLogRelations(s)) {
              ReEvaluateSELECT(inst,count,s,pass,changed);
            }else{
              *count = *count + SelectStatNumberStats(s);
            }
            break;
          default:
            break;
        }
        break;
      case 4:
        switch(StatementType(s)) {
          case WHEN:
            SetBit(blist,*count);
            (*changed)++;
            break;
          case FOR:
            if ( ForContainsWhen(s) ) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case SELECT:
            if (SelectContainsWhen(s)) {
              ReEvaluateSELECT(inst,count,s,pass,changed);
            }else{
              *count = *count + SelectStatNumberStats(s);
            }
            break;
          default:
            break;
        }
				case 5:			/**> DS: Added support for LINK statements inside SELECTs */
        switch(StatementType(s)) {
          case WHEN:
            SetBit(blist,*count);
            (*changed)++;
            break;
          case FOR:
            if ( ForContainsLink(s) ) {
              SetBit(blist,*count);
              (*changed)++;
            }
            break;
          case SELECT:
            if (SelectContainsLink(s)) {
              ReEvaluateSELECT(inst,count,s,pass,changed);
            }else{
              *count = *count + SelectStatNumberStats(s);
            }
            break;
          default:
            break;
        }
        break;
      default:
        FPRINTF(ASCERR,"Wrong pass Number in SetBitsOnOfSELECTStats \n");
        break;
    }
  }
  return;
}


/**
	This function will determine which case of a SELECT statement
	applies for the current values of the selection variables.
	Similar performance from RealExecuteSELECT, but this function
	does not call for execution, it is used only for "jumping"
	the statements inside a non-matching case, or seting the
	bits on for some statements in the matching case.
	It handles OTHERWISE properly (case when set == NULL).
*/
static
void SetBitOfSELECTStat(struct Instance *inst, unsigned long *c,
                        struct Statement *statement, int pass, int *changed)
{
  struct VariableList *vlist;
  struct SelectList *sel1;
  struct Set *set;
  struct StatementList *sl;
  int case_match;

  vlist = SelectStatVL(statement);
  sel1 = SelectStatCases(statement);
  case_match =0;

  while (sel1!=NULL){
    set = SelectSetList(sel1);
    sl = SelectStatementList(sel1);
    if (case_match==0) {
      if (set != NULL) {
        case_match = AnalyzeSelectCase(inst,vlist,set);
        if (case_match==1) {
          SetBitsOnOfSELECTStats(inst,c,sl,pass,changed);
        }else{
          JumpSELECTStats(c,sl);
        }
      }else{
        SetBitsOnOfSELECTStats(inst,c,sl,pass,changed);
        case_match = 1;
      }
    }else{
      JumpSELECTStats(c,sl);
    }
    sel1 = NextSelectCase(sel1);
  }
}

/**
	For compilation passes > 1, this function will tell me if I
	should Set the Bits on for statements inside the CASEs of
	a SELECT statement. This evaluation is needed because there may be
	relations, whens or log rels that should not be executed
	at all (when the selection variables do not exist, for example)
	or should  not be reanlyzed in pass2 3 and 4 (when they are
	already dummys, for example). This re-evaluation will not be done
	if the SELECT does not contain rels, logrels or when.
	NOTE for efficiency: Maybe we should integrate the
	Check function of the SELECT together with the analysis
	of the CASEs to see which of them matches.We are doing
	twice the execution of some C functions.
*/
static
void ReEvaluateSELECT(struct Instance *inst, unsigned long *c,
                      struct Statement *statement, int pass, int *changed)
{
  unsigned long tmp;
  //struct BitList *blist;

  //blist = InstanceBitList(inst);
  if (CheckSELECT(inst,statement)){
    SetBitOfSELECTStat(inst,c,statement,pass,changed);
  }else{
    tmp = SelectStatNumberStats(statement);
    *c = (*c) + tmp;
  }
  return;
}


/**
	This function is used only for setting  the
	bits ON for some statements in the matching case of a
	SELECT statement. Only these statements will be
	analyzed in Pass > 1. The conditions to set a bit ON
	depend on the number of pass.
*/
static
void ExecuteDefaultsInSELECTCase(struct Instance *inst, unsigned long *count,
                                 struct StatementList *sl,
                                 unsigned long int *depth)
{
  unsigned long c,length;
  struct Statement *s;
  struct for_table_t *SavedForTable;

  length = StatementListLength(sl);
  for(c=1;c<=length;c++){
    s = GetStatement(sl,c);
    asc_assert(s!=NULL);
    (*count)++;
    switch(StatementType(s)) {
      case ASGN:
        ExecuteDefault(inst,s,depth);
        break;
      case FOR:
        if ( ForContainsDefaults(s) ){
          SavedForTable = GetEvaluationForTable();
          SetEvaluationForTable(CreateForTable());
          RealDefaultFor(inst,s,depth);
          DestroyForTable(GetEvaluationForTable());
          SetEvaluationForTable(SavedForTable);
        }
        break;
      case SELECT:
        ExecuteDefaultsInSELECT(inst,count,s,depth);
        break;
      default:
        break;
    }
  }
  return;
}


/**
	This function will determine which case of a SELECT statement
	applies for the current values of the selection variables.
	Similar performance from RealExecuteSELECT. This function
	is used only for "jumping"  the statements inside a non-matching
	case, or Executing Defaults in the matching case.
	It handles OTHERWISE properly (case when set == NULL).
*/
static
void ExecuteDefaultsInSELECTStat(struct Instance *inst, unsigned long *c,
                                 struct Statement *statement,
                                 unsigned long int *depth)
{
  struct VariableList *vlist;
  struct SelectList *sel1;
  struct Set *set;
  struct StatementList *sl;
  int case_match;

  vlist = SelectStatVL(statement);
  sel1 = SelectStatCases(statement);
  case_match =0;

  while (sel1!=NULL){
    set = SelectSetList(sel1);
    sl = SelectStatementList(sel1);
    if (case_match==0) {
      if (set != NULL) {
        case_match = AnalyzeSelectCase(inst,vlist,set);
        if (case_match==1) {
          ExecuteDefaultsInSELECTCase(inst,c,sl,depth);
        }else{
          JumpSELECTStats(c,sl);
        }
      }else{
        ExecuteDefaultsInSELECTCase(inst,c,sl,depth);
        case_match = 1;
      }
    }else{
      JumpSELECTStats(c,sl);
    }
    sel1 = NextSelectCase(sel1);
  }
}

/**
	For Execution of Defaults, which uses a Visit Instance Tree instead of
	a BitList. this function will tell me if I
	should Set the Bits on for statements inside the CASEs of
	a SELECT statement. This evaluation is needed because there is
	the possibility of different assignments to the same variable in
	different cases of the select. I need to execute only those in
	cases mathing the selection variables.

	@TODO It is becoming annoying to have so similar functions, I need
	to create a robust and general function which considers all the
	possible applications.
*/
static
void ExecuteDefaultsInSELECT(struct Instance *inst, unsigned long *c,
                             struct Statement *statement,
                             unsigned long int *depth)
{
  unsigned long tmp;

  if (CheckSELECT(inst,statement)){
    ExecuteDefaultsInSELECTStat(inst,c,statement,depth);
  }else{
    tmp = SelectStatNumberStats(statement);
    *c = (*c) + tmp;
  }
  return;
}

/*------------------------------------------------------------------------------
  'FOR' STATEMENT PROCESSING
*/
static
void WriteForValueError(struct Statement *statement, struct value_t value)
{
  switch(ErrorValue(value)){
  case type_conflict:
    STATEMENT_ERROR(statement, "Type conflict in FOR expression");
    break;
  case incorrect_name:
    STATEMENT_ERROR(statement, "Impossible instance in FOR expression");
    break;
  case temporary_variable_reused:
    STATEMENT_ERROR(statement, "Temporary variable reused in FOR expression");
    break;
  case dimension_conflict:
    STATEMENT_ERROR(statement, "Dimension conflict in FOR expression");
    break;
  case incorrect_such_that:
    STATEMENT_ERROR(statement, "Incorrect such that expression in FOR expression");
    break;
  case empty_choice:
    STATEMENT_ERROR(statement,
                         "CHOICE is called on an empty set in FOR expression");
    break;
  case empty_intersection:
    STATEMENT_ERROR(statement, "Empty INTERSECTION() in FOR expression");
    break;
  default:
    STATEMENT_ERROR(statement, "Unexpected error in FOR expression");
    break;
  }
}

static
int Pass5ExecuteForStatements(struct Instance *inst,
                              struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case LNK:
      if (!ExecuteLNK(inst,statement))return 0;
      break;
    case UNLNK:
      STATEMENT_ERROR(statement,"Inappropriate statement type in declarative "
        "section (UNLINK only possible in the METHODS section)"
      );
      Asc_Panic(2, NULL,"Inappropriate statement type in declarative section "
      	"(UNLINK only possible in the METHODS section)"
      );
      break;
    case FNAME:
      if (!ExecuteFNAME(inst,statement)) return 0;
      break;
    case FOR:
      if (!Pass5ExecuteFOR(inst,statement)) return 0;
      break;
    case SELECT:
      STATEMENT_ERROR(statement,
           "SELECT statements are not allowed inside a FOR Statement");
      return 0;
    case WHEN:
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case REF:
    case ASGN:
    case CASGN:
    case REL:
    case LOGREL:
    case COND:
    case CALL:
    case EXT:  /* ignore'm */
    break;
    default:
      STATEMENT_ERROR(statement,
           "Inappropriate statement type in declarative section LINK");
      Asc_Panic(2, NULL,
                "Inappropriate statement type in declarative section LINK");
    }
  }
  return 1;
}

static
int Pass4ExecuteForStatements(struct Instance *inst,
                              struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case LNK:
      return 1; /* ignore'm until pass 5 */
      break;
    case UNLNK:
      return 0;
      break;
    case WHEN:
      if (!ExecuteWHEN(inst,statement)) return 0;
      break;
    case FNAME:
      if (!ExecuteFNAME(inst,statement)) return 0;
      break;
    case FOR:
      if (!Pass4ExecuteFOR(inst,statement)) return 0;
      break;
    case SELECT:
      STATEMENT_ERROR(statement,
           "SELECT statements are not allowed inside a FOR Statement");
      return 0;
      /* I probably need to change NP4REF to integer */
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case REF:
    case ASGN:
    case CASGN:
    case REL:
    case LOGREL:
    case COND:
    case CALL:
    case EXT:  /* ignore'm */
    break;
    default:
      STATEMENT_ERROR(statement,
           "Inappropriate statement type in declarative section WHEN");
      Asc_Panic(2, NULL,
                "Inappropriate statement type in declarative section WHEN");
    }
  }
  return 1;
}


/**
	@NOTE this function must not be called until all the rel,ext
	statements in sl pass their checks.
*/
static
int Pass3ExecuteForStatements(struct Instance *inst,
                              struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);

  return_value =1;
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case LNK:
    case UNLNK:
    case REF:
    case ASGN:
    case REL:
    case CALL:
    case EXT: /* ignore'm */
    case CASGN:
    case WHEN:
      return_value = 1; /* ignore'm until pass 4 */
      break;
    case FNAME:
      STATEMENT_ERROR(statement,
                 "FNAME statements are only allowed inside a WHEN Statement");
      return_value = 0;
      break;
    case SELECT:
      STATEMENT_ERROR(statement,
           "SELECT statements are not allowed inside a FOR Statement");
      return_value = 0;
      break;
    case FOR:
      if ( ForContainsLogRelations(statement) ) {
        return_value = Pass3RealExecuteFOR(inst,statement);
      }
      break;
    case COND:
      STATEMENT_ERROR(statement,
                 "COND not allowed inside a FOR. Try FOR inside COND");
      return_value = 0;
      break;
    case LOGREL:
      if (ExecuteLOGREL(inst,statement)) {
        return_value = 1;
      }else{
        return_value = 0;
      }
      break;
    default:
      STATEMENT_ERROR(statement,
           "Inappropriate statement type in declarative section log rel\n");
      ASC_PANIC("Inappropriate statement type"
                " in declarative section log rel\n");
    }
    if (!return_value) {
      return 0;
    }
  }
  return 1;
}


/* Note: this function must not be called until all the rel,ext
 * statements in sl pass their checks.
 * This is because if any of the Executes fail
 * (returning 0) we abort (at least when assert is active).
 */
static
void Pass2ExecuteForStatements(struct Instance *inst,
                               struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value = 0;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case ALIASES:
    case ARR:
    case ISA:
    case IRT:
    case ATS:
    case AA:
    case LNK:
    case UNLNK:
    case CALL:
    case REF:
    case ASGN: /* ignore'm */
    case CASGN:
    case LOGREL:
      return_value = 1; /* ignore'm until pass 3 */
      break;
    case WHEN:
      return_value = 1; /* ignore'm until pass 4 */
      break;
    case SELECT:
      STATEMENT_ERROR(statement,
           "SELECT statements are not allowed inside a FOR Statement");
      return_value = 0;
      break;
    case FNAME:
      STATEMENT_ERROR(statement,
                 "FNAME statements are only allowed inside a WHEN Statement");
      return_value = 0;
      break;
    case FOR:
      return_value = 1;
      if ( ForContainsRelations(statement) ) {
#ifdef DEBUG_RELS
        ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
        WriteStatement(stderr, statement, 6);
        error_reporter_end_flush();
#endif
        Pass2RealExecuteFOR(inst,statement);
        /* p2ref expected to succeed or fail permanently.
         * if it doesn't, this needs fixing.
         */
      }
      break;
    case COND:
      STATEMENT_ERROR(statement,
                 "COND not allowed inside a FOR. Try FOR inside COND");
      return_value = 0;
      break;
    case REL:
#ifdef DEBUG_RELS
       ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
       WriteStatement(stderr, statement, 6);
       error_reporter_end_flush();
#endif
      return_value = ExecuteREL(inst,statement);
      /* ER expected to succeed or fail permanently,returning 1.
       * if it doesn't, this needs fixing.
       */
      break;
    case EXT:
      return_value = ExecuteEXT(inst,statement);
      /* ER expected to succeed or fail permanently,returning 1.
       * if it doesn't, this needs fixing.
       */
      if (return_value == 0) {
        STATEMENT_ERROR(statement,"Impossible external relation encountered unexpectedly.");
      }
      break;
    default:
      STATEMENT_ERROR(statement,
      "Inappropriate statement type in declarative section relations");
      ASC_PANIC("Inappropriate statement type"
                " in declarative section relations");
    }
    asc_assert(return_value);
  }
}


/**
	@NOTE this function must not be called until all the statements in sl
	(except rel, ext)pass their checks.
	This is because if any of the Executes fail
	(returning 0) we abort (at least when assert is active)
*/
static
void Pass1ExecuteForStatements(struct Instance *inst,
                               struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value = 0;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
    case ALIASES:
      return_value = ExecuteALIASES(inst,statement);
      break;
    case ARR:
      return_value = ExecuteARR(inst,statement);
      break;
    case ISA:
      return_value = ExecuteISA(inst,statement);
      break;
    case IRT:
      return_value = ExecuteIRT(inst,statement);
      break;
    case ATS:
      return_value = ExecuteATS(inst,statement);
      break;
    case AA:
      return_value = ExecuteAA(inst,statement);
      break;
    case LNK:
      return_value = 1; /*DS: ignore'm until pass 5*/
      break;
    case UNLNK:
      STATEMENT_ERROR(statement,
        "UNLINK statements are not allowed in the declarative section");
      return_value = 0;
      break;
    case FOR:
      return_value = 1;
      Pass1RealExecuteFOR(inst,statement);
      break;
    case REL:
    case CALL:
    case EXT:
    case ASGN: /* ignore'm */
    case LOGREL:
    case COND:
    case WHEN:
      return_value = 1; /* ignore'm until pass 2, 3 or 4 */
      break;
    case REF:
      return_value = ExecuteREF(inst,statement);
      break;
    case CASGN:
      return_value = ExecuteCASGN(inst,statement);
      break;
    case FNAME:
      STATEMENT_ERROR(statement,
                "FNAME statements are only allowed inside a WHEN Statement");
      return_value = 0;
      break;
    case SELECT:
      STATEMENT_ERROR(statement,
                "SELECT statements are not allowed inside a FOR Statement");
      return_value = 0;
      break;
    default:
      STATEMENT_ERROR(statement,
           "Inappropriate statement type in declarative section");
      Asc_Panic(2, NULL,
                "Inappropriate statement type in declarative section");
    }
    asc_assert(return_value);
  }
}


/**
	Execute UnSelected statements inside a FOR loop
	Note that we are not expanding arrays. This actually
	may be impossible even if we want to do it.
*/
static
int ExecuteUnSelectedForStatements(struct Instance *inst,
                                   struct StatementList *sl)
{
  struct Statement *statement;
  unsigned long c,len;
  int return_value;
  struct gl_list_t *list;
  list = GetList(sl);
  len = gl_length(list);
  for(c=1;c<=len;c++){
    statement = (struct Statement *)gl_fetch(list,c);
    switch(StatementType(statement)){
      case ARR:
      case IRT:
      case ATS:
      case AA:
      case LNK:
      case UNLNK:
      case CALL:
      case CASGN:
      case ASGN:
        return_value = 1;
        break;
      case FNAME:
        if (g_iteration>=MAXNUMBER) {
          STATEMENT_ERROR(statement,
              "FNAME not allowed inside a SELECT Statement");
        }
        return_value = 1; /*ignore it */
        break;
      case ALIASES:
        return_value = ExecuteUnSelectedALIASES(inst,statement);
        break;
      case ISA:
        return_value = ExecuteUnSelectedISA(inst,statement);
        break;
      case FOR:
        return_value =  ExecuteUnSelectedForStatements(inst,
                                 ForStatStmts(statement));
        break;
      case REL:
      case EXT:
      case LOGREL:
        return_value = ExecuteUnSelectedEQN(inst,statement);
        break;
      case WHEN:
        return_value = ExecuteUnSelectedWHEN(inst,statement);
        break;
      case COND:
        STATEMENT_ERROR(statement,
        "CONDITIONAL not allowed inside a FOR loop. Try FOR inside COND");
        ASC_PANIC("CONDITIONAL not allowed inside a FOR loop."
                  " Try FOR inside COND");
      case SELECT:
        STATEMENT_ERROR(statement, "SELECT not allowed inside a FOR Statement");
        ASC_PANIC("SELECT not allowed inside a FOR Statement");
        break;
      default:
        WSEM(stderr,statement,
             "Inappropriate statement type in declarative section unSEL FOR");
        ASC_PANIC("Inappropriate statement type in"
                  " declarative section unSEL FOR");
    }
  }
  /* FIXME this should be 'return_value', shouldn't it??? */
  return 1;
}

static
int Pass5RealExecuteFOR(struct Instance *inst, struct Statement *statement)
{
	printf("\n Pass5RealExecuteFOR called \n");
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return 0;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 5 FOR has undefined values");
      return 0;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return 0;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    return 0;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass5ExecuteForStatements(inst,sl)) return 0;
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass5ExecuteForStatements(inst,sl)) return 0;
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
  return 1;
}


static
int Pass4RealExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return 0;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 4 FOR has undefined values");
      return 0;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return 0;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    return 0;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass4ExecuteForStatements(inst,sl)) {
           RemoveForVariable(GetEvaluationForTable());
           DestroyValue(&value);
           return 0 ;
        /*  currently designed to always succeed or fail permanently */
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass4ExecuteForStatements(inst,sl)) {
           RemoveForVariable(GetEvaluationForTable());
           DestroyValue(&value);
           return 0 ;
        /*  currently designed to always succeed or fail permanently */
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
  /*  currently designed to always succeed or fail permanently.
   *  We reached this point meaning we've processed everything.
   *  Therefore the statment returns 1 and becomes no longer pending.
   */
  return 1;
}

static
void MakeRealWhenCaseReferencesFOR(struct Instance *inst,
                                   struct Instance *child,
                                   struct Statement *statement,
                                   struct gl_list_t *listref)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return ;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 2 FOR has undefined values");
      break;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      break;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    break;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        MakeRealWhenCaseReferencesList(inst,child,sl,listref);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        MakeRealWhenCaseReferencesList(inst,child,sl,listref);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
}

/**
	@TODO this function needs to be made much less aggressive about exiting
	and more verbose about error messages  so we can skip the np3checkfor
	probably also means it needs the 0/1 fail/succeed return code.
*/
static
int Pass3RealExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return 0;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 3 FOR has undefined values");
      return 0;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return 0;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    return 0;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass3ExecuteForStatements(inst,sl)) return 0;
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass3ExecuteForStatements(inst,sl)) return 0;
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
  return 1;
}


static
void Pass3FORMarkCondLogRels(struct Instance *inst,
                             struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return ;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 3 FOR has undefined values");
      break;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      break;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    break;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        Pass3MarkCondLogRelStatList(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        Pass3MarkCondLogRelStatList(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
}

static
void Pass3FORMarkCond(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;

  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  Pass3FORMarkCondLogRels(inst,statement);
  DestroyForTable(GetEvaluationForTable());
  SetEvaluationForTable(SavedForTable);
}


/* This function requires all the preconditions for success have
 * been checked. Verifying correctness is separate from and prior to building
 * instance data. This pattern is followed throughout instantiation.
 */
static
int Pass2RealExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return 0;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 2 FOR has undefined values");
      return 0;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return 0;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    ERROR_REPORTER_START_NOLINE(ASC_USER_ERROR);
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    error_reporter_end_flush();
    DestroyValue(&value);
    return 0;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set:
#ifdef DEBUG_RELS
      ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Pass2RealExecuteFOR empty_set.\n");
#endif
      break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
#ifdef DEBUG_RELS
      ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Pass2RealExecuteFOR integer_set %lu.\n",len);
#endif
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        Pass2ExecuteForStatements(inst,sl);
        /*  currently designed to always succeed or fail permanently */
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
#ifdef DEBUG_RELS
      ERROR_REPORTER_NOLINE(ASC_PROG_NOTE,"Pass2RealExecuteFOR string_set %lu.\n",len);
#endif
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        Pass2ExecuteForStatements(inst,sl);
        /*  currently designed to always succeed or fail permanently */
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
  /*  currently designed to always succeed or fail permanently.
   *  We reached this point meaning we've processed everything.
   *  Therefore the statment returns 1 and becomes no longer pending.
   */
  return 1;
}

static
void Pass2FORMarkCondRelations(struct Instance *inst,
                               struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return ;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "Phase 2 FOR has undefined values");
      break;
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      break;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    break;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        Pass2MarkCondRelStatList(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        Pass2MarkCondRelStatList(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
}

static
void Pass2FORMarkCond(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;

  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  Pass2FORMarkCondRelations(inst,statement);
  DestroyForTable(GetEvaluationForTable());
  SetEvaluationForTable(SavedForTable);
}

static
void Pass1RealExecuteFOR(struct Instance *inst, struct Statement *statement)
{
	/*printf("\n Pass1RealExecuteFOR called \n");*/
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable */
    STATEMENT_ERROR(statement, "FOR construct uses duplicate index variable");
    return;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      STATEMENT_ERROR(statement, "FOR has undefined values");
      ASC_PANIC("FOR has undefined values");
    default:
      WriteForValueError(statement,value);
      DestroyValue(&value);
      return;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    WriteStatement(ASCERR,statement,0);
    FPRINTF(ASCERR,"FOR expression returns the wrong type.\n");
    DestroyValue(&value);
    return;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        Pass1ExecuteForStatements(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        Pass1ExecuteForStatements(inst,sl);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
}

static
int Pass4CheckFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)) return 1; /* will give error */
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      return 0;
    default:
      DestroyValue(&value);
      return 1;			/* will give an error */
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    DestroyValue(&value);
    return 1;			/* will give error */
  case set_value:		/* okay thus far */
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;	/* always okay */
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass4CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass4CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
    return 1;			/* everything checks out */
  }
  /*NOTREACHED*/
  return 0; /* we here? */
}

static
int Pass4RealCheckFOR (struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if (Pass4CheckFOR(inst,statement)) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

static
int Pass3CheckFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)) {
    return 1; /* will give error */
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      return 0;
    default:
      DestroyValue(&value);
      return 1;			/* will give an error */
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    DestroyValue(&value);
    return 1;			/* will give error */
  case set_value:		/* okay thus far */
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;	/* always okay */
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass3CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass3CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
    return 1;			/* everything checks out */
  }
  /*NOTREACHED*/
  return 0; /* we here? */
}

static
int Pass3RealCheckFOR (struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if (Pass3CheckFOR(inst,statement)) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}


/**
	a currently unused function, with therefore unused subsidiary functions
*/
static
int Pass2CheckFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)) return 1; /* will give error */
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      return 0;
    default:
      DestroyValue(&value);
      return 1;			/* will give an error */
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    DestroyValue(&value);
    return 1;			/* will give error */
  case set_value:		/* okay thus far */
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;	/* always okay */
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass2CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass2CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
    return 1;			/* everything checks out */
  }
  /*NOTREACHED*/
  return 0; /* we here? */
}

static
int Pass2RealCheckFOR (struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if (Pass2CheckFOR(inst,statement)) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

/* checks every statement against every value of the loop index */
static
int Pass1CheckFOR(struct Instance *inst, struct Statement *statement)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  name = ForStatIndex(statement);
  ex = ForStatExpr(statement);
  sl = ForStatStmts(statement);
  if (FindForVar(GetEvaluationForTable(),name)) return 1; /* will give error */
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(inst);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      return 0;
    default:
      DestroyValue(&value);
      return 1;			/* will give an error */
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    DestroyValue(&value);
    return 1;			/* will give error */
  case set_value:		/* okay thus far */
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;	/* always okay */
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        if (!Pass1CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        if (!Pass1CheckStatementList(inst,sl)){
          RemoveForVariable(GetEvaluationForTable());
          DestroyValue(&value);
          return 0;
        }
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
    return 1;			/* everything checks out */
  }
  /*NOTREACHED*/
  return 0; /* we here? */
}


#ifdef THIS_IS_AN_UNUSED_FUNCTION
static
int Pass1RealCheckFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if (Pass1CheckFOR(inst,statement)){
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}
#endif  /*  THIS_IS_AN_UNUSED_FUNCTION  */



static
int Pass5ExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if ( Pass5RealExecuteFOR(inst,statement) ) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}



static
int Pass4ExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if ( Pass4RealExecuteFOR(inst,statement) ) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

static
void MakeWhenCaseReferencesFOR(struct Instance *inst,
                               struct Instance *child,
                               struct Statement *statement,
                               struct gl_list_t *listref)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
    MakeRealWhenCaseReferencesFOR(inst,child,statement,listref);
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return;
}

static
int Pass3ExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if ( Pass3RealExecuteFOR(inst,statement) ) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

/* This function is seen exactly once when handling a set of
nested for loops in the same model.
In pass2 models are handled from a list rather than recursively,
so the SavedForTable should always be null (as best I can tell).
BAA; 8/2006.
*/
static
int Pass2ExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if ( Pass2RealExecuteFOR(inst,statement) ) {
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

static
int Pass1ExecuteFOR(struct Instance *inst, struct Statement *statement)
{
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());
  if (Pass1CheckFOR(inst,statement)){
    Pass1RealExecuteFOR(inst,statement);
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 1;
  }else{
    DestroyForTable(GetEvaluationForTable());
    SetEvaluationForTable(SavedForTable);
    return 0;
  }
}

/*------------------------------------------------------------------------------
  GENERAL STATEMENT PROCESSING
*/

static
int Pass5ExecuteStatement(struct Instance *inst,struct Statement *statement)
{
  switch(StatementType(statement)){ /* should be a LNK statement */
  case LNK:
    return ExecuteLNK(inst,statement);
  case UNLNK:
    STATEMENT_ERROR(statement," UNLINK statement not allowed in the declarative section");
    return 0;
  case FOR:
    return Pass5ExecuteFOR(inst,statement);
  default:
    return 1;
    /* For anything else but a LINK and FOR statement */
  }
}

static
int Pass4ExecuteStatement(struct Instance *inst,struct Statement *statement)
{
  switch(StatementType(statement)){ /* should be a WHEN statement */
  case WHEN:
    return ExecuteWHEN(inst,statement);
  case FOR:
    return Pass4ExecuteFOR(inst,statement);
  case LNK:
    return 1; /* automatically assume done */
  case UNLNK:
    return 1;
  default:
    return 1;
    /* For anything else but a WHEN and FOR statement */
  }
}

static
int Pass3ExecuteStatement(struct Instance *inst,struct Statement *statement)
{
  switch(StatementType(statement)){ /* should be an if relinstance */
  case FOR:
    return Pass3ExecuteFOR(inst,statement);
  case LOGREL:
    return ExecuteLOGREL(inst,statement);
  case COND:
    return Pass3ExecuteCOND(inst,statement);
  case WHEN:
    return 1; /* assumed done  */
  case LNK:
    return 1; /* assumed done */
  case UNLNK:
    return 1;
  case FNAME:
    STATEMENT_ERROR(statement,"FNAME are allowed only inside a WHEN statement");
    return 0;
  default:
    return 0;
    /* Nondeclarative statements flagged in pass3 */
  }
}

static
int Pass2ExecuteStatement(struct Instance *inst,struct Statement *statement)
{
  switch(StatementType(statement)){ /* should be an if relinstance */
  case FOR:
#ifdef DEBUG_RELS
    ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
    WriteStatement(stderr, statement, 3);
    error_reporter_end_flush();
#endif
    return Pass2ExecuteFOR(inst,statement);
  case REL:
#ifdef DEBUG_RELS
    ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
    WriteStatement(stderr, statement, 3);
    error_reporter_end_flush();
#endif
    /* ER expected to succeed or fail permanently. this may change. */
    return ExecuteREL(inst,statement);
  case EXT:
	/* CONSOLE_DEBUG("ABOUT TO EXECUTEEXT"); */
    return ExecuteEXT(inst,statement);
  case COND:
    return Pass2ExecuteCOND(inst,statement);
  case LOGREL:
		return 1; /* assumed done */
  case WHEN:
    return 1; /* assumed done  */
  case LNK:
    return 1; /* assumed done */
  case UNLNK:
    return 0; /* meaning what??? FIXME */
  case FNAME:
    STATEMENT_ERROR(statement,"FNAME are allowed only inside a WHEN statement");
    return 0;
  default:
    return 0;
    /* Nondeclarative statements flagged in pass2 */
  }
}

static
int Pass1ExecuteStatement(struct Instance *inst, unsigned long *c,
                          struct Statement *statement)
{
  switch(StatementType(statement)){
  case ALIASES:
    return ExecuteALIASES(inst,statement);
  case ARR:
    return ExecuteARR(inst,statement);
  case ISA:
    return ExecuteISA(inst,statement);
  case IRT:
    return ExecuteIRT(inst,statement);
  case ATS:
    return ExecuteATS(inst,statement);
  case AA:
    return ExecuteAA(inst,statement);
  case FOR:
    return Pass1ExecuteFOR(inst,statement);
  case REL:
    return 1; /* automatically assume done */
  case CALL:
  case EXT:
    return 1; /* automatically assume done */
  case REF:
    return ExecuteREF(inst,statement);
  case CASGN:
    return ExecuteCASGN(inst,statement);
  case ASGN: /* don't do these in instantiation phase. just mark off */
    return 1;
  case LOGREL:
    return 1; /* automatically assume done */
  case COND:
    return 1; /* automatically assume done */
  case WHEN:
    return 1; /* automatically assume done */
  case LNK:
    return 1; /* automatically assume done */
  case UNLNK:
    STATEMENT_ERROR(statement,"UNLINK is allowed only inside the declarative part of the model; statement not executed");
    return 0;
  case FNAME:
    STATEMENT_ERROR(statement,"FNAME are allowed only inside a WHEN statement");
		ERROR_REPORTER_HERE(ASC_PROG_ERR,"while running %s",__FUNCTION__);
    return 0;
  case SELECT:
    return ExecuteSELECT(inst,c,statement);
  default:
    STATEMENT_ERROR(statement,
                       "Inappropriate statement type in declarative section");
    ASC_PANIC("Inappropriate statement type in declarative section");
  }
  return 0;
}


static
int ArraysExpanded(struct Instance *work)
{
  unsigned long c,len;
  struct Instance *child;
  len = NumberChildren(work);
  for(c=1;c<=len;c++){
    child = InstanceChild(work,c);
    if (child!=NULL)
      if ((InstanceKind(child)==ARRAY_INT_INST)||
          (InstanceKind(child)==ARRAY_ENUM_INST))
        if (!RectangleArrayExpanded(child)) return 0;
  }
  return 1;
}


/**
	Try to execute all the LINK statements in instance work.
	It assumes that work is the top of the pending instance list.
	Will skip all non-LINK statements.
*/
static
void Pass5ExecuteLinkStatements(struct BitList *blist,
                                struct Instance *work,
                                int *changed
){
  unsigned long c;
  struct TypeDescription *def;
  struct gl_list_t *statements;
  CONST struct StatementList *stats;
  def = InstanceTypeDesc(work);
  stats = GetStatementList(def);
  statements = GetList(stats);
  for(c=FirstNonZeroBit(blist);c<BLength(blist);c++){
    if (ReadBit(blist,c)){
      if ( Pass5ExecuteStatement(work,
           (struct Statement *)gl_fetch(statements,c+1)) ) {
        ClearBit(blist,c);
        *changed = 1;
      }
    }
  }
}


/**
	Try to execute all the when statements in instance work.
	It assumes that work is the top of the pending instance list.
	Will skip all non-when statements.
*/
static
void Pass4ExecuteWhenStatements(struct BitList *blist,
                                struct Instance *work,
                                int *changed
){
  unsigned long c;
  struct TypeDescription *def;
  struct gl_list_t *statements;
  CONST struct StatementList *stats;
  def = InstanceTypeDesc(work);
  stats = GetStatementList(def);
  statements = GetList(stats);
  for(c=FirstNonZeroBit(blist);c<BLength(blist);c++){
    if (ReadBit(blist,c)){
      if ( Pass4ExecuteStatement(work,
           (struct Statement *)gl_fetch(statements,c+1)) ) {
        ClearBit(blist,c);
        *changed = 1;
      }
    }
  }
}

/**
	Try to execute all the unexecuted logical relations in instance work.
	It assumes that work is the top of the pending instance list.
	Will skip all non-logical relations.
*/
static
void Pass3ExecuteLogRelStatements(struct BitList *blist,
                                     struct Instance *work,
                                     int *changed
){
  unsigned long c;
  struct TypeDescription *def;
  struct gl_list_t *statements;
  CONST struct StatementList *stats;
  def = InstanceTypeDesc(work);
  stats = GetStatementList(def);
  statements = GetList(stats);
  for(c=FirstNonZeroBit(blist);c<BLength(blist);c++){
    if (ReadBit(blist,c)){
      if ( Pass3ExecuteStatement(work,
           (struct Statement *)gl_fetch(statements,c+1)) ) {
        ClearBit(blist,c);
        *changed = 1;
      }
    }
  }
}

/**
	Try to execute all the unexecuted relations in instance work.
	Does not assume that work is the top of the pending instance list.
	Will skip all non-relations in instance work.
*/
static
void Pass2ExecuteRelationStatements(struct BitList *blist,
                                    struct Instance *work,
                                    int *changed
){
  unsigned long c;
  struct TypeDescription *def;
  struct gl_list_t *statements;
  CONST struct StatementList *stats;
  def = InstanceTypeDesc(work);
  stats = GetStatementList(def);
  statements = GetList(stats);
  for(c=FirstNonZeroBit(blist);c<BLength(blist);c++){
    if (ReadBit(blist,c)){
      if ( Pass2ExecuteStatement(work,
           (struct Statement *)gl_fetch(statements,c+1)) ) {
        //CONSOLE_DEBUG("Got error code here, clearing bit in blist, setting '*changed' to 1");
        ClearBit(blist,c);
        *changed = 1;
      }
    }
  }
}

/**
	Try to execute all the unexecuted statements in instance work.
	It assumes that work is the top of the pending instance list.
	Will skip relations in a new way. Relations instances and arrays of
	relations will be left as NULL instances (not merely hollow relations)
*/
static
void Pass1ExecuteInstanceStatements(struct BitList *blist,
                                    struct Instance *work,
                                    int *changed
){
  unsigned long c;
  struct TypeDescription *def;
  struct gl_list_t *statements;
  CONST struct StatementList *stats;
  struct Statement *stat;

  def = InstanceTypeDesc(work);
  stats = GetStatementList(def);
  statements = GetList(stats);
  c=FirstNonZeroBit(blist);
  while(c<BLength(blist)) {
    if (ReadBit(blist,c)){
      stat = (struct Statement *)gl_fetch(statements,c+1);
      if ( Pass1ExecuteStatement(work,&c,stat) ) {
        if (StatementType(stat) != SELECT ) {
          ClearBit(blist,c);
        }
        *changed = 1;
      }
    }
    c++;
  }
}


static
void Pass5ProcessPendingInstances(void)
{
  struct pending_t *work;
  struct Instance *inst;
  struct BitList *blist;
  int changed = 0,count=0;
  unsigned long c;
  /*
   * pending will have at least one instance, or while will fail
   */
  while((count < PASS5MAXNUMBER) && NumberPending()>0){
    changed = 0;
    c = 0;
    while(c < NumberPending()){
      work = TopEntry();
      if (work!=NULL) {
        inst = PendingInstance(work);
        blist = InstanceBitList(inst);
      }else{
        blist = NULL;   /* this shouldn't be necessary, but is */
		inst = NULL;
      }
      if ((blist!=NULL)&&!BitListEmpty(blist)){
        /* only models get here */
        Pass5ExecuteLinkStatements(blist,inst,&changed);
        /* we do away with TryArrayExpansion because it doesn't do links either */
        if (BitListEmpty(blist)) {
          /*
		   * delete PENDING model.
		   */
          RemoveInstance(PendingInstance(work));
        }else{
		  /*
		   * bitlist is still unhappy, but there's nothing to do about it.
           * Move the instance to the bottom and increase the counter
		   * so that we do not visit it again.
		   */
          if (work == TopEntry()) {
            MoveToBottom(work);
          }
          c++;
        }
      }else{
        /* We do not attempt to expand non-link arrays in pass5. */
      }
    }
#if (PASS5MAXNUMBER > 1)
    if (!changed) {
#endif
      count++;
      g_iteration++;   /* The global iteration counter */
#if (PASS5MAXNUMBER > 1)
    }
#endif
  }
  /* done, or there were no pendings at all and while failed */
}

static
void Pass4ProcessPendingInstances(void)
{
  struct pending_t *work;
  struct Instance *inst;
  struct BitList *blist;
  int changed = 0,count=0;
  unsigned long c;
  /*
   * pending will have at least one instance, or while will fail
   */
  while((count < PASS4MAXNUMBER) && NumberPending()>0){
    changed = 0;
    c = 0;
    while(c < NumberPending()){
      work = TopEntry();
      if (work!=NULL) {
        inst = PendingInstance(work);
        blist = InstanceBitList(inst);
      }else{
        blist = NULL;   /* this shouldn't be necessary, but is */
		inst = NULL;
      }
      if ((blist!=NULL)&&!BitListEmpty(blist)){
        /* only models get here */
        Pass4ExecuteWhenStatements(blist,inst,&changed);
        /* we do away with TryArrayExpansion because it doesn't do whens */
        if (BitListEmpty(blist)) {
          /*
		   * delete PENDING model.
		   */
          RemoveInstance(PendingInstance(work));
        }else{
		  /*
		   * bitlist is still unhappy, but there's nothing to do about it.
           * Move the instance to the bottom and increase the counter
		   * so that we do not visit it again.
		   */
          if (work == TopEntry()) {
            MoveToBottom(work);
          }
          c++;
        }
      }else{
        /* We do not attempt to expand non-when arrays in pass4. */
      }
    }
#if (PASS4MAXNUMBER > 1)
    if (!changed) {
#endif
      count++;
      g_iteration++;   /* The global iteration counter */
#if (PASS4MAXNUMBER > 1)
    }
#endif
  }
  /* done, or there were no pendings at all and while failed */
}

static
void Pass3ProcessPendingInstances(void)
{
  struct pending_t *work;
  struct Instance *inst;
  struct BitList *blist;
  int changed = 0,count=0;
  unsigned long c;
  /* Reinitialize the number of iterations */
  ClearIteration();
  g_iteration++;

  /* pending will have at least one instance, or while will fail */
  while((count < PASS3MAXNUMBER) && NumberPending()>0){
    changed = 0;
    c = 0;
    while(c < NumberPending()){
      work = TopEntry();
      if (work!=NULL) {
        inst = PendingInstance(work);
        /* WriteInstanceName(stderr,inst,NULL); FPRINTF(stderr,"\n"); */
        blist = InstanceBitList(inst);
      }else{
        blist = NULL; /* this shouldn't be necessary, but is */
        inst = NULL;
      }
      if ((blist!=NULL)&&!BitListEmpty(blist)){
        /* only models get here */
        Pass3ExecuteLogRelStatements(blist,inst,&changed);
        /* we do away with TryArrayExpansion because it doesn't do rels */

#if (PASS3MAXNUMBER > 1)
        if (BitListEmpty(blist) && ArraysExpanded(inst)) {
        /* removal is now unconditional because even if there are
                pendings, theres nothing we can do. If we
                go back to some uglier scheme, we would still need to test,
                but only against bitlist, not ArraysExpanded. */
#endif
          RemoveInstance(PendingInstance(work));
                /* delete PENDING model. bitlist could still be unhappy,
                        but there's nothing to do about it. */
          /* instance could move while being worked. reget the pointer.
             work itself cannot move, in memory that is. its list position
             can change. Actually in relation phase, this may not be
                true. */
#if (PASS3MAXNUMBER > 1)
        /* we aren't touching any model twice, so this isn't needed
                unless back to uglier scheme */
        }else{
          if (work == TopEntry())
            MoveToBottom(work);
          c++;
        }
#endif
      }else{
        /* We do not attempt to expand non-logical relation arrays in pass3.*/
      }
    }
    if (!changed) {
      count++;
      g_iteration++;		/* The global iteration counter */
    }
  }
  /* done, or there were no pendings at all and while failed */
}

/**
	This is the singlepass phase2 with anontype sharing of
	relations implemented. If relations can depend on other
	relations (as in future differential work) then this function
	needs to be slightly more sophisticated.
*/
static
void Pass2ProcessPendingInstancesAnon(struct Instance *result)
{
  struct BitList *blist;
  struct Instance *proto;	/* first of an anon clique */
  struct gl_list_t *atl;	/* anonymous types in result */
  struct gl_list_t *protovarindices; /* all vars in all rels in local MODEL */
  struct AnonType *at;
  int changed = 0;		/* will become 1 if any local relation made */
  int anychange = 0;		/* will become 1 if any change anywhere */
  unsigned long c,n,alen,clen;
#if TIMECOMPILER
  double start,classt;
#endif
  /*CONSOLE_DEBUG("...");*/

  /* pending will have at least one instance, or quick return. */
  asc_assert(PASS2MAXNUMBER==1);

  if (NumberPending() > 0) {
#if TIMECOMPILER
    start = tm_cpu_time();
#endif
    atl = Asc_DeriveAnonList(result);
#if TIMECOMPILER
    classt = tm_cpu_time();
    CONSOLE_DEBUG("Classification: %0.6f s (for relation sharing)",(classt-start));
    start = tm_cpu_time();
#endif
    alen = gl_length(atl);
    /* iterate over all anontypes, working on only models. */
    for (n=1; n <= alen; n++) {
      changed = 0;
      at = Asc_GetAnonType(atl,n);
      proto = Asc_GetAnonPrototype(at);
      if (InstanceKind(proto) == MODEL_INST && InstanceInList(proto)) {
#ifdef DEBUG_RELS
        ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
        FPRINTF(stderr,"Rels in model: ");
        WriteInstanceName(stderr,proto,NULL); FPRINTF(stderr,"\n");
        error_reporter_end_flush();
#endif
        blist = InstanceBitList(proto);
        if ((blist!=NULL) && !BitListEmpty(blist)) {
          Pass2ExecuteRelationStatements(blist,proto,&changed);
          RemoveInstance(proto);
          anychange += changed;
        }
        /* finish rest of AT clique, if there are any, if we made something */
        clen = Asc_GetAnonCount(atl,n);
        if (clen==1 || changed == 0) {
          continue;
        }
        protovarindices = Pass2CollectAnonProtoVars(proto);
        for (c=2; c <= clen; c++) {
          Pass2CopyAnonProto(proto,blist,protovarindices,
                             Asc_GetAnonTypeInstance(at,c));
        }
        Pass2DestroyAnonProtoVars(protovarindices);
      }
    }
    Asc_DestroyAnonList(atl);
    if (!anychange) {
      g_iteration++;		/* The global iteration counter */
    }else{
      /* we did something, so try the binary compile */
#if TIMECOMPILER
      classt = tm_cpu_time();
      CONSOLE_DEBUG("Making tokens: %0.6f s (for relations)",(classt-start));
      start = tm_cpu_time();
#endif
      BinTokensCreate(result,BT_C);
#if TIMECOMPILER
      classt = tm_cpu_time();
      CONSOLE_DEBUG("build/link: %0.6f s (for bintokens)",(classt-start));
#endif
    }
  }
  /* done, or there were no pendings at all and while failed */
}

/**
	This is the old pass1-like flavor of pass2process.
	Do not delete it yet, as it is the way we'll have to
	start thinking if relations reference relations, i.e.
	in the use of derivatives in the ASCEND language.
*/
static
void Pass2ProcessPendingInstances(void)
{
  struct pending_t *work;
  struct Instance *inst;
  struct BitList *blist;
  int changed = 0,count=0;
  unsigned long c;
  /* pending will have at least one instance, or while will fail */
  while((count < PASS2MAXNUMBER) && NumberPending()>0){
    changed = 0;
    c = 0;
    while(c < NumberPending()){
      work = TopEntry();
      if (work!=NULL) {
        inst = PendingInstance(work);
        /* WriteInstanceName(stderr,inst,NULL); FPRINTF(stderr,"\n"); */
        blist = InstanceBitList(inst);
      }else{
        blist = NULL; /* this shouldn't be necessary, but is */
        inst = NULL;
      }
      if ((blist!=NULL)&&!BitListEmpty(blist)){
        /* only models get here */
        Pass2ExecuteRelationStatements(blist,inst,&changed);
        /* we do away with TryArrayExpansion because it doesn't do rels */

#if (PASS2MAXNUMBER > 1)
        if (BitListEmpty(blist) && ArraysExpanded(inst)) {
        /* removal is now unconditional because even if there are
                pendings, theres nothing we can do. If we
                go back to some uglier scheme, we would still need to test,
                but only against bitlist, not ArraysExpanded. */
#endif
          RemoveInstance(PendingInstance(work));
                /* delete PENDING model. bitlist could still be unhappy,
                        but there's nothing to do about it. */
          /* instance could move while being worked. reget the pointer.
             work itself cannot move, in memory that is. its list position
             can change. Actually in relation phase, this may not be
                true. */
#if (PASS2MAXNUMBER > 1)
        /* we aren't touching any model twice, so this isn't needed
                unless back to uglier scheme */
        }else{
          if (work == TopEntry())
            MoveToBottom(work);
          c++;
        }
#endif
      }else{
        /* We do not attempt to expand non-relation arrays in pass2. */
      }
    }
    if (!changed) {
      count++;
      g_iteration++;		/* The global iteration counter */
    }
  }
  /* done, or there were no pendings at all and while failed */
}


/*
 * in a bizarre way, this will generally lead to a bottom up
 * instantiation finishing process, though it is started in a
 * top down fashion. While not quite a recursion, work proceeds
 * in a nested fashion and so the FOR tables must be pushed
 * and popped to get the right interpretation.
 */
static
void Pass1ProcessPendingInstances(void)
{
  struct pending_t *work;
  struct Instance *inst;
  struct BitList *blist;
  int changed = 0,count=0;
  unsigned long c;
  while((count <= MAXNUMBER)&&NumberPending()>0){
    changed = 0;
    c = 0;
    while(c < NumberPending()){
      work = TopEntry();
      inst = PendingInstance(work);
      blist = InstanceBitList(inst);
      if ((blist!=NULL)&&!BitListEmpty(blist)){
        /* only models get here */
        Pass1ExecuteInstanceStatements(blist,inst,&changed);
        TryArrayExpansion(inst,&changed);
        /* try to expand any nonalias,nonparameterized arrays */
        if (BitListEmpty(blist)&&ArraysExpanded(inst)) {
          RemoveInstance(PendingInstance(work));
                /* delete PENDING model */
          /* instance could move while being worked. reget the pointer.
             work itself cannot move, in memory that is. its list position
             can change */
        }else{
          if (work == TopEntry()) {
            MoveToBottom(work);
          }
          c++;
        }
      }else{
        TryArrayExpansion(inst,&changed);
        /* try to expand any nonalias,nonparameterized arrays */
        if (ArraysExpanded(inst)) {
          RemoveInstance(PendingInstance(work));
                /* delete PENDING array */
          /* instance could move while being worked. reget the pointer.
             work itself cannot move, in memory that is. its list position
             can change */
        }else{
          if (work == TopEntry())
            MoveToBottom(work);
          c++;
        }
      }
    }
    if (!changed) {
      count++;
      g_iteration++;		/* The global iteration counter */
    }
  }
}


static struct gl_list_t *GetInstanceStatementList(struct Instance *i){
  struct TypeDescription *def;
  CONST struct StatementList *slist;
  def = InstanceTypeDesc(i);
  if (def==NULL) return NULL;
  slist = GetStatementList(def);
  if (slist==NULL) return NULL;
  return GetList(slist);
}


/* run the given default statements of i */
static void ExecuteDefault(struct Instance *i
	, struct Statement *stat,unsigned long int *depth
){
  struct gl_list_t *lvals;
  register unsigned long c,length;
  register struct Instance *ptr;
  struct value_t value;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  if(NULL != (lvals = FindInstances(i,DefaultStatVar(stat),&err))){
    for(c=1,length=gl_length(lvals);c<=length;c++){
      ptr = (struct Instance *)gl_fetch(lvals,c);
      switch(InstanceKind(ptr)){
      case REAL_ATOM_INST:
      case REAL_INST:
        if (*depth == 0) *depth = InstanceDepth(i);
        if (DepthAssigned(ptr) >= *depth){
          asc_assert(GetEvaluationContext()==NULL);
          SetEvaluationContext(i);
          value = EvaluateExpr(DefaultStatRHS(stat),NULL,
                               InstanceEvaluateName);
          SetEvaluationContext(NULL);
          if ( IsWild(RealAtomDims(ptr)) ) {
            switch(ValueKind(value)) {
            case real_value:
              SetRealAtomValue(ptr,RealValue(value),*depth);
              if ( !IsWild(RealValueDimensions(value)) ) {
                SetRealAtomDims(ptr,RealValueDimensions(value));
              }
              break;
            case integer_value:
              SetRealAtomValue(ptr,(double)IntegerValue(value),*depth);
              SetRealAtomDims(ptr,Dimensionless());
              break;
            default:
              STATEMENT_ERROR(stat,"Bad real default value");
              break;
            }
          }else{
            switch(ValueKind(value)) {
            case real_value:
              if ( !SameDimen(RealValueDimensions(value),RealAtomDims(ptr)) ){
                STATEMENT_ERROR(stat,
                "Default right hand side is dimensionally inconsistent");
              }else{
                SetRealAtomValue(ptr,RealValue(value),*depth);
              }
              break;
            case integer_value:
              if ( !SameDimen(Dimensionless(),RealAtomDims(ptr)) ){
                STATEMENT_ERROR(stat,
                "Default right hand side is dimensionally inconsistent");
              }else{
                SetRealAtomValue(ptr,(double)IntegerValue(value),*depth);
              }
              break;
            default:
              STATEMENT_ERROR(stat,"Bad real default value");
              break;
            }
          }
          DestroyValue(&value);
        }
        break;
      case BOOLEAN_ATOM_INST:
      case BOOLEAN_INST:
        if (*depth == 0) *depth = InstanceDepth(i);
        if (DepthAssigned(ptr) > *depth){
          asc_assert(GetEvaluationContext()==NULL);
          SetEvaluationContext(i);
          value = EvaluateExpr(DefaultStatRHS(stat),NULL,
                               InstanceEvaluateName);
          SetEvaluationContext(NULL);
          if (ValueKind(value) == boolean_value){
            SetBooleanAtomValue(ptr,BooleanValue(value),*depth);
          }else{
            STATEMENT_ERROR(stat, "Bad boolean default value");
          }
          DestroyValue(&value);
        }
        break;
      case INTEGER_ATOM_INST:
      case INTEGER_INST:
        asc_assert(GetEvaluationContext()==NULL);
        SetEvaluationContext(i);

        value = EvaluateExpr(DefaultStatRHS(stat),NULL,
                               InstanceEvaluateName);
        SetEvaluationContext(NULL);
        if (ValueKind(value) == integer_value){
          SetIntegerAtomValue(ptr,IntegerValue(value),0);
        }else{
          STATEMENT_ERROR(stat, "Bad integer default value");
        }
        DestroyValue(&value);
        break;
      case SYMBOL_ATOM_INST:
      case SYMBOL_INST:
        asc_assert(GetEvaluationContext()==NULL);
        SetEvaluationContext(i);
        value = EvaluateExpr(DefaultStatRHS(stat),NULL,
                               InstanceEvaluateName);
        SetEvaluationContext(NULL);
        if (ValueKind(value) == symbol_value){
          SetSymbolAtomValue(ptr,SymbolValue(value));
        }else{
          STATEMENT_ERROR(stat, "Bad symbol default value");
        }
        DestroyValue(&value);
        break;
      default: /* NEED stuff here */
 	break;
      }
    }
    gl_destroy(lvals);
  }else{
    STATEMENT_ERROR(stat, "Nonexistent LHS variable in default statement.");
  }
}

/**
	run the default statements of i, including nested fors, but
	not recursive to i children.
*/
static
void ExecuteDefaultStatements(struct Instance *i,
                              struct gl_list_t *slist,
                              unsigned long int *depth)
{
  register unsigned long c,length;
  register struct Statement *stat;

  if (slist){
    length = gl_length(slist);
    for(c=1;c<=length;c++){
      stat = (struct Statement *)gl_fetch(slist,c);
      switch(StatementType(stat)){
      case ASGN:
        ExecuteDefault(i,stat,depth);
        break;
      case FOR:
        if ( ForContainsDefaults(stat) ){
          RealDefaultFor(i,stat,depth);
        }
        break;
      default: /* nobody else is a default */
        break;
      }
    }
  }
}

static
void RealDefaultFor(struct Instance *i,
                    struct Statement *stat,
                    unsigned long int *depth)
{
  symchar *name;
  struct Expr *ex;
  struct StatementList *sl;
  unsigned long c,len;
  struct value_t value;
  struct set_t *sptr;
  struct for_var_t *fv;
  sl = ForStatStmts(stat);
  name = ForStatIndex(stat);
  ex = ForStatExpr(stat);
  if (FindForVar(GetEvaluationForTable(),name)){ /* duplicated for variable*/
    FPRINTF(ASCERR,"Error during default stage.\n");
    STATEMENT_ERROR(stat, "FOR construct uses duplicate index variable");
    return;
  }
  asc_assert(GetEvaluationContext()==NULL);
  SetEvaluationContext(i);
  value = EvaluateExpr(ex,NULL,InstanceEvaluateName);
  SetEvaluationContext(NULL);
  switch(ValueKind(value)){
  case error_value:
    switch(ErrorValue(value)){
    case name_unfound:
    case undefined_value:
      DestroyValue(&value);
      FPRINTF(ASCERR,"Error in default stage.\n");
      STATEMENT_ERROR(stat, "FOR has undefined values");
      return;
    default:
      WriteForValueError(stat,value);
      DestroyValue(&value);
      return;
    }
  case real_value:
  case integer_value:
  case symbol_value:
  case boolean_value:
  case list_value:
    FPRINTF(ASCERR,"Error during default stage.\n");
    STATEMENT_ERROR(stat, "FOR expression returns the wrong type");
    DestroyValue(&value);
    return;
  case set_value:
    sptr = SetValue(value);
    switch(SetKind(sptr)){
    case empty_set: break;
    case integer_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_integer);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForInteger(fv,FetchIntMember(sptr,c));
        ExecuteDefaultStatements(i,GetList(sl),depth);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    case string_set:
      fv = CreateForVar(name);
      SetForVarType(fv,f_symbol);
      AddLoopVariable(GetEvaluationForTable(),fv);
      len = Cardinality(sptr);
      for(c=1;c<=len;c++){
        SetForSymbol(fv,FetchStrMember(sptr,c));
        ExecuteDefaultStatements(i,GetList(sl),depth);
      }
      RemoveForVariable(GetEvaluationForTable());
      break;
    }
    DestroyValue(&value);
  }
}

static
void DefaultStatementList(struct Instance *i,
                          struct gl_list_t *slist,
                          unsigned long int *depth)
{
  unsigned long c,length;
  struct Statement *stat;
  struct for_table_t *SavedForTable;
  if (slist){
    length = gl_length(slist);
    for(c=1;c<=length;c++){
      stat = (struct Statement *)gl_fetch(slist,c);
      switch(StatementType(stat)){
      case ASGN:
        ExecuteDefault(i,stat,depth);
        break;
      case FOR:
        if ( ForContainsDefaults(stat) ){
          SavedForTable = GetEvaluationForTable();
          SetEvaluationForTable(CreateForTable());
          RealDefaultFor(i,stat,depth);
          DestroyForTable(GetEvaluationForTable());
          SetEvaluationForTable(SavedForTable);
        }
        break;
      case SELECT:
        if (SelectContainsDefaults(stat)) {
          ExecuteDefaultsInSELECT(i,&c,stat,depth);
        }else{
          c = c + SelectStatNumberStats(stat) ;
        }
        break;
      default:
        break;
      }
    }
  }
}

static
void DefaultInstance(struct Instance *i)
{
  if (i && (InstanceKind(i) == MODEL_INST)){
    unsigned long depth=0;
    if (TypeHasDefaultStatements(InstanceTypeDesc(i)))
      DefaultStatementList(i,GetInstanceStatementList(i),&depth);
  }
}

static
void DefaultInstanceTree(struct Instance *i)
{
  VisitInstanceTree(i,DefaultInstance,0,0);
}



/**
	This just handles instantiating LINKs,
	ignoring anything else.
	This works with Pass5ProcessPendingInstances.
*/
static
struct Instance *Pass5InstantiateModel(struct Instance *result,
                                       unsigned long *pcount)
{
  /* do we need a ForTable on the stack here? don't think so. np4ppi does it */
  if (result!=NULL) {
    /* pass5 pendings already set by visit */
    Pass5ProcessPendingInstances();
    if (NumberPending()!=0) {
      FPRINTF(ASCERR,
        "There are unexecuted Phase 5 (LINKs) in the instance.\n");
      *pcount = NumberPending();
    }
    ClearList();
  }
  return result;
}

static
void Pass5SetLinkBits(struct Instance *inst)
{
  struct Statement *stat;

  if (inst != NULL && InstanceKind(inst)==MODEL_INST) {
    struct BitList *blist;

    blist = InstanceBitList(inst);
    if (blist!=NULL){
      unsigned long c;
      struct gl_list_t *statements = NULL;
      enum stat_t st;
      int changed;

      changed=0;
      if (BLength(blist)) {
        statements = GetList(GetStatementList(InstanceTypeDesc(inst)));
      }
      for(c=0;c<BLength(blist);c++){
        stat = (struct Statement *)gl_fetch(statements,c+1);
        st= StatementType(stat);
        if (st == SELECT) {
          if (SelectContainsLink(stat)) {
            ReEvaluateSELECT(inst,&c,stat,5,&changed);
          }else{
            c = c + SelectStatNumberStats(stat);
          }
        }else{
          if ( st == LNK || (st == FOR && ForContainsLink(stat)) ) {
            SetBit(blist,c);
            changed++;
          }
        }
      }
      /* if changed = 0 but bitlist not empty, we don't want to retry
        thoroughly done insts. if whens, then we can't avoid.
        if we did add any bits, then changed!= 0 is sufficient test. */
      if ( changed ) {
        AddBelow(NULL,inst);
        /* add PENDING model */
      }
    }
  }
}


/**
	This just handles instantiating whens,
	ignoring anything else.
	This works with Pass4ProcessPendingInstances.
*/
static
struct Instance *Pass4InstantiateModel(struct Instance *result,
                                       unsigned long *pcount)
{
  /* do we need a ForTable on the stack here? don't think so. np4ppi does it */
  if (result!=NULL) {
    /* pass4 pendings already set by visit */
    Pass4ProcessPendingInstances();
    if (NumberPending()!=0) {
      FPRINTF(ASCERR,
        "There are unexecuted Phase 4 (whens) in the instance.\n");
      *pcount = NumberPending();
    }
    ClearList();
  }
  return result;
}

static
void Pass4SetWhenBits(struct Instance *inst)
{
  struct Statement *stat;

  if (inst != NULL && InstanceKind(inst)==MODEL_INST) {
    struct BitList *blist;

    blist = InstanceBitList(inst);
    if (blist!=NULL){
      unsigned long c;
      struct gl_list_t *statements = NULL;
      enum stat_t st;
      int changed;

      changed=0;
      if (BLength(blist)) {
        statements = GetList(GetStatementList(InstanceTypeDesc(inst)));
      }
      for(c=0;c<BLength(blist);c++){
        stat = (struct Statement *)gl_fetch(statements,c+1);
        st= StatementType(stat);
        if (st == SELECT) {
          if (SelectContainsWhen(stat)) {
            ReEvaluateSELECT(inst,&c,stat,4,&changed);
          }else{
            c = c + SelectStatNumberStats(stat);
          }
        }else{
          if ( st == WHEN || (st == FOR && ForContainsWhen(stat)) ) {
            SetBit(blist,c);
            changed++;
          }
        }
      }
      /* if changed = 0 but bitlist not empty, we don't want to retry
        thoroughly done insts. if whens, then we can't avoid.
        if we did add any bits, then changed!= 0 is sufficient test. */
      if ( changed ) {
        AddBelow(NULL,inst);
        /* add PENDING model */
      }
    }
  }
}



/**
	This just handles instantiating logical relations,
	ignoring anything else.
	This works with Pass3ProcessPendingInstances.
	No recursion. No reallocation of result.
*/
static
struct Instance *Pass3InstantiateModel(struct Instance *result,
                                       unsigned long *pcount)
{
  if (result!=NULL) {
    /* pass3 pendings already set by visit */
    Pass3ProcessPendingInstances();
    if (NumberPending()!=0) {
      FPRINTF(ASCERR,
      "There are unexecuted Phase 3 (logical relations) in the instance.\n");
      *pcount = NumberPending();
    }
    ClearList();
  }
  return result;
}

static
void Pass3SetLogRelBits(struct Instance *inst)
{
  struct Statement *stat;
  if (inst != NULL && InstanceKind(inst)==MODEL_INST) {
    struct BitList *blist;

    blist = InstanceBitList(inst);
    if (blist!=NULL){
      unsigned long c;
      struct gl_list_t *statements = NULL;
      enum stat_t st;
      int changed;

      changed=0;
      if (BLength(blist)) {
        statements = GetList(GetStatementList(InstanceTypeDesc(inst)));
      }
      for(c=0;c<BLength(blist);c++){
        stat = (struct Statement *)gl_fetch(statements,c+1);
        st= StatementType(stat);
        if (st == SELECT) {
          if (SelectContainsLogRelations(stat)) {
            ReEvaluateSELECT(inst,&c,stat,3,&changed);
          }else{
            c = c + SelectStatNumberStats(stat);
          }
        }else{
          if ((st == LOGREL)
              || (st == COND && CondContainsLogRelations(stat))
              || (st == FOR && ForContainsLogRelations(stat)) ) {
            SetBit(blist,c);
            changed++;
          }
        }
      }
      /* if changed = 0 but bitlist not empty, we don't want to retry
        thoroughly done insts. if relations, then we can't avoid.
        if we did add any bits, then changed!= 0 is sufficient test. */
      if ( changed ) {
        AddBelow(NULL,inst);
        /* add PENDING model */
      }
    }
  }
}

/**
	This just handles instantiating relations, ignoring anything else.
	This works with Pass2ProcessPendingInstances AND
	Pass2ProcessPendingInstancesAnon, both of which are required to
	maintain a correct compilation.
	No recursion. No reallocation of result.
*/
#define ANONFORCE 0 /* require anonymous type use, even if whining OTHERWISE */
static struct Instance *Pass2InstantiateModel(struct Instance *result,
		unsigned long *pcount
){
#ifdef INST_DEBUG
  CONSOLE_DEBUG("starting...");
#endif

  /* do we need a ForTable on the stack here? don't think so. np2ppi does it */
  if (result!=NULL) {
    /* CONSOLE_DEBUG("result!=NULL..."); */
    /* pass2 pendings already set by visit */
    if (ANONFORCE || g_use_copyanon != 0) {
#if TIMECOMPILER
      g_ExecuteREL_CreateTokenRelation_calls = 0;
      g_CopyAnonRelation = 0;
#endif
      Pass2ProcessPendingInstancesAnon(result);
#if TIMECOMPILER
      CONSOLE_DEBUG("Relations in the instance U %d + C %d = T %d." ,
         g_ExecuteREL_CreateTokenRelation_calls,g_CopyAnonRelation,
         g_CopyAnonRelation+g_ExecuteREL_CreateTokenRelation_calls);
#endif
    }else{
      Pass2ProcessPendingInstances();
    }
    if (NumberPending()!=0) {
      FPRINTF(ASCERR,
        "There are unexecuted Phase 2 (relations) in the instance.\n");
        /* dump them here, nitwit. BAA. */
      *pcount = NumberPending();
    }
    ClearList();
  }
#ifdef INST_DEBUG
  CONSOLE_DEBUG("...done");
#endif
  return result;
}

static
void Pass2SetRelationBits(struct Instance *inst)
{
  struct Statement *stat;
  if (inst != NULL && InstanceKind(inst)==MODEL_INST) {
    struct BitList *blist;
#ifdef DEBUG_RELS
    ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
    FPRINTF(ASCERR,"P2SRB: ");
    WriteInstanceName(ASCERR,inst,debug_rels_work);
    error_reporter_end_flush();
#endif

    blist = InstanceBitList(inst);
    if (blist!=NULL){
      unsigned long c;
      struct gl_list_t *statements = NULL;
      enum stat_t st;
      int changed;

      changed=0;
      if (BLength(blist)) {
        statements = GetList(GetStatementList(InstanceTypeDesc(inst)));
      }
      for(c=0;c<BLength(blist);c++){
        stat = (struct Statement *)gl_fetch(statements,c+1);
        st= StatementType(stat);
        if (st == SELECT) {
          if (SelectContainsRelations(stat) ||
              SelectContainsExternal(stat))
          {
            ReEvaluateSELECT(inst,&c,stat,2,&changed);
          }else{
            c = c + SelectStatNumberStats(stat);
          }
        }else{
          if ( st == REL ||
               st == EXT ||
	       (st == COND &&
                 (CondContainsRelations(stat) ||
                  CondContainsExternal(stat) )
               ) ||
               (st == FOR &&
                 (ForContainsRelations(stat) ||
                  ForContainsExternal(stat) )
               )
             ){
            SetBit(blist,c);
            changed++;
          }
        }
      }
      /* if changed = 0 but bitlist not empty, we don't want to retry
        thoroughly done insts. if relations, then we can't avoid.
        if we did add any bits, then changed!= 0 is sufficient test. */
      if ( changed ) {
        AddBelow(NULL,inst);
        /* add PENDING model */
#ifdef DEBUG_RELS
        ERROR_REPORTER_START_NOLINE(ASC_PROG_NOTE);
        FPRINTF(stderr,"Changed: ");
        WriteInstanceName(ASCERR,inst,debug_rels_work);
        error_reporter_end_flush();
#endif
      }
    }
  }
}


/**
	This just handles instantiating models and reinstantiating models/arrays,
	ignoring defaults and relations.
	This works with Pass1ProcessPendingInstances.
	This is not a recursive function.
	Either def should be null or oldresult should null.
	If def is null, it is a reinstantiation, else result will be created.
*/
static
struct Instance *Pass1InstantiateModel(struct TypeDescription *def,
                                       unsigned long *pcount,
                                       struct Instance *oldresult)
{
  struct Instance *result;
  struct for_table_t *SavedForTable;
  SavedForTable = GetEvaluationForTable();
  SetEvaluationForTable(CreateForTable());

  if (def != NULL && oldresult != NULL) {
    Asc_Panic(2, "Pass1InstantiateModel",
              "Pass1InstantiateModel called with both type and instance.");
  }
  if (def!=NULL) { /* usual case */
    result = ShortCutMakeUniversalInstance(def);
    if (result==NULL) {
      result = CreateModelInstance(def); /*need to account for absorbed here.*/
      /* at present, creating parameterized sims illegal */
    }
  }else{
    result = oldresult;
  }
  if (result!=NULL) {
    ClearList();
    if (oldresult !=NULL) {
      SilentVisitInstanceTree(result,AddIncompleteInst,1,0);
    }else{
      AddBelow(NULL,result);
    }

    /* add PENDING model */
    Pass1ProcessPendingInstances();
    if(NumberPending()!=0) {
      *pcount = NumberPending();
      FPRINTF(ASCERR,
          "There are %lu unexecuted Phase 1 statements in the instance.\n"
          ,*pcount
      );
        if(g_compiler_warnings < 2 && *pcount >10L) {
          FPRINTF(ASCWAR,"More than 10 pending statements and warning %s"
              ,"level too low to allow printing.\n"
          );
        }else{
          FPRINTF(ASCWAR,"---- Pass 1 pending: -------------\n");
          if (g_compiler_warnings > 1) {
            CheckInstanceLevel(ASCWAR,result,1);
          }else{
            FPRINTF(ASCWAR,"(Total object check suppressed: g_compiler_warnings = %d)\n",g_compiler_warnings);
          }
          FPRINTF(ASCWAR,"---- End pass 1 pending-----------\n");
        }
        /* could instead start an error pool data structure with
        a review protocol in place post instantiation. */
    }
    ClearList();
  }
  DestroyForTable(GetEvaluationForTable());
  SetEvaluationForTable(SavedForTable);
  return result;
}

/**
	we have to introduce a new head to instantiatemodel to manage
	the phases.
	6 phases: model creation, relation creation,
	logical relation creation, when creation, LINK creation
	defaulting.
	BAA
	each pass is responsible for clearing the pending list it leaves.
*/
static
struct Instance *NewInstantiateModel(struct TypeDescription *def)
{
  struct Instance *result;
  unsigned long pass1pendings,pass2pendings,pass3pendings,pass4pendings,pass5pendings;
#if TIMECOMPILER
  double start, phase1t,phase2t,phase3t,phase4t,phase5t,phase6t;
#endif

#ifdef INST_DEBUG
  CONSOLE_DEBUG("starting...");
#endif

  pass1pendings = 0L;
  pass2pendings = 0L;
  pass3pendings = 0L;
  pass4pendings = 0L;
	pass5pendings = 0L;
#if TIMECOMPILER
  start = tm_cpu_time();
#endif
  result = Pass1InstantiateModel(def,&pass1pendings,NULL);

#if TIMECOMPILER
  phase1t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 1 models = %0.6f s",phase1t-start);
#endif

  /* At this point, there may be unexecuted non-relation
   * statements, but they can never be executed. The
   * pending list is therefore empty. We know how many.
   * The bitlists know which ones.
   */
  if (result!=NULL) {
#ifdef DEBUG_RELS
    debug_rels_work = result;
#endif
    /* now set the bits for relation statements and add pending models */
    SilentVisitInstanceTree(result,Pass2SetRelationBits,0,0);
    /* note, the order of the visit might be better 1 than 0. don't know
     * at present order 0, so we do lower models before those near root
     */
    if (g_use_copyanon) {
    }
    result = Pass2InstantiateModel(result,&pass2pendings);
    /* result will not move as currently implemented */
#ifdef DEBUG_RELS
    debug_rels_work = NULL;
#endif
  }else{
    return result;
  }

#if TIMECOMPILER
  phase2t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 2 relations = %0.6f s",(phase2t-phase1t));
#endif

  /* CONSOLE_DEBUG("Starting phase 3..."); */
  /* at this point, there may be unexecuted non-logical relation
   * statements, but they can never be executed. The
   * pending list is therefore empty. We know how many.
   * The bitlists know which ones.
   */
  if (result!=NULL) {
    /* now set the bits for relation statements and add pending models */
    SilentVisitInstanceTree(result,Pass3SetLogRelBits,0,0);
    /* note, the order of the visit might be better 1 than 0. don't know
     * at present order 0, so we do lower models before those near root
     */
    result = Pass3InstantiateModel(result,&pass3pendings);
   /* result will not move as currently implemented */
  }else{
    return result;
  }

#if TIMECOMPILER
  phase3t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 3 logicals = %0.6f s",(phase3t-phase2t));
#endif

  if (result!=NULL) {
    /* now set the bits for when statements and add pending models */
    SilentVisitInstanceTree(result,Pass4SetWhenBits,0,0);
    /* note, the order of the visit might be better 1 than 0. don't know */
    /* at present order 0, so we do lower models before those near root */
    result = Pass4InstantiateModel(result,&pass4pendings);
   /* result will not move as currently implemented */
  }else{
    return result;
  }

#if TIMECOMPILER
  phase4t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 4 when-case = %0.6f s",(phase4t-phase3t));
#endif

  if (result!=NULL) {
		/* now set the bits for LINK statements and add pending models */
	  SilentVisitInstanceTree(result,Pass5SetLinkBits,0,0);
	  /* note, the order of the visit might be better 1 than 0. don't know */
	  /* at present order 0, so we do lower models before those near root */
		result = Pass5InstantiateModel(result,&pass5pendings);
		/* result will not move as currently implemented <-DS: what do you really mean by this? */
  }else{
    return result;
  }
#if TIMECOMPILER
  phase5t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 5 LINK-case = %0.6f s",(phase5t-phase4t));
#endif
  if (result!=NULL) {
    if (!pass1pendings && !pass2pendings && !pass3pendings && !pass4pendings && !pass5pendings){
      DefaultInstanceTree(result);
    }else{
      ERROR_REPORTER_NOLINE(ASC_USER_WARNING,"There are unexecuted statements "
		"in the instance.\nDefault assignments not executed.");
    }
  }

#if TIMECOMPILER
  phase6t = tm_cpu_time();
  CONSOLE_DEBUG("Phase 6 defaults = %0.6f s",(phase6t-phase5t));
  if(pass1pendings || pass2pendings || pass3pendings || pass4pendings || pass5pendings) {
    CONSOLE_DEBUG("Phase 1 models \t\t%0.6f s\n", (phase1t-start));
    CONSOLE_DEBUG("Phase 2 relations \t\t%0.6f s\n", (phase2t-phase1t));
    CONSOLE_DEBUG("Phase 3 logical \t\t%0.6f s\n", (phase3t-phase2t));
    CONSOLE_DEBUG("Phase 4 when-case \t\t%0.6f s\n", (phase4t-phase3t));
    CONSOLE_DEBUG("Phase 5 LINK-case \t\t%0.6f s\n", (phase5t-phase4t));
    CONSOLE_DEBUG("Phase 6 defaults\t\t%0.6f s\n", (phase6t-phase5t));
  }
  CONSOLE_DEBUG("Total = %0.6f s",(phase6t-start));
# if 0 /* deep performance tuning */
  gl_reportrecycler(ASCERR);
# endif
#endif

  return result;
}



/**
	@return 1 if the type is uninstantiable as a sim or 0 otherwise
*/
static
int ValidRealInstantiateType(struct TypeDescription *def)
{
  if (def==NULL) return 1;
  switch(GetBaseType(def)){
  case real_constant_type:
  case boolean_constant_type:
  case integer_constant_type:
  case symbol_constant_type:
  case real_type:
  case boolean_type:
  case integer_type:
  case symbol_type:
  case set_type:
  case dummy_type:
    return 0;
  case model_type:
    if (GetModelParameterCount(def) !=0) {
      FPRINTF(ASCERR,
            "You cannot instance parameterized types by themselves yet.\n");
      FPRINTF(ASCERR,"They can only be contained in models or arrays.\n");
      return 1;
    }
    return 0;
  case array_type:
  case relation_type:
  case logrel_type:
  case when_type:
    FPRINTF(ASCERR,
            "You cannot instance arrays and relations by themselves.\n");
    FPRINTF(ASCERR,"They can only be contained in models or arrays.\n");
    return 1;
  default:
    ASC_PANIC("Unknown definition type.\n");			/*NOTREACHED*/

  }
}

/**
	this function not recursive
*/
static
struct Instance *NewRealInstantiate(struct TypeDescription *def,
                                 int intset)
{
  struct Instance *result;
  /* CONSOLE_DEBUG("..."); */

  result = ShortCutMakeUniversalInstance(def); /*does quick Universal check */
  if (result) return result;

  switch(GetBaseType(def)){
  case real_type:
  case real_constant_type:
    return CreateRealInstance(def);
  case boolean_type:
  case boolean_constant_type:
    return CreateBooleanInstance(def);
  case integer_type:
  case integer_constant_type:
    return CreateIntegerInstance(def);
  case symbol_type:
  case symbol_constant_type:
    return CreateSymbolInstance(def);
  case set_type:
    return CreateSetInstance(def,intset);
  case dummy_type:
    return CreateDummyInstance(def);
  case model_type:
    return NewInstantiateModel(def); /*this is now a nonrecursive controller */
  case array_type:
  case relation_type:
  case logrel_type:
  case when_type:
    FPRINTF(ASCERR,
            "You cannot instance arrays and relations by themselves.\n");
    FPRINTF(ASCERR,
            "They can only be contained in models or arrays.\n");
    return NULL; /* how did we get here? */
  default:
    ASC_PANIC("Unknown definition type.\n");	/*NOTREACHED*/

  }
}

static
void ExecDefMethod(struct Instance *root,symchar *simname, symchar *defmethod)
{
  //enum Proc_enum runstat;
  struct Name *name;
  if (InstanceKind(root) == MODEL_INST && defmethod != NULL) {
    name = CreateIdName(defmethod);
    Initialize(root,name,(char *)SCP(simname),ASCERR,(WP_BTUIFSTOP|WP_STOPONERR),NULL,NULL);
    DestroyName(name);
  }
}

struct Instance *NewInstantiate(symchar *type, symchar *name, int intset,
                                symchar *defmethod)
{
  struct Instance *result;	/* the SIM_INSTANCE */
  struct Instance *root;	/* the thing created by instantiate */
  struct TypeDescription *def;

  ++g_compiler_counter;/*instance tree may change:increment compiler counter*/
  def = FindType(type);
  if (def==NULL) {
    FPRINTF(ASCERR,"Cannot find the type for %s in the library\n",SCP(type));
    return NULL;
  }
  if (ValidRealInstantiateType(def)) return NULL;
  /* don't want to set up all the sim crap and then destroy it.
   * this stuff below core dumps if root comes back NULL, so we
   * check here first.
   */

  ClearIteration();
  result = CreateSimulationInstance(def,name);
  root = NewRealInstantiate(def,intset);
  LinkToParentByPos(result,root,1);
  if (g_ExtVariablesTable!=NULL) {
    SetSimulationExtVars(result,g_ExtVariablesTable);
    g_ExtVariablesTable = NULL;
  }
  ClearIteration();
  ExecDefMethod(root,name,defmethod);
  return result;
}


#ifdef THIS_IS_AN_UNUSED_FUNCTION
static
int IsInstanceComplete(struct Instance *i)
{
  struct BitList *blist;
  if (i==NULL) {
    return 0;
  }
  blist = InstanceBitList(i);
  if (blist) { /* only MODEL_INST have bitlists */
    if (BitListEmpty(blist))
      return 1;
  }
  return 1; /* atoms are assumed to be complete */
}
#endif  /* THIS_IS_AN_UNUSED_FUNCTION */


int IncompleteArray(CONST struct Instance *i)
{
  unsigned long c,len;
  struct Instance *child;
  register struct TypeDescription *desc;
  len = NumberChildren(i);
  for(c=1;c<=len;c++){
    child = InstanceChild(i,c);
    if (child != NULL){
      switch(InstanceKind(child)){
      case ARRAY_INT_INST:
      case ARRAY_ENUM_INST:
        desc = InstanceTypeDesc(child);
        if ((!GetArrayBaseIsRelation(desc))&&
            (!RectangleArrayExpanded(child))&&
            (!GetArrayBaseIsLogRel(desc))) {
          return 1;
        }
      default:
        break; /* out of switch, not out of for */
      }
    }
  }
  return 0;
}

static
void AddIncompleteInst(struct Instance *i)
{
  struct BitList *blist;
  asc_assert(i!=NULL);
  if ( ( (blist = InstanceBitList(i)) != NULL &&
        !BitListEmpty(blist)  ) ||
      IncompleteArray(i)) {
    /* model and atom/model array inst pending even if they aren't */
    AddBelow(NULL,i);
    /* add PENDING model or non-relation array */
  }
}

/**
	On entry it is assumed that the instance i has already been
	refined and so will not MOVE during subsequent work.
	The process here must be kept in sync with NewRealInstantiateModel,
	but must, additionally, deal ok with array instances as input.
*/
void NewReInstantiate(struct Instance *i)
{
  struct Instance *result;
  unsigned long pass1pendings,pass2pendings,pass3pendings,pass4pendings,pass5pendings;
#if TIMECOMPILER
  double start, phase1t,phase2t,phase3t,phase4t,phase5t,phase6t;
#endif
  ++g_compiler_counter;/*instance tree will change:increment compiler counter*/
  asc_assert(i!=NULL);
  if (i==NULL || !IsCompoundInstance(i)) return;
  /* can't reinstantiate simple objects, missing objects */

  pass1pendings = 0L;
  pass2pendings = 0L;
  pass3pendings = 0L;
  pass4pendings = 0L;
  pass5pendings = 0L;
#if TIMECOMPILER
  start = tm_cpu_time();
#endif
  result = Pass1InstantiateModel(NULL,&pass1pendings,i);
#if TIMECOMPILER
  phase1t = tm_cpu_time();
#endif
  if (result!=NULL) {
    SilentVisitInstanceTree(result,Pass2SetRelationBits,0,0);
    result = Pass2InstantiateModel(result,&pass2pendings);
  }else{
    ASC_PANIC("Reinstantiation phase 2 went insane. Bye!\n");
  }
#if TIMECOMPILER
  phase2t = tm_cpu_time();
#endif
  if (result!=NULL) {
    SilentVisitInstanceTree(result,Pass3SetLogRelBits,0,0);
    result = Pass3InstantiateModel(result,&pass3pendings);
  }else{
    ASC_PANIC("Reinstantiation phase 3 went insane. Bye!\n");
  }
#if TIMECOMPILER
  phase3t = tm_cpu_time();
#endif
  if (result!=NULL) {
    SilentVisitInstanceTree(result,Pass4SetWhenBits,0,0);
    result = Pass4InstantiateModel(result,&pass4pendings);
  }else{
    ASC_PANIC("Reinstantiation phase 4 went insane. Bye!\n");
  }
#if TIMECOMPILER
  phase4t = tm_cpu_time();
#endif
	if (result!=NULL) {
    SilentVisitInstanceTree(result,Pass5SetLinkBits,0,0);
    result = Pass5InstantiateModel(result,&pass5pendings);
  }else{
    ASC_PANIC("Reinstantiation phase 5 went insane. Bye!\n");
  }
#if TIMECOMPILER
  phase5t = tm_cpu_time();
#endif
  if (result!=NULL) {
    if (!pass1pendings && !pass2pendings && !pass3pendings && !pass4pendings && !pass5pendings){
      DefaultInstanceTree(result);
    }else{
      FPRINTF(ASCERR,"There are unexecuted statements in the instance.\n");
      FPRINTF(ASCERR,"Default assignments not executed.\n");
    }
  }else{
    ASC_PANIC("Reinstantiation phase 6 went insane. Bye!\n");
  }
#if TIMECOMPILER
  phase6t = tm_cpu_time();
  CONSOLE_DEBUG("Reinstantiation times:\n");
  CONSOLE_DEBUG("Phase 1 models \t\t%0.6f s\n",(phase1t-start));
  CONSOLE_DEBUG("Phase 2 relations \t\t%0.6f s\n",(phase2t-phase1t));
  CONSOLE_DEBUG("Phase 3 logicals \t\t%0.6f s\n",(phase3t-phase2t));
  CONSOLE_DEBUG("Phase 4 when-case \t\t%0.6f s\n",(phase4t-phase3t));
  CONSOLE_DEBUG("Phase 5 LINKs \t\t%0.6f s\n",(phase5t-phase4t));
  CONSOLE_DEBUG("Phase 6 defaults \t\t%0.6f s\n",(phase6t-phase5t));
  CONSOLE_DEBUG("Total\t\t%0.6f s\n",(phase6t-start));
#endif
  return;
}

/*------------------------------------------------------------------------------
	Some supporting code for the new (how new?) partial instantiation,
	and encapsulation schemes.
*/

void SetInstantiationRelnFlags(unsigned int flag)
{
  g_instantiate_relns = flag;
}

unsigned int GetInstantiationRelnFlags(void)
{
  return g_instantiate_relns;
}

#if 0 && defined(DISUSED)
/**
	This is the version of instantiate to deal with with 'patched'
	types. Here name is the name of the patch that is to be
	instantiated. We first find the 'original' type, instantiate it
	and then apply the patch. The things that are properly and fully
	supported is external relations, which is the real reason that
	the patch was designed.
*/
void UpdateInstance(struct Instance *root, /* the simulation root */
                    struct Instance *target,
                    CONST struct StatementList *slist)
{
  struct gl_list_t *list, *instances = NULL;
  unsigned long len, c;
  struct Statement *stat;
  REL_ERRORLIST err = REL_ERRORLIST_EMPTY;
  struct Instance *scope;
  struct Name *name;

  (void)root;  /*  stop gcc whine about unused parameter */

  list = GetList(slist);
  if (!list) return;
  len = gl_length(list);
  for (c=1;c<=len;c++) {
    stat = (struct Statement *)gl_fetch(list,c);
    switch (StatementType(stat)) {
    case EXT:
      name = ExternalStatScope(stat);
      if (name==NULL) {
        scope = target;
      }else{
        instances = FindInstances(target,name,&err);
        if (instances) {
          if (gl_length(instances)!=1) {
            FPRINTF(ASCERR,"More than 1 scope instance found !!\n");
			scope = NULL;
          }else{
            scope = (struct Instance *)gl_fetch(instances,1L);
          }
          gl_destroy(instances);
        }else{
          FPRINTF(ASCERR,"Unable to find scope instance !!\n");
          scope = target;
        }
      }
      ExecuteEXT(scope,stat);
      break;
    default:
      break;
    }
  }
}

/**
	this function instantiates a thing of type name
	without doing relations.

	Relations are then hacked in from external places
	but OTHERWISE the object appears as a regular
	ASCEND object. (note HACKED is the right word.)

	@DEPRECATED This function is obsolete; bintoken.c and multiphase
	instantiation make it irrelevant.
*/
struct Instance *InstantiatePatch(symchar *patch,
                                  symchar *name, int intset)
{
  struct Instance *result;	/* the SIM_INSTANCE */
  struct Instance *root;	/* the thing created by instantiate */
  struct TypeDescription *patchdef;
  symchar *original;
  unsigned int oldflags;

  ++g_compiler_counter;/*instance tree will change:increment compiler counter*/
  patchdef = FindType(patch);
  if (patchdef==NULL) {
    FPRINTF(ASCERR,"Cannot find the patch %s in the libary\n",SCP(patch));
    return NULL;
  }
  if (GetBaseType(patchdef)!=patch_type) {
    FPRINTF(ASCERR,"Given type \"%s\" is not a patch\n",SCP(patch));
    return NULL;
  }
  /*
   * Do the partial instantiation with the original.
   * This requires setting up the instantiate relations flags.
   * Any failures after this require going to cleanup.
   */

  original = GetName(GetPatchOriginal(patchdef));
  asc_assert(original!=NULL);
  oldflags = GetInstantiationRelnFlags();
  SetInstantiationRelnFlags(EXTRELS);
  result = Instantiate(original,name,intset,NULL);
  if (result) {
    root = GetSimulationRoot(result);
    if (!root) {
      FPRINTF(ASCERR,"NULL root instance\n");
      goto cleanup;
    }
    UpdateInstance(root,root,GetStatementList(patchdef)); /* cast statement?*/
  }else{
    FPRINTF(ASCERR,"Instantiation failure: NULL simulation\n");
  }

 cleanup:
  SetInstantiationRelnFlags(oldflags);
  return result;
}
#endif