File: std.ct

package info (click to toggle)
tela 1.28-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 6,596 kB
  • ctags: 5,519
  • sloc: ansic: 14,013; cpp: 13,376; lex: 1,651; fortran: 1,048; yacc: 834; sh: 715; makefile: 464
file content (4144 lines) | stat: -rw-r--r-- 112,001 bytes parent folder | download
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
/*
 * This file is part of tela the Tensor Language.
 * Copyright (c) 1994-1996 Pekka Janhunen
 */

/*
	std.ct
	Standard functions.
	Preprocess with ctpp.
	C-tela code is C++ equipped with []=f() style function definition.
*/

// --------------- Elementary transcendental functions ------------------

#include <ctype.h>
#include "prg.H"

inline Treal conj(Treal x) {return x;}
inline Tint conj(Tint x) {return x;}

#if USE_ATT_COMPLEX_CLASS

// The AT&T complex class is missing tanh,asin,acos,atan

inline Tcomplex tanh(Tcomplex x) {
	// tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x))
	// = (1 - exp(-2*x))/(1 + exp(-2*x))
	const Tcomplex e = exp(-2*x);
	return (1-e)/(1+e);
}

inline Tcomplex asin(Tcomplex z) {
	const Tcomplex I(0,1);
	return -I*log(sqrt(1-z*z)+I*z);
}

inline Tcomplex acos(Tcomplex z) {
	const Tcomplex I(0,1);
	return -I*log(z+I*sqrt(1-z*z));
}

inline Tcomplex atan(Tcomplex z) {
	const Tcomplex I(0,1);
	return 0.5*I*log((1-I*z)/(1+I*z));
}

#endif

#define DEFVFN(fn)\
static void v##fn(Treal x[], int N) {\
	for (int i=0; i<N; i++) x[i] = fn(x[i]);\
}\
\
static void v##fn(Tcomplex x[], int N) {\
    for (int i=0; i<N; i++) x[i] = fn(x[i]);\
}\
\
static TTranscenFunctionPack tfpack_##fn(#fn,fn,fn,v##fn,v##fn);

DEFVFN(sqrt);
DEFVFN(exp);
DEFVFN(log);
DEFVFN(sin);
DEFVFN(cos);
DEFVFN(sinh);
DEFVFN(cosh);
DEFVFN(tanh);
DEFVFN(conj);
DEFVFN(asin);
DEFVFN(acos);
DEFVFN(atan);

INLINE int SomeNegative(const Tint x[], int N) {
	for (int i=0; i<N; i++) if (x[i]<0) return 1;
	return 0;
}

INLINE int SomeNegative(const Treal x[], int N) {
	for (int i=0; i<N; i++) if (x[i]<0) return 1;
	return 0;
}

[y] = sqrt(x)
/* y = sqrt(x) computes the square root of x.
   If x is complex, the result is complex. If x is real or
   integer, but negative, the result is complex (purely
   imaginary). If x is real or integer and non-negative,
   the result is real.
   If x is an array, the operation is applied componentwise.
   If some of the components are negative, all components
   of the result are complex.*/
{
	switch (x.kind()) {
	case Kint:
		if (x.IntValue() < 0)
			y = Tcomplex(0,sqrt(Treal(-x.IntValue())));
		else
			y = sqrt(Treal(x.IntValue()));
		global::nops++;
		break;
	case Kreal:
		if (x.RealValue() < 0)
			y = Tcomplex(0,sqrt(-x.RealValue()));
		else
			y = sqrt(x.RealValue());
		global::nops++;
		break;
	case KIntArray:
		{
			const Tint *px = x.IntPtr();
			int N = x.length();
			if (SomeNegative(px,N)) {
				y.copydimsComplexArray(x);
				Tcomplex *py = y.ComplexPtr();
				for (int i=0; i<N; i++) py[i] = sqrt(Tcomplex(Treal(px[i]),0));
			} else {
				y.copydimsRealArray(x);
				Treal *py = y.RealPtr();
				for (int i=0; i<N; i++) py[i] = sqrt(px[i]);
			}
			global::nops+= N;
		}
		break;
	case KRealArray:
		{
			const Treal *px = x.RealPtr();
			int N = x.length();
			if (SomeNegative(px,N)) {
				y.copydimsComplexArray(x);
				Tcomplex *py = y.ComplexPtr();
				for (int i=0; i<N; i++) py[i] = sqrt(Tcomplex(px[i],0));
			} else {
				y.copydimsRealArray(x);
				Treal *py = y.RealPtr();
				for (int i=0; i<N; i++) py[i] = sqrt(px[i]);
			}
			global::nops+= N;
		}
		break;
	default:
		Transcen(tfpack_sqrt,y,x);
		break;
	}
	return 0;
}

[y] = exp(x)
/* y = exp(x) computes the exponent function of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_exp,y,x);
	global::nops++;
	return 0;
}

[y] = log(x)
/* y = log(x) computes the natural logarithm of x.
   If x is complex, the result is complex. If x is real or
   integer, but negative, the result is complex (purely
   imaginary). If x is real or integer and non-negative,
   the result is real.
   If x is an array, the operation is applied componentwise.
   If some of the components are negative, all components
   of the result are complex. */
{
	switch (x.kind()) {
	case Kint:
		if (x.IntValue() < 0)
			y = log(Tcomplex(Treal(x.IntValue()),0));
		else
			y = log(Treal(x.IntValue()));
		global::nops++;
		break;
	case Kreal:
		if (x.RealValue() < 0)
			y = log(Tcomplex(x.RealValue(),0));
		else
			y = log(x.RealValue());
		global::nops++;
		break;
	case KIntArray:
		{
			const Tint *px = x.IntPtr();
			int N = x.length();
			if (SomeNegative(px,N)) {
				y.copydimsComplexArray(x);
				Tcomplex *py = y.ComplexPtr();
				for (int i=0; i<N; i++) py[i] = log(Tcomplex(Treal(px[i]),0));
			} else {
				y.copydimsRealArray(x);
				Treal *py = y.RealPtr();
				for (int i=0; i<N; i++) py[i] = log(px[i]);
			}
			global::nops+= N;
		}
		break;
	case KRealArray:
		{
			const Treal *px = x.RealPtr();
			int N = x.length();
			if (SomeNegative(px,N)) {
				y.copydimsComplexArray(x);
				Tcomplex *py = y.ComplexPtr();
				for (int i=0; i<N; i++) py[i] = log(Tcomplex(px[i],0));
			} else {
				y.copydimsRealArray(x);
				Treal *py = y.RealPtr();
				for (int i=0; i<N; i++) py[i] = log(px[i]);
			}
			global::nops+= N;
		}
		break;
	default:
		Transcen(tfpack_log,y,x);
		break;
	}
	global::nops++;
	return 0;
}

[y] = sin(x)
/* y = sin(x) computes the sine function of x.
   If x is complex, the result is complex, otherwise real.
   The argument must be in radians.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_sin,y,x);
	return 0;
}

[y] = cos(x)
/* y = cos(x) computes the cosine function of x.
   If x is complex, the result is complex, otherwise real.
   The argument must be in radians.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_cos,y,x);
	return 0;
}

[y] = sinh(x)
/* y = sinh(x) computes the hyperbolic sine function of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_sinh,y,x);
	return 0;
}

[y] = cosh(x)
/* y = cosh(x) computes the hyperbolic cosine function of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_cosh,y,x);
	return 0;
}

[y] = tan(x)
/* y = tan(x) computes the tangent function of x.
   If x is complex, the result is complex, otherwise real.
   The argument must be in radians.
   If x is an array, the operation is applied componentwise.*/
{
	Tobject a;						// need one object workspace
	Transcen(tfpack_sin,y,x);		// y = sin(x)
	const
#	if SLOW_FLOATING_POINT_MATH
	int
#	else
	double
#	endif
		global_nops_saved = global::nops;	// record only ops from the sin, so that tan is one op
	Transcen(tfpack_cos,a,x);		// a = cos(x)
	Div(y,a);						// y = y/a
	global::nops = global_nops_saved;
	return 0;
}

[y] = tanh(x)
/* y = tanh(x) computes the hyperbolic tangent function of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_tanh,y,x);
	return 0;
}

[y] = asin(x)
/* y = asin(x) computes the arc sine of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_asin,y,x);
	return 0;
}

[y] = acos(x)
/* y = acos(x) computes the arc cosine of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.*/
{
	Transcen(tfpack_acos,y,x);
	return 0;
}

[y] = atan(x)
/* y = atan(x) computes the arc tangent of x.
   If x is complex, the result is complex, otherwise real.
   If x is an array, the operation is applied componentwise.
   See also: atan2. */
{
	Transcen(tfpack_atan,y,x);
	return 0;
}

static int RealObject(const Tobject& obj, Treal& result) {
	int ret=1;
	if (obj.kind() == Kint)
		result = Treal(obj.IntValue());
	else if (obj.kind() == Kreal)
		result = obj.RealValue();
	else {
		result = 0;
		ret = 0;
	}
	return ret;
}
				
[z] = atan2(y,x)
/* z = atan2(y,x) computes the arcus tangent of y/x using the signs
   of both arguments to determine the quadrant of the return value.
   The input argument must be integer or real scalars and the
   return value is real.
   See also: atan.
   Error codes:
   -1: Bad input argument */
{
	Treal X,Y;
	if (!RealObject(y,Y)) return -1;
	if (!RealObject(x,X)) return -1;
	z = atan2(Y,X);
	return 0;
}

[y] = csc(x)
/* y = csc(x) is the cosecant function
   csc(x) = 1/sin(x). */
{
	Tobject invy;
	Transcen(tfpack_sin,invy,x);
	Div(y,Tobject(1.0),invy);
	return 0;
}

[y] = sec(x)
/* y = sec(x) is the secant function
   sec(x) = 1/cos(x). */
{
	Tobject invy;
	Transcen(tfpack_cos,invy,x);
	Div(y,Tobject(1.0),invy);
	return 0;
}

[y] = cot(x)
/* y = cot(x) is the cotangent function
   cot(x) = 1/tan(x) = cos(x)/sin(x). */
{
	TConstObjectPtr inputs[1]; TObjectPtr outputs[1];
	Tobject invy;
	*inputs = &x;
	*outputs = &invy;
	tanfunction(inputs,1,outputs,1);
	Div(y,Tobject(1.0),invy);
	return 0;
}

[y] = conj(x)
/* y = conj(x) computes the complex conjugate of x.
   Real and integer arguments are returned as such.
   If x is an array, the operation is applied componentwise.
   See also: Re, Im, arg. */
{
	Transcen(tfpack_conj,y,x);
	return 0;
}

[y] = HeavisideTheta(x)
/* y = HeavisideTheta(x) returns 1 if x>=0 and 0 if x<0.
   x must be real. If x is array, the operation is applied componentwise.
   See also: sign.
   Error codes:
   -1: Complex or nonnumeric input argument */
{
	switch (x.kind()) {
	case Kint:
		y = (x.IntValue() >= 0) ? 1 : 0;
		break;
	case Kreal:
		y = (x.RealValue() >= 0) ? 1 : 0;
		break;
	case KIntArray:
		{
			y.copydimsIntArray(x);
			Tint * const xp = x.IntPtr();
			Tint * const yp = y.IntPtr();
			for (int i=0; i<x.length(); i++)
				yp[i] = (xp[i] >= 0) ? 1 : 0;
		}
		break;
	case KRealArray:
		{
			y.copydimsIntArray(x);
			Treal * const xp = x.RealPtr();
			Tint * const yp = y.IntPtr();
			for (int i=0; i<x.length(); i++)
				yp[i] = (xp[i] >= 0) ? 1 : 0;
		}
		break;
	default:
		return -1;
	}
	return 0;
}

[y] = ones(...)
/* ones(n,m...) returns an integer array with all elements
   equal to 1 of size n x m x ... .

   ones(V) where V is an integer vector, and thus
   ones(size(A)), works also.

   See also: rand, eye.
   
   Error codes:
   -1: Input argument not an integer or IntVector
   -2: Rank of requested tensor array exceeds MAXRANK
   -3: Non-positive input argument
   -4: Negative input argument
   -5: Integer array rank not 1
   */
{
	int dims[MAXRANK],i;
	if (Nargin > MAXRANK) return -2;
	if (Nargin == 1) {
		if (argin[0]->kind() == Kint) {
			dims[0] = argin[0]->IntValue();
			if (dims[0]<0) return -4;
			y.izeros(TDimPack(dims,Nargin));
		} else if (argin[0]->kind() == KIntArray) {
			if (argin[0]->rank() != 1) return -5;
			Tint L = argin[0]->length();
			if (L > MAXRANK) return -2;
			for (i=0; i<L; i++) {
				dims[i] = argin[0]->IntPtr()[i];
				if (dims[i]<=0) return -3;
			}
			y.izeros(TDimPack(dims,L));
		} else return -1;
	} else {
		for (i=0; i<Nargin; i++) {
			if (argin[i]->kind()!=Kint) return -1;
			dims[i] = argin[i]->IntValue();
			if (dims[i]<=0) return -3;
		}
		y.izeros(TDimPack(dims,Nargin));
	}
	Add(y,Tobject(1));
	return 0;
}

[y] = diag(x)
/* diag(V) (V is a vector) returns a square diagonal matrix,
   whose diagonal elements are given by V.
   diag(M) (M is a matrix) returns the main diagonal of M
   as a vector. M need not necessarily be square.
   Error codes:
   -1: Input array not vector or matrix
   */
{
	const Tkind k = x.kind();
	if (k!=KIntArray && k!=KRealArray && k!=KComplexArray) {y=x; return 0;}
	if (x.rank()!=1 && x.rank()!=2) return -1;
	Tint i;
	if (x.rank() == 1) {
		const Tint n = x.length();
		switch (k) {
		case KIntArray:
			y.izeros(TDimPack(n,n));
			for (i=0; i<n; i++) y.IntPtr()[i*n+i] = x.IntPtr()[i];
			break;
		case KRealArray:
			y.rzeros(TDimPack(n,n));
			for (i=0; i<n; i++) y.RealPtr()[i*n+i] = x.RealPtr()[i];
			break;
		case KComplexArray:
			y.czeros(TDimPack(n,n));
			for (i=0; i<n; i++) y.ComplexPtr()[i*n+i] = x.ComplexPtr()[i];
			break;
		default:;
		}
	} else {
		const Tint n = x.dims()[0], m = x.dims()[1];
		const Tint nm = min(n,m);
		switch (k) {
		case KIntArray:
			y.izeros(nm);
			for (i=0; i<nm; i++) y.IntPtr()[i] = x.IntPtr()[i*m+i];
			break;
		case KRealArray:
			y.rzeros(nm);
			for (i=0; i<nm; i++) y.RealPtr()[i] = x.RealPtr()[i*m+i];
			break;
		case KComplexArray:
			y.czeros(nm);
			for (i=0; i<nm; i++) y.ComplexPtr()[i] = x.ComplexPtr()[i*m+i];
			break;
		default:;
		}
	}
	return 0;
}

[y] = sign(x)
/* y = sign(x) returns 1 if x>0, 0 if x==0, and -1 if x<0.
   x must be real. If x is array, the operation is applied componentwise.
   See also: HeavisideTheta.
   Error codes:
   -1: Complex or nonnumeric input argument */
{
	switch (x.kind()) {
	case Kint:
		if (x.IntValue() == 0)
			y = 0;
		else
			y = (x.IntValue() > 0) ? 1 : -1;
		break;
	case Kreal:
		if (x.RealValue() == 0.0)
			y = 0;
		else
			y = (x.RealValue() > 0) ? 1 : -1;
		break;
	case KIntArray:
		{
			y.copydimsIntArray(x);
			Tint * const xp = x.IntPtr();
			Tint * const yp = y.IntPtr();
			for (int i=0; i<x.length(); i++) {
				if (xp[i] == 0)
					yp[i] = 0;
				else
					yp[i] = (xp[i] > 0) ? 1 : -1;
			}
		}
		break;
	case KRealArray:
		{
			y.copydimsIntArray(x);
			Treal * const xp = x.RealPtr();
			Tint * const yp = y.IntPtr();
			for (int i=0; i<x.length(); i++) {
				if (xp[i] == 0.0)
					yp[i] = 0;
				else
					yp[i] = (xp[i] > 0) ? 1 : -1;
			}
		}
		break;
	default:
		return -1;
	}
	return 0;
}

