File: doscmd.c

package info (click to toggle)
regina 3.3-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 4,928 kB
  • ctags: 7,233
  • sloc: ansic: 50,555; sh: 2,727; lex: 2,298; yacc: 1,498; makefile: 1,010; cpp: 117
file content (3478 lines) | stat: -rw-r--r-- 102,164 bytes parent folder | download | duplicates (3)
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
#ifndef lint
static char *RCSid = "$Id: doscmd.c,v 1.58 2004/03/12 12:20:17 mark Exp $";
#endif

/*
 *  The Regina Rexx Interpreter
 *  Copyright (C) 1992-1994  Anders Christensen <anders@pvv.unit.no>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* FGC: From now it is intended to put additional (!!) things here for
 * shell.c which are related to the different OS.
 */

#if defined(OS2) || defined(__EMX__)
# define INCL_BASE
# include <os2.h>
# define DONT_TYPEDEF_PFN
#endif

#include "rexx.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(DOS)                                        /* MH 10-06-96 */
# ifdef _POSIX_SOURCE
#  undef _POSIX_SOURCE
# endif
# include <dos.h>
#endif                                                  /* MH 10-06-96 */

#include <errno.h>

#if defined(HAVE_ASSERT_H)
# include <assert.h>
#endif

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif

#if defined(HAVE_SYS_STAT_H)
# include <sys/stat.h>
#endif

#if defined(HAVE_SYS_WAIT_H)
# include <sys/wait.h>
#endif

#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif

#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#endif

#if defined(WIN32)
# include <share.h>
# if defined(__BORLANDC__) || defined(__LCC__)
#  include <time.h>
#  include <process.h>
# endif
# ifdef _MSC_VER
#  if _MSC_VER >= 1100
/* Stupid MSC can't compile own headers without warning at least in VC 5.0 */
#   pragma warning(disable: 4115 4201 4214 4514)
#  endif
# endif
# include <windows.h>
# ifdef _MSC_VER
#  if _MSC_VER >= 1100
#   pragma warning(default: 4115 4201 4214)
#  endif
# endif
#endif

#if defined(MAC) || (defined(__WATCOMC__) && !defined(__QNX__)) || defined(_MSC_VER) || defined(__SASC) || defined(__MINGW32__) || defined(__BORLANDC__) || defined(__EPOC32__) || defined(__WINS__) || defined(__LCC__) || defined(SKYOS)
# include "utsname.h"                                   /* MH 10-06-96 */
# define NEED_UNAME
# if !defined(__WINS__) && !defined(__EPOC32__) && !defined(SKYOS)
#  define MAXPATHLEN  _MAX_PATH                          /* MH 10-06-96 */
# endif
#else                                                   /* MH 10-06-96 */
# if defined(WIN32) && defined(__IBMC__)                /* LM 26-02-99 */
#  include "utsname.h"
#  define NEED_UNAME
#  define MAXPATHLEN (8192)
#  include <io.h>
# else
#  ifndef VMS
#   include <sys/param.h>                                 /* MH 10-06-96 */
#  endif
#  include <sys/utsname.h>                               /* MH 10-06-96 */
#  include <sys/wait.h>
# endif
#endif

#if defined(MAC) || defined(GO32) || defined (__EMX__) || (defined(__WATCOMC__) && !defined(__QNX__)) || defined(_MSC_VER) || defined(DJGPP) || defined(__CYGWIN32__) || defined(__BORLANDC__) || defined(__MINGW32__) || defined(__WINS__) || defined(__EPOC32__)
# define HAVE_BROKEN_TMPNAM
# define PATH_DELIMS ":\\/"
# if defined(__EMX__) || defined(__CYGWIN32__)
#  define ISTR_SLASH "/"  /* This is not a must, \\ works, too */
#  define I_SLASH '/'  /* This is not a must, \\ works, too */
# elif defined(MAC)
#  define ISTR_SLASH ":"
#  define I_SLASH ':'
# else
#  define ISTR_SLASH "\\" /* This is not a must, / works at least for MSC, too */
#  define I_SLASH '\\'    /* This is not a must, / works at least for MSC, too */
# endif
# if !defined(MAC) && !defined(__WINS__) && !defined(__EPOC32__) && !defined(__CYGWIN__)
#  ifndef HAVE_UNISTD_H
#   include <io.h> /* access() */
#  endif
#  include <process.h>
#  include <share.h>
# endif
# include <time.h>
#endif

#if defined(__LCC__)
# if !defined(HasOverlappedIoCompleted)
#  define HasOverlappedIoCompleted(lpOverlapped) ((lpOverlapped)->Internal != STATUS_PENDING)
# endif
#endif

static char **makeargs(const char *string, char escape);
static char **makesimpleargs(const char *string);
static char *splitoffarg(const char *string, const char **trailer, char escape);
static void destroyargs(char **args);
static int local_mkstemp(const tsd_t *TSD, char *base);

#if defined(WIN32)
/*
 * The following; WIN9X_VER is used to determine if we are running under
 * a DOS-based Win32 platform; ie 95/98/Me
 * It can be changed to ( 1 ) for example to force the code through the
 * Win9X code if running on a different Win32 platform like NT.
#define WIN9X_VER ( 1 )
 */
#define WIN9X_VER ( _osver & 0x8000 )
/*****************************************************************************
 *****************************************************************************
 ** Win32 ********************************************************************
 *****************************************************************************
 *****************************************************************************/
typedef struct {
   const tsd_t   *TSD;
   struct {
      HANDLE      hdl;
      OVERLAPPED  ol;
      char       *buf;
      unsigned    maxbuf;
      unsigned    rused;
      unsigned    rusedbegin;
      unsigned    reading;
      unsigned    wused;
      int         is_reader;
   } h[3];
} AsyncInfo;

int open_subprocess_connection_dos(const tsd_t *TSD, environpart *ep);
void unblock_handle_dos(int *handle, void *async_info);
void restart_file_dos(int hdl);
int __regina_close_dos(int handle, void *async_info);
int __regina_read_dos(int handle, void *buf, unsigned size, void *async_info);
int __regina_write_dos(int handle, const void *buf, unsigned size,
                                                             void *async_info);
void *create_async_info_dos(const tsd_t *TSD);
void delete_async_info_dos(void *async_info);
void reset_async_info_dos(void *async_info);
void add_async_waiter_dos(void *async_info, int handle, int add_as_read_handle);
void wait_async_info_dos(void *async_info);

static BOOL MyCancelIo(HANDLE handle)
{
   static BOOL (WINAPI *DoCancelIo)(HANDLE handle) = NULL;
   static BOOL first = TRUE;
   HMODULE mod;

   if ( first )
   {
      /*
       * The kernel is always mapped, a LoadLibrary is useless
       */
      if ( ( mod = GetModuleHandle( "kernel32" ) ) != NULL )
      {
         DoCancelIo = (BOOL (WINAPI*)(HANDLE)) GetProcAddress( mod, "CancelIo" );
      }

      /*
       * It's safe now to set first. Never do it before the main work,
       * otherwise we're not reentrant.
       */
      first = FALSE;
   }

   if ( DoCancelIo == NULL )
      return FALSE;

   return DoCancelIo( handle );
}

int my_win32_setenv( const char *name, const char *value )
{
   return (SetEnvironmentVariable( name, value ) );
}

/* fork_exec spawns a new process with the given commandline.
 * it returns -1 on error (errno set), 0 on process start error (rcode set),
 * a process descriptor otherwise.
 * Basically this is a child process and we run in the child's environment
 * after the first few lines. The setup hasn't been done and the command needs
 * to be started.
 * Redirection takes place if one of the handles env->input.hdls[0],
 * env->output.hdls[1] or env->error.hdls[1] is defined. Other handles (except
 * standard handles) are closed. env->subtype must be a SUBENVIR_... constant.
 * cmdline is the whole command line.
 * Never use TSD after the fork() since this is not only a different thread,
 * it's a different process!
 */