[y] = Re(x)
/* y = Re(x) takes the real part of a complex quantity x.
   If x is real or integer, it is returned as such.
   If x is an array, the operation is applied componentwise.
   See also: Im, conj, arg.
   Error codes:
   -1: Nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
	case Kreal:
	case KIntArray:
	case KRealArray:
		y = x;
		break;
	case Kcomplex:
		y = real(x.ComplexValue());
		break;
	case KComplexArray:
		{
			int i;
			Tcomplex * const p = x.ComplexPtr();
			const Tint N = x.length();
			if (&y == &x) {
				Tobject y1;
				y1.copydimsRealArray(x);
				Treal * const yp = y1.RealPtr();
				for (i=0; i<N; i++) yp[i] = real(p[i]);
				y = y1;
			} else {
				y.copydimsRealArray(x);
				Treal * const yp = y.RealPtr();
				for (i=0; i<N; i++) yp[i] = real(p[i]);
			}
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // Re

[y] = Im(x)
/* y = Im(x) takes the imaginary part of a complex quantity x.
   If x is real or integer, the result is zero.
   If x is an array, the operation is applied componentwise.
   See also: Re, conj, arg.
   Error codes:
   -1: Nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
		y = 0;
		break;
	case Kreal:
		y = 0.0;
		break;
	case KIntArray:
		y.izeros(x.dims());
		break;
	case KRealArray:
		y.rzeros(x.dims());
		break;
	case Kcomplex:
		y = imag(x.ComplexValue());
		break;
	case KComplexArray:
		{
			int i;
			Tcomplex * const p = x.ComplexPtr();
			const Tint N = x.length();
			if (&y == &x) {
				Tobject y1;
				y1.copydimsRealArray(x);
				Treal * const yp = y1.RealPtr();
				for (i=0; i<N; i++) yp[i] = imag(p[i]);
				y = y1;
			} else {
				y.copydimsRealArray(x);
				Treal * const yp = y.RealPtr();
				for (i=0; i<N; i++) yp[i] = imag(p[i]);
			}
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // Im

[y] = abs2(x)
/* y = abs2(x) computes the square of the absolute value of x.
   If x is real or integer, the result is just the square of x.
   If x is complex, the result is equal to x*conj(x), except that
   the latter would produce a complex result with zero or tiny
   (because of possible roundoff error) imaginary part.
   If x is an array, the operation is applied componentwise.
   Error codes:
   -1: Nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
	case Kreal:
	case KIntArray:
	case KRealArray:
		Mul(y,x,x);
		break;
	case Kcomplex:
		y = real(x.ComplexValue())*real(x.ComplexValue()) + imag(x.ComplexValue())*imag(x.ComplexValue());
		break;
	case KComplexArray:
		{
			int i;
			Tcomplex * const p = x.ComplexPtr();
			const Tint N = x.length();
			if (&y == &x) {
				Tobject y1;
				y1.copydimsRealArray(x);
				Treal * const yp = y1.RealPtr();
				for (i=0; i<N; i++) yp[i] = real(p[i])*real(p[i]) + imag(p[i])*imag(p[i]);
				y.bitwiseMoveFrom(y1);
			} else {
				y.copydimsRealArray(x);
				Treal * const yp = y.RealPtr();
				for (i=0; i<N; i++) yp[i] = real(p[i])*real(p[i]) + imag(p[i])*imag(p[i]);
			}
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // abs2

[y] = floor(x)
/* floor(x) returns the largest integer which is smaller than x.
   x must be integer or real scalar or array. If it is an array,
   the operation is applied componentwise.
   See also: ceil.
   Error codes:
   -1: Complex or nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
	case KIntArray:
		y = x;
		break;
	case Kreal:
		y = Tint(floor(x.RealValue()));
		break;
	case KRealArray:
		{
			Tobject y1;
			y1.copydimsIntArray(x);
			Treal *xp = x.RealPtr(); Tint *y1p = y1.IntPtr();
			for (int i=0; i<x.length(); i++) y1p[i] = Tint(floor(xp[i]));
			y = y1;
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // floor

[y] = ceil(x)
/* ceil(x) returns the smallest integer which is larger than x.
   x must be integer or real scalar or array. If it is an array,
   the operation is applied componentwise.
   See also: floor.
   Error codes:
   -1: Complex or nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
	case KIntArray:
		y = x;
		break;
	case Kreal:
		y = Tint(ceil(x.RealValue()));
		break;
	case KRealArray:
		{
			Tobject y1;
			y1.copydimsIntArray(x);
			Treal *xp = x.RealPtr(); Tint *y1p = y1.IntPtr();
			for (int i=0; i<x.length(); i++) y1p[i] = Tint(ceil(xp[i]));
			y = y1;
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // ceil

[y] = round(x)
/* round(x) returns the nearest integer.
   x must be integer or real scalar or array. If it is an array,
   the operation is applied componentwise.
   See also: floor, ceil.
   Error codes:
   -1: Complex or nonnumeric input argument */
{
	int ret = 0;
	switch (x.kind()) {
	case Kint:
	case KIntArray:
		y = x;
		break;
	case Kreal:
		y = round(x.RealValue());
		break;
	case KRealArray:
		{
			Tobject y1;
			y1.copydimsIntArray(x);
			Treal *xp = x.RealPtr(); Tint *y1p = y1.IntPtr();
			for (int i=0; i<x.length(); i++) y1p[i] = round(xp[i]);
			y = y1;
		}
		break;
	default:
		ret = -1;
	}
	return ret;
} // round

[y] = rank(x)
/* rank(A) returns the number of dimensions of array A.
   The rank of a scalar is 0. The rank of a nonnumeric
   object, including undefined value, is -1. The rank function
   never generates an error.
   See also: length, size. */
{
	if (x.IsArray())
		y = x.rank();
	else if (x.IsScalar())
		y = 0;
	else
		y = -1;
	return 0;
}

[...] = size(x)
/* [n,m,...] = size(A) finds out the dimensions of array A.
   The number of n,m... must not exceed rank(A). If rank(A)==0
   (that is, A is scalar), n=size(A) sets 1 to n.
   V = size(A) assigns the dimension vector [n,m,..] to V.
   If A is scalar, V is set to 1, if A is vector, V becomes
   a one-element vector.
   See also: length, rank.
   Error codes:
   -1: No output arguments
   -2: Argument has undefined value
   1: More than one output arg but non-array input arg
   2: Too many output args relative to input arg rank */
{
	if (Nargout == 1) {
		if (x.IsArray()) {
			argout[0]->ireserv(TDimPack(x.rank()));
			NOVECTOR for (int d=0; d<x.rank(); d++) argout[0]->IntPtr()[d] = x.dims()[d];
		} else {
			*argout[0] = 1;
		}
		return x.kind()==Kundef ? -2 : 0;
	} else if (Nargout > 1) {
		if (x.IsArray()) {
			NOVECTOR for (int d=0; d<min(x.rank(),Nargout); d++) *argout[d] = x.dims()[d];
			return (x.rank()>=Nargout) ? 0 : 2;
		} else {
			*argout[0] = 1;
			return x.kind()==Kundef ? -2 : 1;
		}
	}
	return -1;
}

[L] = length(x)
/* length(x) returns the total number of elements in array x.
   If x is scalar, length(x) is 1. If x is undefined, an error
   results. Notice that if x is e.g. a matrix, its length is
   equal to the product of the row and column dimensions,
   which is different from e.g. the Matlab convention.
   See also: size, rank.
   Error codes:
   -1: Argument has undefined value */
{
	if (x.IsArray())
		L = x.length();
	else {
		if (x.kind()==Kundef) return -1;
		L = x.IsScalar() ? 1 : 0;
	}
	return 0;
}

[phi] = arg(z)
/* arg(z) returns the argument of a complex quantity
   (in radians). The result is between -pi and pi.
   If z is a complex array, the operation is applied
   componentwise.
   See also: Re, Im, conj.
   Error codes:
   -1: Argument has undefined value
   1: Nonnumeric argument */
{
	switch (z.kind()) {
	case Kint:
	case Kreal:
		phi = 0;
		break;
	case KIntArray:
	case KRealArray:
		phi.izeros(z.dims());
		break;
	case Kcomplex:
		phi = arg(z.ComplexValue());
		break;
	case KComplexArray:
		{
			phi.copydimsRealArray(z);
			for (int i=0; i<z.length(); i++)
				phi.RealPtr()[i] = arg(z.ComplexPtr()[i]);
		}
		break;
	 case Kundef:
		return -1;
	default:
		phi = 0;
		return 1;
	}
	return 0;
}



inline Tkind VectorKind(Tkind k) {
	int ki = int(k);
	if (ki < int(KIntArray)) ki+= 3;
	return Tkind(ki);
}

[y] = where(c,a,b)
/* where(c,a,b) returns a where c is nonzero and b where c is zero.
   Usually the arguments are arrays, and if they are, they must be
   of similar dimensions.
   Error codes:
   -1: First argument not integer-valued
   -2: Second arg non-numeric
   -3: Second arg is incompatible array
   -4: Third arg non-numeric
   -5: Third arg incompatible array
*/
{
	if (c.kind()!=Kint && c.kind()!=KIntArray) return -1;
	if (c.kind()==Kint) {		// Scalar c works as simple if statement
		if (c.IntValue())
			y = a;
		else
			y = b;
	} else {					// Vector c. This is the normal case.
		Tint *const cp = c.IntPtr();
		const TDimPack& dp = c.dims();
		const Tint L = dp.length();
		Tint i;
		if (!a.IsNumerical()) return -2;
		if (a.IsArray()) {if (a.dims()!=dp) return -3;}
		if (!b.IsNumerical()) return -4;
		if (b.IsArray()) {if (b.dims()!=dp) return -5;}
		const Tkind akind = a.kind();
		const Tkind bkind = b.kind();
		// Idea: reserve y; y = b; y[find(c)] = a[find(c)];
		Tkind k = Tkind( max(int(VectorKind(a.kind())), int(VectorKind(b.kind()))) );
		if (k == KIntArray) {
			y.ireserv(dp);
			Tint *const yp = y.IntPtr();
			if (b.kind()==Kint) {
				const Tint B = b.IntValue();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = B;
			} else
				memcpy(yp,b.IntPtr(),sizeof(Tint)*L);	// y = b
		} else if (k == KRealArray) {
			y.rreserv(dp);
			Treal *const yp = y.RealPtr();
			if (bkind==Kint || bkind==Kreal) {
				const Treal B = (bkind==Kint ? b.IntValue() : b.RealValue());
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = B;
			} else if (bkind==KIntArray) {
				const Tint *const bp = b.IntPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = bp[i];
			} else if (bkind==KRealArray)
				memcpy(yp,b.RealPtr(),sizeof(Treal)*L);	// y = b
		} else {		// k must be KComplexArray
			y.creserv(dp);
			Tcomplex *const yp = y.ComplexPtr();
			if (b.IsScalar()) {
				const Tcomplex B = (bkind==Kcomplex ? b.ComplexValue() : Tcomplex(bkind==Kreal ? b.RealValue() : b.IntValue()));
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = B;
			} else if (bkind==KIntArray) {
				const Tint *const bp = b.IntPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = bp[i];
			} else if (bkind==KRealArray) {
				const Treal *const bp = b.RealPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) yp[i] = bp[i];
			} else
				memcpy(yp,b.ComplexPtr(),sizeof(Tcomplex)*L);	// y = b
		}

		// -----------------------
		// Now y = b has been done
		// -----------------------
		// - Now do y[find(c)] = a[find(c)]
		if (k == KIntArray) {
			Tint *const yp = y.IntPtr();
			if (akind==Kint) {
				const Tint A = a.IntValue();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = A;
			} else {	// akind must be KIntArray
				const Tint *const ap = a.IntPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = ap[i];
			}
		} else if (k == KRealArray) {
			Treal *const yp = y.RealPtr();
			if (akind==Kint || akind==Kreal) {
				const Treal A = (akind==Kint ? a.IntValue() : a.RealValue());
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = A;
			} else if (akind==KIntArray) {
				const Tint *const ap = a.IntPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = ap[i];
			} else {		// akind must be KRealArray
				const Treal *const ap = a.RealPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = ap[i];
			}
		} else {		// k must be KComplexArray
			Tcomplex *const yp = y.ComplexPtr();
			if (a.IsScalar()) {
				const Tcomplex A = (akind==Kcomplex ? a.ComplexValue() : Tcomplex(akind==Kreal ? a.RealValue() : a.IntValue()));
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = A;
			} else if (akind==KIntArray) {
				const Tint *const ap = a.IntPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = Tcomplex(ap[i]);
			} else if (akind==KRealArray) {
				const Treal *const ap = a.RealPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = Tcomplex(ap[i]);
			} else {		// akind must be KComplexArray
				const Tcomplex *const ap = a.ComplexPtr();
#				pragma _CRI ivdep
				for (i=0; i<L; i++) if (cp[i]) yp[i] = ap[i];
			}
		}
	}
	return 0;
}




[B] = map(fn,A,darg)
/* [B] = map(fn,A,d) maps function fn along d'th dimension
   in array A. Fn is a functional argument. It must return a scalar
   or a vector when called with one vector argument. The type and length
   of the returned value must not change from call to call.

   For example, map(mean,A,1) computes the columnwise means
   of matrix A, returning a vector. map(sort,A,2) sorts all rows
   of matrix A in ascending order. Notice than many standard
   functions, including mean, have a builtin mapping capabability;
   using map in these cases is unnecessary.
   See also: mapmin, mapmax, flip.
   Error codes:
   -1: First arg not a function
   -2: Second arg not a numerical array
   -3: Third arg not an integer scalar
   -4: Third arg (the dimension) out of range
   -5: First arg (function) did not return a numerical object
   -6: First arg (function) unexpectedly changed its return type
   -7: First arg is an intrinsic function; it is no good
   -8: Function returned rank>1 array when first called
*/
{
	Tkind fnk = fn.kind();
	if (fnk==KIntrinsicFunction) return -7;
	if (fnk!=Kfunction && fnk!=KCfunction) return -1;
	if (!A.IsNumericalArray()) return -2;
	if (A.length()==0) {B.izeros(0); return 0;}
	if (darg.kind()!=Kint) return -3;
	const Tint d = darg.IntValue()-ArrayBase;
	const Tint r = A.rank();
	if (d<0 || d>=r) return -4;
	const TDimPack Adims = A.dims();
	const Tint n = Adims[d];
	Tint bdims[MAXRANK];
	int d1;
	NOVECTOR for (d1=0; d1<d; d1++) bdims[d1] = Adims[d1];
	NOVECTOR for (d1=d+1; d1<r; d1++) bdims[d1-1] = Adims[d1];
	const TDimPack Bdims(bdims,r-1);
	Tobject IndexObjects[MAXRANK];
	TConstObjectPtr indices[MAXRANK];
	Tint* Aindexptrs[MAXRANK];
	for (d1=0; d1<r; d1++) {
		if (d1==d)
			IndexObjects[d1].SetToVoid();
		else {
			IndexObjects[d1] = ArrayBase;
			Aindexptrs[(d1<d) ? d1 : d1-1] = &(IndexObjects[d1].IntRef());
		}
		indices[d1] = &IndexObjects[d1];
	}
	Tobject V,S;
	TConstObjectPtr inputs[1];
	TObjectPtr outputs[1];
	Tobject Bindex = 0;
	TConstObjectPtr Bindices[1];
	Bindices[0] = &Bindex;
	Tkind Skind;
	Tint divisors[MAXRANK];
	for (d1=0; d1<r-1; d1++) {
		divisors[d1] = 1;
		NOVECTOR for (int d2=d1+1; d2<r-1; d2++) divisors[d1]*= Bdims[d2];
	}
	int VectorCase = 0;
	Tint Slength;
	for (Tint i=0; i<Bdims.length(); i++) {
		NOVECTOR for (d1=0; d1<r-1; d1++)
			*(Aindexptrs[d1]) = ArrayBase + (i / divisors[d1]) % Bdims[d1];
		Gather(V,A,indices,r);
		inputs[0] = &V;
		outputs[0] = &S;
		Call(fn,inputs,1,outputs,1);
		if (i==0) {
			Skind = S.kind();
			switch (Skind) {
			case Kint:
				B.ireserv(Bdims);
				break;
			case Kreal:
				B.rreserv(Bdims);
				break;
			case Kcomplex:
				B.creserv(Bdims);
				break;
			case KIntArray:
			case KRealArray:
			case KComplexArray:
				{
					if (S.rank() > 1) return -8;
					Tint trueBdims1[MAXRANK];
					NOVECTOR for (d1=0; d1<r; d1++) trueBdims1[d1] = Adims[d1];
					Slength = S.length();
					trueBdims1[d] = Slength;
					const TDimPack trueBdims(trueBdims1,r);
					if (Skind == KIntArray)
						B.ireserv(trueBdims);
					else if (Skind == KRealArray)
						B.rreserv(trueBdims);
					else
						B.creserv(trueBdims);
					VectorCase = 1;
				}
				break;
			default:
				return -5;
			}
		}
		if (S.kind()!=Skind) return -6;
		if (VectorCase) {
			if (S.rank() != 1 || S.length() != Slength) return -6;
			Scatter(S,B,indices,r);
		} else  {
			Bindex.IntRef() = i+ArrayBase;
			Scatter(S,B,Bindices,1);
		}
	}
	return 0;
}


static void DimpackLoopData
    (const TDimPack& dp, Tint d,		// inputs
	 Tint& Nhigher, Tint& N, Tint& Nlower, Tint& chunksize, TDimPack& ydims)	// outputs
/* Prepare parameters for looping over dimension d under dimpack dp.
   Inputs:
   - dp			:	the dimpack data
   - d			:	dimension along which to build the loop
   Outputs:
   - Nhigher	:	Product of dimensions higher than d
   - N			:	Length of dimension d (essentially, N=dp[d], but return to caller anyway)
   - Nlower		:	Product of dimensions lower than d
   - chunksize	:	Step by which higher dimensions should leap
   - ydims		:	dp from which dimension d has been dropped */
{
	const int r = dp.rank();
	Nhigher = 1;
	int d1;
	NOVECTOR for (d1=0; d1<d; d1++) Nhigher*= dp[d1];
	N = dp[d];
	Nlower = dp.length()/(N*Nhigher);
	chunksize = dp.length()/Nhigher;
	Tint Ydims[MAXRANK];
	NOVECTOR for (d1=0; d1<d; d1++) Ydims[d1] = dp[d1];
	NOVECTOR for (d1=d+1; d1<r; d1++) Ydims[d1-1] = dp[d1];
	ydims = TDimPack(Ydims,r-1);
}

[y] = sum(x;d)
/* sum(x) sums all the elements of x, if x is an array.
   The result type is always the same as the component type
   of x. If x is scalar, it is returned as such.
   sum(x,d) sums only along d'th dimension, returning array
   of rank one less than rank(x).
   See also: cumsum, prod, map.
   Error codes:
   -1: Nonnumeric input arg
   -2: Second argument not an integer
   -3: Second argument (dimension spec) out of range */
{
	if (x.IsScalar()) {y=x; return 0;}
	if (!x.IsNumericalArray()) return -1;
	// Handle special case of degenerate input array
	if (x.length()==0) {
		if (x.kind()==KIntArray)
			y = 0;
		else if (x.kind()==KRealArray)
			y = 0.0;
		else
			y = Tcomplex(0,0);
		return 0;
	}
	int dval;
	TDimPack dp;
	const int yieldscalar = (Nargin == 1) || (x.rank() == 1);
	if (!yieldscalar) {
		if (d.kind()!=Kint) return -2;
		if (d.IntValue()<ArrayBase || d.IntValue()>=x.rank()+ArrayBase) return -3;
		dval = d.IntValue() - ArrayBase;
		dp = x.dims();
	} else {
		dval = 0;
		dp = x.length();
		if (Nargin==2) {
			if (d.kind()!=Kint || d.IntValue()!=ArrayBase) return -3;
		}
	}
	Tint Nhigher, N, Nlower, chunksize;
	TDimPack ydims;
	DimpackLoopData(dp, dval, Nhigher, N, Nlower, chunksize, ydims);
	Tint yindex = 0;
	if (x.kind() == KIntArray) {
		const Tint* a = x.IntPtr();
		Tint result, k, p;
		if (yieldscalar) {
			result = 0;
			VECTORIZED for (p=0; p<N; p++) result+= a[p];
			y = result;
		} else {
			y.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 0;
				a = x.IntPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result+= a[p];
				y.IntPtr()[yindex++] = result;
			}
		}
	} else if (x.kind() == KRealArray) {
		Treal result; Tint k, p;
		const Treal* a = x.RealPtr();
		if (yieldscalar) {
			result = 0;
			VECTORIZED for (p=0; p<N; p++) result+= a[p];
			y = result;
		} else {
			y.rreserv(ydims);
#			ifdef VECTOR_MACHINE
			if (N < Nhigher*Nlower) {
				VECTORIZED for (int i=0; i<Nhigher*Nlower; i++) y.RealPtr()[i] = 0.0;
				// Vectorize the longer loop
				if (Nlower >= Nhigher) {
					for (k=0,p=0; k<N; k++,p+=Nlower) {
						yindex = 0;
						for (i=0; i<Nhigher; i++) {
							VECTORIZED for (int j=0; j<Nlower; j++)
								y.RealPtr()[yindex++]+= x.RealPtr()[i*chunksize+j+p];
						}
					}
				} else {
					for (k=0,p=0; k<N; k++,p+=Nlower) {
						yindex = 0;
						for (int j=0; j<Nlower; j++) {
							VECTORIZED for (i=0; i<Nhigher; i++)
								y.RealPtr()[yindex++]+= x.RealPtr()[i*chunksize+j+p];
						}
					}
				}
			} else {
				for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
					result = 0;
					a = x.RealPtr() + i*chunksize + j;
					VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result+= a[p];
					y.RealPtr()[yindex++] = result;
				}
			}
#			else
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 0;
				a = x.RealPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result+= a[p];
				y.RealPtr()[yindex++] = result;
			}
#			endif
		}
		global::nops+= Nhigher*Nlower*N;
	} else {
		Tcomplex result; Tint k, p;
		const Tcomplex* a = x.ComplexPtr();
		if (yieldscalar) {
			result = 0;
			VECTORIZED for (p=0; p<N; p++) result+= a[p];
			y = result;
		} else {
			y.creserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 0;
				a = x.ComplexPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result+= a[p];
				y.ComplexPtr()[yindex++] = result;
			}
		}
		global::nops+= 2*Nhigher*Nlower*N;
	}
    return 0;
} // sum

[y] = prod(x;d)
/* prod(x) multiplies all the elements of x, if x is an array.
   prod(x,d) takes the product along d'th dimension only, returning
   an array of rank one less than rank(x).
   If x is scalar, it is returned as such.
   If I is integer array, prod(I) will be of type real if the product
   would cause integer overflow. In all other cases, including prod(I,d),
   the type of y equals the component type of x.
   See also: sum, cumprod.
   Error codes:
   -1: Nonnumeric input arg
   -2: Second argument not an integer
   -3: Second argument (dimension spec) out of range */
{
	if (x.IsScalar()) {y=x; return 0;}
	if (!x.IsNumericalArray()) return -1;
	// Handle special case of degenerate input array
	if (x.length()==0) {
		if (x.kind()==KIntArray)
			y = 1;
		else if (x.kind()==KRealArray)
			y = 1.0;
		else
			y = Tcomplex(1,0);
		return 0;
	}
	int dval;
	TDimPack dp;
	const int yieldscalar = (Nargin == 1) || (x.rank() == 1);
	if (!yieldscalar) {
		if (d.kind()!=Kint) return -2;
		if (d.IntValue()<ArrayBase || d.IntValue()>=x.rank()+ArrayBase) return -3;
		dval = d.IntValue() - ArrayBase;
		dp = x.dims();
	} else if (x.kind() == KIntArray) {
		// Special handling of prod(<integer array>), eliminate integer overflow problems
		if (Nargin==2) {
			if (d.kind()!=Kint || d.IntValue()!=ArrayBase) return -3;
		}
		Treal prod = 1;
		Tint *const p = x.IntPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) prod*= p[i];
		if (fabs(round(prod)-prod) < 1.0)
			y = round(prod);
		else
			y = prod;
		return 0;
	} else	{// Real or complex flattened prod
		dval = 0;
		dp = x.length();
		if (Nargin==2) {
			if (d.kind()!=Kint || d.IntValue()!=ArrayBase) return -3;
		}
	}
	Tint Nhigher, N, Nlower, chunksize;
	TDimPack ydims;
	DimpackLoopData(dp, dval, Nhigher, N, Nlower, chunksize, ydims);
	Tint yindex = 0;
	if (x.kind() == KIntArray) {
		Tint result, k, p;
		const Tint *a = x.IntPtr();
		if (yieldscalar) {
			result = 1;
			VECTORIZED for (p=0; p<N; p++) result*= a[p];
			y = result;
		} else {
			y.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 1;
				a = x.IntPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result*= a[p];
				y.IntPtr()[yindex++] = result;
			}
		}
	} else if (x.kind() == KRealArray) {
		Treal result; Tint k, p;
		const Treal *a = x.RealPtr();
		if (yieldscalar) {
			result = 1;
			VECTORIZED for (p=0; p<N; p++) result*= a[p];
			y = result;
		} else {
			y.rreserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 1;
				a = x.RealPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result*= a[p];
				y.RealPtr()[yindex++] = result;
			}
		}
		global::nops+= Nhigher*Nlower*N;
	} else {
		Tcomplex result; Tint k, p;
		Tcomplex *a = x.ComplexPtr();
		if (yieldscalar) {
			result = 1;
			VECTORIZED for (p=0; p<N; p++) result*= a[p];
			y = result;
		} else {
			y.creserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				result = 1;
				a = x.ComplexPtr() + i*chunksize + j;
				VECTORIZED for (k=0,p=0; k<N; k++,p+=Nlower) result*= a[p];
				y.ComplexPtr()[yindex++] = result;
			}
		}
		global::nops+= 4*Nhigher*Nlower*N;
	}
    return 0;
} // prod

[y] = cumsum(x)
/* y = cumsum(x) forms an array of partial sums
   y = #(x[1],x[1]+x[2],...,sum(x[1:n]),...).
   The result y has the same size and type as x.
   The array x is logically flattened, to apply
   along a specified dimension use map(cumsum,...).
   If x is scalar, it is returned as such.
   See also: sum, cumprod, map.
   Error codes:
   -1: Nonnumeric input arg */
{
	if (x.IsScalar()) {y=x; return 0;}
	if (!x.IsNumericalArray()) return -1;
	y = x;
	if (x.kind() == KIntArray) {
		Tint sum = 0;
		Tint *const p = x.IntPtr(), *const q = y.IntPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) {sum+= p[i]; q[i] = sum;}
	} else if (x.kind() == KRealArray) {
		Treal sum = 0;
		Treal *const p = x.RealPtr(), *const q = y.RealPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) {sum+= p[i]; q[i] = sum;}
		global::nops+= x.length();
	} else {
		Tcomplex sum = 0;
		Tcomplex *const p = x.ComplexPtr(), *const q = y.ComplexPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) {sum+= p[i]; q[i] = sum;}
		global::nops+= 2*x.length();
	}
    return 0;
} // cumsum

[y] = cumprod(x)
/* y = cumprod(x) forms an array of partial products
   y = #(x[1],x[1]*x[2],...,prod(x[1:n]),...).
   The result y has the same size and type as x. Unlike
   prod, cumprod does not try to avoid integer overflows.
   The array x is logically flattened, to apply
   along a specified dimension use map(cumsum,...).
   If x is scalar, it is returned as such.
   See also: prod, cumsum, map.
   Error codes:
   -1: Nonnumeric input arg */
{
	if (x.IsScalar()) {y=x; return 0;}
	if (!x.IsNumericalArray()) return -1;
	y = x;
	if (x.kind() == KIntArray) {
		Tint prod = 1;
		Tint *const p = x.IntPtr(), *const q = y.IntPtr();
		for (int i=0; i<x.length(); i++) {prod*= p[i]; q[i] = prod;}
	} else if (x.kind() == KRealArray) {
		Treal prod = 1;
		Treal *const p = x.RealPtr(), *const q = y.RealPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) {prod*= p[i]; q[i] = prod;}
		global::nops+= x.length();
	} else {
		Tcomplex prod = 1;
		Tcomplex *const p = x.ComplexPtr(), *const q = y.ComplexPtr();
		VECTORIZED for (int i=0; i<x.length(); i++) {prod*= p[i]; q[i] = prod;}
		global::nops+= 4*x.length();
	}
    return 0;
} // cumprod

[y;P] = mapmin(x;d)
/* mapmin(x,d) finds minimum along d'th dimension in array x.
   The result is an array with rank one less than rank(x).
   The array x may not be complex.
   [m,p] = mapmin(x,d) returns the minimum positions p along with
   the minimum values m. The array p is of the same shape as m,
   but is integer-valued.

   mapmin(x) is a flattened form which returns a scalar result.
   It is equivalent to min(x). [m,p] = mapmin(x) also works.

   Using mapmin is faster than using map and min together.
   In the latter case you would also have to define another function:
       function y=min1(x) {y=min(x)}
   because being intrinsic function, min can not be passed
   to map directly. 
   
   See also: mapmax, map, limit.
   Error codes:
   -1: First arg not a numerical array
   -2: Second arg not an integer scalar
   -3: Second arg (the dimension) out of range
   -4: First arg is complex */
{
	if (!x.IsNumericalArray()) return -1;
	if (x.kind()==KComplexArray) return -4;
	if (x.length()==0) {y.izeros(0); P.SetToVoid(); return 0;}
	Tint dval;
	TDimPack dp;
	const int yieldscalar = (Nargin == 1) || (x.rank() == 1);
	if (!yieldscalar) {
		if (d.kind()!=Kint) return -2;
		if (d.IntValue()<ArrayBase || d.IntValue()>=x.rank()+ArrayBase) return -3;
		dval = d.IntValue() - ArrayBase;
		dp = x.dims();
	} else {
		dval = 0;
		dp = x.length();
		if (Nargin == 2) {
			if (d.kind()!=Kint || d.IntValue()!=ArrayBase) return -3;
		}
	}
	Tint Nhigher, N, Nlower, chunksize;
	TDimPack ydims;
	DimpackLoopData(dp, dval, Nhigher, N, Nlower, chunksize, ydims);
	Tint yindex = 0;
	// result holds the position, not the value here, hence it is always of type Tint
	Tint result, minpos, k, p;
	if (x.kind() == KIntArray) {
		const Tint *a = x.IntPtr();
		if (yieldscalar) {
			result = 0;
			for (p=0; p<N; p++)
				if (a[p] < a[result]) result = p;
			y = a[result];
			if (Nargout == 2) P = result+ArrayBase;
		} else {
			y.ireserv(ydims);
			if (Nargout == 2) P.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.IntPtr() + i*chunksize + j;
				result = minpos = 0;
				for (k=0,p=0; k<N; k++,p+=Nlower)
					if (a[p] < a[minpos]) {minpos = p; result = k;}
				y.IntPtr()[yindex] = a[minpos];
				if (Nargout == 2) P.IntPtr()[yindex] = result + ArrayBase;
				yindex++;
			}
		}
	} else {
		const Treal *a = x.RealPtr();
		if (yieldscalar) {
			result = 0;
			for (p=0; p<N; p++)
				if (a[p] < a[result]) result = p;
			y = a[result];
			if (Nargout == 2) P = result+ArrayBase;
		} else {
			y.rreserv(ydims);
			if (Nargout == 2) P.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.RealPtr() + i*chunksize + j;
				result = minpos = 0;
				for (k=0,p=0; k<N; k++,p+=Nlower)
					if (a[p] < a[minpos]) {minpos = p; result = k;}
				y.RealPtr()[yindex] = a[minpos];
				if (Nargout == 2) P.IntPtr()[yindex] = result + ArrayBase;
				yindex++;
			}
		}
	}
	return 0;
}