int fork_exec(tsd_t *TSD, environment *env, const char *cmdline, int *rcode)
{
   static const char *interpreter[] = { "regina.exe", /* preferable even if */
                                                      /* not dynamic        */
                                        "rexx.exe" };
   PROCESS_INFORMATION pinfo;
   STARTUPINFO         sinfo;
   DWORD               done;
   char               *execname = NULL;
   const char         *commandline = NULL;
   char               *argline = NULL;
   BOOL                rc;
   int                broken_address_command = get_options_flag( TSD->currlevel, EXT_BROKEN_ADDRESS_COMMAND );
   int                subtype;

   if (env->subtype == SUBENVIR_REXX) /*special situation caused by recursion*/
   {
      environment e = *env;
      char *new_cmdline;
      int i, rc;
      unsigned len;

      if (argv0 == NULL)
         len = 11; /* max("rexx.exe", "regina.exe") */
      else
      {
         len = strlen(argv0) + 2;
         if (len < 11)
            len = 11; /* max("rexx.exe", "regina.exe") */
      }
      len += strlen(cmdline) + 2; /* Blank + term ASCII0 */

      if ((new_cmdline = malloc(len)) == NULL)
         return(-1); /* ENOMEM is set */

      if (argv0 != NULL) /* always the best choice */
      {
         strcpy(new_cmdline, "\"");
         strcat(new_cmdline, argv0);
         strcat(new_cmdline, "\" ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_COMMAND;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

      /* load an interpreter by name from the path */
      for (i = 0; i < sizeof(interpreter) / sizeof(interpreter[0]);i++)
      {
         strcpy(new_cmdline, interpreter[i]);
         strcat(new_cmdline, " ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_COMMAND;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

      *rcode = -errno; /* assume a load error */
      free(new_cmdline);
      return(0);
   }

   memset(&sinfo, 0, sizeof(sinfo));
   sinfo.cb = sizeof(sinfo);

   sinfo.dwFlags = STARTF_USESTDHANDLES;

   /* The following three handles have been created inheritable */
   if (env->input.hdls[0] != -1)
   {
      if ( WIN9X_VER )
      {
         sinfo.hStdInput  = (HANDLE) _get_osfhandle(env->input.hdls[0]);
         /*
          * fixes Bug 587687
          * We must ensure the called process already *uses* the handles;
          * they are closed by the OS in the other case. One chance is to
          * delay the execution until this happens, the other chance is to
          * wait with the closing until the called process works or
          * terminates. We use the latter one. For more info see MSDN.
          * Topics: Q190351, *Q150956*
          * I think, Q150956 is a workaround for the bug they didn't solve.
          * M$ just close the handles too early.
          */
         DuplicateHandle( GetCurrentProcess(),
                          sinfo.hStdInput,
                          GetCurrentProcess(),
                          &sinfo.hStdInput,
                          0,
                          TRUE,
                          DUPLICATE_SAME_ACCESS );
         /*
          * fixes bug 700405
          */
         env->input.hdls[2] = (int) sinfo.hStdInput;
      }
      else
         sinfo.hStdInput  = (HANDLE) env->input.hdls[0];
   }
   else
      sinfo.hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
   if (env->output.hdls[1] != -1)
   {
      if ( WIN9X_VER )
      {
         sinfo.hStdOutput = (HANDLE) _get_osfhandle(env->output.hdls[1]);
         DuplicateHandle( GetCurrentProcess(),
                          sinfo.hStdOutput,
                          GetCurrentProcess(),
                          &sinfo.hStdOutput,
                          0,
                          TRUE,
                          DUPLICATE_SAME_ACCESS );
         /*
          * fixes bug 700405
          */
         env->output.hdls[2] = (int) sinfo.hStdOutput;
      }
      else
         sinfo.hStdOutput = (HANDLE) env->output.hdls[1];
   }
   else
      sinfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
   if (env->error.SameAsOutput)
      sinfo.hStdError  = (HANDLE) sinfo.hStdOutput;
   else if (env->error.hdls[1] != -1)
   {
      if ( WIN9X_VER )
      {
         sinfo.hStdError  = (HANDLE) _get_osfhandle(env->error.hdls[1]);
         DuplicateHandle( GetCurrentProcess(),
                          sinfo.hStdError,
                          GetCurrentProcess(),
                          &sinfo.hStdError,
                          0,
                          TRUE,
                          DUPLICATE_SAME_ACCESS );
         /*
          * fixes bug 700405
          */
         env->error.hdls[2] = (int) sinfo.hStdError;
      }
      else
         sinfo.hStdError  = (HANDLE) env->error.hdls[1];
   }
   else
      sinfo.hStdError  = GetStdHandle(STD_ERROR_HANDLE);

   /*
    * If the BROKEN_ADDRESS_COMMAND OPTION is in place,
    * and our environment is COMMAND, change it to SYSTEM
    */
   if ( env->subtype == SUBENVIR_PATH /* was SUBENVIR_COMMAND */
   &&   broken_address_command )
      subtype = SUBENVIR_SYSTEM;
   else
      subtype = env->subtype;

   switch ( subtype )
   {
      case SUBENVIR_PATH:
         execname = NULL;
         commandline = cmdline;
         break;

      case SUBENVIR_COMMAND:
         execname = NULL;
         commandline = cmdline;
#define NEED_SPLITOFFARG
         execname = splitoffarg(cmdline, NULL, '^');
         commandline = cmdline;
         break;

      case SUBENVIR_SYSTEM:
      /* insert "%COMSPEC% /c " or "%SHELL% -c " in front */
         if ((done = GetEnvironmentVariable("COMSPEC","",0)) != 0)
         {
            argline = MallocTSD(done + strlen(cmdline) + 5);
            GetEnvironmentVariable("COMSPEC",argline,done + 5);
            strcat(argline," /c ");
         }
         else if ((done = GetEnvironmentVariable("SHELL","",0)) != 0)
         {
            argline = MallocTSD(done + strlen(cmdline) + 5);
            GetEnvironmentVariable("SHELL",argline,done + 5);
            strcat(argline," -c ");
         }
         else
         {
            argline = MallocTSD(11 + strlen(cmdline) + 5);
            if (GetVersion() & 0x80000000) /* not NT ? */
               strcpy(argline,"COMMAND.COM /c ");
            else
               strcpy(argline,"CMD.EXE /c ");
         }
         strcat(argline, cmdline);
         execname = NULL;
         commandline = argline;
         break;

      case SUBENVIR_REXX:
         /* fall through */

      default: /* illegal subtype */
         errno = EINVAL;
         return -1;
   }

   /*
    * FGC: I checked different configurations.
    * 1) Never use DETACHED_PROCESS, the communication gets lost in NT
    *    kernels to a text program invoked using shells.
    * 2) Never use STARTF_USESHOWWINDOW/SW_HIDE in Win9x, this gives problems
    *    under Win9x or you have to know which combination fits to COMSPEC and
    *    your called program's type.
    * --> We can fiddle with CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
    *     CREATE_DEFAULT_ERROR_MODE. Select your choice!
    */
   if ( !WIN9X_VER )
   {
      sinfo.dwFlags |= STARTF_USESHOWWINDOW;
      sinfo.wShowWindow = SW_HIDE;
   }
   rc = CreateProcess(execname,
                      (char *) commandline,
                      NULL,        /* pointer to process security attributes */
                      NULL,        /* pointer to thread security attributes  */
                      TRUE,        /* no inheritance except sinfo.hStd...    */
                      CREATE_NEW_PROCESS_GROUP | CREATE_DEFAULT_ERROR_MODE,
                      NULL,        /* pointer to new environment block       */
                      NULL,        /* pointer to current directory name      */
                      &sinfo,
                      &pinfo);
   *rcode = (int) GetLastError();
   if (argline)
      FreeTSD(argline);
   if (execname)
      free(execname);
   if ( !rc )
      return 0;

   CloseHandle(pinfo.hThread); /* We don't need it */
   return (int) pinfo.hProcess;

   /* NT and W9x share the same functionality but we want to compile the */
   /* DOS-part below. Don't set this code to top */
# undef fork_exec
# define fork_exec fork_exec_dos
}

/* __regina_wait waits for a process started by fork_exec.
 * In general, this is called after the complete IO to the called process but
 * it isn't guaranteed. Never call if you don't expect a sudden death of the
 * subprocess.
 * Returns the exit status of the subprocess under normal circumstances. If
 * the subprocess has died by a signal, the return value is -signalnumber.
 */
int __regina_wait(int process)
{
   DWORD code = (DWORD) -1; /* in case something goes wrong */

   /* NT and W9x share the same functionality but we want to compile*/
# undef __regina_wait
# define __regina_wait __regina_wait_dos

   WaitForSingleObject((HANDLE) process, INFINITE);
   GetExitCodeProcess((HANDLE) process, &code);
   CloseHandle((HANDLE) process);

   if ((code & 0xC0000000) == 0xC0000000) /* assume signal */
      return -(int)(code & ~0xC0000000);
   return (int) code;
}

/* open_subprocess_connection acts like the unix-known function pipe and sets
 * ep->RedirectedFile if necessary. Just in the latter case ep->data
 * is set to the filename.
 * Close the handles with __regina_close later.
 * Do IO by using __regina_read() and __regina_write().
 */
int open_subprocess_connection(const tsd_t *TSD, environpart *ep)
{
#define MAGIC_MAX 2000000 /* Much beyond maximum, see below */
   static volatile unsigned BaseIndex = MAGIC_MAX;
   char buf[40];
   unsigned i;
   unsigned start,run;
   DWORD openmode, err;
   HANDLE in, out;
   OVERLAPPED ol;
   SECURITY_ATTRIBUTES sa;

# define NEED_STUPID_DOSCMD
# undef open_subprocess_connection
# define open_subprocess_connection open_subprocess_connection_dos
   if ( WIN9X_VER )
      return(open_subprocess_connection(TSD, ep));

   in = INVALID_HANDLE_VALUE;

   /* Anonymous pipes can't be run in overlapped mode. Therefore we use
    * named pipes (and files for W9x).
    */
   sa.nLength = sizeof(sa);
   sa.lpSecurityDescriptor = NULL;
   sa.bInheritHandle = TRUE;
   openmode = (ep->flags.isinput) ? PIPE_ACCESS_OUTBOUND : PIPE_ACCESS_INBOUND;
   openmode |= FILE_FLAG_OVERLAPPED;

   /* algorithm:
    * select a random number, e.g. a mixture of pid, tid and time.
    * increment this number by a fixed amount until we reach the starting
    * value again. Do a wrap around and an increment which is a unique prime.
    * The number 1000000 has the primes 2 and 5. We may use all primes
    * except 2 and 5; 9901 (which is prime) will give a good distribution.
    *
    * We want to be able to create several temporary files at once without
    * more OS calls than needed. Thus, we have a program wide runner to
    * ensure a simple distribution without strength.
    */
   if (BaseIndex == MAGIC_MAX)
   {
      /*
       * We have to create (nearly) reentrant code.
       */
      i = (unsigned) getpid() * (unsigned) time(NULL);
      i %= 1000000;
      if (!i)
         i = 1;
      BaseIndex = i;
   }
   if (++BaseIndex >= 1000000)
      BaseIndex = 1;

   start = TSD->thread_id;
   if (start == 0)
      start = 999999;
   start *= (unsigned) (clock() + 1);
   start *= BaseIndex;
   start %= 1000000;

   run = start;
   for (i = 0;i <= 1000000;i++)
   {
      sprintf(buf,"%s%06u._rx", "\\\\.\\pipe\\tmp\\", run );
      in = CreateNamedPipe(buf,
                           openmode,
                           PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                           1, /* just this instance! */
                           0, /* OutBufferSize: use system minimum, e.g.4K */
                           0, /* InBufferSize: use system minimum, e.g.4K */
                           0, /* nDefaultTimeout */
                           NULL); /* This handle won't be shared */
      if (in != INVALID_HANDLE_VALUE)
         break;

      err = GetLastError();
      if (err != ERROR_ACCESS_DENIED)
      {
         errno = EPIPE;
         return(-1);
      }

      /* Check the next possible candidate */
      run += 9901;
      run %= 1000000;
      if (run == start) /* paranoia check. i <= 1000000 should hit exactly */
         break;         /* here */
   }

   if (in == INVALID_HANDLE_VALUE)
   {
      errno = EPIPE;
      return(-1);
   }

   /* Prepare this pipe and then try to connect it to ourself. */
   if ((ol.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL)
   {
      CloseHandle(in);
      errno = EPIPE;
      return(-1);
   }
   ConnectNamedPipe(in, &ol); /* ignore the return */

   out = CreateFile(buf,
                    (ep->flags.isinput) ? GENERIC_READ : GENERIC_WRITE,
                    0, /* dwShareMode */
                    &sa,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL, /* not OVERLAPPED! */
                    NULL); /* hTemplateFile */
   if (out == INVALID_HANDLE_VALUE)
   {
      MyCancelIo(in);
      CloseHandle(ol.hEvent);
      CloseHandle(in);
      errno = EPIPE; /* guess */
      return(-1);
   }

   /* Now do the final checking, the server end must be connected */
   if (!GetOverlappedResult(in, &ol, &openmode /* dummy */, FALSE))
   {
      CloseHandle(out);
      MyCancelIo(in);
      CloseHandle(ol.hEvent);
      CloseHandle(in);
      errno = EPIPE; /* guess */
      return(-1);
   }
   CloseHandle(ol.hEvent);

   /* We always want to have the server's end of the named pipe: */
   if (ep->flags.isinput)
   {
      ep->hdls[0] = (int) out;
      ep->hdls[1] = (int) in;
   }
   else
   {
      ep->hdls[0] = (int) in;
      ep->hdls[1] = (int) out;
   }
   return(0);
#undef MAGIC_MAX
}

/* sets the given handle to the non-blocking mode. The value may change.
 * async_info CAN be used to add the handle to the internal list of watched
 * handles.
 */
void unblock_handle( int *handle, void *async_info )
{
   AsyncInfo *ai;
   HANDLE hdl;
   unsigned i;

# define NEED_STUPID_DOSCMD
# undef unblock_handle
# define unblock_handle unblock_handle_dos
   if ( WIN9X_VER )
   {
      unblock_handle(handle, async_info);
      return;
   }

   ai = async_info;
   hdl = (HANDLE) *handle;

   assert(async_info != NULL);
   for (i = 0; i < 3;i++)
      if (ai->h[i].hdl == INVALID_HANDLE_VALUE)
         break;
   assert(i < 3);
   ai->h[i].hdl = hdl;
   ai->h[i].ol.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
}

/* sets the file pointer of the given handle to the beginning.
 */
void restart_file(int hdl)
{
# define NEED_STUPID_DOSCMD
# undef restart_file
# define restart_file restart_file_dos
   if ( WIN9X_VER )
   {
      restart_file(hdl);
      return;
   }

   assert((HANDLE) hdl == INVALID_HANDLE_VALUE);
}

/* __regina_close acts like close() but closes a handle returned by
 * open_subprocess_connection.
 * async_info MAY be used to delete the handle from the internal list of
 * watched handles.
 */
int __regina_close(int handle, void *async_info)
{
   AsyncInfo *ai;
   HANDLE hdl;
   unsigned i;

# define NEED_STUPID_DOSCMD
# define __regina_close __regina_close_dos
   if ( WIN9X_VER )
      return(__regina_close_dos(handle, async_info));

   ai = async_info;
   hdl = (HANDLE) handle;

   if (hdl == INVALID_HANDLE_VALUE)
   {
      errno = EINVAL;
      return(-1);
   }

   if (ai == NULL) /* unblocked handle? */
   {
      if (CloseHandle(hdl))
         return(0);
      errno = ENOSPC; /* guess */
      return(-1);
   }

   for (i = 0; i < 3;i++)
      if (ai->h[i].hdl == hdl)
         break;

   if (i == 3)
   {
      CloseHandle(hdl);
      errno = EINVAL;
      return(-1);
   }

   MyCancelIo(hdl);
   CloseHandle(ai->h[i].ol.hEvent);
   ai->h[i].hdl = INVALID_HANDLE_VALUE;
   if (ai->h[i].buf)
      Free_TSD(ai->TSD, ai->h[i].buf);
   if (CloseHandle(hdl))
      return(0);
   errno = ENOSPC; /* guess */
   return(-1);
}

/*
 * __regina_close_special acts like close() but closes any OS specific handle.
 * The close happens if the handle is not -1. A specific operation may be
 * associated with this. Have a look for occurances of "hdls[2]".
 */
void __regina_close_special( int handle )
{
   /*
    * DOS part not needed but we will get it. Rename the function.
    */
#define __regina_close_special __regina_close_special_dos
   if ( handle )
      CloseHandle( (HANDLE) handle );
}

/* __regina_read acts like read() but returns either an error (return code
 * == -errno) or the number of bytes read. EINTR and friends leads to a
 * re-read.
 * async_info is both a structure and a flag. If set, asynchronous IO shall
 * be used, otherwise blocked IO has to be used.
 */
int __regina_read(int handle, void *buf, unsigned size, void *async_info)
{
   AsyncInfo *ai;
   HANDLE hdl;
   unsigned i;
   OVERLAPPED *ol;
   DWORD done;
   int retval;

# define NEED_STUPID_DOSCMD
# define __regina_read __regina_read_dos
   if ( WIN9X_VER )
      return(__regina_read(handle, buf, size, async_info));

   ai = async_info;
   hdl = (HANDLE) handle;
   retval = 0;

   if (ai == NULL)
   {
      if (!ReadFile( (HANDLE) hdl, buf, size, &done, NULL))
      {
         retval = (int) GetLastError();
         if (retval == ERROR_BROKEN_PIPE)
            return(0); /* "Normal" EOF */
         return(-EPIPE); /* guess */
      }
      retval = (int) done;
      return(retval);
   }

   /* Async IO */
   for (i = 0;i < 3;i++)
      if (ai->h[i].hdl == hdl)
         break;
   if (i == 3)
      return(-EINVAL);

   ol = &ai->h[i].ol;

   if (ai->h[i].reading) /* pending IO? */
   {
      if (!HasOverlappedIoCompleted(ol))
      {
         done = 0;
         retval = -EAGAIN;
      }
      else if (!GetOverlappedResult(hdl, ol, &done, FALSE))
      {
         done = 0;
         if (GetLastError() == ERROR_IO_PENDING)
         {
            retval = -EAGAIN;
         }
         else
         {
            ai->h[i].reading = 0;
            retval = -EPIPE;
         }
      }
      else
         ai->h[i].reading = 0;

      if (done)
         ai->h[i].rused += done;
   }

   if (ai->h[i].rused)
   {
      if (size > ai->h[i].rused)
         size = ai->h[i].rused;
      memcpy(buf, ai->h[i].buf + ai->h[i].rusedbegin, size);
      ai->h[i].rusedbegin += size;
      ai->h[i].rused -= size;
      retval = size;
   }
   else
      retval = -EAGAIN; /* still may change! */

   if (ai->h[i].maxbuf < 0x1000) /* Buffer not allocated? */
   {
      /* Never allocate too much, we want a fast response to do some
       * work!
       */
      if (ai->h[i].buf) /* THIS IS DEFINITELY A BUG! */
         Free_TSD(ai->TSD, ai->h[i].buf);
      ai->h[i].maxbuf = 0x1000;
      ai->h[i].rusedbegin = 0;
      ai->h[i].rused = 0;
      ai->h[i].reading = 0;
      ai->h[i].buf = Malloc_TSD(ai->TSD, ai->h[i].maxbuf);
   }

   if (ai->h[i].reading) /* Pending IO, we can't do more */
      return(retval);

   /* not reading or no longer reading, initiate a new reading */
   if (ai->h[i].rused && (ai->h[i].rusedbegin != 0))
      memmove(ai->h[i].buf, ai->h[i].buf + ai->h[i].rusedbegin, ai->h[i].rused);
   ai->h[i].rusedbegin = 0;

   if (ai->h[i].rused < ai->h[i].maxbuf)
   {
      ai->h[i].reading = ai->h[i].maxbuf - ai->h[i].rused;
      ResetEvent(ai->h[i].ol.hEvent);
      if (!ReadFile((HANDLE) hdl,
                    ai->h[i].buf + ai->h[i].rused,
                    ai->h[i].reading,
                    &done,
                    ol))
      {
         done = GetLastError();
         if (done == ERROR_IO_PENDING)
            return(retval);

         ai->h[i].reading = 0;
         if ((retval > 0) || (ai->h[i].rused != 0))
            return(retval);

         if (done == ERROR_BROKEN_PIPE)
            return(0); /* "Normal" EOF */
         return(-EPIPE); /* guess */
      }

      /* success */
      ai->h[i].reading = 0;
      ai->h[i].rused += done;
   }

   if ((retval < 0) && ai->h[i].rused) /* fresh data? return at once */
   {
      if (size > ai->h[i].rused)
         size = ai->h[i].rused;
      memcpy(buf, ai->h[i].buf + ai->h[i].rusedbegin, size);
      ai->h[i].rusedbegin += size;
      ai->h[i].rused -= size;
      retval = size;
   }
   return(retval);
}

/* __regina_write acts like write() but returns either an error (return code
 * == -errno) or the number of bytes written. EINTR and friends leads to a
 * re-write.
 * async_info is both a structure and a flag. If set, asynchronous IO shall
 * be used, otherwise blocked IO has to be used.
 * The file must be flushed if both buf and size are 0.
 */
int __regina_write(int handle, const void *buf, unsigned size, void *async_info)
{
   AsyncInfo *ai;
   HANDLE hdl;
   unsigned i;
   OVERLAPPED *ol;
   DWORD done;
   int retval;

# define NEED_STUPID_DOSCMD
# define __regina_write __regina_write_dos
   if ( WIN9X_VER )
      return(__regina_write(handle, buf, size, async_info));

   ai = async_info;
   hdl = (HANDLE) handle;
   retval = 0;

   if (!ai)
   {
      if (buf == NULL)
         return(0); /* flushing is useless here! */

      if (!WriteFile(hdl, buf, size, &done, NULL))
      {
         retval = (int) GetLastError();
         return(-EPIPE); /* guess */
      }
      retval = (int) done;
      return(retval);
   }

   /* Async IO */
   for (i = 0;i < 3;i++)
      if (ai->h[i].hdl == hdl)
         break;
   if (i == 3)
      return(-EINVAL);

   ol = &ai->h[i].ol;

   if (buf == NULL)
   {
      if (ai->h[i].wused) /* pending IO? */
      {
         if (!GetOverlappedResult(hdl, ol, &done, TRUE))
            return(-EPIPE); /* guess */
         if (done != ai->h[i].wused)
            return(-EPIPE); /* guess */
      }
      return(0); /* OK */
   }

   if (ai->h[i].wused) /* pending IO? */
   {
      if (!HasOverlappedIoCompleted(ol))
         return(-EAGAIN);
      if (!GetOverlappedResult(hdl, ol, &done, FALSE))
      {
         done = GetLastError();
         if (done == ERROR_IO_PENDING)
            return(-EAGAIN);
         return(-EPIPE); /* guess */
      }
      if (done < ai->h[i].wused)
      {
         memmove(ai->h[i].buf, ai->h[i].buf + done, ai->h[i].wused - done);
         ai->h[i].wused -= done;
      }
      else
         ai->h[i].wused = 0;
   }

   if (ai->h[i].wused < 0x10000) /* Never buffer too much at once! */
   {
      /* We have to add the argumented stuff to the local buffer */
      if (ai->h[i].wused + size >= ai->h[i].maxbuf)
      {
         char *new;

         ai->h[i].maxbuf = ai->h[i].wused + size + 0x400;
         if (ai->h[i].maxbuf < 0x2000) /* initial minimum value */
            ai->h[i].maxbuf = 0x2000;
         new = Malloc_TSD(ai->TSD, ai->h[i].maxbuf);
         if (ai->h[i].wused)
            memcpy(new, ai->h[i].buf, ai->h[i].wused);
         if (ai->h[i].buf)
            Free_TSD(ai->TSD, ai->h[i].buf);

         ai->h[i].buf = new;
      }
      memmove(ai->h[i].buf + ai->h[i].wused, buf, size);
      ai->h[i].wused += size;
      retval = size;
   }
   else
      retval = -EAGAIN;

   if (ai->h[i].wused == 0)
      return(retval);

   ResetEvent(ai->h[i].ol.hEvent);

   if (!WriteFile(hdl, ai->h[i].buf, ai->h[i].wused, &done, ol))
   {
      done = (int) GetLastError();
      if (done == ERROR_IO_PENDING)
         return(retval);
      return(-EPIPE); /* guess */
   }
   /* No errors, thus success. We don't want to redo all the stuff. We
    * simply set your wait-semaphore to prevent sleeping.
    */
   SetEvent(ai->h[i].ol.hEvent);

   return(retval);
}

/* create_async_info return an opaque structure to allow the process wait for
 * asyncronous IO. There are three IO slots (in, out, error) which can be
 * filled by add_waiter. The structure can be cleaned by reset_async_info.
 * The structure must be destroyed by delete_async_info.
 */
void *create_async_info(const tsd_t *TSD)
{
   AsyncInfo *retval;

# define NEED_STUPID_DOSCMD
# undef create_async_info
# define create_async_info create_async_info_dos
   if ( WIN9X_VER )
      return(create_async_info(TSD));

   retval = MallocTSD(sizeof(AsyncInfo));
   memset(retval, 0, sizeof(AsyncInfo));

   retval->TSD = TSD;
   retval->h[0].hdl = INVALID_HANDLE_VALUE;
   retval->h[0].ol.hEvent = INVALID_HANDLE_VALUE;
   retval->h[1] = retval->h[0];
   retval->h[2] = retval->h[0];
   return(retval);
}

/* delete_async_info deletes the structure created by create_async_info and
 * all of its components.
 */
void delete_async_info(void *async_info)
{
   AsyncInfo *ai;
   unsigned i;

# define NEED_STUPID_DOSCMD
# undef delete_async_info
# define delete_async_info delete_async_info_dos
   if ( WIN9X_VER )
   {
      delete_async_info(async_info);
      return;
   }

   ai = async_info;
   if (ai == NULL)
      return;

   for (i = 0; i < 3;i++)
      __regina_close((int) ai->h[i].hdl, ai);
   Free_TSD(ai->TSD, ai);
}

/* reset_async_info clear async_info in such a way that fresh add_waiter()
 * calls can be performed.
 */
void reset_async_info(void *async_info)
{
# define NEED_STUPID_DOSCMD
# undef reset_async_info
# define reset_async_info reset_async_info_dos
   if ( WIN9X_VER )
   {
      reset_async_info(async_info);
      return;
   }
}

/* add_async_waiter adds a further handle to the asyncronous IO structure.
 * add_as_read_handle must be != 0 if the next operation shall be a
 * __regina_read, else it must be 0 for __regina_write.
 * Call reset_async_info before a wait-cycle to different handles and use
 * wait_async_info to wait for at least one IO-able handle.
 */
void add_async_waiter(void *async_info, int handle, int add_as_read_handle)
{
   AsyncInfo *ai;
   HANDLE hdl;
   unsigned i;

# define NEED_STUPID_DOSCMD
# undef add_async_waiter
# define add_async_waiter add_async_waiter_dos
   if ( WIN9X_VER )
   {
      add_async_waiter(async_info, handle, add_as_read_handle);
      return;
   }

   ai = async_info;
   hdl = (HANDLE) handle;
   if (ai)
   {
      for (i = 0;i < 3;i++)
         if (ai->h[i].hdl == hdl)
         {
            if (add_as_read_handle)
               ai->h[i].is_reader = 1;
            else
               ai->h[i].is_reader = 0;
         }
   }
}

/* wait_async_info waits for some handles to become ready. This function
 * returns if at least one handle becomes ready.
 * A handle can be added with add_async_waiter to the bundle of handles to
 * wait for.
 * No special handling is implemented if an asyncronous interrupt occurs.
 * Thus, there is no guarantee to have handle which works.
 */
void wait_async_info(void *async_info)
{
   AsyncInfo *ai;
   unsigned i, used;
   HANDLE list[3];

# define NEED_STUPID_DOSCMD
# undef wait_async_info
# define wait_async_info wait_async_info_dos
   if ( WIN9X_VER )
   {
      wait_async_info(async_info);
      return;
   }

   ai = async_info;
   for (i = 0, used = 0; i < 3; i++)
   {
      if (ai->h[i].hdl == INVALID_HANDLE_VALUE)
         continue;
      if (ai->h[i].ol.hEvent == INVALID_HANDLE_VALUE)
         continue;
      if (ai->h[i].is_reader)
      {
         if (ai->h[i].rused != 0) /* Still data to read? this is a killer! */
            return;
         if (ai->h[i].reading == 0)
            continue;
      }
      else
      {
         if (ai->h[i].wused == 0)
            continue;
      }
      if (HasOverlappedIoCompleted(&ai->h[i].ol)) /* fresh meat arrived? */
         return;
      list[used++] = ai->h[i].ol.hEvent;
   }
   if (used)
      WaitForMultipleObjects(used, list, FALSE, INFINITE);
}
#elif defined(__EMX__) || defined(OS2) /* until here not WIN32 */
/*****************************************************************************
 *****************************************************************************
 ** EMX **********************************************************************
 *****************************************************************************
 *****************************************************************************/
#include <io.h>

  typedef struct {
   const tsd_t *TSD;
   HEV          sem;
   int          mustwait;
   int          hdl[3];
  } AsyncInfo;

/* fork_exec spawns a new process with the given commandline.
 * it returns -1 on error (errno set), 0 on process start error (rcode set),
 * a process descriptor otherwise.
 * Basically this is a child process and we run in the child's environment
 * after the first few lines. The setup hasn't been done and the command needs
 * to be started.
 * Redirection takes place if one of the handles env->input.hdls[0],
 * env->output.hdls[1] or env->error.hdls[1] is defined. Other handles (except
 * standard handles) are closed. env->subtype must be a SUBENVIR_... constant.
 * cmdline is the whole command line.
 * Never use TSD after the fork() since this is not only a different thread,
 * it's a different process!
 * Although mentioned in the documentation we have to use a backslash a
 * escape character nevertheless. It's a bug of EMX not to recognize a
 * circumflex as the default escape character and therefore we have to
 * use the "wrong" escape character. Note the difference between EMX and OS/2.
 * Maybe, I'm wrong. Drop me an email in this case. FGC
 */
int fork_exec(tsd_t *TSD, environment *env, const char *cmdline, int *rcode)
{
   static const char *interpreter[] = { "regina.exe", /* preferable even if */
                                                      /* not dynamic        */
                                        "rexx.exe" };
   char **args = NULL;
   int saved_in = -1, saved_out = -1, saved_err = -1;
   int rc;
   const char *ipret;
   char *argline;
   int broken_address_command = get_options_flag( TSD->currlevel, EXT_BROKEN_ADDRESS_COMMAND );
   int subtype;

   if (env->subtype == SUBENVIR_REXX) /*special situation caused by recursion*/
   {
      environment e = *env;
      char *new_cmdline;
      int i, rc;
      unsigned len;

      if (argv0 == NULL)
         len = 11; /* max("rexx.exe", "regina.exe") */
      else
      {
         len = strlen(argv0);
         if (len < 11)
            len = 11; /* max("rexx.exe", "regina.exe") */
      }
      len += strlen(cmdline) + 2; /* Blank + term ASCII0 */

      if ((new_cmdline = malloc(len)) == NULL)
         return(-1); /* ENOMEM is set */

      if (argv0 != NULL) /* always the best choice */
      {
         strcpy(new_cmdline, argv0);
         strcat(new_cmdline, " ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_COMMAND;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

      /* load an interpreter by name from the path */
      for (i = 0; i < sizeof(interpreter) / sizeof(interpreter[0]);i++)
      {
         strcpy(new_cmdline, interpreter[i]);
         strcat(new_cmdline, " ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_COMMAND;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

#ifndef __EMX__
      *rcode = -errno; /* assume a load error */
      free( new_cmdline );
      return 0;
#else
      if ( ( rc = fork() ) != 0 ) /* EMX is fork-capable */
         return rc;
#endif
   }
#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
   /* SUBENVIR_REXX must(!!) fork if we are here! */
# undef fork_exec
# define fork_exec __regina_fork_exec_dos
   {
      int fork_exec(tsd_t *TSD, environment *env, const char *cmdline);
      if ((_osmode != OS2_MODE) && (env->subtype != SUBENVIR_REXX))
      return(fork_exec(TSD, env, cmdline));
   }
#endif

#define STD_REDIR(hdl,dest,save) if ((hdl != -1) && (hdl != dest)) \
                                    { save = dup(dest); dup2(hdl, dest); }
#define STD_RESTORE(saved,dest) if (saved != -1) \
                                    { close(dest); dup2(saved,dest); \
                                      close(saved); }
#define SET_MAXHDL(hdl) if (hdl > max_hdls) max_hdls = hdl
#define SET_MAXHDLS(ep) SET_MAXHDL(ep.hdls[0]); SET_MAXHDL(ep.hdls[1])

                                        /* Force the standard redirections:  */
   STD_REDIR(env->input.hdls[0],    0, saved_in);
   STD_REDIR(env->output.hdls[1],   1, saved_out);
   if (env->error.SameAsOutput)
   {
      saved_err = dup(2);
      dup2(1, 2);
   }
   else
   {
      STD_REDIR(env->error.hdls[1], 2, saved_err);
   }

   /*
    * If the BROKEN_ADDRESS_COMMAND OPTION is in place,
    * and our environment is COMMAND, change it to SYSTEM
    */
   if ( env->subtype == SUBENVIR_PATH /* was SUBENVIR_COMMAND */
   &&   broken_address_command )
      subtype = SUBENVIR_SYSTEM;
   else
      subtype = env->subtype;

   rc = -1;
   switch ( subtype )
   {
      case SUBENVIR_PATH:
         args = makeargs(cmdline, '^');
#define NEED_MAKEARGS
         rc = spawnvp(P_NOWAIT, *args, args);
         break;

      case SUBENVIR_COMMAND:
         args = makeargs(cmdline, '^');
         rc = spawnv(P_NOWAIT, *args, args);
         break;

      case SUBENVIR_SYSTEM:
         /* insert "%COMSPEC% /c " or "%SHELL% -c " in front */
         if ((ipret = getenv("COMSPEC")) != NULL)
         {
            argline = MallocTSD(strlen(ipret) + strlen(cmdline) + 5);
            strcpy(argline,ipret);
            strcat(argline," /c ");
         }
         else if ((ipret = getenv("SHELL")) != NULL)
         {
            argline = MallocTSD(strlen(ipret) + strlen(cmdline) + 5);
            strcpy(argline,ipret);
            strcat(argline," -c ");
         }
         else
         {
            ipret = "CMD.EXE";
            argline = MallocTSD(strlen(ipret) + strlen(cmdline) + 5);
            strcpy(argline,ipret);
            strcat(argline," /c ");
         }
         strcat(argline, cmdline);
         args = makeargs(argline, '^');
         rc = spawnvp(P_NOWAIT, *args, args);
         break;

      case SUBENVIR_REXX:
         {
            /* we are forked and we are the child!!!! */
            /* last chance, worst choice, use the re-entering code: */
            char *new_cmdline = malloc(strlen(cmdline) + 4);
            char **run;
            int i;

            strcpy(new_cmdline, "\"\" ");
            strcat(new_cmdline, cmdline);
            args = makeargs(new_cmdline, '^');

            for (i = 0, run = args; *run; run++)
                  i++;
            exit(__regina_reexecute_main(i, args));
         }

      default: /* illegal subtype */
         STD_RESTORE(saved_in, 0);
         STD_RESTORE(saved_out, 1);
         STD_RESTORE(saved_err, 2);
         errno = EINVAL;
         return -1;
   }

   *rcode = errno;
   STD_RESTORE(saved_in, 0);
   STD_RESTORE(saved_out, 1);
   STD_RESTORE(saved_err, 2);
   if (args != NULL)
      destroyargs(args);
#define NEED_DESTROYARGS

   return ( rc == -1 ) ? 0 : rc;
#undef SET_MAXHDLS
#undef SET_MAXHDL
#undef STD_RESTORE
#undef STD_REDIR
}

/* __regina_wait waits for a process started by fork_exec.
 * In general, this is called after the complete IO to the called process but
 * it isn't guaranteed. Never call if you don't expect a sudden death of the
 * subprocess.
 * Returns the exit status of the subprocess under normal circumstances. If
 * the subprocess has died by a signal, the return value is -signalnumber.
 */
int __regina_wait(int process)
{
   int rc, retval, status;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# define __regina_wait __regina_wait_dos
   int __regina_wait(int process);
   if (_osmode != OS2_MODE)
      return(__regina_wait(process));
#endif

#ifdef __WATCOMC__
   /*
    * Watcom is strange. EINTR isn't an indicator for a retry of the call.
    */
   status = -1;
   rc = cwait(&status, process, WAIT_CHILD);
   if (rc == -1)
   {
      if ((status != -1) && (errno == EINTR))
         retval = -status; /* Exception reason in lower byte */
      else
         retval = -errno;  /* I don't have a better idea */
   }
   else
   {
      if (status & 0xFF)
         retval = -status; /* Exception reason in lower byte */
      else
         retval = status >> 8;
   }
#else
   do {
      rc = waitpid(process, &status, 0);
   } while ((rc == -1) && (errno == EINTR));

   if (WIFEXITED(status))
   {
      retval = (int) WEXITSTATUS(status);
      if ( retval < 0 )
         retval = -retval;
   }
   else if (WIFSIGNALED(status))
   {
      retval = -WTERMSIG(status);
      if ( retval > 0 )
         retval = -retval;
      else if ( retval == 0 )
         retval = -1;
   }
   else
   {
      retval = -WSTOPSIG(status);
      if ( retval > 0 )
         retval = -retval;
      else if ( retval == 0 )
         retval = -1;
   }
#endif

   return(retval);
}

/* open_subprocess_connection acts like the unix-known function pipe and sets
 * ep->RedirectedFile if necessary. Just in the latter case ep->data
 * is set to the filename.
 * Close the handles with __regina_close later.
 * Do IO by using __regina_read() and __regina_write().
 */
int open_subprocess_connection(const tsd_t *TSD, environpart *ep)
{
#define MAGIC_MAX 2000000 /* Much beyond maximum, see below */
   static volatile unsigned BaseIndex = MAGIC_MAX;
   char buf[40];
   unsigned i;
   unsigned start,run;
   ULONG rc, openmode, dummy;
   HPIPE in = (HPIPE) -1, out;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef open_subprocess_connection
# define open_subprocess_connection __regina_open_subprocess_connection_dos
   int open_subprocess_connection(const tsd_t *TSD, environpart *ep);
   if (_osmode != OS2_MODE)
      return(open_subprocess_connection(TSD, ep));
#endif

   /* We have to use named pipes for various reasons. */
   openmode = (ep->flags.isinput) ? NP_ACCESS_OUTBOUND : NP_ACCESS_INBOUND;
   openmode |= NP_NOINHERIT | NP_WRITEBEHIND;

   /* algorithm:
    * select a random number, e.g. a mixture of pid, tid and time.
    * increment this number by a fixed amount until we reach the starting
    * value again. Do a wrap around and an increment which is a unique prime.
    * The number 1000000 has the primes 2 and 5. We may use all primes
    * except 2 and 5; 9901 (which is prime) will give a good distribution.
    *
    * We want to be able to create several temporary files at once without
    * more OS calls than needed. Thus, we have a program wide runner to
    * ensure a simple distribution without strength.
    */
   if (BaseIndex == MAGIC_MAX)
   {
      /*
       * We have to create (nearly) reentrant code.
       */
      i = (unsigned) getpid() * (unsigned) time(NULL);
      i %= 1000000;
      if (!i)
         i = 1;
      BaseIndex = i;
   }
   if (++BaseIndex >= 1000000)
      BaseIndex = 1;

   start = TSD->thread_id;
   if (start == 0)
      start = 999999;
   start *= (unsigned) (clock() + 1);
   start *= BaseIndex;
   start %= 1000000;

   run = start;
   for (i = 0;i <= 1000000;i++)
   {
      sprintf(buf,"%s%06u._rx", "\\pipe\\tmp\\", run );
      rc = DosCreateNPipe(buf,
                          &in,
                          openmode,
                          NP_TYPE_BYTE | NP_READMODE_BYTE | NP_NOWAIT | 1,
                          4096,
                          4096,
                          0); /* msec timeout */
      if (rc == NO_ERROR)
         break;

      if (rc != ERROR_PIPE_BUSY)
      {
         errno = EPIPE;
         return(-1);
      }

      /* Check the next possible candidate */
      run += 9901;
      run %= 1000000;
      if (run == start) /* paranoia check. i <= 1000000 should hit exactly */
         break;         /* here */
   }

   if (in == (HPIPE) -1)
   {
      errno = EPIPE;
      return(-1);
   }

   DosConnectNPipe(in); /* ignore the return */

   openmode = (ep->flags.isinput) ? OPEN_ACCESS_READONLY :
                                    OPEN_ACCESS_WRITEONLY;
   openmode |= OPEN_FLAGS_SEQUENTIAL | OPEN_SHARE_DENYREADWRITE;
   rc = DosOpen(buf,
                &out,
                &dummy, /* action */
                0ul, /* initial size */
                FILE_NORMAL,
                OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                openmode,
                NULL); /* peaop2 */
   if (rc != NO_ERROR)
   {
      DosClose(in);
      errno = EPIPE; /* guess */
      return(-1);
   }

   /* Now do the final checking, the server end must be connected */
   if (DosConnectNPipe(in) != NO_ERROR)
   {
      DosClose(out);
      DosClose(in);
      errno = EPIPE; /* guess */
      return(-1);
   }

   /* We always want to have the server's end of the named pipe: */
   if (ep->flags.isinput)
   {
      ep->hdls[0] = (int) out;
      ep->hdls[1] = (int) in;
   }
   else
   {
      ep->hdls[0] = (int) in;
      ep->hdls[1] = (int) out;
   }
   return(0);
#undef MAGIC_MAX
}

/* sets the given handle to the non-blocking mode. The value may change.
 * async_info CAN be used to add the handle to the internal list of watched
 * handles.
 */
void unblock_handle( int *handle, void *async_info )
{
   AsyncInfo *ai = async_info;
   int i;
   ULONG rc;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef unblock_handle
# define unblock_handle __regina_unblock_handle_dos
   void unblock_handle( int *handle, void *async_info );
   if (_osmode != OS2_MODE)
   {
      unblock_handle(handle, async_info);
      return;
   }
#endif
   if (*handle == -1)
      return ;

   for (i = 0;i < 3;i++)
   {
      if ((ai->hdl[i] != *handle) && (ai->hdl[i] == -1))
      {
         ai->hdl[i] = *handle;
         rc = DosSetNPipeSem((HFILE) *handle, (HSEM) ai->sem, 0);

         if (rc != NO_ERROR)
            ai->hdl[i] = *handle = -2;
            /* This shall produce an error. -1 isn't a good idea: special
             * meaning
             */
         return;
      }
   }
}

/* restart_file sets the file pointer of the given handle to the beginning.
 */
void restart_file(int hdl)
{
#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef restart_file
# define restart_file __regina_restart_file_dos
   void restart_file(int hdl);
   if (_osmode != OS2_MODE)
   {
      restart_file(hdl);
      return;
   }
#endif

   lseek(hdl, 0l, SEEK_SET); /* unused! */
}

/* __regina_close acts like close() but closes a handle returned by
 * open_subprocess_connection.
 * async_info MAY be used to delete the handle from the internal list of
 * watched handles.
 */
int __regina_close(int handle, void *async_info)
{
   AsyncInfo *ai = async_info;
   int i;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# define __regina_close __regina_close_dos
   int __regina_close(int handle, void *async_info);
   if (_osmode != OS2_MODE)
      return(__regina_close(handle, async_info));
#endif

   if ((handle != -1) && (ai != NULL))
      for (i = 0;i < 3;i++)
         if ((int) ai->hdl[i] == handle)
            DosSetNPipeSem((HPIPE) handle, NULLHANDLE, 0);
   return(DosClose((HFILE) handle));
}

/*
 * __regina_close_special acts like close() but closes any OS specific handle.
 * The close happens if the handle is not -1. A specific operation may be
 * associated with this. Have a look for occurances of "hdls[2]".
 */
void __regina_close_special( int handle )
{
#define __regina_close_special __regina_close_special_dos
   assert( handle == -1 );
}

/* __regina_read acts like read() but returns either an error (return code
 * == -errno) or the number of bytes read. EINTR and friends leads to a
 * re-read.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 */
int __regina_read(int hdl, void *buf, unsigned size, void *async_info)
{
   ULONG rc;
   ULONG done;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# define __regina_read __regina_read_dos
   int __regina_read(int hdl, void *buf, unsigned size, void *async_info);
   if (_osmode != OS2_MODE)
      return(__regina_read(hdl, buf, size, async_info));
#endif

   do {
      rc = DosRead((HFILE) hdl, buf, size, &done);
   } while (rc == ERROR_INTERRUPT);

   if (rc != 0)
   {
      if (rc == ERROR_NO_DATA)
         return(-EAGAIN);
      if (rc == ERROR_BROKEN_PIPE)
         return(-EPIPE);
      return(-EINVAL);   /* good assumption */
   }

   return(done);
}

/* __regina_write acts like write() but returns either an error (return code
 * == -errno) or the number of bytes written. EINTR and friends leads to a
 * re-write.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 * The file must be flushed, if both buf and size are 0.
 */
int __regina_write(int hdl, const void *buf, unsigned size, void *async_info)
{
   ULONG rc;
   ULONG done;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# define __regina_write __regina_write_dos
   int __regina_write(int hdl, const void *buf, unsigned size, void *async_info);
   if (_osmode != OS2_MODE)
      return(__regina_write(hdl, buf, size, async_info));
#endif

   if ((buf == NULL) || (size == 0)) /* nothing to to for flushing buffers */
      return(0);

   do {
      rc = DosWrite((HFILE) hdl, buf, size, &done);
   } while (rc == ERROR_INTERRUPT);

   if (rc != 0)
   {
      if (rc == ERROR_NO_DATA)
         return(-EAGAIN);
      if ((rc == ERROR_BROKEN_PIPE) || (rc == ERROR_DISCARDED))
         return(-EPIPE);
      if (rc == ERROR_INVALID_HANDLE)
         return(-EINVAL);
      return(-ENOSPC);   /* good assumption */
   } else if (done == 0)
      return(-EAGAIN);

   return((int) done);
}

/* create_async_info return an opaque structure to allow the process wait for
 * asyncronous IO. There are three IO slots (in, out, error) which can be
 * filled by add_waiter. The structure can be cleaned by reset_async_info.
 * The structure must be destroyed by delete_async_info.
 */
void *create_async_info(const tsd_t *TSD)
{
   AsyncInfo *ai;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef create_async_info
# define create_async_info __regina_create_async_info_dos
   void *create_async_info(const tsd_t *TSD);
   if (_osmode != OS2_MODE)
      return(create_async_info(TSD));
#endif

   ai = MallocTSD(sizeof(AsyncInfo));
   ai->TSD = TSD;
   ai->sem = NULLHANDLE;
   ai->hdl[0] = ai->hdl[1] = ai->hdl[2] = (HFILE) -1;
   ai->mustwait = 0;
   DosCreateEventSem(NULL, &ai->sem, DC_SEM_SHARED, FALSE);
   return(ai);
}

/* delete_async_info deletes the structure created by create_async_info and
 * all of its components.
 */
void delete_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef delete_async_info
# define delete_async_info __regina_delete_async_info_dos
   void delete_async_info(void *async_info);
   if (_osmode != OS2_MODE)
   {
      delete_async_info(async_info);
      return;
   }
#endif

   if (ai == NULL)
      return;
   DosCloseEventSem(ai->sem);
   Free_TSD(ai->TSD, ai);
}

/* reset_async_info clear async_info in such a way that fresh add_waiter()
 * calls can be performed.
 */
void reset_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;
   ULONG ul;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef reset_async_info
# define reset_async_info __regina_reset_async_info_dos
   void reset_async_info(void *async_info);
   if (_osmode != OS2_MODE)
   {
      reset_async_info(async_info);
      return;
   }
#endif

   DosResetEventSem(ai->sem, &ul);
   ai->mustwait = 0;
}

/* add_async_waiter adds a further handle to the asyncronous IO structure.
 * add_as_read_handle must be != 0 if the next operation shall be a
 * __regina_read, else it must be 0 for __regina_write.
 * Call reset_async_info before a wait-cycle to different handles and use
 * wait_async_info to wait for at least one IO-able handle.
 */
void add_async_waiter(void *async_info, int handle, int add_as_read_handle)
{
   AsyncInfo *ai = async_info;
   int i;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef add_async_waiter
# define add_async_waiter __regina_add_async_waiter_dos
   void add_async_waiter(void *async_info, int handle, int add_as_read_handle);
   if (_osmode != OS2_MODE)
   {
      add_async_waiter(async_info, handle, add_as_read_handle);
      return;
   }
#endif

   if (handle != -1)
      for (i = 0;i < 3;i++)
         if ((int) ai->hdl[i] == handle)
            ai->mustwait = 1;
}

/* wait_async_info waits for some handles to become ready. This function
 * returns if at least one handle becomes ready.
 * A handle can be added with add_async_waiter to the bundle of handles to
 * wait for.
 * No special handling is implemented if an asyncronous interrupt occurs.
 * Thus, there is no guarantee to have handle which works.
 */
void wait_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

#ifdef __EMX__ /* redirect this call to the non-OS/2-code if DOS is running */
# define NEED_STUPID_DOSCMD
# undef wait_async_info
# define wait_async_info __regina_wait_async_info_dos
   void wait_async_info(void *async_info);
   if (_osmode != OS2_MODE)
   {
      wait_async_info(async_info);
      return;
   }
#endif

   if (ai->mustwait)
      DosWaitEventSem(ai->sem, SEM_INDEFINITE_WAIT);
}
/* end of elif define(__EMX__) */
#elif defined(MAC) || defined(DOS) || defined(__WINS__) || defined(__EPOC32__) || defined(_AMIGA) || defined(SKYOS)
#define NEED_STUPID_DOSCMD
#else /* !(MAC || DOS || WIN32 || OS2 || _AMIGA || __WINS__ || __EPOC32__) */
/*****************************************************************************
 *****************************************************************************
 ** unix and others **********************************************************
 *****************************************************************************
 *****************************************************************************/

#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#if defined(HAVE_ASSERT_H)
# include <assert.h>
#endif

#if (defined(__WATCOMC__) && !defined(__QNX__)) || defined(_MSC_VER) || defined(__MINGW32__) || defined(__BORLANDC__)
# include <process.h>
#else
# include <sys/wait.h>
# include <sys/time.h>
#endif
#if defined(HAVE_POLL_H)
# include <poll.h>
  /* implement a simple(!) wait mechanism for a max. of 3 handles */
  typedef struct {
   const tsd_t *TSD;
   struct pollfd _p[3] ;
   int _p_cnt ;
  } AsyncInfo;
#elif defined(HAVE_SYS_SELECT_H) || defined(SELECT_IN_TIME_H) || defined(HAVE_SYS_SOCKET_H)
# if defined(HAVE_SYS_SELECT_H)
#   include <sys/select.h>
# elif defined(HAVE_SYS_SOCKET_H)
#   include <sys/socket.h>
# else
#   include <time.h>
# endif
  /* implement a simple(!) wait mechanism for a max. of 3 handles */
  typedef struct {
   const tsd_t *TSD;
   fd_set _p_in;
   fd_set _p_out;
   int _p_max ;
  } AsyncInfo;
#endif
#if defined(HAVE_SYS_RESOURCE_H)
# include <sys/resource.h>
#endif
#define I_SLASH '/'

/* MaxFiles returns the maximum number of files which can be addressed by a
 * single process. We guess the result if we can't determine it.
 */
#if defined(__QNX__) && !defined(__QNXNTO__)
#include <sys/osinfo.h>
static int MaxFiles(void)
/*
 * returns the maximum number of files which can be addressed by a single
 * process. We guess the result if we can't determine it.
 */
{
   struct _osinfo osdata;
   if ( qnx_osinfo( 0, &osdata ) != -1 )
   {
      return osdata.num_fds[1];
   }
   else
   {
      return 256;
   }
}
#else
static int MaxFiles(void)
{
   int rlmax = INT_MAX; /* resource's limit */
   int scmax = INT_MAX; /* sysconf limit */

#ifdef _SC_OPEN_MAX
   scmax = sysconf(_SC_OPEN_MAX); /* systemwide maximum */
#endif

#if defined(HAVE_SYS_RESOURCE_H) && defined(RLIMIT_OFILE)
   /* user's limit might be decreased by himself: */
   {
      struct rlimit rl;

      if (getrlimit(RLIMIT_OFILE,&rl) == 0)
         if ((unsigned) rl.rlim_cur < (unsigned) INT_MAX)
            rlmax = (int) rl.rlim_cur;
   }
#endif

   if (rlmax < scmax) /* map rlmax to scmax */
      scmax = rlmax;
   if (scmax != INT_MAX) /* either getrlimit or sysconf valid? */
      return(scmax);

#ifdef POSIX_OPEN_MAX
   /* maybe, we have a hardcoded limit */
   if (POSIX_OPEN_MAX != INT_MAX) /* shall work in most cases */
        return(POSIX_OPEN_MAX);
#endif

   return(256); /* just a guess */
}
#endif

/* fork_exec spawns a new process with the given commandline.
 * it returns -1 on error (errno set), 0 on process start error (rcode set),
 * a process descriptor otherwise.
 * Basically this is a child process and we run in the child's environment
 * after the first few lines. The setup hasn't been done and the command needs
 * to be started.
 * Redirection takes place if one of the handles env->input.hdls[0],
 * env->output.hdls[1] or env->error.hdls[1] is defined. Other handles (except
 * standard handles) are closed. env->subtype must be a SUBENVIR_... constant.
 * cmdline is the whole command line.
 * Never use TSD after the fork() since this is not only a different thread,
 * it's a different process!
 */
int fork_exec(tsd_t *TSD, environment *env, const char *cmdline, int *rcode)
{
   static const char *interpreter[] = { "regina", /* preferable even if not */
                                                  /* dynamic                */
                                        "rexx" };
   char **args ;
   int i, rc, max_hdls = MaxFiles() ;
   int broken_address_command = get_options_flag( TSD->currlevel, EXT_BROKEN_ADDRESS_COMMAND );
   int subtype;

   if ( ( rc = fork() ) != 0 )
      return( rc );

   /* Now we are the child */

#define STD_REDIR(hdl,dest) if ((hdl != -1) && (hdl != dest)) dup2(hdl, dest)
#define SET_MAXHDL(hdl) if (hdl > max_hdls) max_hdls = hdl
#define SET_MAXHDLS(ep) SET_MAXHDL(ep.hdls[0]); SET_MAXHDL(ep.hdls[1])

                                        /* Force the standard redirections:  */
   STD_REDIR(env->input.hdls[0],    0);
   STD_REDIR(env->output.hdls[1],   1);
   if (env->error.SameAsOutput)
   {
      STD_REDIR(1,                  2);
   }
   else
   {
      STD_REDIR(env->error.hdls[1], 2);
   }

                                    /* any handle greater than the default ? */
   SET_MAXHDLS(env->input);
   SET_MAXHDLS(env->output);
   if (!env->error.SameAsOutput)
      SET_MAXHDLS(env->error);

   for (i=3; i <= max_hdls; i++)
      close( i ) ;

   /*
    * If the BROKEN_ADDRESS_COMMAND OPTION is in place,
    * and our environment is COMMAND, change it to SYSTEM
    */
   if ( env->subtype == SUBENVIR_PATH /* was SUBENVIR_COMMAND */
   &&   broken_address_command )
      subtype = SUBENVIR_SYSTEM;
   else
      subtype = env->subtype;

   switch ( subtype )
   {
      case SUBENVIR_PATH:
         args = makeargs(cmdline, '\\');
#define NEED_MAKEARGS
         execvp(*args, args);
         break;

      case SUBENVIR_COMMAND:
         args = makeargs(cmdline, '\\');
         execv(*args, args);
         break;

      case SUBENVIR_SYSTEM:
#if defined(HAVE_WIN32GUI)
         rc = mysystem( cmdline ) ;
#else
         rc = system( cmdline ) ;
#endif
#ifdef VMS
         exit (rc); /* This is a separate process, exit() is allowed */
#else
         if ( WIFEXITED( rc ) )
         {
            fflush( stdout );
            _exit( (int) WEXITSTATUS(rc) ); /* This is a separate process, exit() is allowed */
         }
         else if ( WIFSIGNALED( rc ) )
            raise( WTERMSIG( rc ) ); /* This is a separate process, raise() is allowed */
         else
            raise( WSTOPSIG( rc ) ); /* This is a separate process, raise() is allowed */
#endif
         break;
      case SUBENVIR_REXX:
         {
            char *new_cmdline;
            char **run;
            int i;
            unsigned len;

            if (argv0 == NULL)
               len = 7; /* max("rexx", "regina") */
            else
               {
                  len = strlen(argv0);
                  if (len < 7)
                     len = 7; /* max("rexx", "regina") */
               }
            len += strlen(cmdline) + 2; /* Blank + term ASCII0 */

            if ((new_cmdline = malloc(len)) == NULL)
               raise( SIGKILL ); /* This is a separate process, raise() is allowed */

            if (argv0 != NULL) /* always the best choice */
            {
               strcpy(new_cmdline, argv0);
               strcat(new_cmdline, " ");
               strcat(new_cmdline, cmdline);
               args = makeargs(new_cmdline, '\\');
               execv(*args, args);
#define NEED_DESTROYARGS
               destroyargs(args);
            }

            /* load an interpreter by name from the path */
            for (i = 0; i < sizeof(interpreter) / sizeof(interpreter[0]);i++)
            {
               strcpy(new_cmdline, interpreter[i]);
               strcat(new_cmdline, " ");
               strcat(new_cmdline, cmdline);
               args = makeargs(new_cmdline, '\\');
               execvp(*args, args);
#define NEED_DESTROYARGS
               destroyargs(args);
            }

            /* last chance, worst choice, use the re-entering code: */
            strcpy(new_cmdline, "\"\" ");
            strcat(new_cmdline, cmdline);
            args = makeargs(new_cmdline, '\\');

            for (i = 0, run = args; *run; run++)
               i++;
            fflush( stdout );
            _exit(__regina_reexecute_main(i, args));
   }

      default: /* illegal subtype */
         raise( SIGKILL ) ; /* This is a separate process, raise() is allowed */
   }

   /* exec() failed */
   raise( SIGKILL ); /* This is a separate process, raise() is allowed */
#undef SET_MAXHDLS
#undef SET_MAXHDL
#undef STD_REDIR
   return -1; /* keep the compiler happy */
}

/* __regina_wait waits for a process started by fork_exec.
 * In general, this is called after the complete IO to the called process but
 * it isn't guaranteed. Never call if you don't expect a sudden death of the
 * subprocess.
 * Returns the exit status of the subprocess under normal circumstances. If
 * the subprocess has died by a signal, the return value is -(100+signalnumber)
 */
int __regina_wait(int process)
{
   int rc, retval, status;
#ifdef VMS
   for ( ; ; )
   {
      rc = wait( &status ) ;
      if (rc != -1)
         break;
      rc = errno;
      if (rc == EINTR)
         continue;
      break;
   }
   retval = status & 0xff ;
#else
   for ( ; ; )
   {
# ifdef NEXT
      /*
       * According to Paul F. Kunz, NeXTSTEP 3.1 Prerelease doesn't have
       * the waitpid() function, so wait() must be used instead. The
       * following klugde will remain until NeXTSTEP gets waitpid().
       */
      wait( &status ) ;
# else /* ndef NEXT */
#  ifdef DOS
      rc = wait( &status ) ;
#  else /* ndef DOS */
      rc = waitpid( process, &status, 0 ) ;
#  endif /* def DOS */
# endif /* def NEXT */
      if (rc != -1)
         break;
      rc = errno;
      if (rc == EINTR)
         continue;
      break;
   }
   /* still ndef VMS */
   if (WIFEXITED(status))
   {
      retval = (int) WEXITSTATUS(status);
      if ( retval < 0 )
         retval = -retval;
   }
   else if (WIFSIGNALED(status))
   {
      retval = -WTERMSIG(status);
      if ( retval > 0 )
         retval = -retval;
      else if ( retval == 0 )
         retval = -1;
   }
   else
   {
      retval = -WSTOPSIG(status);
      if ( retval > 0 )
         retval = -retval;
      else if ( retval == 0 )
         retval = -1;
   }
#endif /* def VMS */
   return(retval);
}

/* open_subprocess_connection acts like the unix-known function pipe and sets
 * ep->RedirectedFile if necessary. Just in the latter case ep->data
 * is set to the filename.
 */
int open_subprocess_connection(const tsd_t *TSD, environpart *ep)
{
   return(pipe(ep->hdls));
}

/* sets the given handle to the non-blocking mode. The value may change.
 * async_info CAN be used to add the handle to the internal list of watched
 * handles.
 */
void unblock_handle( int *handle, void *async_info )
{
   int fl ;

   if (*handle == -1)
      return ;

   fl = fcntl( *handle, F_GETFL ) ;

   if ( fl == -1 ) /* We can either abort or try to continue, try to */
      return ;     /* continue for now.                              */

   fcntl( *handle, F_SETFL, fl | O_NONBLOCK ) ;
}

/* restart_file sets the file pointer of the given handle to the beginning.
 */
void restart_file(int hdl)
{
   lseek(hdl, 0l, SEEK_SET);
}

/* __regina_close acts like close() but closes a handle returned by
 * open_subprocess_connection.
 * async_info MAY be used to delete the handle from the internal list of
 * watched handles.
 */
int __regina_close(int handle, void *async_info)
{
   return(close(handle));
}

/*
 * __regina_close_special acts like close() but closes any OS specific handle.
 * The close happens if the handle is not -1. A specific operation may be
 * associated with this. Have a look for occurances of "hdls[2]".
 */
void __regina_close_special( int handle )
{
   assert( handle == -1 );
}

/* __regina_read acts like read() but returns either an error (return code
 * == -errno) or the number of bytes read. EINTR and friends leads to a
 * re-read.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 */
int __regina_read(int hdl, void *buf, unsigned size, void *async_info)
{
   int done ;

   do {
      done = read( hdl, buf, size ) ;
   } while ((done == -1) && (errno == EINTR));

   if (done < 0)
   {
      done = errno;
      if (done == 0)      /* no error set? */
         done = EPIPE ;   /* good assumption */
#if defined(EWOULDBLOCK) && defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
      /* BSD knows this value with the same meaning as EAGAIN */
      if (done == EWOULDBLOCK)
         done = EAGAIN ;
#endif
      return( -done ) ; /* error */
   }

   return(done);
}

/* __regina_write acts like write() but returns either an error (return code
 * == -errno) or the number of bytes written. EINTR and friends leads to a
 * re-write.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 * The file must be flushed, if both buf and size are 0.
 */
int __regina_write(int hdl, const void *buf, unsigned size, void *async_info)
{
   int done ;

   if ((buf == NULL) || (size == 0)) /* nothing to to for flushing buffers */
      return(0);

   do {
      done = write( hdl, buf, size ) ;
   } while ((done == -1) && (errno == EINTR));

   if (done < 0)
   {
      done = errno;
      if (done == 0)       /* no error set? */
         done = ENOSPC ;   /* good assumption */
#if defined(EWOULDBLOCK) && defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
      /* BSD knows this value with the same meaning as EAGAIN */
      if (done == EWOULDBLOCK)
         done = EAGAIN ;
#endif
      return( -done ) ; /* error */
   }

   return(done);
}

/* create_async_info return an opaque structure to allow the process wait for
 * asyncronous IO. There are three IO slots (in, out, error) which can be
 * filled by add_waiter. The structure can be cleaned by reset_async_info.
 * The structure must be destroyed by delete_async_info.
 */
void *create_async_info(const tsd_t *TSD)
{
   AsyncInfo *ai = MallocTSD(sizeof(AsyncInfo));

   ai->TSD = TSD;
   return(ai);
}
/* delete_async_info deletes the structure created by create_async_info and
 * all of its components.
 */
void delete_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

   if (ai == NULL)
      return;
   Free_TSD(ai->TSD, ai);
}

#ifdef POLLIN /* we have poll() */

/* reset_async_info clear async_info in such a way that fresh add_waiter()
 * calls can be performed.
 */
void reset_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

   ai->_p_cnt = 0;
}

/* add_async_waiter adds a further handle to the asyncronous IO structure.
 * add_as_read_handle must be != 0 if the next operation shall be a
 * __regina_read, else it must be 0 for __regina_write.
 * Call reset_async_info before a wait-cycle to different handles and use
 * wait_async_info to wait for at least one IO-able handle.
 */
void add_async_waiter(void *async_info, int handle, int add_as_read_handle)
{
   AsyncInfo *ai = async_info;

   assert(ai->_p_cnt < 3);
   ai->_p[ai->_p_cnt].fd = handle;
   ai->_p[ai->_p_cnt++].events = (add_as_read_handle) ? POLLIN : POLLOUT;
}

/* wait_async_info waits for some handles to become ready. This function
 * returns if at least one handle becomes ready.
 * A handle can be added with add_async_waiter to the bundle of handles to
 * wait for.
 * No special handling is implemented if an asyncronous interrupt occurs.
 * Thus, there is no guarantee to have handle which works.
 */
void wait_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

   if (ai->_p_cnt)
      poll(ai->_p, ai->_p_cnt, -1);
}

#else /* end of POLLIN, must be select */

/* reset_async_info clear async_info in such a way that fresh add_waiter()
 * calls can be performed.
 */
void reset_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

   FD_ZERO( &ai->_p_in );
   FD_ZERO( &ai->_p_out );
   ai->_p_max = -1 ;
}

/* add_async_waiter adds a further handle to the asyncronous IO structure.
 * add_as_read_handle must be != 0 if the next operation shall be a
 * __regina_read, else it must be 0 for __regina_write.
 * Call reset_async_info before a wait-cycle to different handles and use
 * wait_async_info to wait for at least one IO-able handle.
 */
void add_async_waiter(void *async_info, int handle, int add_as_read_handle)
{
   AsyncInfo *ai = async_info;

   FD_SET(handle,(add_as_read_handle) ? &ai->_p_in : &ai->_p_out ) ;
   if (handle > ai->_p_max)
      ai->_p_max = handle ;
}

/* wait_async_info waits for some handles to become ready. This function
 * returns if at least one handle becomes ready.
 * A handle can be added with add_async_waiter to the bundle of handles to
 * wait for.
 * No special handling is implemented if an asyncronous interrupt occurs.
 * Thus, there is no guarantee to have handle which works.
 */
void wait_async_info(void *async_info)
{
   AsyncInfo *ai = async_info;

   if (ai->_p_max >= 0)
      select( ai->_p_max+1, &ai->_p_in, &ai->_p_out, NULL, NULL);
}

#endif /* POLLIN or select */
#endif /* WIN32 */

/*****************************************************************************
 *****************************************************************************
 ** DOS and unknown or trivial systems ***************************************
 *****************************************************************************
 *****************************************************************************/
#ifdef NEED_STUPID_DOSCMD
#include <errno.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#else
# include <io.h>
#endif

#if defined(HAVE_SYS_STAT_H)
# include <sys/stat.h>
#endif

#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif

#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#endif

#ifndef I_SLASH
# define I_SLASH '/'
#endif

#ifndef ISTR_SLASH
# define ISTR_SLASH "/"
#endif

/* This flavour is the default style. It doesn't use pipes. It uses temporary
 * files instead.
 * Slow, but shall work with all machines.
 */

/* fork_exec spawns a new process with the given commandline.
 * it returns -1 on error (errno set), 0 on process start error (rcode set),
 * a process descriptor otherwise.
 * Basically this is a child process and we run in the child's environment
 * after the first few lines. The setup hasn't been done and the command needs
 * to be started.
 * Redirection takes place if one of the handles env->input.hdls[0],
 * env->output.hdls[1] or env->error.hdls[1] is defined. Other handles (except
 * standard handles) are closed. env->subtype must be a SUBENVIR_... constant.
 * cmdline is the whole command line.
 * Never use TSD after the fork() since this is not only a different thread,
 * it's a different process!
 */
int fork_exec(tsd_t *TSD, environment *env, const char *cmdline, int *rcode)
{
   static const char *interpreter[] = { "regina", /* preferable even if not */
                                                  /* dynamic                */
                                        "rexx" };
   char **args = NULL;
   int saved_in = -1, saved_out = -1, saved_err = -1;
   int rc, eno ;
   int broken_address_command = get_options_flag( TSD->currlevel, EXT_BROKEN_ADDRESS_COMMAND );
   int subtype;

   if (env->subtype == SUBENVIR_REXX) /*special situation caused by recursion*/
   {
      environment e = *env;
      char *new_cmdline;
      int i, rc;
      unsigned len;

      if (argv0 == NULL)
         len = 7; /* max("rexx", "regina") */
      else
         {
            len = strlen(argv0);
            if (len < 7)
               len = 7; /* max("rexx", "regina") */
         }
      len += strlen(cmdline) + 2; /* Blank + term ASCII0 */

      if ((new_cmdline = malloc(len)) == NULL)
         return -1; /* ENOMEM is set */

      if (argv0 != NULL) /* always the best choice */
      {
         strcpy(new_cmdline, argv0);
         strcat(new_cmdline, " ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_COMMAND;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

      /* load an interpreter by name from the path */
      for (i = 0; i < sizeof(interpreter) / sizeof(interpreter[0]);i++)
      {
         strcpy(new_cmdline, interpreter[i]);
         strcat(new_cmdline, " ");
         strcat(new_cmdline, cmdline);
         e.subtype = SUBENVIR_SYSTEM;
         rc = fork_exec(TSD, &e, new_cmdline, &rc);
         if ( ( rc != 0 ) && ( rc != -1 ) )
         {
            free(new_cmdline);
            return(rc);
         }
      }

      *rcode = -errno; /* assume a load error */
      free(new_cmdline);
      return 0;
   }

#define STD_REDIR(hdl,dest,save) if ((hdl != -1) && (hdl != dest)) \
                                    { save = dup(dest); dup2(hdl, dest); }
#define STD_RESTORE(saved,dest) if (saved != -1) \
                                    { close(dest); dup2(saved,dest); \
                                      close(saved); }
#define SET_MAXHDL(hdl) if (hdl > max_hdls) max_hdls = hdl
#define SET_MAXHDLS(ep) SET_MAXHDL(ep.hdls[0]); SET_MAXHDL(ep.hdls[1])

                                        /* Force the standard redirections:  */
   STD_REDIR(env->input.hdls[0],    0, saved_in);
   STD_REDIR(env->output.hdls[1],   1, saved_out);
   if (env->error.SameAsOutput)
   {
      saved_err = dup(2);
      dup2(1, 2);
   }
   else
   {
      STD_REDIR(env->error.hdls[1], 2, saved_err);
   }

   /*
    * If the BROKEN_ADDRESS_COMMAND OPTION is in place,
    * and our environment is COMMAND, change it to SYSTEM
    */
   if ( env->subtype == SUBENVIR_PATH /* was SUBENVIR_COMMAND */
   &&   broken_address_command )
      subtype = SUBENVIR_SYSTEM;
   else
      subtype = env->subtype;
   rc = -1;

   switch (env->subtype)
   {
      case SUBENVIR_PATH:
#ifdef P_WAIT
# if defined(DOS) && !defined(__EMX__)
         args = makesimpleargs(cmdline);
# define NEED_MAKESIMPLEARGS
# else
         args = makeargs(cmdline, '\\');
# define NEED_MAKEARGS
# endif
         rc = spawnvp(P_WAIT, *args, args);
#else
         goto USE_SUBENVIR_SYSTEM;
#endif
         break;

      case SUBENVIR_COMMAND:
#ifdef P_WAIT
# if defined(DOS) && !defined(__EMX__)
         args = makesimpleargs(cmdline);
# else
         args = makeargs(cmdline, '\\');
# endif
         rc = spawnv(P_WAIT, *args, args);
#else
         goto USE_SUBENVIR_SYSTEM;
#endif
         break;

      case SUBENVIR_SYSTEM:
#ifndef P_WAIT
         USE_SUBENVIR_SYSTEM:
#endif
         rc = system(cmdline);
         break;

      case SUBENVIR_REXX:
         /* fall through */

      default: /* illegal subtype */
         STD_RESTORE(saved_in, 0);
         STD_RESTORE(saved_out, 1);
         STD_RESTORE(saved_err, 2);
#ifdef NEED_MAKEARGS
         if (args != NULL)
            destroyargs(args);
#define NEED_DESTROYARGS
#endif
         errno = EINVAL;
         rc = -1;
         break;
   }

   eno = errno;
   STD_RESTORE(saved_in, 0);
   STD_RESTORE(saved_out, 1);
   STD_RESTORE(saved_err, 2);
#ifdef NEED_MAKEARGS
   if (args != NULL)
      destroyargs(args);
#endif
   errno = eno;

   if ( rc == -1 )
      return(0);

   rc -= 0x4000; /* do a remap */
   if ( (rc == -1) || ( rc == 0 ) )
      rc = -0x4000 + 127;
   return rc;
#undef SET_MAXHDLS
#undef SET_MAXHDL
#undef STD_RESTORE
#undef STD_REDIR
}

/* __regina_wait waits for a process started by fork_exec.
 * In general, this is called after the complete IO to the called process but
 * it isn't guaranteed. Never call if you don't expect a sudden death of the
 * subprocess.
 * Returns the exit status of the subprocess under normal circumstances. If
 * the subprocess has died by a signal, the return value is -signalnumber.
 */
int __regina_wait(int process)
{
   return(process + 0x4000);
}

/* open_subprocess_connection acts like the unix-known function pipe and sets
 * ep->RedirectedFile if necessary. Just in the latter case ep->data
 * is set to the filename.
 * Close the handles with __regina_close later.
 * Do IO by using __regina_read() and __regina_write().
 */
int open_subprocess_connection(const tsd_t *TSD, environpart *ep)
{
   char *name;
   int eno;

   name = MallocTSD(REXX_PATH_MAX + 1);
   /* Remember to create two handles to be "pipe()"-conform. */
#define NEED_LOCAL_MKSTEMP
   if ((ep->hdls[0] = local_mkstemp(TSD, name)) == -1)
   {
      eno = errno;
      free( name );
      errno = eno;
      return(-1);
   }

   if ((ep->hdls[1] = dup(ep->hdls[0])) == -1)
   {
      eno = errno;
      close(ep->hdls[0]);
      ep->hdls[0] = -1;
      unlink(name);
      free(name);
      errno = eno;
      return(-1);
   }

   ep->FileRedirected = 1;
   ep->tempname = name;
   return(0);
}

/* sets the given handle to the non-blocking mode. The value may change.
 * async_info CAN be used to add the handle to the internal list of watched
 * handles.
 */
void unblock_handle( int *handle, void *async_info )
{
   (handle = handle);
   (async_info = async_info);
}

/* restart_file sets the file pointer of the given handle to the beginning.
 */
void restart_file(int hdl)
{
   lseek(hdl, 0l, SEEK_SET);
}

/* __regina_close acts like close() but closes a handle returned by
 * open_subprocess_connection.
 * async_info MAY be used to delete the handle from the internal list of
 * watched handles.
 */
int __regina_close(int handle, void *async_info)
{
   (async_info = async_info);
   return(close(handle));
}

/*
 * __regina_close_special acts like close() but closes any OS specific handle.
 * The close happens if the handle is not -1. A specific operation may be
 * associated with this. Have a look for occurances of "hdls[2]".
 */
void __regina_close_special( int handle )
{
   assert( handle == -1 );
}

/* __regina_read acts like read() but returns either an error (return code
 * == -errno) or the number of bytes read. EINTR and friends leads to a
 * re-read.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 */
int __regina_read(int hdl, void *buf, unsigned size, void *async_info)
{
   int done;

#ifdef EINTR
   do {
      done = read(hdl, buf, size);
   } while ((done == -1) && (errno == EINTR));
#else
   done = read(hdl, buf, size);
#endif

   if (done < 0)
   {
      done = errno;
      if (done == 0)      /* no error set? */
         done = EPIPE ;   /* good assumption */
#if defined(EWOULDBLOCK) && defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
      /* BSD knows this value with the same meaning as EAGAIN */
      if (done == EWOULDBLOCK)
         done = EAGAIN;
#endif
      return(-done); /* error */
   }

   return(done);
}

/* __regina_write acts like write() but returns either an error (return code
 * == -errno) or the number of bytes written. EINTR and friends leads to a
 * re-write.
 * use_blocked_io is a flag. If set, the handle is set to blocked IO and
 * we shall use blocked IO here.
 * The file must be flushed, if both buf and size are 0.
 */
int __regina_write(int hdl, const void *buf, unsigned size, void *async_info)
{
   int done;

   if ((buf == NULL) || (size == 0)) /* nothing to to for flushing buffers */
      return(0);

#ifdef EINTR
   do {
      done = write( hdl, buf, size ) ;
   } while ((done == -1) && (errno == EINTR));
#else
   done = write( hdl, buf, size ) ;
#endif

   if (done <= 0)
   {
      done = errno;
      if (done == 0)      /* no error set? */
         done = ENOSPC;   /* good assumption */
#if defined(EWOULDBLOCK) && defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
      /* BSD knows this value with the same meaning as EAGAIN */
      if (done == EWOULDBLOCK)
         done = EAGAIN;
#endif
      return(-done); /* error */
   }

   return(done);
}

/* create_async_info return an opaque structure to allow the process wait for
 * asyncronous IO. There are three IO slots (in, out, error) which can be
 * filled by add_waiter. The structure can be cleaned by reset_async_info.
 * The structure must be destroyed by delete_async_info.
 */
void *create_async_info(const tsd_t *TSD)
{
   (TSD = TSD);
   return(NULL);
}

/* delete_async_info deletes the structure created by create_async_info and
 * all of its components.
 */
void delete_async_info(void *async_info)
{
   (async_info = async_info);
}

/* reset_async_info clear async_info in such a way that fresh add_waiter()
 * calls can be performed.
 */
void reset_async_info(void *async_info)
{
   (async_info = async_info);
}

/* add_async_waiter adds a further handle to the asyncronous IO structure.
 * add_as_read_handle must be != 0 if the next operation shall be a
 * __regina_read, else it must be 0 for __regina_write.
 * Call reset_async_info before a wait-cycle to different handles and use
 * wait_async_info to wait for at least one IO-able handle.
 */
void add_async_waiter(void *async_info, int handle, int add_as_read_handle)
{
   (async_info = async_info);
   (handle = handle);
   (add_as_read_handle = add_as_read_handle);
}

/* wait_async_info waits for some handles to become ready. This function
 * returns if at least one handle becomes ready.
 * A handle can be added with add_async_waiter to the bundle of handles to
 * wait for.
 * No special handling is implemented if an asyncronous interrupt occurs.
 * Thus, there is no guarantee to have handle which works.
 */
void wait_async_info(void *async_info)
{
   (async_info = async_info);
}
#endif /* NEED_STUPID_DOSCMD */
/*****************************************************************************
 *****************************************************************************
 ** fork_exec and depending functions ends here ******************************
 *****************************************************************************
 *****************************************************************************/

#if defined(NEED_MAKEARGS) || defined(NEED_SPLITOFFARG)
/* nextarg parses source for the next argument in unix shell terms. If target
 * is given, it must consist of enough free characters to hold the result +
 * one byte for the terminator. If len != NULL it will become the length of
 * the string (which might not been return if target == NULL). The return value
 * is either NULL or a new start value for nextarg.
 * escape is the current escape value which should be used, must be set.
 */
static const char *nextarg(const char *source, unsigned *len, char *target,
                                                                   char escape)
{
   unsigned l;
   char c, term;

   if (len != NULL)
      *len = 0;
   if (target != NULL)
      *target = '\0';
   l = 0;  /* cached length */

   if (source == NULL)
      return(NULL);

   while (rx_isspace(*source)) /* jump over initial spaces */
      source++;
   if (*source == '\0')
      return(NULL);

   do {
      /* There's something to return. Check for delimiters */
      term = *source++;

      if ((term == '\'') || (term == '\"'))
      {
         while ((c = *source++) != term) {
            if (c == escape)
               c = *source++;
            if (c == '\0')  /* stray \ at EOS is equiv to normal EOS */
            {
               /* empty string is valid! */
               if (len != NULL)
                  *len = l;
               if (target != NULL)
                  *target = '\0';
               return(source - 1); /* next try returns NULL */
            }
            l++;
            if (target != NULL)
               *target++ = c;
         }
      }
      else /* whitespace delimiters */
      {
         c = term;
         while (!rx_isspace(c) && (c != '\'') && (c != '\"')) {
            if (c == escape)
               c = *source++;
            if (c == '\0')  /* stray \ at EOS is equiv to normal EOS */
            {
               /* at least a stray \ was found, empty string checked in
                * the very beginning.
                */
               if (len != NULL)
                  *len = l;
               if (target != NULL)
                  *target = '\0';
               return(source - 1); /* next try returns NULL */
            }
            l++;
            if (target != NULL)
               *target++ = c;
            c = *source++;
         }
         source--; /* undo the "wrong" character */
      }
   } while (!rx_isspace(*source));

   if (len != NULL)
      *len = l;
   if (target != NULL)
      *target = '\0';
   return(source);
}
#endif

#ifdef NEED_MAKEARGS
/* makeargs chops string into arguments and returns an array of x+1 strings if
 * string contains x args. The last argument is NULL. This function usually is
 * called from the subprocess if fork/exec is used.
 * Example: "xx y" -> { "xx", "y", NULL }
 * escape must be the escape character of the command line and is usually ^
 * or \
 */
static char **makeargs(const char *string, char escape)
{
   char **retval;
   const char *p;
   int i, argc = 0;
   unsigned size;

   p = string; /* count the number of strings */
   while ((p = nextarg(p, NULL, NULL, escape)) != NULL)
      argc++;
   if ((retval = malloc((argc + 1) * sizeof(char *))) == NULL)
      return(NULL);

   p = string; /* count each string length */
   for (i = 0; i < argc; i++)
   {
      p = nextarg(p, &size, NULL, escape);
      if ((retval[i] = malloc(size + 1)) == NULL)
      {
         i--;
         while (i >= 0)
            free(retval[i--]);
         free(retval);
         return(NULL);
      }
   }

   p = string; /* assign each string */
   for (i = 0; i < argc; i++)
      p = nextarg(p, NULL, retval[i], escape);
   retval[argc] = NULL;

   return(retval);
}
#endif

#ifdef NEED_SPLITOFFARG
/* splitoffarg chops string into two different pieces: The first argument and
 * all other (uninterpreted) arguments. The first argument is returned in a
 * freshly allocated string. The rest is a pointer somewhere within string
 * and returned in *trailer.
 * Example: "xx y" -> returns "xx", *trailer == "xx y"+2
 * escape must be the escape character of the command line and is usually ^
 * or \
 */
static char *splitoffarg(const char *string, const char **trailer, char escape)
{
   unsigned size;
   char *retval;
   const char *t;

   if (trailer != NULL)
      *trailer = ""; /* just a default */
   nextarg(string, &size, NULL, escape);
   if ((retval = malloc(size + 1)) == NULL)
      return(NULL);

   t = nextarg(string, NULL, retval, escape);
   if (trailer != NULL)
      *trailer = t;
   return(retval);
}
#endif

#ifdef NEED_MAKESIMPLEARGS
/* nextarg parses source for the next argument as a simple word. If target
 * is given, it must consist of enough free characters to hold the result +
 * one byte for the terminator. If len != NULL it will become the length of
 * the string (which might not been return if target == NULL). The return value
 * is either NULL or a new start value for nextarg.
 */
static const char *nextsimplearg(const char *source, unsigned *len,
                                                                  char *target)
{
   unsigned l;
   char c, term;

   if (len != NULL)
      *len = 0;
   if (target != NULL)
      *target = '\0';
   l = 0;  /* cached length */

   if (source == NULL)
      return(NULL);

   while (rx_isspace(*source)) /* jump over initial spaces */
      source++;
   if (*source == '\0')
      return(NULL);

   c = *source++;

   while (!rx_isspace(c))
   {
      if (c == '\0')  /* stray \ at EOS is equiv to normal EOS */
      {
         /* something's found, therefore we don't have to return NULL */
         if (len != NULL)
            *len = l;
         if (target != NULL)
            *target = '\0';
         return(source - 1); /* next try returns NULL */
      }
      l++;
      if (target != NULL)
         *target++ = c;
      c = *source++;
   }
   source--; /* undo the "wrong" character */

   if (len != NULL)
      *len = l;
   if (target != NULL)
      *target = '\0';
   return(source);
}

/* makesimpleargs chops string into arguments and returns an array of x+1
 * strings if string contains x args. The last argument is NULL. This function
 * usually is called from the subprocess if fork/exec is used.
 * Example: "xx y" -> { "xx", "y", NULL }
 */
static char **makesimpleargs(const char *string)
{
   char **retval;
   const char *p;
   int i, argc = 0;
   unsigned size;

   p = string; /* count the number of strings */
   while ((p = nextsimplearg(p, NULL, NULL)) != NULL)
      argc++;
   if ((retval = malloc((argc + 1) * sizeof(char *))) == NULL)
      return(NULL);

   p = string; /* count each string length */
   for (i = 0; i < argc; i++)
   {
      p = nextsimplearg(p, &size, NULL);
      if ((retval[i] = malloc(size + 1)) == NULL)
      {
         i--;
         while (i >= 0)
            free(retval[i--]);
         free(retval);
         return(NULL);
      }
   }

   p = string; /* assign each string */
   for (i = 0; i < argc; i++)
      p = nextsimplearg(p, NULL, retval[i]);

   return(retval);
}
#endif

#ifdef NEED_DESTROYARGS
/* destroyargs destroys the array created by makeargs */
static void destroyargs(char **args)
{
   char **run = args;

   while (*run) {
      free(*run);
      run++;
   }
   free(args);
}
#endif

#ifdef NEED_LOCAL_MKSTEMP
/* local_mkstemp() works mostly like the commands
 * strcpy(base, system_specific_temppath), mkstemp( TSD, base);
 * mkstemp opens a newly created file and returns its name in "base".
 * The handle of the file is the function return value. The function
 * returns -1 if an error occurs. Use the errno value in this case.
 *
 * The handle is at least suitable for fork_exec(), __regina_read(),
 * __regina_write() and __regina_close().
 * base should have REXX_PATH_MAX characters.
 * Be careful: Don't forget to delete the file afterwards.
 */
static int local_mkstemp(const tsd_t *TSD, char *base)
{
#ifndef S_IRWXU
# define S_IRWXU (_S_IREAD|_S_IWRITE)
#endif
#ifdef HAVE_MKSTEMP
   /* We are using a unix system. We either have mkstemp or you
    * should enable the above code.
    */
   strcpy(base, "/tmp/rxXXXXXX");
   return(mkstemp(base));
#else
#define MAGIC_MAX 2000000 /* Much beyond maximum, see below */
   static volatile unsigned BaseIndex = MAGIC_MAX;
   int retval;
   char *slash;
   char buf[REXX_PATH_MAX]; /* enough space for largest path name */
   unsigned i;
   unsigned start,run;

   if ( mygetenv( TSD, "TMP", buf, sizeof(buf) ) == NULL)
   {
      if ( mygetenv( TSD, "TEMP", buf, sizeof(buf) ) == NULL)
      {
         if ( mygetenv( TSD, "TMPDIR", buf, sizeof(buf) ) == NULL)
         {
#ifdef UNIX
            strcpy(buf,"/tmp");
#else
            strcpy(buf,"C:");
#endif
         }
      }
   }

   if (strlen(buf) > REXX_PATH_MAX - 14 /* 8.3 + "\0" + ISLASH */)
      buf[REXX_PATH_MAX - 14] = '\0';

   if ( buf[strlen(buf)-1] != I_SLASH )
      slash = ISTR_SLASH;
   else
      slash = "";

   /* algorithm:
    * select a random number, e.g. a mixture of pid, tid and time.
    * increment this number by a fixed amount until we reach the starting
    * value again. Do a wrap around and an increment which is a unique prime.
    * The number 1000000 has the primes 2 and 5. We may use all primes
    * except 2 and 5; 9901 (which is prime) will give a good distribution.
    *
    * We want to be able to create several temporary files at once without
    * more OS calls than needed. Thus, we have a program wide runner to
    * ensure a simple distribution without strength.
    */
   if (BaseIndex == MAGIC_MAX)
   {
      /*
       * We have to create (nearly) reentrant code.
       */
      i = (unsigned) getpid() * (unsigned) time(NULL);
      i %= 1000000;
      if (!i)
         i = 1;
      BaseIndex = i;
   }
   if (++BaseIndex >= 1000000)
      BaseIndex = 1;

   start = TSD->thread_id;
   if (start == 0)
      start = 999999;
   start *= (unsigned) (clock() + 1);
   start *= BaseIndex;
   start %= 1000000;

   strcat( buf, slash );
   slash = buf + strlen( buf );
   run = start;
   for (i = 0;i <= 1000000;i++)
   {
      /* form a name like "c:\temp\345302._rx" or "/tmp/345302._rx" */
      /*
       * fixes Bug 587687
       */
      sprintf( slash, "%06u._rx", run );
#if defined(_MSC_VER) /* currently not used but what's about CE ? */
      retval = _sopen(buf,
                      _O_RDWR|_O_CREAT|_O_BINARY|_O_SHORT_LIVED|_O_EXCL|
                                                                 _O_SEQUENTIAL,
                      SH_DENYRW,
                      S_IRWXU);
#else
      retval = open(buf,
                    O_RDWR|O_CREAT|O_EXCL
# if defined(O_NOCTTY)
                    |O_NOCTTY
# endif
                    ,
                    S_IRWXU);
#endif
      if (retval != -1) /* success */
      {
         strcpy(base,buf);
         return(retval);
      }
      /* Check for a true failure */
      if (errno != EEXIST)
         break;

      /* Check the next possible candidate */
      run += 9901;
      run %= 1000000;
      if (run == start) /* paranoia check. i <= 1000000 should hit exactly */
         break;         /* here */
   }
   return( -1 ); /* pro forma */
#undef MAGIC_MAX
#endif /* HAVE_MKSTEMP */
}
#endif /* LOCAL_MKSTEMP */

# ifdef NEED_UNAME
/********************************************************* MH 10-06-96 */
int uname(struct utsname *name)                         /* MH 10-06-96 */
/********************************************************* MH 10-06-96 */
{                                                       /* MH 10-06-96 */
#  if defined (WIN32)
 SYSTEM_INFO sysinfo;
 OSVERSIONINFO osinfo;
 char computername[MAX_COMPUTERNAME_LENGTH+1];
 char *pComputerName=computername;
 DWORD namelen=MAX_COMPUTERNAME_LENGTH+1;
#  endif
/*
 * Set up values for utsname structure...
 */
#  if defined(OS2)
 strcpy( name->sysname, "OS2" );
 sprintf( name->version, "%d" ,_osmajor );
 sprintf( name->release, "%d" ,_osminor );
 strcpy( name->nodename, "standalone" );
 strcpy( name->machine, "i386" );
#  elif defined(_AMIGA)
 strcpy( name->sysname, "AMIGA" );
 sprintf( name->version, "%d", 0 );
 sprintf( name->release, "%d", 0 );
 strcpy( name->nodename, "standalone" );
 strcpy( name->machine, "m68k" );
#  elif defined(MAC)
 strcpy( name->sysname, "MAC" );
 sprintf( name->version, "%d", 0 );
 sprintf( name->release, "%d", 0 );
 strcpy( name->nodename, "standalone" );
 strcpy( name->machine, "m68k" );
#  elif defined(__WINS__) || defined(__EPOC32__)
 epoc32_uname( name );
#  elif defined(WIN32)
 osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
 GetVersionEx( &osinfo );
 sprintf( name->version, "%d", osinfo.dwMajorVersion );
 sprintf( name->release, "%d", osinfo.dwMinorVersion );

 /* get specific OS version... */
 switch( osinfo.dwPlatformId )
 {
    case VER_PLATFORM_WIN32s:
       strcpy( name->sysname, "WIN32S" );
       break;
    case VER_PLATFORM_WIN32_WINDOWS:
       if ( osinfo.dwMinorVersion >= 90 )
          strcpy( name->sysname, "WINME" );
       else if ( osinfo.dwMinorVersion >= 10 )
          strcpy( name->sysname, "WIN98" );
       else
          strcpy( name->sysname, "WIN95" );
       break;
    case VER_PLATFORM_WIN32_NT:
       if ( osinfo.dwMajorVersion == 4 )
          strcpy( name->sysname, "WINNT" );
       else if ( osinfo.dwMajorVersion == 5 )
       {
          if ( osinfo.dwMinorVersion == 1 )
             strcpy( name->sysname, "WINXP" );
          else
             strcpy( name->sysname, "WIN2K" );
       }
       else
          strcpy( name->sysname, "UNKNOWN" );
       break;
    default:
       strcpy( name->sysname, "UNKNOWN" );
       break;
 }
 /*
  * get name of computer if possible.
  */
 if ( GetComputerName(pComputerName, &namelen) )
    strcpy( name->nodename, pComputerName );
 else
    strcpy( name->nodename, "UNKNOWN" );
 GetSystemInfo( &sysinfo );
 switch( sysinfo.dwProcessorType )
 {
    case PROCESSOR_INTEL_386:
       strcpy( name->machine, "i386" );
       break;
    case PROCESSOR_INTEL_486:
       strcpy( name->machine, "i486" );
       break;
    case PROCESSOR_INTEL_PENTIUM:
       strcpy( name->machine, "i586" );
       break;
#if 0
    case PROCESSOR_INTEL_MIPS_R4000:
       strcpy( name->machine, "mipsR4000" );
       break;
    case PROCESSOR_INTEL_ALPHA_21064:
       strcpy( name->machine, "alpha21064" );
       break;
#endif
 }
#  endif /* WIN32 */

 return(0);
}
# endif /* NEED_UNAME */