[y;P] = mapmax(x;d)
/* mapmax(x,d) finds maximum along d'th dimension in array x.
   The result is an array with rank one less than rank(x).
   The array may not be complex.
   [M,p] = mapmax(x,d) returns the maximum positions p along with
   the maximums m. The array p is of the same shape as M, but is
   integer-valued.

   mapmax(x) is a flattened form which returns a scalar result.
   It is equivalent to max(x). [M,p] = mapmax(x) also works.

   Using mapmax is faster than using map and max together.
   In the latter case you would also have to define another function:
       function y=max1(x) {y=max(x)}
   because being intrinsic function, max can not be passed
   to map directly. 
   
   See also: mapmin, map, limit.
   Error codes:
   -1: First arg not a numerical array
   -2: Second arg not an integer scalar
   -3: Second arg (the dimension) out of range
   -4: First arg is complex */
{
	if (!x.IsNumericalArray()) return -1;
	if (x.kind()==KComplexArray) return -4;
	if (x.length()==0) {y.izeros(0); P.SetToVoid(); return 0;}
	Tint dval;
	TDimPack dp;
	const int yieldscalar = (Nargin == 1) || (x.rank() == 1);
	if (!yieldscalar) {
		if (d.kind()!=Kint) return -2;
		if (d.IntValue()<ArrayBase || d.IntValue()>=x.rank()+ArrayBase) return -3;
		dval = d.IntValue() - ArrayBase;
		dp = x.dims();
	} else {
		dval = 0;
		dp = x.length();
		if (Nargin == 2) {
			if (d.kind()!=Kint || d.IntValue()!=ArrayBase) return -3;
		}
	}
	Tint Nhigher, N, Nlower, chunksize;
	TDimPack ydims;
	DimpackLoopData(dp, dval, Nhigher, N, Nlower, chunksize, ydims);
	Tint yindex = 0;
	// result holds the position, not the value here, hence it is always of type Tint
	Tint result, maxpos, k, p;
	if (x.kind() == KIntArray) {
		const Tint *a = x.IntPtr();
		if (yieldscalar) {
			result = 0;
			for (p=0; p<N; p++)
				if (a[p] > a[result]) result = p;
			y = a[result];
			if (Nargout == 2) P = result + ArrayBase;
		} else {
			y.ireserv(ydims);
			if (Nargout == 2) P.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.IntPtr() + i*chunksize + j;
				result = maxpos = 0;
				for (k=0,p=0; k<N; k++,p+=Nlower)
					if (a[p] > a[maxpos]) {maxpos = p; result = k;}
				y.IntPtr()[yindex] = a[maxpos];
				if (Nargout == 2) P.IntPtr()[yindex] = result + ArrayBase;
				yindex++;
			}
		}
	} else {
		const Treal *a = x.RealPtr();
		if (yieldscalar) {
			result = 0;
			for (p=0; p<N; p++)
				if (a[p] > a[result]) result = p;
			y = a[result];
			if (Nargout == 2) P = result + ArrayBase;
		} else {
			y.rreserv(ydims);
			if (Nargout == 2) P.ireserv(ydims);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.RealPtr() + i*chunksize + j;
				result = maxpos = 0;
				for (k=0,p=0; k<N; k++,p+=Nlower)
					if (a[p] > a[maxpos]) {maxpos = p; result = k;}
				y.RealPtr()[yindex] = a[maxpos];
				if (Nargout == 2) P.IntPtr()[yindex] = result + ArrayBase;
				yindex++;
			}
		}
	}
	return 0;
}

[y] = limit(x,a,b)
/* limit(x,a,b) limits x to the range [a,b].
   x may be an integer or real array or scalar,
   the a and b arguments must be integer or real
   scalars. The result type is integer only
   if all x,a,b are integers, otherwise it is real.
   limit(x,a,b) is equivalent to min(b,max(x,a)).

   Notice: limit is builtin function in >=1.23
   version. Before 1.23 it was a t-file function.

   (Usually a<=b, if a>b then limit(x,a,b) has the
   value of b but this behavior should not be trusted.)
   Error codes:
   -1: First arg not int or real
   -2: Second arg not int or real scalar
   -3: Third arg not int or real scalar
*/
{
	const Tkind k = x.kind();
	if (k!=Kint && k!=Kreal && k!=KIntArray && k!=KRealArray) return -1;
	if (a.kind()!=Kint && a.kind()!=Kreal) return -2;
	if (b.kind()!=Kint && b.kind()!=Kreal) return -3;
	if (a.kind()==Kint && b.kind()==Kint && (k==Kint || k==KIntArray)) {
		const Tint A = a.IntValue();
		const Tint B = b.IntValue();
		Tint tmp;
		if (k == Kint) {
			tmp = (x.IntValue() > A) ? x.IntValue() : A;
			y = (B < tmp) ? B : tmp;
		} else {
			y.ireserv(x.dims());
			for (Tint i=0; i<x.length(); i++) {
				tmp = (x.IntPtr()[i] > A) ? x.IntPtr()[i] : A;
				y.IntPtr()[i] = (B < tmp) ? B : tmp;
			}
		}
	} else {
		Tint i;
		const Treal A = (a.kind()==Kint) ? a.IntValue() : a.RealValue();
		const Treal B = (b.kind()==Kint) ? b.IntValue() : b.RealValue();
		switch (k) {
		case Kint:
			y = min(B,max(Treal(x.IntValue()),A));
			break;
		case Kreal:
			y = min(B,max(x.RealValue(),A));
			break;
		case KIntArray:
			y.rreserv(x.dims());
			VECTORIZED for (i=0; i<x.length(); i++)
				y.RealPtr()[i] = min(B,max(Treal(x.IntPtr()[i]),A));
			break;
		case KRealArray:
			y.rreserv(x.dims());
			VECTORIZED for (i=0; i<x.length(); i++)
				y.RealPtr()[i] = min(B,max(x.RealPtr()[i],A));
			break;
		default:;
		}
	}
	return 0;
}

[B] = transpose(A; P)
/* B = transpose(A) returns a transpose of array A: B[i,j,k...l] = A[l...k,j,i].
   B = transpose(A,P) where P is integer vector transposes the indices according
   to the permutation defined by P.
   For example if A has rank 3, B = transpose(A,[2,1,3]) causes the assignment
   B[j,i,k] = A[i,j,k] to be carried out. B = transpose(A) would in this case
   correspond to B[k,j,i] = A[i,j,k].

   The second argument is meaningful only if rank(A) is greater than 2.
   
   You can abbreviate "transpose(A)" by "A.'".
   See also: herm, flip.
   Error codes:
   -1: Permutation argument not integer array
   -2: Permutation argument of bad rank or size
   -3: Permutation argument contains invalid integers */
{
	Tkind k = A.kind();
	if (k!=KIntArray && k!=KRealArray && k!=KComplexArray)
		B = A;
	else if (A.rank() <= 1)
		B = A;
	else if (A.rank() == 2) {
		Tint n=A.dims()[0], m=A.dims()[1],i,j;
		switch (k) {
		case KIntArray:
			B.ireserv(TDimPack(m,n));
			VECTORIZED for (i=0; i<n; i++) {
				VECTORIZED for (j=0; j<m; j++)
					B.IntPtr()[j*n+i] = A.IntPtr()[i*m+j];
			}
			break;
		case KRealArray:
			B.rreserv(TDimPack(m,n));
			VECTORIZED for (i=0; i<n; i++) {
				VECTORIZED for (j=0; j<m; j++)
					B.RealPtr()[j*n+i] = A.RealPtr()[i*m+j];
			}
			break;
		case KComplexArray:
			B.creserv(TDimPack(m,n));
			VECTORIZED for (i=0; i<n; i++) {
				VECTORIZED for (j=0; j<m; j++)
					B.ComplexPtr()[j*n+i] = A.ComplexPtr()[i*m+j];
			}
			break;
		default:;
		}
	} else {	// General case, rank>=3
		Tint d,d1,pA, pA0,pA1;
		TDimPack Adims = A.dims();
		Tint D = Adims.rank();
		Tint Bdims[MAXRANK];
		Tint perm[MAXRANK];
		for (d=0; d<D; d++) perm[d] = D-d-1;
		if (Nargin == 2) {	// P given ?
			if (P.kind()==KIntArray) {
				if (P.rank()==1 && P.length()==D)
					for (d=0; d<D; d++) {
						perm[d] = P.IntPtr()[d]-1;	// note -1: P is eg. [2,1]
						if (perm[d]<0 || perm[d]>=D) return -3;
					}
				else
					return -2;
			} else
				return -1;
		}
		NOVECTOR for (d=0; d<D; d++) Bdims[d] = Adims[perm[d]];
		// now Adims, Bdims, D are ready
		TDimPack modulus = Adims;
		Tint divisor[MAXRANK];
		for (d=0; d<D; d++) {
			divisor[d] = 1;
			NOVECTOR for (d1=d+1; d1<D; d1++) divisor[d]*= Adims[d1];
		}
		Tint mult[MAXRANK];
		for (d=0; d<D; d++) {
			mult[d] = 1;
			NOVECTOR for (d1=d+1; d1<D; d1++) mult[d]*= Bdims[d1];
		}
		// Allocate B
		TDimPack Bdimpack(Bdims,D);
		switch (k) {
		case KIntArray:
			B.ireserv(Bdimpack); break;
		case KRealArray:
			B.rreserv(Bdimpack); break;
		case KComplexArray:
			B.creserv(Bdimpack); break;
		default:;
		}
		// Now the dirty work
#		define VECLENGTH 128
		Tint ind[MAXRANK][VECLENGTH];
		Tint pB[VECLENGTH];
		for (pA0=0; pA0<A.length(); pA0+=VECLENGTH) {
#			define THELOOP(pA,pA1) for (pA=pA0,pA1=0; pA<A.length() && pA1<VECLENGTH; pA++,pA1++)
			for (d=0; d<D; d++) {
				const Tint div = divisor[d];
				const Tint mod = modulus[d];
				if (div == 1) {
					THELOOP(pA,pA1) ind[d][pA1] = pA % mod;
				} else {
					THELOOP(pA,pA1)
						ind[d][pA1] = (pA / div) % mod;
				}
			}
			THELOOP(pA,pA1) pB[pA1] = 0;
			for (d=0; d<D; d++) {
				const Tint p = perm[d];
				const Tint m = mult[d];
				THELOOP(pA,pA1) pB[pA1]+= ind[p][pA1]*m;
			}
			switch (k) {
			case KIntArray:
				THELOOP(pA,pA1) B.IntPtr()[pB[pA1]] = A.IntPtr()[pA];
				break;
			case KRealArray:
				THELOOP(pA,pA1) B.RealPtr()[pB[pA1]] = A.RealPtr()[pA];
				break;
			case KComplexArray:
				THELOOP(pA,pA1) B.ComplexPtr()[pB[pA1]] = A.ComplexPtr()[pA];
				break;
			default:;
			}
#			undef THELOOP
		}
#		undef VECLENGTH
	}
	return 0;
}
[B] = herm(A; P)
/* herm(A) is the same as conj(transpose(A)).
   herm(A,P) is the same as conj(transpose(A,P)).
   You can abbreviate "herm(A)" as "A'".
   See also: transpose, flip, conj.
   Error codes:
   -1: Permutation argument not integer array
   -2: Permutation argument of bad rank or size
   -3: Permutation argument contains invalid integers */
{
	TConstObjectPtr inputs[2];
	TObjectPtr outputs[1];
	inputs[0] = argin[0];
	inputs[1] = argin[1];
	outputs[0] = argout[0];
	int errcode = transposefunction(inputs,Nargin,outputs,Nargout);
	if (errcode) return errcode;
	if (B.kind()==Kcomplex || B.kind()==KComplexArray)
		Transcen(tfpack_conj,B,B);
	return 0;
}

[y] = flip(x;d)
/* flip(A) reverses the first dimension of array A.
   flip(A,d) reverses the d'th dimension. For example,
   flip(#(1,6,2; 7,9,2.3),2) returns #(2,6,1; 2.3,9,7).
   If A is non-array it is returned as such, regardless of d.
   See also: transpose.
   Error codes:
   -1: Second argument not an integer scalar
   -2: Second argument out of range */
{
	if (x.IsNumericalArray()) {
		int dval;
		const TDimPack dp = x.dims();
		if (Nargin == 2) {
			if (d.kind()!=Kint) return -1;
			if (d.IntValue()<ArrayBase || d.IntValue()>=x.rank()+ArrayBase) return -2;
			dval = d.IntValue() - ArrayBase;
		} else
			dval = 0;
		Tint Nhigher, N, Nlower, chunksize;
		TDimPack dummy;
		DimpackLoopData(dp, dval, Nhigher, N, Nlower, chunksize,dummy);
		Tint k, p;
		const Tint indmax = (N-1)*Nlower;
		if (x.kind() == KIntArray) {
			const Tint *a;
			Tint *b;
			y.ireserv(dp);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.IntPtr() + i*chunksize + j;
				b = y.IntPtr() + i*chunksize + j;
				for (p=0; p<=indmax; p+=Nlower) b[indmax-p] = a[p];
			}
		} else if (x.kind() == KRealArray) {
			const Treal *a;
			Treal *b;
			y.rreserv(dp);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.RealPtr() + i*chunksize + j;
				b = y.RealPtr() + i*chunksize + j;
				for (p=0; p<=indmax; p+=Nlower) b[indmax-p] = a[p];
			}
		} else {	// now x.kind()==KComplexArray
			const Tcomplex *a;
			Tcomplex *b;
			y.creserv(dp);
			for (int i=0; i<Nhigher; i++) for (int j=0; j<Nlower; j++) {
				a = x.ComplexPtr() + i*chunksize + j;
				b = y.ComplexPtr() + i*chunksize + j;
				for (p=0; p<=indmax; p+=Nlower) b[indmax-p] = a[p];
			}
		}
	} else {
		y = x;
	};
	return 0;
}

//----------------- Query functions ------------------

[y] = isscalar(x)
/* isscalar(x) returns 1 if x is scalar and 0 if it is not.
   See also: isvector, ismatrix, isarray. */
{
	y = x.IsScalar();
	return 0;
}

[y] = isvector(x)
/* isvector(x) returns 1 if x is a vector and 0 if it is not.
   See also: isscalar, ismatrix, isarray. */
{
	y = x.IsArray() && x.rank()==1;
	return 0;
}

[y] = ismatrix(x)
/* ismatrix(x) returns 1 if x is a matrix (2D array)
   and 0 if it is not.
   See also: isscalar, isvector, isarray. */
{
	y = x.IsArray() && x.rank()==2;
	return 0;
}

[y] = isarray(x)
/* isarray(x) returns 1 if x is an array and 0 if it is not.
   See also: isscalar, isvector, ismatrix. */
{
	y = x.IsArray();
	return 0;
}

[y] = isreal(x)
/* isreal(x) returns 1 if x is numerical non-complex
   array or scalar, and 0 otherwise.
   See also: isfloat, isint, iscomplex. */
{
	Tkind k = x.kind();
	y = (k==Kint || k==Kreal || k==KIntArray || k==KRealArray);
	return 0;
}

[y] = isint(x)
/* isint(x) returns 1 if x is integer scalar or array
   and 0 if it is not.
   See also: isreal, isfloat, iscomplex. */
{
	Tkind k = x.kind();
	y = (k==Kint || k==KIntArray);
	return 0;
}

[y] = iscomplex(x)
/* iscomplex(x) returns 1 if x is a complex array or scalar,
   and 0 if it is real or integer or a nonnumeric object.
   See also: isreal, isfloat, isint. */
{
	Tkind k = x.kind();
	y = (k==Kcomplex || k==KComplexArray);
	return 0;
}

[y] = isfloat(x)
/* isfloat(x) returns 1 if x is a floating point array
   or scalar, and 0 otherwise. Notice the difference between
   isfloat and isreal. isreal(x) is 1 for integer objects,
   while isfloat(x) is 0.
   See also: isreal, isint, iscomplex. */
{
	Tkind k = x.kind();
	y = (k==Kreal || k==KRealArray);
	return 0;
}

[y] = isvoid(x)
/* isvoid(x) returns 1 if x is a void value and 0 otherwise. */
{
	y = x.kind() == Kvoid;
	return 0;
}

[y] = isstring(x)
/* isstring(x) returns 1 if x is a string and 0 otherwise.
   See also: ischar, isstr. */
{
	y = x.IsString();
	return 0;
}

[y] = ischar(x)
/* ischar(x) returns 1 if x is a character and 0 otherwise.
   See also: isstring, isstr. */
{
	y = x.IsChar();
	return 0;
}

[y] = isstr(x)
/* isstr(x) returns 1 if x is a character or string
   and 0 otherwise.
   See also: isstring, ischar. */
{
	y = x.IsString() || x.IsChar();
	return 0;
}

#ifdef UNICOS
#  define finite(x) (-1e1000 < (x) && (x) < 1e1000)
#endif

[y] = isfinite(x)
/* isfinite(x) returns 1 if x is a finite number and 0 otherwise.
   If x is array, the operation is applied componentwise.
   If x is non-numeric it is considered not finite.
   Integer and consequently strings and chars are always finite. */
{
	Tint *yp, i;
	switch (x.kind()) {
	case Kint: y = 1; break;
	case Kreal: y = finite(x.RealValue()); break;
	case Kcomplex: y = finite(real(x.ComplexValue())) && finite(imag(x.ComplexValue())); break;
	case KIntArray:
		y.copydimsIntArray(x);
		yp = y.IntPtr();
		for (i=0; i<x.length(); i++) yp[i] = 1;
		break;
	case KRealArray:
		{
			y.copydimsIntArray(x);
			yp = y.IntPtr();
			Treal *xp = x.RealPtr();
			for (i=0; i<x.length(); i++) yp[i] = finite(xp[i]);
		}
		break;
	case KComplexArray:
		{
			y.copydimsIntArray(x);
			yp = y.IntPtr();
			Tcomplex *xp = x.ComplexPtr();
			for (i=0; i<x.length(); i++) yp[i] = finite(real(xp[i])) && finite(imag(xp[i]));
		}
		break;
	default:
		y = 0;
	}
	return 0;
}

[y] = isfunction(x)
/* isfunction(x) returns 1 if x is a function
   (Tela-function, C-tela function or intrinsic function)
   and 0 otherwise.
   See also: isCfunction, isTfunction. */
{
	y = x.IsFunction() || x.IsCfunction() || x.IsIntrinsicFunction();
	return 0;
}

[y] = isCfunction(x)
/* isCfunction(x) returns 1 if x is a C-tela function.
   and 0 otherwise.
   See also: isfunction, isTfunction. */
{
	y = x.IsCfunction();
	return 0;
}

[y] = isTfunction(x)
/* isTfunction(x) returns 1 if x is a function written in Tela
   and 0 otherwise.
   See also: isfunction, isCfunction. */
{
	y = x.IsFunction();
	return 0;
}

[y] = isdefined(x)
/* isdefined(x) returns 1 if x is not undefined and 0 if
   it is undefined. Optional function arguments are undefined
   if not assigned by the caller; isdefined can be used
   inside the function to test whether this is the case.
   See also: isundefined. */
{
	y = x.kind() != Kundef;
	return 0;
}

[y] = isundefined(x)
/* isundefined(x) returns 1 if x is not undefined and 0 if
   it is undefined. Optional function arguments are undefined
   if not assigned by the caller; isdefined can be used
   inside the function to test whether this is the case.
   See also: isdefined. */
{
	y = x.kind() == Kundef;
	return 0;
}

// --------------- Miscellaneous functions ----------------

[y] = tostring(x)
/* tostring(x) converts an integer vector to a string.
   Transfer of characters is stopped if zero element
   is encountered.
   tostring(A) where A is geneeral integer array copies
   A and sets the string flag.
   Error codes:
   -1: Argument not an integer array
   */
{
	if (x.kind()!=KIntArray) return -1;
	if (x.rank() > 1) {		// Matrix or tensor: just copy it
		y = x;
	} else {				// Vector: copy up to zero element
		int L;
		for (L=0; L<x.length() && x.IntPtr()[L]!=0; L++);
		y.ireserv(L);
		memcpy(y.IntPtr(),x.IntPtr(),L*sizeof(Tint));
	}
	y.SetStringFlag();
	return 0;
}

[y] = SilentMode()
/* SilentMode() returns 1 if this Tela process is in silent mode
   (command line switch -s), otherwise 0.
   See also: BatchMode, VerboseMode, CheckReadOnlyMode. */
{
	y = flags::silent;
	return 0;
}

[y] = BatchMode()
/* BatchMode() returns 1 if this Tela process is in batch mode
   (command line switch -b), otherwise 0.
   See also: SilentMode, VerboseMode, UsingReadline. */
{
	y = flags::batch;
	return 0;
}

extern "C" FILE *rl_instream;

[y] = UsingReadline()
/* UsingReadline() returns 1 if this Tela was compiled
   to use the GNU readline library, otherwise 0.
   See also: BatchMode, SilentMode, VerboseMode. */
{
	y = !rl_instream || strcmp((char*)rl_instream,"noreadline");
	return 0;
}

[;y] = VerboseMode(;x)
/* VerboseMode() returns 1 if this Tela process is in verbose mode
   (command line switch -v), otherwise 0.
   VerboseMode(on) and VerboseMode(off) set the verbose mode on
   and off, respectively. They return the old mode setting.
   See also: SilentMode, BatchMode.
   Error codes:
   1: Argument not integer */
{
	if (Nargout == 1) y = flags::verbose;
	if (Nargin == 1) {
		if (x.kind()!=Kint) return 1;
		flags::verbose = x.IntValue();
	}
	return 0;
}

[;y] = CheckReadOnlyMode(;x)
/* CheckReadOnlyMode() returns 1 if this Tela process checks that function
   input arguments are not modified by the function. The check is done by
   default, but if it causes problems (bugs in Tela) you can turn it off
   using CheckReadOnlyMode(off).
   CheckReadOnlyMode returns the old mode setting.
   See also: SilentMode, BatchMode, VerboseMode.
   Error codes:
   1: Argument not integer */
{
	if (Nargout == 1) y = flags::checkRO;
	if (Nargin == 1) {
		if (x.kind()!=Kint) return 1;
		flags::checkRO = x.IntValue();
	}
	return 0;
}

[;y] = DebugQueryMode(;x)
/* DebugQueryMode() returns 1 if the debug query mode
   has been set, otherwise 0.
   DebugQueryMode(on) and DebugQueryMode(off) change
   the current setting.

   If debug query mode is on, the program will ask whether
   the user wants to enter debug mode if control-C is
   pressed (INT signal sent). Otherwise the program simply
   stops on pressing control-C.
   Error codes:
   1: Argument not integer */
{
	if (Nargout == 1) y = flags::debugquery;
	if (Nargin == 1) {
		if (x.kind()!=Kint) return 1;
		flags::debugquery = x.IntValue();
	}
	return 0;
}

[y] = all(x)
/* all(x) returns 1 if all elements of x are nonzero,
   and 0 otherwise.
   x must be an integer array or scalar.

   Conditional statements (if, while, for, until) assume
   implicit all, for example saying
       if (A > 0) ...
   is equivalent of saying
       if (all(A > 0)) ... ,
   thus you will need all less frequently than you need any.
   
   See also: any.
   Error codes:
   1: Argument not integer or IntArray */
{
	if (x.kind()==Kint) {
		y = x.IntValue()!=0;
		return 0;
	} else if (x.kind()==KIntArray) {
		Tint *ip = x.IntPtr();
		y = 1;
		VECTORIZED for (int i=0; i<x.length(); i++)
			if (ip[i]==0) {
				y = 0;
				break;
			}
		return 0;
	}
	y = 0;
	return 1;
}

[y] = any(x)
/* any(x) returns 1 if at least one element of x is nonzero,
   and 0 otherwise.
   x must be a integer array or scalar.

   Conditional statements (if, while, for, until) default
   to implicit all, thus you sometimes need to use any
   with these statements.
   
   See also: all.
   Error codes:
   1: Argument not integer or IntArray */
{
	if (x.kind()==Kint) {
		y = x.IntValue()!=0;
		return 0;
	} else if (x.kind()==KIntArray) {
		Tint *ip = x.IntPtr();
		y = 0;
		VECTORIZED for (int i=0; i<x.length(); i++)
			if (ip[i]) {
				y = 1;
				break;
			}
		return 0;
	}
	y = 0;
	return 1;
}

[B] = reshape(A...)
/* reshape(A,n,m,...) returns the data in array A rearranged
   to have dimensionality n x m x ... . The product of the indices
   must equal the length of A.
   reshape(A,#(n,m...)) works also.

   Example: reshape(#(1,2,3,4,5,6), 2,3) returns
       #(1, 2, 3;
	     4, 5, 6)  
   Error codes:
   -1: First argument not an array
   -2: Later argument not an integer
   -3: Product of dimensions does not equal the length of first argument
   -4: Number of input arguments exceeds MAXRANK
   -5: Second arg is array but not integer vector
   */
{
	if (!A.IsArray()) return -1;
	int newrank;
	int newdims[MAXRANK];
	if (Nargin>1 && argin[1]->IsArray()) {
		if (argin[1]->kind()!=KIntArray || argin[1]->rank()!=1) return -5;
		newrank = argin[1]->length();
		if (newrank > MAXRANK) return -4;
		Tint newlength = 1;
		for (int i=0; i<newrank; i++) {
			newdims[i] = argin[1]->IntPtr()[i];
			newlength*= newdims[i];
		}
	} else {
		newrank = Nargin - 1;
		if (newrank > MAXRANK) return -4;
		Tint newlength = 1;
		for (int i=0; i<newrank; i++) {
			if (argin[i+1]->kind() != Kint) return -2;
			newdims[i] = argin[i+1]->IntValue();
			newlength*= newdims[i];
		}
		if (newlength != A.length()) return -3;
	}
	B = A;
	B.SetNewDimPack(TDimPack(newdims,newrank));
	return 0;
}

[y] = find(x)
/* I=find(V) returns the index vector I=(i) for which
   V[i] is nonzero. V must be an integer array. The length
   of I is equal to the number of nonzeros in V.
   If V is multidimensional, it is used in flattened form.

   Example: If V=#(1,-2.3,4,5,-8.2), find(V < 0) returns
   #(2, 5).
   
   See also: any, all, flatten.
   Error codes:
   1: Argument not integer vector */
{
	if (x.kind()!=KIntArray) return 1;
	Tint *ip = x.IntPtr();
	int L = x.length();
	int len = 0;	// the length of y
	int i;
	for (i=0; i<L; i++) if (ip[i]) len++;	// count number of nonzeros in len
	y.ireserv(TDimPack(len));
	int j = 0;
	Tint *jp = y.IntPtr();
	for (i=0; i<L; i++) if (ip[i]) jp[j++] = i + ArrayBase;
	return 0;
}

[y] = flatten(;x)
/* flatten(x) returns the array x flattened to a vector.
   If x is not an array, it is returned as is.

   Example: flatten(#(1,2; 3,4)) returns #(1,2,3,4).
   
   x = flatten() flattens x "in place". This is much faster
   (it works in constant time) than to do x = flatten(x),
   since no data movement is involved. */
{
	if (Nargin==1) y = x;
	y.flatten();
	return 0;
}

[] = autoglobal(...)
/* autoglobal("sym1","sym2",...) sets the 'autoglobal' attribute
   to given symbols. The symbols are then globally accessible
   from inside packages and functions without need to explicitly
   declaring them global. Constants such as pi carry the autoglobal
   attribute automatically, but with this function it is possible
   for the user to define more autoglobal symbols.

   Warning: This function is for experts only. It is not advisable
   to say autoglobal("x"), for instance, because many existing code
   may then break down.

   See also: hide.
   Error codes:
   1: Argument not a string */
{
	for (int i=0; i<Nargin; i++) {
		if (!argin[i]->IsString()) return 1;
		Tstring ARG = *argin[i];
		Tsymbol *symptr = theHT.add((const Tchar*)ARG);
		symptr->SetGlobalFlag();
	}
	return 0;
}

// Comparison functions for stdlib qsort function
// ----------------------------------------------

static Tint *sort_iptr = 0;
static Treal *sort_rptr = 0;
static Tcomplex *sort_cptr = 0;

static int IntComparison(const void*x1, const void*y1) {
	const Tint *x=(const Tint*)x1, *y=(const Tint*)y1;
	const Tint a = sort_iptr[*x], b = sort_iptr[*y];
	if (a < b)
		return -1;
	else if (a == b)
		return 0;
	return 1;
}

static int RealComparison(const void*x1, const void*y1) {
	const Tint *x=(const Tint*)x1, *y=(const Tint*)y1;
	const Treal a = sort_rptr[*x], b = sort_rptr[*y];
	if (a < b)
		return -1;
	else if (a == b)
		return 0;
	return 1;
}

static int ComplexComparison(const void*x1, const void*y1) {
	const Tint *x=(const Tint*)x1, *y=(const Tint*)y1;
	const Treal a = real(sort_cptr[*x]), b = real(sort_cptr[*y]);
	if (a < b)
		return -1;
	else if (a == b)
		return 0;
	return 1;
}

[y;I] = sort(x)
/* sort(x) returns array x sorted in ascending order.
   If x is complex, it is sorted by the real parts.
   If x is not an array, it is returned as is.
   [y,I] = sort(x) returns also an index vector I such that
   y == x[I].

   To sort with user-defined comparisons, do the following.
   For example, if you want to sort a complex vector z by
   absolute value as Matlab does, first sort a vector of
   absolute values saving the index information:

   [y,I] = sort(abs(z));

   Then y=z[I] is the wanted result.

   If x is multidimensional, it is implicitly flattened.
   Use the map function to get around this problem.
*/
{
	const Tkind k = x.kind();
	if (x.IsArray()) {
		int (*comparison)(const void*, const void*);
		Tobject indices;
		const Tint N = x.length();
		indices.ireserv(N);
		int i;
		for (i=0; i<N; i++) indices.IntPtr()[i] = i;
		if (k == KIntArray) {
			sort_iptr = x.IntPtr();
			comparison = IntComparison;
		} else if (k == KRealArray) {
			sort_rptr = x.RealPtr();
			comparison = RealComparison;
		} else {
			sort_cptr = x.ComplexPtr();
			comparison = ComplexComparison;
		}
		qsort(indices.IntPtr(),N,sizeof(Tint),comparison);
		y = x;
		if (k == KIntArray)
			for (i=0; i<N; i++) y.IntPtr()[i] = x.IntPtr()[indices.IntPtr()[i]];
		else if (k == KRealArray)
			for (i=0; i<N; i++) y.RealPtr()[i] = x.RealPtr()[indices.IntPtr()[i]];
		else
			for (i=0; i<N; i++) y.ComplexPtr()[i] = x.ComplexPtr()[indices.IntPtr()[i]];
		if (Nargout == 2) {
			I.bitwiseMoveFrom(indices);
			for (i=0; i<N; i++) I.IntPtr()[i]+= ArrayBase;
		}
	} else {
		y = x;
		if (Nargout == 2) {
			I.ireserv(1);
			I.IntPtr()[0] = ArrayBase;
		}
	}
	return 0;
}

#if HAVE_RUSAGE && defined(SUN)
extern "C" int getpagesize(void);
#endif

#if HAVE_UNISTD_H
#  include <unistd.h>
#  define HAVE_UNIX_FUNCTIONS 1
#else
#  define HAVE_UNIX_FUNCTIONS 0
#endif

[m] = meminuse()
/* meminuse() returns the size of the current Tela process
   in bytes. The result is a real number.

   Implementation: It uses the getrusage function if it is available
   and if it seems to be working properly. Otherwise it calls sbrk(0),
   which should return the data segment size in bytes. On Cray UNICOS
   it multiplies the sbrk(0) value by 8 (Cray is a word machine).
   If sbrk is not available, it returns always 0.
   - Surprisingly, many Unix systems have the getrusage function but
   the relevant field in struct rusage is always returned as zero.
   In this case the sbrk method is used.
   - On some machines the result is unreliable.

   If Tela has been compiled with TELASPECIFIC_NEWDELETE defined,
   Tela's own new/delete operators are in use. In this case meminuse
   will report the memory asked from the OS with malloc from C++ code
   only. Any use of malloc from C code (GNU readline library, HDF library ...)
   will thus not be included, as also not the data segment and stack size.
   The result can nevertheless be a useful measure of the user memory.
   You can tell if TELASPECIFIC_NEWDELETE is on by looking at the output
   of the info() function.
   See also: info
*/
{
#ifdef TELASPECIFIC_NEWDELETE
	m = Treal(global::memalloc);
#else
#	ifdef UNICOS
	// Cray does not have getrusage, and it counts things in 8-byte words
	m = 8.0*Treal(TPtrInt(sbrk(0)));
#	elif HAVE_RUSAGE
	// We assume that if getrusage is available, also getpagesize() must be there
	// On Sun (Solaris2.5) the prototype is missing so we must declare it (see above)
	getrusage(RUSAGE_SELF,&struct_ru);
//	cout << "getrusage ru_maxrss is " << struct_ru.ru_maxrss << "\n";
#	if HAVE_UNISTD_H
	if (struct_ru.ru_maxrss == 0) {
		// On some (many?) Unixes the getrusage call is there but it always returns zero
		// in the ru_maxrss field. Detect this and use the sbrk way instead.
//		cout << "resorting to sbrk(0)\n";
		m = Treal(TPtrInt(sbrk(0)));
	} else
#	endif
		m = Treal(struct_ru.ru_maxrss)
#ifdef __sgi
			* 1024.0;
#else
			* Treal(getpagesize());
#endif
#	elif HAVE_UNISTD_H
	// Last resort, use sbrk (but this will ignore program text size?)
	m = Treal(TPtrInt(sbrk(0)));
#	else
	// Lastest resort, we are probably not on Unix at all
	m = 0.0;
#	endif
#endif
	return 0;
}

static int IsPerfDataArray(const Tobject& p)
// Return 1 if p is a performance data array, 0 otherwise.
{
	const int L = int(Fnop) - int(Fadd) + 2;
	if (p.kind()!=KRealArray || p.rank()!=2) return 0;
	if (p.dims()[0]!=L || p.dims()[1]!=2) return 0;
	return 1;
}

[t] = cputime(;p)
/* cputime() returns the CPU time in seconds used by the current
   tela session. cputime(p) returns CPU time from performance data
   array p, previously obtained from perf().
   See also: tic, toc, perf.
   Error codes:
   -1: Bad argument, must be obtained from perf() */
{
	if (Nargin == 1) {
		if (!IsPerfDataArray(p)) return -1;
		t = p.RealPtr()[0];
	} else
		t = CPUSeconds();
	return 0;
}

[Ninstructions,Noperations] = GetInstructionData(p,mnemo)
/* [Ninstr,Nops] = GetInstructionData(p,"mnemonic") returns
   the number of specific instructions executed when p=perf() was
   gathered, and the number of (floating point) operations associated
   with the instruction.
   The mnemonic must be a string, and it may be any of the names
   that appear in the disasm(f) listing. In addition, mnemonic may
   be "flop", which includes all instructions that may perform floating
   point arithmetic, or it may be "*", which includes all instructions.
   Error codes:
   -1: Bad first argument, must be obtained from perf()
   -2: Second arg not a string
   -3: Second arg not a recognized string
   */
{
	if (!IsPerfDataArray(p)) return -1;
	Treal *const pv = p.RealPtr();
	if (!mnemo.IsString()) return -2;
	const Tstring MN = mnemo;
	const char *mnorig = (char*)MN;
	char *mn = strdup(mnorig);
	int i;
	for (i=0; mn[i]; i++) if (islower(mn[i])) mn[i] = char(toupper(mn[i]));
	Treal totalNinstr=0, totalNops=0, floatNinstr=0, floatNops=0;
	Treal specificNinstr=0, specificNops=0;
	int matched = 0;
	i = 1;
	for (int k=Fadd; k<=Fnop; k++,i++) {
		const Treal ninstr = pv[2*i];
		const Treal nops = pv[2*i+1];
		totalNinstr+= ninstr;
		totalNops+= nops;
		if (instrinfo[k].isflop) {
			floatNinstr+= ninstr;
			floatNops+= nops;
		}
		if (!strcmp(mn,instrinfo[k].mnemonic)) {
			specificNinstr+= ninstr;
			specificNops+= nops;
			matched = 1;
		}
	}
	if (!strcmp(mn,"FLOP")) {
		Ninstructions = floatNinstr;
		Noperations = floatNops;
	} else if (!strcmp(mn,"*")) {
		Ninstructions = totalNinstr;
		Noperations = totalNops;
	} else if (!matched)
		return -3;
	else {
		Ninstructions = specificNinstr;
		Noperations = specificNops;
	}
	return 0;
}

static Treal TicTocTime = 0;

[] = tic()
/* tic() marks the CPU time at which it was invoked.
   To measure CPU time, use tic() and toc().
   See also: cputime, toc.
   Example:

      a = rand(100,100); tic(); b=inv(a); toc()

  This would measure the CPU time in inverting a 100x100
  random real matrix. See also: toc. */
{
	TicTocTime = CPUSeconds();
	return 0;
}

[t] = toc()
/* toc() gives the CPU seconds used since the last call to tic().
   See also: tic, cputime. */
{
	t = CPUSeconds() - TicTocTime;
	return 0;
}

[v] = perf()
/* perf() returns an array containing all maintained operation
   counters. To measure performance of a code segment, do

   p0=perf(); mycode(); p=perf()-p0;

   Now you can apply various performance-related functions to p:
   for example cputime(p), Mflops(p). */
{
	const int L = int(Fnop) - int(Fadd) + 2;
	v.rzeros(TDimPack(L,2));
	Treal *const vp = v.RealPtr();
	vp[0] = vp[1] = CPUSeconds();
	int i,c;
	for (i=1,c=Fadd; i<L; i++,c++) {
		vp[2*i] = HPM[c].Ninstr;
		vp[2*i+1] = HPM[c].Nops;
	}
	// Subtract spurious operations recorded by rzeros
	global::nops-= 2*L;
	return 0;
}

[] = pause(;seconds)
/* pause() will wait for a keypress on keyboard.
   pause(n) will pause for n seconds and then continue.
   The argument n may be integer or real.

   Note: some systems implicitly round a real argument
   to nearest whole number.
   Error codes:
   1: Argument not a real scalar
   2: Argument is negative
   3: This system does not support pausing for n seconds */
{
	int ch;
	Treal n;
	if (Nargin == 1) {
		if (seconds.kind()==Kint) {
			if (seconds.IntValue() < 0) return 2;
			n = seconds.IntValue();
		} else if (seconds.kind()==Kreal) {
			if (seconds.RealValue() < 0.0) return 2;
			n = seconds.RealValue();
		} else
			return 1;
#		if HAVE_UNIX_FUNCTIONS
		sleep(round(n));
#		else
		return 3;
#		endif
	} else {
		cout << "Pausing. Hit return to continue." << flush;
		do {ch=getchar();} while (ch != '\n');
	}
	return 0;
}

[] = cd(fn)
/* cd("pathname") will change the current directory to "pathname".
   cd("") will change to home directory.
   cd("~/my/dir") will change to directory "my/dir" in the
   home directory.

   See also: getenv.
   Error codes:
   1: Input argument not a string
   2: Directory not found
   3: This system does not support cd */
{
	if (!fn.IsString()) return 1;
#	if HAVE_UNIX_FUNCTIONS
	Tstring S = fn;
	char *s = (char*)S;
	// If the string is empty, go to home directory
	if (!s[0]) return (chdir(getenv("HOME"))!=0) ? 2 : 0;
	// If the string starts with "~/", first cd to home, then remove the "~/"
	if (s[0]=='~' && s[1]=='/') {
		s+= 2;
		if (chdir(getenv("HOME"))!=0) return 2;		// return is unsuccessful, continue if not
	}
	// If last char is newline, first try cd with the newline, if it fails
	// then try again with newline removed. This enables the user to write
	// e.g. x=run("pwd"); cd(x);
	const int L = strlen(s);
	if (s[L-1] == '\n') {
		if (chdir(s)==0) return 0;
		s[L-1] = '\0';
	}
	return (chdir(s)!=0) ? 2 : 0;
#	else
	return 3;
#	endif
}

[y] = getenv(varname)
/* getenv("envvar") returns the value of environment variable
   "envvar", or VOID if such variable is not defined in
   the UNIX environment.

   For example, getenv("LOGNAME") returns the login name of
   the owner of the Tela prcess.
   (If Unix functions are not available, getenv will always
   return VOID.)

   See also: getpid, cd.
   Error codes:
   -1: Argument not a string
   */
{
	y.SetToVoid();
	if (!varname.IsString()) return -1;
#	if HAVE_UNIX_FUNCTIONS
	Tstring VARNAME = varname;
	char *result = getenv((char*)VARNAME);
	if (result) {
		int L = strlen(result);
		y.ireserv(TDimPack(L));
		for (int i=0; i<L; i++) y.IntPtr()[i] = Tint(result[i]);
		y.SetStringFlag();
	}
#	endif
	return 0;
}

[y] = getpid()
/* getpid() returns the process ID of the Tela process.
   This can be used e.g. to generate unique temporary
   file names. If Unix functions are not available,
   getpid() returns 0. */
{
#	if HAVE_UNIX_FUNCTIONS
	y = Tint(getpid());
#	else
	y = 0;
#	endif
	return 0;
}

extern int  ExecuteFile(const Tchar fn[], int silent);     					// defined in tela.C
extern void ExecuteLine(Tchar *line, int SetJump=0, int printsetflag=1);	// also in tela.C

[] = source(fn)
/* source("file.t") loads the tela code from given file.
   See also: source_silent, autosource, load.
   Error codes:
   1: Operation did not succeed
   2: Argument not a string */
{
	if (fn.IsString()) {
		Tstring s = fn;
		return ExecuteFile((Tchar*)s,0);
	} else
		return 2;
}

[] = source_silent(fn)
/* source_silent("file.t") is similar to source("file.t"),
   but it does not complain if e.g. the file does not exist.
   See also: source, autosource, load.
   Error codes:
   1: Argument not a string */
{
	if (fn.IsString()) {
		Tstring s = fn;
		ExecuteFile((Tchar*)s,1);
		return 0;
	} else
		return 1;
}

[] = autosource(fn...)
/* autosource("file.t","name1","name2",...) tags symbols
   name1, name2,... such that the command source("file.t")
   is effectively executed when any of the symbols name
   is used. This is load-on-demand.
   See also: source.
   Error codes:
   1: Argument not a string */
{
	int i;
	for (i=0; i<Nargin; i++) if (!argin[i]->IsString()) return 1;
	Tchar *stub = new Tchar [fn.length() + 1];
	for (i=0; i<fn.length(); i++) stub[i] = fn.IntPtr()[i];
	stub[fn.length()] = '\0';
	typedef const void *TConstVoidPtr;
	TConstVoidPtr *stubinfo = new TConstVoidPtr [Nargin+1];
	*stubinfo = stub;
	for (i=1; i<Nargin; i++) {
		Tchar *symname = new Tchar [argin[i]->length() + 1];
		for (int j=0; j<argin[i]->length(); j++) symname[j] = argin[i]->IntPtr()[j];
		symname[argin[i]->length()] = '\0';
		Tsymbol *symptr = theHT.add(symname);
		symptr->SetStubInfo(stubinfo);
		stubinfo[i] = symptr;
		delete [] symname;
	}
	stubinfo[Nargin] = 0;
	return 0;
}

[] = eval(s)
/* eval("string") executes string as a Tela command, as it had been
   typed from the keyboard.
   The evaluation is done in global context. The symbols appearing
   in the string refer to the global ones.
   See also: evalexpr.
   Error codes:
   1: Argument not a string */
{
	if (s.IsString()) {
		Tstring S = s;
		ExecuteLine((Tchar*)S);
		return 0;
	}
	return 1;
}

[y] = evalexpr(s)
/* evalexpr("expression") executes string as a Tela command,
   returning its value in y.
   The evaluation is done in global context. The symbols appearing
   in the string refer to the global ones.
   See also: eval.
   Error codes:
   1: Argument not a string */
{
	if (s.IsString()) {
		Tstring S = s;
		Tchar* str = new Tchar [strlen((Tchar*)S) + 7];
		strcpy(str,(Tchar*)"a_n_s=");
		strcat(str,(Tchar*)S);
		ExecuteLine(str,0,0);
		delete [] str;
		Tsymbol*anssymbol=theHT.assoc((Tchar*)"a_n_s");
		if (anssymbol->value()) {
			y = *(anssymbol->value());
			anssymbol->value()->SetToUndefined();
		} else
			y.SetToVoid();
		return 0;
	}
	return 1;
}

[y] = str2num(s)
/* str2num(s) converts a string to a number.
   The string must represent a scalar. If an error
   occurs, str2num returns a void value.
   Error codes:
   1: Argument not a string */
{
	y.SetToVoid();
	if (!s.IsString()) return 1;
	Tstring S = s;
	double X,Y;
	char *str = (char*)S;
	int L = strlen(str);
	if (str[L-1]=='\n') L--;
	if (!strchr(str,'.') && !strchr(str,'e') && !strchr(str,'E') && !strchr(str,'i')) {
		long int I;
		if (sscanf(str,"%ld",&I)==1)
			y = Tint(I);
	} else if (str[L-1]=='i') {
		int cnt = sscanf(str,"%lf%lfi",&X,&Y);
		if (cnt==1)
			y = Tcomplex(0,X);
		else if (cnt==2)
			y = Tcomplex(X,Y);
	} else {
		if (sscanf(str,"%lf",&X)==1)
			y = X;
	}
	return 0;
}

[] = system(s)
/* system("string") executes string as an external
   operating system command.
   See also: run.
   Error codes:
   1: Argument not a string */
{
	if (s.IsString()) {
		Tstring S = s;
		system((char*)S);
		return 0;
	}
	return 1;
}

#include <fstream.h>
#if HAVE_UNIX_FUNCTIONS
   extern "C" int wait(int*);
#  ifdef HAVE_SYSCONF
#    define max_open_files sysconf(_SC_OPEN_MAX)
#  else
#    define max_open_files 256		/* it doesn't matter if this value is too large */
#  endif
#endif

[output] = run(cmd; input)
/* run("cmd","input") runs operating system (Unix) command
   "cmd", using contents of the second argument string as
   standard input. It returns the standard output of "cmd"
   as a string.

   The form run("cmd") may be used if the command does not
   read standard input. The command is executed by /bin/sh.

   See also: run.

   Error codes:
   -1: First argument not a string
   -2: Second argument not a string
   -3: Error with temporary file
   -4: Error with internal pipe
   -5: run not supported: OS does not provide unistd.h nor popen()
   -7: wait(2) returned error
   -8: pipe(2) returned error
   -9: cannot fork(2) a child process
   */
{
	if (!cmd.IsString()) return -1;
	if (Nargin>1 && !input.IsString()) return -2;
	Tstring CMD = cmd;
	
#	if HAVE_UNIX_FUNCTIONS

	char *SHELL = "/bin/sh";
	int inputpipe[2], outputpipe[2];
	// parent writes to inputpipe[1], child reads from inputpipe[0]
	// parent reads from outputpipe[0], child writes to outputpipe[1]
	if (pipe(inputpipe)!=0) return -8;
	if (pipe(outputpipe)!=0) return -8;
	//fprintf(stderr,"[%d,%d], [%d,%d]\n",inputpipe[0],inputpipe[1], outputpipe[0],outputpipe[1]);
	/* NOTICE: For some reason, using fstreams and .attach() does not work,
	   therefore we use fdopen.*/
	long f;
	if ((f=
#ifdef UNICOS
		 vfork()
#else
		 fork()
#endif
		) > 0) {	// now in parent
		if (Nargin>1 && input.length()>0) {
			FILE *tostream = fdopen(inputpipe[1],"w");
			for (int i=0; i<input.length(); i++) {
				putc(input.IntPtr()[i],tostream);
			}
			fclose(tostream);	// also closed inputpipe[1]
			//fprintf(stderr,"--parent: wrote tostream\n");
		} else
			close(inputpipe[1]);
		FILE *fromstream = fdopen(outputpipe[0],"r");
		//fprintf(stderr,"--parent: opened fromstream\n");
		close(inputpipe[0]);	/* parent does not read from inputpipe, only child does */
		close(outputpipe[1]);	/* parent does not write to outputpipe, only child does */
		strstream S;
		for (;;) {
			char ch;
			ch = fgetc(fromstream);
			if (feof(fromstream)) break;
			S << ch;
			//fprintf(stderr,"transferred char '%c'\n",ch);
		}
		fclose(fromstream);		// also closed outputpipe[0].
		/* Now all four pipe filedes are closed from the parent side. */
		S << ends;
		char *charptr = S.str();
		output = charptr;
		delete [] charptr;
		//fprintf(stderr,"--parent: wait\n");
		if (wait(0) < 0) return -7;
	} else if (f==0) {	/* now in child */
		//close(outputpipe[0]);	// child does not read from outputpipe, only parent does
		//close(inputpipe[1]);	// child does not write to inputpipe, only parent does
		fflush(stdout);			// Flush before closing stdin, stdout
		cout << flush;			//   (dup2 will close descriptors 0 and 1)
		dup2(inputpipe[0],0);	// stdin from inputpipe[0]
		dup2(outputpipe[1],1);	// stdout to outputpipe[1]
		//close(inputpipe[0]);	// no more needed
		//close(outputpipe[1]);	// no more needed
		// close all possible open file descriptors above stdin, stdout, stderr
		for (long i=max_open_files-1; i>2; i--) close((int)i);
		//cerr << "--child: executing " << SHELL << " -c " << (char*)CMD << "\n";
		execl(SHELL,SHELL,"-c",(char*)CMD,0);
		//execlp((char*)CMD,(char*)CMD,0);
		exit(0);		// This child is still Tela so it is better to exit now!
	} else
		return -9;
	return 0;

#	elif HAVE_POPEN		/* no unistd.h but popen() is there */

	// Strategy: Use temporary file for command's input but pipe for its output
	FILE *p;
	char t[MAXFILENAME] = "";
	if (Nargin>1 && input.length()>0) {
		tmpnam(t);
		ofstream o(t);
		if (!o.good()) return -3;
		for (int i=0; i<input.length(); i++)
			o <<
#ifdef _UNICOS
				(unsigned char)
#else
				char
#endif
				(input.IntPtr()[i]);
		o.close();
		char *s = new char [cmd.length() + 8 + strlen(t)];
		sprintf(s,"cat %s | %s",t,(char*)CMD);
		p = popen(s,"r");
		if (!p) return -4;
		delete [] s;
	} else {
		p = popen((char*)CMD,"r");
		if (!p) return -4;
	}
	strstream S;
	for (;;) {
		char ch = fgetc(p);
		if (feof(p)) break;
		S << ch;
	}
	pclose(p);
	if (*t) remove(t);
	S << ends;
	char *charptr = S.str();
	output = charptr;
	delete [] charptr;
	return 0;

#	else	/* no unistd.h, no popen(), cannot deliver! */

	return -5;

#	endif

}	// run

[] = disasm(fn)
/* disasm(f) produces disassembly listing of function f.
   Error codes:
   1: Argument not a Tela function */
{
	if (fn.IsFunction()) {
		cout << *fn.FunctionValue() << '\n';
		return 0;
	}
	return 1;
}

extern void Ctgen(ostream& o, Tprg& prg);
extern void SetAvoidCtorsFlag(int flag);

[] = t2ct(fn)
/* t2ct("filename.t") translates t-code to ct-code.
   This makes it possible to compile t-files into
   faster code.

   To compile a t-file "fyle.t", do the following:

   (1) Generate "fyle.ct" by t2ct("fyle.t") from Tela.
   You can also do this from the shell prompt or Makefile by

   tela -sbe 't2ct("fyle.t")'

   (use single quotes around the argument but cannot show it here, sorry).
   
   (2) Compile it using

   telakka -c fyle.ct

   from the shell or the Makefile. (From within Tela,
   you can use the system function, or precede the command
   line by "!" in interactive mode.)

   (3) The resulting object file fyle.o can be linked directly
   to Tela on some systems (e.g. Linux using the DLD library):

   link("fyle.o")

   On systems using the DSO library (SGI, Sun ...) you must first
   make a shared object file:

   ld -o fyle.so -shared fyle.o

   The DSO file can now be linked to Tela:

   link("fyle.so")

   (When using the DLD library you can emulate the previous step
   by ld -o fyle.so -r fyle.o, this makes it possible to write machine-
   independent Makefiles using gmake.)

   (3b) If you do not want dynamic linking, or if your system does
   not support it (e.g. UNICOS), you can always link your stuff in
   a new Tela kernel by simply using the telakka command:

   telakka -o newtela fyle.o

   When you start the binary 'newtela' the functions defined in
   fyle.t are available.
   
   See also: avoid_constructors, system.
   Error codes:
   1: Operation did not succeed
   2: Argument not a string
   3: Could not open output file
   */
{
	if (fn.IsString()) {
		Tstring s = fn;
		char outname[MAXFILENAME];
		strcpy(outname,(char*)s);
		int L = strlen(outname);
		if (outname[L-1] == 't' && outname[L-2] == '.') {
			outname[L-1] = 'c';
			outname[L] = 't';
			outname[L+1] = '\0';
		} else
			strcat(outname,".ct");
		ofstream o(outname);
		if (!o.good()) return 3;
		o << "#include \"gatscat.H\"\n#include \"prg.H\"\n\n";
		global::ctfile = &o;
		int retval = ExecuteFile((Tchar*)s,0);
		o << flush;
		global::ctfile = 0;
		return retval;
	} else
		return 2;
}

[] = avoid_constructors(flag)
/* avoid_constructors(on) affects the operation
   of subsequent t2ct function calls.
   When this flag is on, the generated C-tela (C++)
   code avoids constructing class objects on the stack
   but instead declares these objects as pointers and
   initializes them using the 'new' operator.
   This mode compiles on ATT Cfront versions that do not
   support goto statements in blocks having constructors.

   However, in some rare cases avoid_constructors(on)
   is known to produce incorrect code. The default is
   avoid_constructors(off).

   See also: t2ct.
   Error codes:
   1: Argument not an integer
*/
{
	if (flag.kind()!=Kint) return 1;
	SetAvoidCtorsFlag(flag.IntValue());
	return 0;
}


[] = showcompiled(filename...)
/* showcompiled("filename.ct",f1,f2,...) compiles functions
   f1,f2,... to C-tela code, creating "filename.ct".
   If no suffix is given in "filename", the suffix
   ".ct" will be assumed.
   showcompiled(f1,f2,...) displays on standard output.
   See also: t2ct.
   Error codes:
   1: One of the args is not a Tela-function
   2: Cannot open output file
   */
{
	if (filename.IsString()) {
		Tstring FN = filename;
		char fn[MAXFILENAME];
		strcpy(fn,(char*)FN);
		char *Dotpos = strrchr(fn,'.');
		char *Slashpos = strrchr(fn,'/');
		if (!Dotpos || Slashpos && (Slashpos > Dotpos))
			strcat(fn,".ct");
		ofstream o(fn);
		if (!o.good()) return 2;
		for (int i=1; i<Nargin; i++) {
			if (!(argin[i]->IsFunction())) return 1;
			Ctgen(o,*(argin[i]->FunctionValue()));
		}
	} else {
		for (int i=0; i<Nargin; i++) {
			if (!(argin[i]->IsFunction())) return 1;
			Ctgen(cout,*(argin[i]->FunctionValue()));
		}
	}
	return 0;
}

extern "C" int closefigfunction(const TConstObjectPtr[], const int, const TObjectPtr[], const int);

[] = exit()
/* exit() stops Tela. quit() is synonym for exit(). */
{
	PerformanceReport();
	cout << flush; clog << flush;
	// Do closefig("all")
	// This is necessary since we have defined exit(x) = _exit(x) so that exit(0) does
	// not call global destructors (since these caused other problems such as core dumps
	// on exit on Linux sometimes). If the exit definition is sometimes removed, closing
	// the figures here doesn't harm anyway.
	TConstObjectPtr inputs[1];
	TObjectPtr outputs[1];
	const Tobject all("all");
	inputs[0] = &all;
	closefigfunction(inputs,1,outputs,0);
	exit(0);
	return 0;		// avoid compiler warning in most cases
}

[] = quit()
/* quit() stops Tela. quit() is synonym for exit(). */
{
	PerformanceReport();
	cout << flush; clog << flush;
	// Do closefig("all")
	TConstObjectPtr inputs[1];
	TObjectPtr outputs[1];
	const Tobject all("all");
	inputs[0] = &all;
	closefigfunction(inputs,1,outputs,0);
	exit(0);
	return 0;		// avoid compiler warning in most cases
}

extern void stripwhite(Tchar *s);		// in tela.C
extern "C" Tchar *readline(const char *prompt);		// from GNU readline library
extern "C" void add_history(const Tchar *line);		// from GNU readline/history library

[s] = input_string(;prompt)
/* input_string() waits for an input line from the keyboard
   and returns it as a string. The newline is not included
   in the result.
   If the string is enclosed in double quotes, they are removed.

   input_string("prompt") displays prompt first.
   Error codes:
   -1: EOF encountered. */
{
	Tchar *line;
	if (Nargin==1 && prompt.IsString()) {
		Tstring PROMPT = prompt;
		cout << PROMPT;
	}
	clog << flush; cout << flush;
	line = readline(" ");
	if (!line) return -1;	// readline encountered eof
	int L = strlen(line);
	if (L > 0) add_history(line);
	if (*line == '"' && line[L-1] == '"') {
		memmove(line,line+1,L);
		if (L>=2) line[L-2] = '\0';
	}
	Tobject s1 = line;
	s = s1;
	free(line);
	return 0;
}

static int GenericMenu(const TConstObjectPtr argin[], const int Nargin,
						const TObjectPtr argout[], const int Nargout,
						const int stringflag)
#define result (*(argout[0]))
#define title (*(argin[0]))
{
	if (Nargin<2) return -1;
	int n;
	for (n=0; n<Nargin; n++)
		if (!argin[n]->IsString()) return -1;
	Tstring s;
	int choice;
    for (;;) {
		s = title;
		cout << s << '\n';
		for (n=1; n<Nargin; n++) {
			s = *argin[n];
			int old_width = cout.width();
			long old_flags = cout.flags();
			cout.width(3);
			cout.setf(ios::right);
			cout << n;
			cout.flags(old_flags);
			cout.width(old_width);
			cout << ")  " << s << '\n';
		}
		cout << "  ?)  " << flush;
		char s1[512+1];
		fgets(s1,512,stdin);
		if (sscanf(s1,"%d",&choice)!=1 || choice<1 || choice>Nargin-1) {
			cout << "- Please enter a number between 1 and " << Nargin-1 << ".\n";
		} else break;
	}
	if (stringflag)
		result = *argin[choice];
	else
		result = choice;
	return 0;
#	undef title
#	undef result
}

[result] = menu(title...)
/* choice = menu("title","choice1","choice2",...) displays
   a menu of choices and returns the number entered by
   the user.
   See also: smenu.
   Error codes:
   -1: Less than two input args */
{
	return GenericMenu(argin,Nargin,argout,Nargout,0);
}

[result] = smenu(title...)
/* choice = smenu("title","choice1","choice2",...) displays
   a menu of choices and returns the "choice" string corresponding
   to the number entered by the user.
   See also: menu.
   Error codes:
   -1: Less than two input args */
{
	return GenericMenu(argin,Nargin,argout,Nargout,1);
}

[y] = streq(s1,s2)
/* streq("string1","string2") returns 1 if the argument
   strings are exactly equal and 0 otherwise. If one of
   the args is not a string, the result is also 0.
   See also: strstarteq. */
{
	if (!s1.IsString() || !s2.IsString()) {y=0; return 0;}
	int L = s1.length();
	if (L != s2.length()) {y=0; return 0;}
	for (int i=0; i<L; i++)
		if (s1.IntPtr()[i] != s2.IntPtr()[i]) {y=0; return 0;}
	y = 1;
	return 0;
}

[y] = strstarteq(s1,s2)
/* strstarteq("string1","string2") returns 1 if the argument
   strings are equal on the first min(length(s1),length(s2))
   characters and 0 otherwise.
   If one of the the args is not a string, the result is also 0.
   See also: streq. */
{
	if (!s1.IsString() || !s2.IsString()) {y=0; return 0;}
	int L = min(s1.length(),s2.length());
	for (int i=0; i<L; i++)
		if (s1.IntPtr()[i] != s2.IntPtr()[i]) {y=0; return 0;}
	y = 1;
	return 0;
}

[] = whos(;hidden)
/* whos() displays names of variables together with their
   types and values, if short. 'Hidden' symbols are not shown.
   whos("hidden") shows also hidden symbols.
   See also: hide, unhide.
   Error codes:
   1: Bad argument
   -1: Cannot open pipe to sort
   */
{
	int ShowAlsoHidden = 0;
	if (Nargin == 1 && hidden.IsString()) {
		Tstring HIDDEN = hidden;
		ShowAlsoHidden = !strcmp((Tchar*)HIDDEN,(Tchar*)"hidden");
	}
	if (Nargin==1 && !ShowAlsoHidden) return 1;
	double bytes = 0.0;
	// Options to sort:
	// -b ignore leading blank, -f make lowercase/uppercase equal, -k1 sort with respect to first field
	char *pager;
	if (flags::batch) {
		pager = "cat";
	} else {
		pager = getenv("PAGER");
		if (!pager) pager = "more";
	}
	char *sorter;
	sorter = getenv("TELA_SORTER");
	if (!sorter) sorter = "sort -b -f -k 1";
	char *s = new char [80 + strlen(pager) + strlen(sorter)];
	sprintf(s,"%s | %s",sorter,pager);
	FILE *fp = popen(s,"w");
	if (!fp) return -1;
	cout << flush;
//	ofstream out;
//	out.attach(fileno(fp));
	ofstream out(fileno(fp));
	for (THashEntryPtr p=theHT.first(); p; p=theHT.next()) {TObjectPtr objptr = p->value();
		if (objptr) {
			Tkind k = objptr->kind();
			if ((ShowAlsoHidden || !p->IsHidden()) && k!=Kfunction && k!=KCfunction && k!=KIntrinsicFunction
				&& k!=Kundef && !strchr((char*)(p->name()),':'))
			{
				int old_width = out.width();
				long old_flags = out.flags();
				out.width(16);
				out.setf(ios::right);
				out << *p;
				out.width(old_width);
				out.flags(old_flags);
				out << "  " << Tshort(*objptr);
				if (objptr->HasStringFlag() && objptr->kind()==KIntArray && objptr->rank() > 1) out << " (string array)";
				if (objptr->IsArray()) {
					if (objptr->kind()==KIntArray)
						bytes+= objptr->length()*sizeof(Tint);
					else if (objptr->kind()==KRealArray)
						bytes+= objptr->length()*sizeof(Treal);
					else
						bytes+= objptr->length()*sizeof(Tcomplex);
				}
				if (p->IsHidden() || p->IsGlobal()) {
					out << "   (";
					if (p->IsHidden()) {
						out << "hidden";
						if (p->IsGlobal()) out << " auto-global";
					} else {
						if (p->IsGlobal()) out << "auto-global";
					}
					out << ')';
				}
				out << '\n';
			}
		}
	}
	out.flush();
//	out.close();
	pclose(fp);
	delete [] s;
	if (bytes > 0) {
		cout << "Total visible ";
		if (bytes < 1e5)
			cout << (Tint)bytes << " bytes\n";
		else if (bytes < 1e8)
			cout << (Tint)(bytes/1024) << " kilobytes\n";
		else
			cout << (Tint)(bytes/1048576) << " megabytes\n";
	}
	return 0;
}

[] = clear(...)
/* clear() removes all variables that are visible from
   the whos() function from the workspace. Function definitions
   are not cleared. Variables in loaded packages are also not affected.

   clear("var1","var2",...) removes only the specified variables.
   If a string is not a variable name, no warning is given.
   See also: whos, hide, unhide.
   Error codes:
   1: Bad argument, not a string
*/
{
	if (Nargin == 0) {
		for (THashEntryPtr p=theHT.first(); p; p=theHT.next()) {
			TObjectPtr objptr = p->value();
			if (objptr) {
				Tkind k = objptr->kind();
				if (!p->IsHidden() && k!=Kfunction && k!=KCfunction && k!=KIntrinsicFunction
					&& !strchr((char*)(p->name()),':'))
					{
						objptr->SetToVoid(); objptr->SetToUndefined();
						// SetToUndefined does not call objptr->clear(), to deallocate the object
						// we have to call SetToVoid() first. Maybe this should be changed in object.H,
						// but since we are not sure we don't do it now. See also 9 lines below.
					}
			}
		}
	} else {
		for (int a=0; a<Nargin; a++) {
			if (!argin[a]->IsString()) return 1;
			Tstring ARG = *argin[a];
			Tsymbol *symptr = theHT.assoc((Tchar*)ARG);
			if (symptr) {
				TObjectPtr objptr = symptr->value();
				if (objptr) {objptr->SetToVoid(); objptr->SetToUndefined();}
			}
		}
	}
	return 0;
}

[] = hide(...)
/* hide("sym-name",...) sets the 'hidden' attribute to
   specified symbols.
   See also: whos, unhide, autoglobal.
   Error codes:
   1: Argument not a string
   2: Argument does not name a symbol
   */
{
	for (int p=0; p<Nargin; p++) {
		if (!argin[p]->IsString()) return 1;
		Tstring NAME = *argin[p];
		Tsymbol* symptr = theHT.assoc(NAME);
		if (!symptr) return 2;
		symptr->SetHiddenFlag();
	}
	return 0;
}

[] = unhide(...)
/* hide("sym-name",...) unsets the 'hidden' attribute to
   specified symbols.
   See also: whos, hide.
   Error codes:
   1: Argument not a string
   2: Argument does not name a symbol
   */
{
	for (int p=0; p<Nargin; p++) {
		if (!argin[p]->IsString()) return 1;
		Tstring NAME = *argin[p];
		Tsymbol* symptr = theHT.assoc(NAME);
		if (!symptr) return 2;
		symptr->ClearHiddenFlag();
	}
	return 0;
}

// The help function
// -----------------

extern FILE *FindAndOpenFile(const Tchar*);	// defined in tela.C
extern int CompleteFileName(const Tchar *fn, Tchar totalfn[MAXFILENAME]);	// also in tela.C

static int StringBeginMatch(char*s, const char*pattern, int pattern_len) {
	// Checks if the beginning of s equals pattern.
	// pattern_len must be equal to strlen(pattern).
	char ch = s[pattern_len];
	s[pattern_len] = '\0';
	int result = !strcmp(s,pattern);
	s[pattern_len] = ch;
	return result;
}

static const char *strstr1(const char*s, const char*item) {
	// similar to strstr, but ignores some special chars
	const int BackSlash = 92;	// we cannot type the character because ctpp screws up
	for (const char*s1=s; *s1; s1++) {
		const char *s2 = s1;
		for (const char*item1=item; *item1 && *s2; item1++,s2++) {
			while (*s2 == BackSlash || *s2 == '$') s2++;
			if (*item1 != *s2) goto Continue;
		}
		return s1;
	Continue:
		;
	}
	return 0;
}

static void MacroReplacements(char *buf, const char* from[], const char* to[])
{
	int i;
	for (;;) {
		char*found = 0;
		for (i=0; from[i]; i++) {
			found = strstr(buf,from[i]);
			if (found) {
				int Lfrom=strlen(from[i]);
				int Lto=strlen(to[i]);
				int Lrest=strlen(found+Lfrom);
				memmove(found+Lto,found+Lfrom,Lrest+1);
				memcpy(found,to[i],Lto);
				break;
			}
		}
		if (!found) break;
	}
}

static void TidyUpRefs(char *buf)
{
	for (;;) {
		char *ptr = strstr(buf,"<ref id=\"");
		if (!ptr) break;
		char *ptr2 = strstr(ptr+1,"\">");
		if (!ptr2) break;
		char *quoteptr = strchr(ptr+9,'"');
		if (!quoteptr) break;
		*quoteptr = '\0';
		int L = strlen(ptr+9);
		memmove(ptr,ptr+9,L);
		int L2 = strlen(ptr2+2);
		memmove(ptr+L,ptr2+2,L2);
		*(ptr+L+L2) = '\0';
	}
}

static int BuiltinHelp(const char *item, const char *filename) {
	FILE *fp = FindAndOpenFile((Tchar*)filename);
	if (!fp) return 0;
	const int BUFSIZE = 512;
	char buf[BUFSIZE+1];
	const char *pattern = "<sect1>";
	static const char *frommacros[] =
		{"&amp;","&lt;","&gt;","&etago;","&dollar;","&num;","&percnt;","&circ;","``","''",0};
	static const char *tomacros[] =
		{"&","<",">","</","$","#","%","^","\"","\"",0};
	int pattern_len = strlen(pattern);
	while (!feof(fp)) {
		fgets(buf,BUFSIZE,fp);
		// wanted buf is of the form:   <sect1>keyword1, keyword2,...,keywordN<label...
		if (StringBeginMatch(buf,pattern,pattern_len)) {
			// replace the '<' preceding "label" with null, if it is there
			char *const p = strstr(buf+pattern_len,"<label");
			if (p) *p = '\0';
			// do SGML macro replacements on the keyword1,. keyword2,...,keywordN part
			MacroReplacements(buf+pattern_len,frommacros,tomacros);
			const char *found = strstr1(buf+pattern_len,item);
			if (found && !isalnum(found[-1]) && !isalnum(found[strlen(item)])) {
				// the isalnum's ensures that complete keyword was matched,
				// without it, for example 'help ls' would match 'else' keyword
				const char *endpattern1 = "<sect";
				const char *endpattern2 = "</article";
				int endpattern1_len = strlen(endpattern1);
				int endpattern2_len = strlen(endpattern2);
				for(;;) {
					fgets(buf,BUFSIZE,fp);
					if (feof(fp)) break;
					if (StringBeginMatch(buf,endpattern1,endpattern1_len)) break;
					if (StringBeginMatch(buf,endpattern2,endpattern2_len)) break;
					if (buf[0] != '<') {
						MacroReplacements(buf,frommacros,tomacros);
						TidyUpRefs(buf);
						const int Backslash = 92;	// cannot type the char because ctpp would screw up
						for (int i=0; buf[i]; i++)
#if 0		/* Why don't we print dollar and backslash? Removed 13.5.1995. */
							if (buf[i]!='$' && buf[i]!=Backslash)
#endif
								cout << buf[i];
					}
				}
				fclose(fp);
				return 1;	// success
			}
		}
	}
	fclose(fp);
	return 0;	// not found
}

[] = help(;fn)
/* help(function-name) or help("help-item") displays the help information
   associated with a given function or a given help item. On command line
   you may use the abbreviation

      ?help-item
   or
      help help-item

   These forms are translated to help("help-item") before parsing.

   First tries:
   help operators
   help special
   help if
   help for
   help function
   ...
   
   Error codes:
   1: Item not found
   2: Cannot open help file */
{
	int ret=0;
	const Tobject* fnobjptr = 0;
	const char *helpfile = "telahelp.sgml";
	if (Nargin==0) goto shorthelp;
	if (fn.IsString()) {
		if (fn.length()==0) goto shorthelp;
		Tstring S = fn;
		const Tchar *s = (Tchar*)S;
		while (*s==' ') s++;
		Tsymbol *symptr = theHT.assoc(s);
		if (symptr && symptr->StubInfo()) symptr = theHT.add(s);
		if (symptr && symptr->value() && symptr->value()->kind()!=Kundef) {
			fnobjptr = symptr->value();
			if (fnobjptr->IsIntrinsicFunction()) {
				if (BuiltinHelp((char*)s,helpfile))
					return 0;
				else
					ret = 1;
			}
		} else if (BuiltinHelp((char*)s,helpfile)) {
			return 0;
		} else {
			cout << "Item \'" << (char*)s << "\' not found.\n";
			//ret = 1;
			return 0;	// return 0 because we already gave 'not found' message
		}
	} else
		fnobjptr = &fn;
	if (ret) return ret;
	if (fnobjptr->IsCfunction()) {
		const TCFunctionInfo*p = fnobjptr->CFunctionInfoPtr();
		long help1 = p->helpstart;
		long help2 = p->helpend;
		if (help1 >= help2) {
			cout << "Sorry, no help.\n";
		} else {
			FILE *fp = FindAndOpenFile(p->helpfile);
			if (fp) {
				fseek(fp,help1,SEEK_SET);
				//while (ftell(fp) < help2) cout << char(fgetc(fp));
				int WriteNewline=1;
				while (ftell(fp) < help2) {
					char s1[512+1];
					fgets(s1,512,fp);
					if (strstr(s1,"Error codes:")) {WriteNewline=0; break;}
					int L = strlen(s1);
					if (s1[L-3]=='*' && s1[L-2]=='/' && s1[L-1]=='\n') s1[L-3] = '\0';
					cout << s1;
				}
				if (WriteNewline) cout << '\n';
				cout << flush;
				fclose(fp);
			} else {
				cerr << "*** Cannot open help file '" << p->helpfile << "'.\n";
				ret = 2;
			}
		}
	} else if (fnobjptr->IsFunction()) {
		const Tchar *srcfile = fnobjptr->FunctionValue()->FileName();
		Tsymbol* sptr = (Tsymbol*)(&(fnobjptr->FunctionValue()->Symbol()));
		const Tchar *symname = (Tchar*)(sptr->name());
		Tchar longsrcname[MAXFILENAME];
		if (CompleteFileName(srcfile,longsrcname)) {
			Tchar longtelahelpname[MAXFILENAME];
			if (CompleteFileName((Tchar*)"telahelp.sh",longtelahelpname)) {
				char *s = new char [strlen(longtelahelpname) + strlen(symname) + strlen(longsrcname) + 30];
				strcpy(s,(char*)longtelahelpname);
				strcat(s," ");
				strcat(s,(char*)symname);
				strcat(s," ");
				strcat(s,(char*)longsrcname);
				system(s);
				delete [] s;
			} else {
				cout << "*** telahelp.sh not found on TELAPATH\n";
				ret = 1;
			}
#if 0
			char *pager = getenv("PAGER");
			char *s = new char [(pager?strlen(pager):0) + strlen(longsrcname) + strlen(symname) + 30];
			strcpy(s,pager ? pager : "more");
			strcat(s," '+/function.+");
			strcat(s,(char*)symname);
			strcat(s,"' ");
			strcat(s,(char*)longsrcname);
			system(s);
			delete [] s;
#endif
		}
	} else {
		cout << "Help item not found.\n";
		ret = 1;
	}
	return ret;
shorthelp: cout << "Type '?help <RET>' for first help.\n";
	return 0;
}

#include "tree.H"

extern void ShowFreelist(ostream&);

[] = info()
/* info() shows information about various class sizes for this Tela implementation.
   It also prints the total counts of Tnode, Tprg and Tobject objects at the moment. */
{
	cout << "sizeof(TNodeBlock) = " << sizeof(TNodeBlock)
		 << ", sizeof(Tnode) = " << sizeof(Tnode)
		 << ", sizeof(Tobject) = " << sizeof(Tobject) << '\n';
	cout << theNodePool.NodesInUse() << " Tnodes, "
		 << global::NTprg << " Tprgs, "
		 << global::NTobject << " Tobjects\n";
	if (global::NTobject==0) cout << "  (probably object counting disabled, see object.H)\n";
	cout << "stack length = " << theStack.length() << '\n';
#ifdef TELASPECIFIC_NEWDELETE
	cout << "Tela's own new/delete operators are in use:\n";
	cout << "  Memory in use " << (global::memuse+1023)/1024
		 << "K, Fragmentation " << (global::memalloc - global::memuse + 1023)/1024 << "K\n";
	cout << "  " << global::Nalloc << " allocated blocks, Average block size "
		 << global::memalloc/(global::Nalloc ? global::Nalloc : 1) << "B, " << global::Nmem << " new operations\n";
	cout << "  Freelist length is " << global::FLlen << "\n";
	cout << "Freelist: ";
	ShowFreelist(cout);
#else
	cout << "The underlying C++ new/delete operators are in use, not Tela's own.\n";
#endif
	return 0;
}

// TelaPath and TelaPathLength from tela.C
extern Tchar *TelaPath[100];  // this constant '100' must agree with tela.C, sorry
extern int TelaPathLength;

[s] = telapath()
/* telapath() returns the currently set effective Tela path
   as a string. */
{
	// Determine total length
	int len = 0, i;
	for (i=0; i<TelaPathLength; i++) len+= strlen(TelaPath[i]) + 1;   // +1 for ":"
	len--;    // -1 because there is one less ":" than there are path components
	s.ireserv(len);
	int p = 0;
	for (i=0; i<TelaPathLength; i++) {
		for (int j=0; TelaPath[i][j]; j++)
			s.IntPtr()[p++] = TelaPath[i][j];
		if (i<TelaPathLength-1) s.IntPtr()[p++] = ':';
	}
	s.SetStringFlag();
	return 0;
}

#ifdef UNICOS
   extern "C" double RANF();						/* from system library; scalar version */
   extern "C" void RANSET(int*);					/* from system library */
   extern "C" void VRANF(double a[], const int *n);	/* from vranf.f */
#  define Random() RANF()
#elif HAVE_DRAND48
#  include <math.h>
   extern "C" double drand48();
   extern "C" void srand48(long);
#  define Random() drand48()
#else
#  define Random() (rand()/(1.0+RAND_MAX))
#endif

[x] = rand(...)
/* rand() returns a random real x, 0<=x<1.
   rand(N) (N positive integer) returns a real random vector of length N.
   rand(N,M) returns a random matrix, and so on.
   See also: srand.
   Error codes:
   -1: Tried to create too high rank array
   -2: Argument not an integer
   -3: Non-positive integer argument */
{
	if (Nargin==0) {				// Return scalar
		x = Random();
		return 0;
	}
	if (Nargin > MAXRANK) return -1;		// Too many dimensional tensor requested
	int dims[MAXRANK];
	for (int d=0; d<Nargin; d++) {
		if (argin[d]->kind() != Kint) return -2;		// Arguments must be integers ..
		if (argin[d]->IntValue() <= 0) return -3;		// .. positive
		dims[d] = argin[d]->IntValue();
	}
	x.rreserv(TDimPack(dims,Nargin));	// Allocate result, without zeroing it
	const int N = x.length();
	Treal * const xp = x.RealPtr();
#	ifdef UNICOS
	VRANF(xp,&N);
#	else
	for (int i=0; i<N; i++) xp[i] = Random();
#	endif
	return 0;
}

[] = srand(seed)
/* srand(seed) seeds the random number generator.
   The same seed will always produce the same random
   number sequence. The argument must be an integer.
   See also: rand.
   Error codes:
   1: Argument not an integer */
{
	if (seed.kind()!=Kint) return 1;
#	ifdef UNICOS
	int i = int(seed.IntValue());
	RANSET(&i);
#	elif HAVE_DRAND48
	srand48((long)(seed.IntValue()));
#	else
	srand(seed.IntValue());
#	endif
	return 0;
}

extern char *VersionString;

[x] = version()
/* version() returns the Tela version number (real) currently
   in use. */
{
	x = atof(VersionString);
	return 0;
}

[x] = strmat(...)
/* strmat("string1","string2",...) makes a string matrix
   ouf of individual strings. The strings need not be same length,
   they are padded with zeros (invisible) if they are not.

   Usage example:
   S = strmat("string1","longer_string");
   s = tostring(S[1,:]);
   after which streq(s,"string1") will return true (1).
   The function tostring is needed to get rid of possible
   extra zeros at the end of the string.
   
   See also: strmat2, tostring, streq.
   Error codes:
   -1: Argument not a string
*/
{
	int p;
	for (p=0; p<Nargin; p++) if (!argin[p]->IsString()) return -1;
	Tint maxlen = 0, L, i;
	for (p=0; p<Nargin; p++) {
		L = argin[p]->length();
		if (L > maxlen) maxlen = L;
	}
	x.izeros(TDimPack(Nargin,maxlen));
	for (p=0; p<Nargin; p++) for (i=0; i<argin[p]->length(); i++)
		x.IntPtr()[p*maxlen+i] = argin[p]->IntPtr()[i];
	x.SetStringFlag();
	return 0;
}

[x] = strmat2(str; sep)
/* strmat2("string") creates a string matrix from "string"
   interpreting the newline character as row ending marker.
   strmat2("string",sep) uses separator sep instead of
   newline char; sep may be either character or string.
   If sep is a string, any character that is a member of sep
   is taken to be a separator. If the rows have unequal lengths,
   they are padded with zeros.
   See also: strmat.
   Error codes:
   -1: First arg not a string
   -2: Second arg not a char or string
   */
{
	if (!str.IsString()) return -1;
	Tkind sepk = Kvoid;
	if (Nargin == 2) {
		sepk = sep.kind();
		if (!(sepk==KIntArray && sep.rank()==1) && !sepk==Kint) return -2;
	}
	Tstring STR = str;
	// Determine maximum row length maxL and number of rows, Nrows
	Tint L = 0, maxL = 0, Nrows = 0;
	Tint i;
	for (i=0; i<str.length(); i++) {
		const Tchar ch = ((Tchar*)STR)[i];
		int found;
		if (sepk == Kint) {
			found = (ch == sep.IntValue());
		} else if (sepk == Kvoid) {
			found = (ch == '\n');
		} else {
			found = 0;
			for (Tint j=0; j<sep.length(); j++)
				if (ch == sep.IntPtr()[j]) {
					found = 1;
					break;
				}
		}
		if (found) {
			L = 0;
			Nrows++;
		} else {
			if (i == str.length()-1)
				Nrows++;
			L++;
		}
		if (L > maxL) maxL = L;
	}
	// Make output variable
	x.izeros(TDimPack(Nrows,maxL));
	Tint row = 0;
	L = 0;
	for (i=0; i<str.length(); i++) {
		const Tchar ch = ((Tchar*)STR)[i];
		int found;
		if (sepk == Kint) {
			found = (ch == sep.IntValue());
		} else if (sepk == Kvoid) {
			found = (ch == '\n');
		} else {
			found = 0;
			for (Tint j=0; j<sep.length(); j++)
				if (ch == sep.IntPtr()[j]) {
					found = 1;
					break;
				}
		}
		if (found) {
			L = 0;
			row++;
		} else {
			x.IntPtr()[row*maxL + L] = ch;
			L++;
		}
	}
	x.SetStringFlag();
	return 0;
}