File: pl-file.c

package info (click to toggle)
swi-prolog 3.1.0-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 8,772 kB
  • ctags: 12,869
  • sloc: ansic: 43,657; perl: 12,577; lisp: 4,359; sh: 1,534; makefile: 798; awk: 14
file content (2375 lines) | stat: -rw-r--r-- 46,115 bytes parent folder | download | duplicates (2)
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
/*  pl-file.c,v 1.22 1994/04/11 08:37:36 jan Exp

    Copyright (c) 1990 Jan Wielemaker. All rights reserved.
    See ../LICENCE to find out about your rights.
    jan@swi.psy.uva.nl

    Purpose: file system i/o
*/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This module is far too big.  It defines a layer around open(), etc.   to
get  opening  and  closing  of  files to the symbolic level required for
Prolog.  It also defines basic I/O  predicates,  stream  based  I/O  and
finally  a  bundle  of  operations  on  files,  such  as name expansion,
renaming, deleting, etc.  Most of this module is rather straightforward.

If time is there I will have a look at all this to  clean  it.   Notably
handling times must be cleaned, but that not only holds for this module.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#if defined(__WINDOWS__) || defined(__NT__)
#include "windows.h"
#undef FD_SET
#undef FD_ISSET
#undef FD_ZERO
#endif

#include "pl-incl.h"
#include "pl-ctype.h"
#ifdef __WIN32__
#include <console.h>
#endif

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_BSTRING_H
#include <bstring.h>
#endif

#define ST_TERMINAL 0			/* terminal based stream */
#define ST_FILE	    1			/* File bound stream */
#define ST_PIPE	    2			/* Pipe bound stream */
#define ST_STRING   3			/* String bound stream */

					/* openStream() flags */
#define OPEN_OPEN   0x1			/* Open for open/[3,4] */
#define OPEN_TEXT   0x2			/* Open in text-mode */

typedef struct plfile *	PlFile;

static struct plfile
{ atom_t	name;			/* name of file */
  atom_t	stream_name;		/* stream identifier name */
  IOSTREAM *	stream;			/* IOSTREAM package descriptor */
  char		status;			/* F_CLOSED, F_READ, F_WRITE */
  char		type;			/* ST_FILE, ST_PIPE, ST_STRING */
} *fileTable = (PlFile) NULL;		/* Our file table */

int 	Input;				/* current input */
int	Output;				/* current output */

ttybuf	ttytab;				/* saved terminal status on entry */
int	ttymode;			/* Current tty mode */

static atom_t prompt_atom;		/* current prompt */
static char *first_prompt;		/* First-line prompt */
static int first_prompt_used;		/* flag */
static int protocolStream = -1;		/* doing protocolling on stream <n> */

static int   maxfiles;			/* maximum file index */

typedef struct input_context * InputContext;
typedef struct output_context * OutputContext;

static struct input_context
{ int		stream;			/* pushed input */
  atom_t	term_file;		/* old term_position file */
  int		term_line;		/* old term_position line */
  InputContext	previous;		/* previous context */
} *input_context_stack = NULL;

static struct output_context
{ int		stream;			/* pushed input */
  OutputContext previous;		/* previous context */
} *output_context_stack = NULL;

forwards bool	openStream(term_t file, int mode, int flags);
forwards bool	closeStream(int);
forwards bool	unifyStreamName(term_t, int);
forwards bool	unifyStreamNo(term_t, int);
forwards bool	setUnifyStreamNo(term_t, int);
forwards bool	unifyStreamMode(term_t, int);
forwards int	Get0();

static jmp_buf pipe_context;		/* jmp buffer for pipe operations */
static int inpipe;			/* doing a pipe operation */


#ifdef SIGPIPE
static void
pipeHandler(int sig)
{ if ( inpipe )
  { longjmp(pipe_context, 1);
  }

  warning("Broken pipe\n");		/* Unexpected broken pipe */
  pl_abort();

  signal(SIGPIPE, SIG_DFL);		/* should abort fail. */
  kill(getpid(), SIGPIPE);		/* Unix has both pipes and kill() */
}
#endif /* SIGPIPE */

static void
brokenPipe(int n, atom_t rw)
{ term_t stream = PL_new_term_ref();
  IOSTREAM *s;

  if ( (s = fileTable[n].stream) )
    s->bufp = s->buffer;		/* avoid flush on close! */

  unifyStreamNo(stream, n);

  if ( rw == ATOM_write && n == Output )
    Output = 1;

  PL_error(NULL, 0, "Broken pipe", ERR_STREAM_OP, rw, stream);
}

#define TRYPIPE(no, rw, code, err) \
	if ( fileTable[(no)].type == ST_PIPE ) \
	{ if ( setjmp(pipe_context) != 0 ) \
	  { inpipe--; \
	    brokenPipe(no, rw); \
	    err; \
	  } else \
	  { inpipe++; \
	    code; \
	    inpipe--; \
	  } \
	} else \
	{ code; \
	}


void
initIO(void)
{ int n;

  fileerrors = TRUE;
  if ( maxfiles != getdtablesize() )
  { if ( fileTable != (PlFile) NULL )
      freeHeap(fileTable, sizeof(struct plfile) * maxfiles);
    maxfiles = getdtablesize();
    fileTable = allocHeap(sizeof(struct plfile) * maxfiles);
  }

#ifdef __unix__
  if ( !isatty(0) || !isatty(1) )	/* Sinput is not a tty */
    GD->cmdline.notty = TRUE;
#endif

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Initilise user input, output and error  stream.   How  to do this neatly
without the Unix assumptions?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

  for(n=0; n<maxfiles; n++)
  { PlFile f = &fileTable[n];

    switch(n)
    { case 0:
	f->name	          = ATOM_user;
	f->stream_name    = ATOM_user_input;
	f->stream         = Sinput;
	f->status         = F_READ;
	f->type	          = ST_TERMINAL;
	break;
      case 1:
	f->name           = ATOM_user;
	f->stream_name    = ATOM_user_output;
	f->stream         = Soutput;
	f->status         = F_WRITE;
	f->type	          = ST_TERMINAL;
	break;
      case 2:
	f->name           = ATOM_stderr;
	f->stream_name    = ATOM_user_error;
	f->stream         = Serror;
	f->status         = F_WRITE;
	f->type	          = ST_TERMINAL;
	break;
      default:
	f->name           = NULL_ATOM;
        f->stream         = NULL_ATOM;
	f->type           = ST_FILE;
	f->status         = F_CLOSED;
    }
  }

  ResetTty();
  Sinput->position  = &Sinput->posbuf;	/* position logging */
  Soutput->position = &Sinput->posbuf;
  Serror->position  = &Sinput->posbuf;

  ttymode = TTY_COOKED;
  PushTty(&ttytab, TTY_SAVE);

  Input = 0;
  Output = 1;

  if ( prompt_atom == NULL_ATOM )
    prompt_atom = ATOM_prompt;
}


void
dieIO()
{ if ( GD->io_initialised )
  { pl_noprotocol();
    closeFiles(TRUE);
    PopTty(&ttytab);
  }
}


static bool
closeStream(int n)
{ PlFile f = &fileTable[n];

  if ( f->stream )
  { switch(n)
    { case 0:
	Sclearerr(f->stream);
        break;
      case 1:
      case 2:
	Sflush(f->stream);
        break;
      default:
	if ( f->status == F_WRITE )
	{ TRYPIPE(n, ATOM_write, Sclose(f->stream), (void)0);
	} else
	  Sclose(f->stream);
        f->stream = NULL_ATOM;
	f->name   = NULL_ATOM;
	f->status = F_CLOSED;
	break;
    }
  }

  succeed;
}


void
closeFiles(int all)
{ volatile int n;
#if O_PCE
  extern int read_nesting;
  read_nesting = 0;
#endif

  for(n=0; n<maxfiles; n++)
  { IOSTREAM *s;

    if ( (s=fileTable[n].stream) )
    { if ( all || !(s->flags & SIO_NOCLOSE) )
	closeStream(n);
      else if ( fileTable[n].status == F_WRITE )
      {	TRYPIPE(n, ATOM_write, Sflush(s), (void)0);
      }
    }
  }

  Input = 0;
  Output = 1;
}


void
protocol(char *s, int n)
{ if ( protocolStream >= 0 )
  { int out;
  
    out = Output;
    Output = protocolStream;
    for( ; n > 0; s++, n--)
      Put((int)*s & 0xff);
    Output = out;
  }
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
push/popInputContext() maintain the source_location   info  over see(X),
..., seen(X). This is very  hairy.   Note  the common seeing(O), see(N),
..., seen, see(O) construct. To fix this   one, see/1 will only push the
context if it concerns a new stream and seen() will only pop if it is an
open stream.

Should be fixed decently if we redesign all of I/O stream management.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static void
pushInputContext()
{ InputContext c = allocHeap(sizeof(struct input_context));

  c->stream           = Input;
  c->term_file        = source_file_name;
  c->term_line        = source_line_no;
  c->previous         = input_context_stack;
  input_context_stack = c;
}


static void
popInputContext()
{ InputContext c = input_context_stack;

  if ( c )
  { Input               = c->stream;
    source_file_name    = c->term_file;
    source_line_no      = c->term_line;
    input_context_stack = c->previous;
    freeHeap(c, sizeof(struct input_context));
  } else
    Input = 0;
}

static void
pushOutputContext()
{ OutputContext c = allocHeap(sizeof(struct output_context));

  c->stream            = Output;
  c->previous          = output_context_stack;
  output_context_stack = c;
}


static void
popOutputContext()
{ OutputContext c = output_context_stack;

  if ( c )
  { Output               = c->stream;
    output_context_stack = c->previous;
    freeHeap(c, sizeof(struct output_context));
  } else
    Output = 0;
}


int
currentLinePosition()
{ IOSTREAM *stream = fileTable[Output].stream;

  if ( stream && stream->position )
    return stream->position->linepos;

  return 0;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Get a single character from the terminal without waiting for  a  return.
The  character  should  not  be  echoed.   If  GD->cmdline.notty is true this
function will read the first character and then skip all character  upto
and including the newline.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

int
getSingleChar(void)
{ int c;
  int OldIn = Input;
  ttybuf buf;
  IOSTREAM *stream;
    
  Input = 0;
  stream = fileTable[Input].stream;
  debugstatus.suspendTrace++;
  pl_ttyflush();
  PushTty(&buf, TTY_RAW);		/* just donot prompt */
  
  if ( GD->cmdline.notty )
  { Char c2;

    c2 = Get0();
    while( c2 == ' ' || c2 == '\t' )	/* skip blanks */
      c2 = Get0();
    c = c2;
    while( c2 != EOF && c2 != '\n' )	/* read upto newline */
      c2 = Get0();
  } else
  { if ( stream->position )
    { IOPOS oldpos = *stream->position;
      c = Get0();
      *stream->position = oldpos;
    } else
      c = Get0();
  }

  if ( c == 4 || c == 26 )		/* should ask the terminal! */
    c = -1;

  PopTty(&buf);
  debugstatus.suspendTrace--;
  Input = OldIn;

  return c;
}


word
pl_rawtty(term_t goal)
{ bool rval;
  int OldIn = Input;
  ttybuf buf;
    
  Input = 0;
  debugstatus.suspendTrace++;
  pl_ttyflush();
  PushTty(&buf, TTY_RAW);

  rval = callProlog(NULL, goal, FALSE);

  PopTty(&buf);
  debugstatus.suspendTrace--;

  Input = OldIn;

  return rval;
}


#ifndef DEL
#define DEL 127
#endif

bool
readLine(char *buffer)
{ int oldin = Input;
  int oldout = Output;
  int c;
  char *buf = &buffer[strlen(buffer)];
  ttybuf tbuf;

  Input = 0;
  Output = 1;
  if ( !GD->cmdline.notty )
    PushTty(&tbuf, TTY_RAW);		/* just donot prompt */

  for(;;)
  { pl_flush();

    switch( (c=Get0()) )
    { case '\n':
      case '\r':
      case EOF:
        *buf++ = EOS;
        Input = oldin;
	Output = oldout;
	if ( !GD->cmdline.notty )
	  PopTty(&tbuf);

	return c == EOF ? FALSE : TRUE;
      case '\b':
      case DEL:
	if ( !GD->cmdline.notty && buf > buffer )
	{ Putf("\b \b");
	  buf--;
	}
      default:
	if ( !GD->cmdline.notty )
	  Put(c);
	*buf++ = c;
    }
  }
}


bool
LockStream()
{ IOSTREAM *s = fileTable[Output].stream;

  return (s && Slock(s) < 0) ? FALSE : TRUE;
}


bool
UnlockStream()
{ IOSTREAM *s = fileTable[Output].stream;

  return (s && Sunlock(s) < 0) ? FALSE : TRUE;
}


bool
Put(int c)
{ IOSTREAM *s = fileTable[Output].stream;
  int rval;

  if ( !s )
    fail;

  TRYPIPE(Output, ATOM_write, rval = Sputc(c, s), rval = -1);

  return rval < 0 ? FALSE : TRUE;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PutOpenToken() inserts a space in the output stream if the last-written
and given character require a space to ensure a token-break.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

bool
PutOpenToken(int c)
{ IOSTREAM *s = fileTable[Output].stream;
  
  if ( c == EOF )
  { s->lastc = EOF;
    succeed;
  }

  if ( s->lastc != EOF &&
       ((isAlpha(s->lastc) && isAlpha(c)) ||
	(isSymbol(s->lastc) && isSymbol(c)) ||
	c == '(') )
    return Put(' ');

  succeed;
}


bool
Puts(const char *str)
{ IOSTREAM *s = fileTable[Output].stream;
  int rval;

  if ( !s )
    fail;

  TRYPIPE(Output, ATOM_write, rval = Sfputs(str, s), rval = -1);

  return rval < 0 ? FALSE : TRUE;
}


word
Putf(char *fm, ...)
{ IOSTREAM *s = fileTable[Output].stream;
  va_list args;
  int rval;

  if ( !s )
    fail;

  va_start(args, fm);
  TRYPIPE(Output, ATOM_write, rval = Svfprintf(s, fm, args), rval = -1);
  va_end(args);

  return rval < 0 ? FALSE : TRUE;
}


static int
Get0()
{ IOSTREAM *s = fileTable[Input].stream;
  int c;
  
  if ( s )
  { TRYPIPE(Input, ATOM_read, c=Sgetc(s), c=EOF);
    
    if ( c == EOF && Sfpasteof(s) )
    { term_t stream = PL_new_term_ref();

      unifyStreamNo(stream, Input);
      PL_error(NULL, 0, NULL, ERR_PERMISSION,
	       ATOM_input, ATOM_past_end_of_stream, stream);
    }
  } else
    c = EOF;

  return c;
}


IOSTREAM *
PL_current_input()
{ return fileTable[Input].stream;
}


IOSTREAM *
PL_current_output()
{ return fileTable[Output].stream;
}


word
pl_dup_stream(term_t from, term_t to)
{ int fn, tn;
  PlFile f, t;

  if ( (fn = streamNo(from, F_ANY)) < 0 ||
       (tn = streamNo(to, F_ANY)) < 0 )
    fail;

  f = &fileTable[fn];
  t = &fileTable[tn];

  t->stream = f->stream;
  t->status = f->status;
  t->type   = f->type;

  succeed;
}


bool
PL_open_stream(term_t handle, IOSTREAM *s)
{ int n;
  PlFile f;

  for(n=3, f=&fileTable[n]; n<maxfiles; n++, f++)
  { if ( !f->stream )
    { f->stream = s;
      f->name   = NULL_ATOM;
      f->type   = ST_FILE;
      if ( s->flags & SIO_INPUT )
	f->status = F_READ;
      else
	f->status = F_WRITE;

      return setUnifyStreamNo(handle, n);
    }
  }

  return PL_error(NULL, 0, NULL, ERR_REPRESENTATION, ATOM_max_files);
}


static bool
openStream(term_t file, int mode, int flags)
{ int n;
  IOSTREAM *stream;
  char cmode[3];
  atom_t name;
  functor_t f;
  int type;

  DEBUG(2, Sdprintf("openStream file=0x%lx, mode=%d\n", file, mode));

  if ( PL_get_atom(file, &name) )
  { type = ST_FILE;
  } else if ( PL_get_functor(file, &f) && f == FUNCTOR_pipe1)
  {
#ifdef SIGPIPE
    term_t an = PL_new_term_ref();
    type = ST_PIPE;
    
    if ( !PL_get_arg(1, file, an) ||
	 !PL_get_atom(an, &name) )
      return PL_error(NULL, 0, NULL, ERR_DOMAIN, ATOM_source_sink, file);

    signal(SIGPIPE, pipeHandler);
#else
    return PL_error(NULL, 0, NULL, ERR_NOTIMPLEMENTED, ATOM_pipe);
#endif /*SIGPIPE*/
  } else
    return PL_error(NULL, 0, NULL, ERR_DOMAIN, ATOM_source_sink, file);

  DEBUG(3, Sdprintf("File/command name = %s\n", stringAtom(name)));
  if ( type == ST_FILE )
  { if ( mode == F_READ )
    { if ( name == ATOM_user || name == ATOM_user_input )
      { Input = 0;
	succeed;
      }
    } else
    { if ( name == ATOM_user || name == ATOM_user_output )
      { Output = 1;
        succeed;
      }
      if ( name == ATOM_user_error || name == ATOM_stderr )
      { Output = 2;
	succeed;
      }
    }
  } else if ( type == ST_PIPE && (mode == F_APPEND || mode == F_WRNOTRUNC) )
  { term_t tmp = PL_new_term_ref();
    
    PL_put_atom(tmp, (mode == F_APPEND ? ATOM_append : ATOM_update));
    return PL_error(NULL, 0, NULL, ERR_DOMAIN, ATOM_io_mode, tmp);
  }
    
  if ( !(flags & OPEN_OPEN) )		/* see/1, tell/1, append/1 */
  { for( n=0; n<maxfiles; n++ )
    { if ( fileTable[n].name == name && fileTable[n].type == type )
      { if ( fileTable[n].status == mode )
	{ switch(mode)
	  { case F_READ:	Input = n; break;
	    case F_WRITE:
	    case F_WRNOTRUNC:
	    case F_APPEND:	Output = n; break;
	  }
	  DEBUG(3, Sdprintf("Switched back to already open stream %d\n", n));
	  succeed;
	} else
	{ closeStream(n);
	}
	break;
      }
    }

    if ( mode == F_READ )
      pushInputContext();		/* see/1 to a new file */
  }

  DEBUG(2, Sdprintf("Starting Unix open\n"));
  cmode[0] = FOPENMODE[mode];
  if ( flags & OPEN_TEXT )
    cmode[1] = EOS;
  else
  { cmode[1] = 'b';
    cmode[2] = EOS;
  }

#ifdef HAVE_POPEN
  if ( type == ST_PIPE )
  { if ( !(stream=Sopen_pipe(stringAtom(name), cmode)) )
      goto err;
  } else
#endif /*HAVE_POPEN*/
  { char *fn;
    char tmp[MAXPATHLEN];

    if ( !(fn = ExpandOneFile(stringAtom(name), tmp)) )
      fail;

    if ( !(stream=Sopen_file(fn, cmode)) )
    {
#ifdef HAVE_POPEN
      err:
#endif
      if ( fileerrors )
      { PL_error(NULL, 0, OsError(), ERR_FILE_OPERATION,
		 ATOM_open, ATOM_source_sink, file);
      }
      fail;
    }
  }

  for(n=3; n<maxfiles; n++)
  { if ( !fileTable[n].stream )
      break;
  }
  if ( n >= maxfiles )			/* non-ISO */
    return PL_error(NULL, 0, NULL, ERR_REPRESENTATION, ATOM_max_files);

  fileTable[n].name        = name;
  fileTable[n].stream_name = NULL_ATOM;
  fileTable[n].type        = type;
  fileTable[n].stream      = stream;

  switch(mode)
  { case F_READ:
      Input = n; break;
    case F_WRITE:
    case F_WRNOTRUNC:
    case F_APPEND:
      mode = F_WRITE;
      Output = n; break;
  }
  fileTable[n].status = mode;

  DEBUG(2, Sdprintf("Prolog fileTable[] updated\n"));

  succeed;
}


static bool
unifyStreamName(term_t f, int n)
{ if ( fileTable[n].status == F_CLOSED )
    fail;

  if ( !(PL_is_variable(f) || PL_is_atom(f)) )
    return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_variable, f);

#ifdef HAVE_POPEN
  if ( fileTable[n].type == ST_PIPE )
  { return PL_unify_term(f,
			 PL_FUNCTOR, FUNCTOR_pipe1,
			   PL_ATOM, fileTable[n].name);
  }
#endif /*HAVE_POPEN*/

  return PL_unify_atom(f, fileTable[n].name);
}


static bool
unifyStreamMode(term_t m, int n)
{ if ( fileTable[n].status == F_CLOSED )
    fail;

  return PL_unify_atom(m, fileTable[n].status == F_READ ? ATOM_read
							: ATOM_write);
}


static bool
unifyStreamNo(term_t stream, int n)
{ atom_t name;

  switch( n )
  { case 0:
      name = ATOM_user_input;
      break;
    case 1:
      name = ATOM_user_output;
      break;
    case 2:
      name = ATOM_user_error;
      break;
    default:
      if ( fileTable[n].stream_name )
	name = fileTable[n].stream_name;
      else
	return PL_unify_integer(stream, n);
  }

  return PL_unify_atom(stream, name);
}


word
pl_told()
{ if ( fileTable[Output].status != F_WRITE )
    succeed;

  closeStream(Output);

  Output = 1;
  succeed;
}  


word
pl_flush()
{ IOSTREAM *s;

  if ( fileTable[Output].status == F_WRITE &&
       (s=fileTable[Output].stream) )
  { TRYPIPE(Output, ATOM_write, Sflush(s), fail);
  }

  succeed;
}


word
pl_see(term_t f)
{ return openStream(f, F_READ, OPEN_TEXT);
}


word
pl_seen()
{ if ( fileTable[Input].status != F_READ )
    succeed;

  closeStream(Input);
  popInputContext();

  succeed;
}


static word
openProtocol(term_t f, bool appnd)
{ int out = Output;

  pl_noprotocol();

  if ( openStream(f, appnd ? F_APPEND : F_WRITE, OPEN_TEXT|OPEN_OPEN) )
  { IOSTREAM *s = fileTable[Output].stream;

    s->flags |= SIO_NOCLOSE;
    protocolStream = Output;
    Output = out;

    succeed;
  }
  Output = out;

  fail;
}


word
pl_noprotocol()
{ if ( protocolStream >= 0 )
  { closeStream(protocolStream);
    protocolStream = -1;
  }

  succeed;
}


		/********************************
		*          STRING I/O           *
		*********************************/


bool
seeString(char *s)
{ IOSTREAM *stream = Sopen_string(NULL, s, -1, "r");
  PlFile f;
  int n;
  
  for(n=3, f=&fileTable[n]; n<maxfiles; n++, f++)
  { if ( !f->stream )
    { f->stream = stream;
      f->name   = NULL_ATOM;
      f->status = F_READ;
      f->type   = ST_STRING;

      pushInputContext();
      Input = n;
      succeed;
    }
  }

  return PL_error(NULL, 0, NULL, ERR_REPRESENTATION, ATOM_max_files);
}


bool
seeingString()
{ return fileTable[Input].type == ST_STRING;
}


bool
seenString()
{ PlFile f = &fileTable[Input];

  if ( f->type == ST_STRING && f->stream )
  { Sclose(f->stream);
    f->stream = NULL;
    f->status = F_CLOSED;
    popInputContext();
  }

  succeed;
}


bool
tellString(char **s, int size)
{ static int sbuf;
  IOSTREAM *stream;
  PlFile f;
  int n;
  
  sbuf = size;
  stream = Sopenmem(s, &sbuf, "w");
 
  for(n=3, f=&fileTable[n]; n<maxfiles; n++, f++)
  { if ( !f->stream )
    { f->stream = stream;
      f->name   = NULL_ATOM;
      f->status = F_WRITE;
      f->type   = ST_STRING;

      pushOutputContext();
      Output = n;
      succeed;
    }
  }

  return PL_error(NULL, 0, NULL, ERR_REPRESENTATION, ATOM_max_files);
}


bool
toldString()
{ PlFile f = &fileTable[Output];

  if ( f->type == ST_STRING && f->stream )
  { Sputc(EOS, f->stream);
    Sclose(f->stream);
    f->stream = NULL;
    f->status = F_CLOSED;
    popOutputContext();
  }

  succeed;
}


		/********************************
		*        INPUT IOSTREAM NAME    *
		*********************************/

atom_t
currentStreamName()			/* only if a file! */
{ PlFile f = &fileTable[Input];

  if ( f->type == ST_FILE || f->type == ST_PIPE )
    return f->name;

  return NULL_ATOM;
}

void
setCurrentSourceLocation()
{ PlFile f = &fileTable[Input];

  if ( f->type == ST_FILE || f->type == ST_PIPE )
  { IOSTREAM *stream = f->stream;

    source_file_name = f->name;
    if ( stream && stream->position )
    { source_line_no = stream->position->lineno;
      source_char_no = stream->position->charno - 1; /* char just read! */
    }
  } else
  { source_file_name = NULL_ATOM;
    source_line_no = -1;
    source_char_no = 0;
  }
}

		/********************************
		*       WAITING FOR INPUT	*
		********************************/

#ifndef HAVE_SELECT

word
pl_wait_for_input(term_t streams, term_t available,
		  term_t timeout)
{ return notImplemented("wait_for_input", 3);
}

#else

word
pl_wait_for_input(term_t Streams, term_t Available,
		  term_t timeout)
{ fd_set fds;
  struct timeval t, *to;
  double time;
  int n, max = 0;
  char fdmap[256];
  term_t head      = PL_new_term_ref();
  term_t streams   = PL_copy_term_ref(Streams);
  term_t available = PL_copy_term_ref(Available);

  FD_ZERO(&fds);
  while( PL_get_list(streams, head, streams) )
  { IOSTREAM *s;
    int n, fd;

    if ( (n = streamNo(head, F_READ)) < 0 )
      fail;
    if ( !(s = fileTable[n].stream) || (fd=Sfileno(s)) < 0 )
      fail;
    fdmap[fd] = n;

    FD_SET(fd, &fds);
    if ( fd > max )
      max = fd;
  }
  if ( !PL_get_nil(streams) )
    return PL_error("wait_for_input", 3, NULL, ERR_TYPE, ATOM_list, Streams);
  if ( !PL_get_float(timeout, &time) )
    return PL_error("wait_for_input", 3, NULL, ERR_TYPE, ATOM_float, timeout);
  
  if ( time > 0.0 )
  { t.tv_sec  = (int)time;
    t.tv_usec = ((int)(time * 1000000) % 1000000);
    to = &t;
  } else
    to = NULL;

#ifdef hpux
  select(max+1, (int*) &fds, NULL, NULL, to);
#else
  select(max+1, &fds, NULL, NULL, to);
#endif

  for(n=0; n <= max; n++)
  { if ( FD_ISSET(n, &fds) )
    { if ( !PL_unify_list(available, head, available) ||
	   !unifyStreamName(head, fdmap[n]) )
	fail;
    }
  }
  PL_unify_nil(available);

  succeed;
}

#endif /* HAVE_SELECT */

		/********************************
		*      PROLOG CONNECTION        *
		*********************************/

word
pl_put(term_t c)
{ int chr;
  char *s;

  if ( PL_get_integer(c, &chr) )
  { if ( chr >= 0 && chr <= 255 )
      return Put(chr);
  } else if ( PL_get_chars(c, &s, CVT_ATOM|CVT_LIST|CVT_STRING) )
    return Puts(s);

  return PL_error("put", 1, NULL, ERR_TYPE, ATOM_character, c);
}

word
pl_put2(term_t stream, term_t chr)
{ streamOutput(stream, pl_put(chr));
}

word
pl_get(term_t chr)
{ int c;

  do
  { c = Get0();
  } while( c != EOF && isBlank(c) );

  return PL_unify_integer(chr, c);
}


word
pl_skip(term_t chr)
{ int c;
  int r;

  if ( !PL_get_integer(chr, &c) || c < 0 || c > 255 )
    return PL_error("skip", 1, NULL, ERR_TYPE, ATOM_character, chr);

  while((r=Get0()) != c && r != EOF )
    ;

  succeed;
}


word
pl_skip2(term_t stream, term_t chr)
{ streamInput(stream, pl_skip(chr));
}


word
pl_get2(term_t stream, term_t chr)
{ streamInput(stream, pl_get(chr));
}

word
pl_tty()				/* $tty/0 */
{ if ( GD->cmdline.notty )
    fail;
  succeed;
}

word
pl_get_single_char(term_t c)
{ return PL_unify_integer(c, getSingleChar());
}

word
pl_get0(term_t c)
{ return PL_unify_integer(c, Get0());
}

word
pl_get02(term_t stream, term_t c)
{ streamInput(stream, pl_get0(c))
}

word
pl_seeing(term_t f)
{ return unifyStreamName(f, Input);
}

word
pl_telling(term_t f)
{ return unifyStreamName(f, Output);
}

word
pl_tell(term_t f)
{ return openStream(f, F_WRITE, OPEN_TEXT);
}

word
pl_append(term_t f)
{ return openStream(f, F_APPEND, OPEN_TEXT);
}


word
pl_ttyflush()
{ int OldOut = Output;
  bool rval;

  Output = 1;
  rval = pl_flush();
  Output = OldOut;

  return rval;
}


word
pl_protocol(term_t file)
{ return openProtocol(file, FALSE);
}


word
pl_protocola(term_t file)
{ return openProtocol(file, TRUE);
}


word
pl_protocolling(term_t file)
{ if ( protocolStream >= 0 )
    return unifyStreamName(protocolStream, file);

  fail;
}


word
pl_prompt(term_t old, term_t new)
{ atom_t a;

  if ( PL_unify_atom(old, prompt_atom) &&
       PL_get_atom(new, &a) )
  { prompt_atom = a;
    succeed;
  }

  fail;
}


void
prompt1(char *prompt)
{ if ( first_prompt )
    remove_string(first_prompt);
  first_prompt = store_string(prompt);
  first_prompt_used = FALSE;
}


word
pl_prompt1(term_t prompt)
{ char *s;

  if ( PL_get_chars(prompt, &s, CVT_ALL) )
  { prompt1(s);
    succeed;
  }

  return PL_error("prompt1", 1, NULL, ERR_TYPE, ATOM_atom, prompt);
}


word
pl_tab(term_t spaces)
{ number n;

  if ( valueExpression(spaces, &n) &&
       toIntegerNumber(&n) )
  { int m = n.value.i;

    while(m-- > 0)
      Put(' ');

    succeed;
  }

  return PL_error("tab", 1, NULL, ERR_TYPE, ATOM_integer, spaces);
}


char *
PrologPrompt()
{ if ( !first_prompt_used && first_prompt )
  { first_prompt_used = TRUE;

    return first_prompt;
  }

  if ( Sinput->position && Sinput->position->linepos == 0 )
    return stringAtom(prompt_atom);
  else
    return "";
}


word
pl_tab2(term_t stream, term_t n)
{ streamOutput(stream, pl_tab(n)); /* TBD */
}

		/********************************
		*       STREAM BASED I/O        *
		*********************************/

static bool
setUnifyStreamNo(term_t stream, int n)
{ atom_t a;

  if ( PL_get_atom(stream, &a) )
  { register int i;

    for(i = 0; i < maxfiles; i++ )
    { if ( fileTable[i].status != F_CLOSED &&
	   fileTable[i].stream_name == a )
      { term_t obj = PL_new_term_ref();

	PL_unify_term(obj, PL_FUNCTOR, FUNCTOR_alias1, PL_ATOM, a);

	return PL_error(NULL, 0, NULL,
			ERR_PERMISSION, ATOM_open, ATOM_source_sink, obj);
      }
    }
    fileTable[n].stream_name = a;
    succeed;
  }

  return unifyStreamNo(stream, n);
}
      

static const opt_spec open4_options[] = 
{ { ATOM_type,		 OPT_ATOM },
  { ATOM_reposition,     OPT_BOOL },
  { ATOM_alias,	         OPT_ATOM },
  { ATOM_eof_action,     OPT_ATOM },
  { ATOM_close_on_abort, OPT_BOOL },
  { ATOM_buffer,	 OPT_ATOM },
  { NULL_ATOM,	         0 }
};


word
pl_open4(term_t file, term_t mode,
	 term_t stream, term_t options)
{ int m = -1;
  atom_t mname;
  atom_t type           = ATOM_text;
  bool   reposition     = FALSE;
  atom_t alias	        = NULL_ATOM;
  atom_t eof_action     = ATOM_eof_code;
  atom_t buffer         = ATOM_full;
  bool   close_on_abort = TRUE;
  int	 flags          = OPEN_OPEN;

  if ( !scan_options(options, 0, ATOM_stream_option, open4_options,
		     &type, &reposition, &alias, &eof_action,
		     &close_on_abort, &buffer) )
    fail;

  if ( alias )
    TRY(PL_unify_atom(stream, alias));
  if ( type == ATOM_text )
    flags |= OPEN_TEXT;
  
  if ( PL_get_atom(mode, &mname) )
  {      if ( mname == ATOM_write )
      m = F_WRITE;
    else if ( mname == ATOM_append )
      m = F_APPEND;
    else if ( mname == ATOM_update )
      m = F_WRNOTRUNC;
    else if ( mname == ATOM_read )
      m = F_READ;

    if ( m < 0 )
      return PL_error("open", 4, NULL, ERR_DOMAIN, ATOM_io_mode, mode);
  } else
  { return PL_error("open", 4, NULL, ERR_TYPE, ATOM_atom, mode);
  }

  if ( m == F_READ )
  { int in = Input;

    if ( openStream(file, m, flags) )
    { if ( setUnifyStreamNo(stream, Input) )
      { IOSTREAM *s = fileTable[Input].stream;
	  
	if ( eof_action != ATOM_eof_code )
	{ if ( eof_action == ATOM_reset )
	    s->flags |= SIO_NOFEOF;
	  else if ( eof_action == ATOM_error )
	    s->flags |= SIO_FEOF2ERR;
	}
	if ( !close_on_abort )
	  s->flags |= SIO_NOCLOSE;
	Input = in;
	pushInputContext();
        succeed;
      }
      closeStream(Input);
      Input = in;

      fail;
    }
    Input = in;
    fail;
  } else
  { int out = Output;
    if ( openStream(file, m, flags) )
    { if ( setUnifyStreamNo(stream, Output) )
      { IOSTREAM *s = fileTable[Output].stream;

	if ( !close_on_abort )
	  s->flags |= SIO_NOCLOSE;
	if ( buffer != ATOM_full )
	{ s->flags &= ~SIO_FBUF;
	  if ( buffer == ATOM_line )
	    s->flags |= SIO_LBUF;
	  if ( buffer == ATOM_false )
	    s->flags |= SIO_NBUF;
	}

	Output = out;
        succeed;
      }
      closeStream(Output);
      Output = out;
      
      fail;
    }
    Output = out;
    fail;
  }
}


word
pl_open(term_t file, term_t mode, term_t stream)
{ term_t n = PL_new_term_ref();
  PL_put_nil(n);

  return pl_open4(file, mode, stream, n);
}


		 /*******************************
		 *	   NULL-STREAM		*
		 *******************************/

static int
Swrite_null(void *handle, char *buf, int size)
{ return size;
}


static int
Sread_null(void *handle, char *buf, int size)
{ return 0;
}


static long
Sseek_null(void *handle, long offset, int whence)
{ switch(whence)
  { case SIO_SEEK_SET:
	return offset;
    case SIO_SEEK_CUR:
    case SIO_SEEK_END:
    default:
        return -1;
  }
}


static int
Sclose_null(void *handle)
{ return 0;
}


static IOFUNCTIONS nullFunctions =
{ Sread_null,
  Swrite_null,
  Sseek_null,
  Sclose_null
};


word
pl_open_null_stream(term_t stream)
{ int sflags = SIO_NBUF|SIO_RECORDPOS;
  IOSTREAM *s = Snew((void *)NULL, sflags, &nullFunctions);

  return PL_open_stream(stream, s);
}


int
streamNo(term_t spec, int mode)
{ int n = -1;
  
  if ( !PL_get_integer(spec, &n) )
  { atom_t name;

    if ( PL_get_atom(spec, &name) )
    {      if ( name == ATOM_user )
	n = (mode == F_READ ? 0 : 1);
      else if ( name == ATOM_user_input )
	n = 0;
      else if ( name == ATOM_user_output )
        n = 1;
      else if ( name == ATOM_user_error )
        n = 2;
      else
      { int i;

	for(i = 3; i < maxfiles; i++)
	{ if ( fileTable[i].stream_name == name )
	  { n = i;
	    break;
	  }
	}
      }
    }
  }

  if ( n < 0 || n >= maxfiles )
  { PL_error(NULL, 0, NULL, ERR_DOMAIN, ATOM_stream_or_alias, spec);
    return -1;
  }
  if ( fileTable[n].status == F_CLOSED )
  { PL_error(NULL, 0, "closed", ERR_EXISTENCE, ATOM_stream, spec);
    return -1;
  }

  switch(mode)
  { case F_ANY:
      return n;
    case F_READ:
      if ( fileTable[n].status != F_READ )
      { PL_error(NULL, 0, NULL, ERR_PERMISSION,
		 ATOM_input, ATOM_stream, spec);
	return -1;
      }
      break;
    case F_APPEND:
    case F_WRNOTRUNC:
    case F_WRITE:	
      if ( fileTable[n].status != F_WRITE )
      { PL_error(NULL, 0, NULL, ERR_PERMISSION,
		 ATOM_output, ATOM_stream, spec);
        return -1;
      }
  }

  return n;
}
  

word
pl_close(term_t stream)
{ int n;
  int isread;
  int rval;

  if ( (n = streamNo(stream, F_ANY)) < 0 )
    fail;
  isread = (fileTable[n].status == F_READ);

  if ( isread )
  { rval = closeStream(n);
    popInputContext();
  } else
  { TRYPIPE(n, ATOM_write, rval = closeStream(n), rval = FALSE);
  }
  
  if ( n == Output )
    Output = 1;
  if ( n == Input )
    Input = 0;

  return rval;
}

word
pl_current_stream(term_t file, term_t mode,
		  term_t stream, word h)
{ int n;

  switch( ForeignControl(h) )
  { case FRG_FIRST_CALL:
      n = 3;
      break;
    case FRG_REDO:
      n = ForeignContextInt(h);
      break;
    case FRG_CUTTED:
    default:
      succeed;
  }
  
  for( ; n < maxfiles; n++)
  { fid_t fid = PL_open_foreign_frame();

    if ( unifyStreamName(file, n) == FALSE ||
	 unifyStreamMode(mode, n) == FALSE ||
	 unifyStreamNo(stream, n) == FALSE )
    { PL_discard_foreign_frame(fid);
      continue;
    }

    PL_close_foreign_frame(fid);

    if ( ++n < maxfiles )
      ForeignRedoInt(n);

    succeed;
  }
  
  fail;
}      


word
pl_flush_output(term_t stream)
{ int n;

  if ( (n = streamNo(stream, F_WRITE)) < 0 )
    fail;
  TRYPIPE(n, ATOM_write, Sflush(fileTable[n].stream), fail);

  succeed;
}


static IOSTREAM *
ioStreamWithPosition(term_t stream)
{ int n;
  IOSTREAM *s;

  if ( (n = streamNo(stream, F_ANY)) < 0 )
    fail;
  s = fileTable[n].stream;
  if ( !s->position )
  { PL_error(NULL, 0, NULL, ERR_PERMISSION, /* non-ISO */
	     ATOM_property, ATOM_position, stream);
    return NULL;
  }
  
  return s;
}


word
pl_stream_position(term_t stream, term_t old, term_t new)
{ IOSTREAM *s;
  long oldcharno, charno, linepos, lineno;
  term_t a = PL_new_term_ref();
  functor_t f;

  if ( !(s = ioStreamWithPosition(stream)) )
    fail;

  charno  = s->position->charno;
  lineno  = s->position->lineno;
  linepos = s->position->linepos;
  oldcharno = charno;

  if ( !PL_unify_functor(old, FUNCTOR_stream_position3) ||
       !PL_get_arg(1, old, a) ||
       !PL_unify_integer(a, charno) ||
       !PL_get_arg(2, old, a) ||
       !PL_unify_integer(a, lineno) ||
       !PL_get_arg(3, old, a) ||
       !PL_unify_integer(a, linepos) )
    fail;

  if ( !(PL_get_functor(new, &f) && f == FUNCTOR_stream_position3) ||
       !PL_get_arg(1, new, a) ||
       !PL_get_long(a, &charno) ||
       !PL_get_arg(2, new, a) ||
       !PL_get_long(a, &lineno) ||
       !PL_get_arg(3, new, a) ||
       !PL_get_long(a, &linepos) )
    return PL_error("stream_position", 3, NULL,
		    ERR_DOMAIN, ATOM_stream_position, new);

  if ( charno != oldcharno && Sseek(s, charno, 0) < 0 )
    return PL_error("stream_position", 3, OsError(),
		    ERR_STREAM_OP, ATOM_position, stream);

  s->position->charno  = charno;
  s->position->lineno  = lineno;
  s->position->linepos = linepos;
  
  succeed;
}


word
pl_seek(term_t stream, term_t offset, term_t method, term_t newloc)
{ int n;
  atom_t m;
  int whence = -1;
  long off, new;

  if ( (n = streamNo(stream, F_ANY)) < 0 )
    fail;
  if ( !(PL_get_atom(method, &m)) )
    goto badmethod;

  if ( m == ATOM_bof )
    whence = SIO_SEEK_SET;
  else if ( m == ATOM_current )
    whence = SIO_SEEK_CUR;
  else if ( m == ATOM_eof )
    whence = SIO_SEEK_END;
  else
  { badmethod:
    return PL_error("seek", 4, NULL, ERR_DOMAIN, ATOM_seek_method, method);
  }
  
  if ( !PL_get_long(offset, &off) )
    return PL_error("seek", 4, NULL, ERR_DOMAIN, ATOM_integer, offset);

  new = Sseek(fileTable[n].stream, off, whence);
  if ( new == -1 )
    return PL_error("seek", 4, OsError(), ERR_PERMISSION,
		    ATOM_reposition, ATOM_stream, stream);

  return PL_unify_integer(newloc, new);
}


word
pl_set_input(term_t stream)
{ int n;

  if ( (n = streamNo(stream, F_READ)) < 0 )
    fail;

  Input = n;
  succeed;
}


word
pl_set_output(term_t stream)
{ int n;

  if ( (n = streamNo(stream, F_WRITE)) < 0 )
    fail;

  Output = n;
  succeed;
}


word
pl_current_input(term_t stream)
{ return unifyStreamNo(stream, Input);
}


word
pl_current_output(term_t stream)
{ return unifyStreamNo(stream, Output);
}

word
pl_character_count(term_t stream, term_t count)
{ IOSTREAM *s = ioStreamWithPosition(stream);

  if ( s )
    return PL_unify_integer(count, s->position->charno);

  fail;
}

word
pl_line_count(term_t stream, term_t count)
{ IOSTREAM *s = ioStreamWithPosition(stream);

  if ( s )
    return PL_unify_integer(count, s->position->lineno);

  fail;
}

word
pl_line_position(term_t stream, term_t count)
{ IOSTREAM *s = ioStreamWithPosition(stream);

  if ( s )
    return PL_unify_integer(count, s->position->linepos);

  fail;
}


word
pl_source_location(term_t file, term_t line)
{ char *s;
  char tmp[MAXPATHLEN];

  if ( ReadingSource &&
       (s = AbsoluteFile(stringAtom(source_file_name), tmp)) &&
	PL_unify_atom_chars(file, s) &&
	PL_unify_integer(line, source_line_no) )
    succeed;
  
  fail;
}


word
pl_at_end_of_stream1(term_t stream)
{ int n;

  if ( (n = streamNo(stream, F_READ)) < 0 )
    fail;

  return Sfeof(fileTable[n].stream) ? TRUE : FALSE;
}


word
pl_at_end_of_stream0()
{ IOSTREAM *s = fileTable[Input].stream;
  
  if ( !s || Sfeof(s) )
    succeed;

  fail;
}


word
pl_peek_byte2(term_t stream, term_t chr)
{ int n;
  IOSTREAM *s;
  IOPOS pos;
  int c;

  if ( (n = streamNo(stream, F_READ)) < 0 ||
       !(s = fileTable[n].stream) )
    fail;

  pos = s->posbuf;
  c = Sgetc(s);
  Sungetc(c, s);
  s->posbuf = pos;

  return PL_unify_integer(chr, c);
}


word
pl_peek_byte1(term_t chr)
{ IOSTREAM *s;
  IOPOS pos;
  int c;

  if ( !(s = fileTable[Input].stream) )
    fail;

  pos = s->posbuf;
  c = Sgetc(s);
  Sungetc(c, s);
  s->posbuf = pos;

  return PL_unify_integer(chr, c);
}


		/********************************
		*             FILES             *
		*********************************/

bool
unifyTime(term_t t, long time)
{ return PL_unify_float(t, (double)time);
}


char *
PL_get_filename(term_t n, char *buf, unsigned int size)
{ char *name;
  char tmp[MAXPATHLEN];

  if ( !PL_get_chars(n, &name, CVT_ALL) )
  { PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_atom, n);
    return NULL;
  }
  if ( !(name = ExpandOneFile(name, tmp)) )
    return NULL;

  if ( buf )
  { if ( strlen(name) < size )
    { strcpy(buf, name);
      return buf;
    }

    PL_error(NULL, 0, NULL, ERR_REPRESENTATION,
	     ATOM_max_path_length);
    return NULL;
  } else
    return buffer_string(name, 0);
}


int
PL_get_stream_handle(term_t spec, IOSTREAM **stream)
{ int n = streamNo(spec, F_ANY);

  if ( n >= 0 )
  { *stream = fileTable[n].stream;
    succeed;
  }

  fail;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This should not exists (actually, the  integer stream handles should not
exists). Used in PL_open_resource() to  get   rid  of the Prolog stream,
while maintaining the IOSTREAM handle.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

void
release_stream_handle(term_t spec)
{ int n = streamNo(spec, F_ANY);
  PlFile f = &fileTable[n];

  f->stream = NULL_ATOM;
  f->name   = NULL_ATOM;
  f->status = F_CLOSED;
}


word
pl_time_file(term_t name, term_t t)
{ char *fn;

  if ( (fn = PL_get_filename(name, NULL, 0)) )
  { long time;

    if ( (time = LastModifiedFile(fn)) == -1 )
      fail;

    return unifyTime(t, time);
  }

  fail;
}


word
pl_size_file(term_t name, term_t len)
{ char *n;

  if ( (n = PL_get_filename(name, NULL, 0)) )
  { long size;

    if ( (size = SizeFile(n)) < 0 )
      return PL_error("size_file", 2, OsError(), ERR_FILE_OPERATION,
		      ATOM_size, ATOM_file, name);

    return PL_unify_integer(len, size);
  }

  fail;
}


word
pl_size_stream(term_t stream, term_t len)
{ int n;

  if ( (n = streamNo(stream, F_ANY)) < 0 )
    fail;

  return PL_unify_integer(len, Ssize(fileTable[n].stream));
}


word
pl_access_file(term_t name, term_t mode)
{ char *n;
  int md;
  atom_t m;

  if ( !PL_get_atom(mode, &m) )
    return PL_error("access_file", 2, NULL, ERR_TYPE, ATOM_atom, mode);
  if ( !(n=PL_get_filename(name, NULL, 0)) )
    fail;

  if ( m == ATOM_none )
    succeed;
  
  if      ( m == ATOM_write || m == ATOM_append )
    md = ACCESS_WRITE;
  else if ( m == ATOM_read )
    md = ACCESS_READ;
  else if ( m == ATOM_execute )
    md = ACCESS_EXECUTE;
  else if ( m == ATOM_exist )
    md = ACCESS_EXIST;
  else
    return PL_error("access_file", 2, NULL, ERR_DOMAIN, ATOM_io_mode, mode);

  if ( AccessFile(n, md) )
    succeed;

  if ( md == ACCESS_WRITE && !AccessFile(n, ACCESS_EXIST) )
  { char tmp[MAXPATHLEN];
    char *dir = DirName(n, tmp);

    if ( dir[0] )
    { if ( !ExistsDirectory(dir) )
	fail;
    }
    if ( AccessFile(dir[0] ? dir : ".", md) )
      succeed;
  }

  fail;
}


word
pl_read_link(term_t file, term_t link, term_t to)
{ char *n, *l, *t;
  char buf[MAXPATHLEN];

  if ( !(n = PL_get_filename(file, NULL, 0)) )
    fail;

  if ( (l = ReadLink(n, buf)) &&
       PL_unify_atom_chars(link, l) &&
       (t = DeRefLink(n, buf)) &&
       PL_unify_atom_chars(to, t) )
    succeed;

  fail;
}


word
pl_exists_file(term_t name)
{ char *n;

  if ( !(n = PL_get_filename(name, NULL, 0)) )
    fail;
  
  return ExistsFile(n);
}


word
pl_exists_directory(term_t name)
{ char *n;

  if ( !(n = PL_get_filename(name, NULL, 0)) )
    fail;
  
  return ExistsDirectory(n);
}


word
pl_tmp_file(term_t base, term_t name)
{ char *n;

  if ( !PL_get_chars(base, &n, CVT_ALL) )
    return PL_error("tmp_file", 2, NULL, ERR_TYPE, ATOM_atom, base);

  return PL_unify_atom(name, TemporaryFile(n));
}


word
pl_delete_file(term_t name)
{ char *n;

  if ( !(n = PL_get_filename(name, NULL, 0)) )
    fail;
  
  return RemoveFile(n);
}


word
pl_same_file(term_t file1, term_t file2)
{ char *n1, *n2;
  char name1[MAXPATHLEN];

  if ( (n1 = PL_get_filename(file1, name1, sizeof(name1))) &&
       (n2 = PL_get_filename(file2, NULL, 0)) )
    return SameFile(name1, n2);

  fail;
}


word
pl_rename_file(term_t old, term_t new)
{ char *o, *n;
  char ostore[MAXPATHLEN];

  if ( (o = PL_get_filename(old, ostore, sizeof(ostore))) &&
       (n = PL_get_filename(new, NULL, 0)) )
  { if ( RenameFile(ostore, n) )
      succeed;

    if ( fileerrors )
      return PL_error("rename_file", 2, OsError(), ERR_FILE_OPERATION,
		      ATOM_rename, ATOM_file, old);
    fail;
  }

  fail;
}


word
pl_fileerrors(term_t old, term_t new)
{ return setBoolean(&fileerrors, "fileerrors", old, new);
}


word
pl_absolute_file_name(term_t name, term_t expanded)
{ char *n;
  char tmp[MAXPATHLEN];

  if ( (n = PL_get_filename(name, NULL, 0)) &&
       (n = AbsoluteFile(n, tmp)) )
    return PL_unify_atom_chars(expanded, n);

  fail;
}


word
pl_is_absolute_file_name(term_t name)
{ char *n;

  if ( (n = PL_get_filename(name, NULL, 0)) &&
       IsAbsolutePath(n) )
    succeed;

  fail;
}


word
pl_chdir(term_t dir)
{ char *n;

  if ( (n = PL_get_filename(dir, NULL, 0)) )
  { if ( ChDir(n) )
      succeed;

    if ( fileerrors )
      return PL_error("chdir", 1, NULL, ERR_FILE_OPERATION,
		      ATOM_chdir, ATOM_directory, dir);
    fail;
  }

  fail;
}


word
pl_file_base_name(term_t f, term_t b)
{ char *n;

  if ( !PL_get_chars(f, &n, CVT_ALL) )
    return PL_error("file_base_name", 2, NULL, ERR_TYPE, ATOM_atom, f);

  return PL_unify_atom_chars(b, BaseName(n));
}


word
pl_file_dir_name(term_t f, term_t b)
{ char *n;
  char tmp[MAXPATHLEN];

  if ( !PL_get_chars(f, &n, CVT_ALL) )
    return PL_error("file_dir_name", 2, NULL, ERR_TYPE, ATOM_atom, f);

  return PL_unify_atom_chars(b, DirName(n, tmp));
}


static int
has_extension(const char *name, const char *ext)
{ const char *s = name + strlen(name);

  if ( ext[0] == EOS )
    succeed;

  while(*s != '.' && *s != '/' && s > name)
    s--;
  if ( *s == '.' && s > name && s[-1] != '/' )
  { if ( ext[0] == '.' )
      ext++;
    if ( trueFeature(FILE_CASE_FEATURE) )
      return strcmp(&s[1], ext) == 0;
    else
      return stricmp(&s[1], ext) == 0;
  }

  fail;
}


word
pl_file_name_extension(term_t base, term_t ext, term_t full)
{ char *b = NULL, *e = NULL, *f;
  char buf[MAXPATHLEN];

  if ( PL_get_chars(full, &f, CVT_ALL) )
  { char *s = f + strlen(f);		/* ?base, ?ext, +full */

    while(*s != '.' && *s != '/' && s > f)
      s--;
    if ( *s == '.' )
    { if ( PL_get_chars(ext, &e, CVT_ALL) )
      { if ( e[0] == '.' )
	  e++;
	if ( trueFeature(FILE_CASE_FEATURE) )
	{ TRY(strcmp(&s[1], e) == 0);
	} else
	{ TRY(stricmp(&s[1], e) == 0);
	}
      } else
      { TRY(PL_unify_atom_chars(ext, &s[1]));
      }
      if ( s-f > MAXPATHLEN )
      { maxpath:
	return PL_error("file_name_extension", 3, NULL, ERR_REPRESENTATION,
			ATOM_max_path_length);
      }
      strncpy(buf, f, s-f);
      buf[s-f] = EOS;

      return PL_unify_atom_chars(base, buf);
    }
    if ( PL_unify_atom_chars(ext, "") &&
	 PL_unify(full, base) )
      PL_succeed;

    PL_fail;
  } else if ( !PL_is_variable(full) )
    return PL_error("file_name_extension", 3, NULL, ERR_TYPE,
		    ATOM_atom, full);

  if ( PL_get_chars(base, &b, CVT_ALL|BUF_RING) &&
       PL_get_chars(ext, &e, CVT_ALL) )
  { char *s;

    if ( e[0] == '.' )		/* +Base, +Extension, -full */
      e++;
    if ( has_extension(b, e) )
      return PL_unify(base, full);
    if ( strlen(b) + 1 + strlen(e) + 1 > MAXPATHLEN )
      goto maxpath;
    strcpy(buf, b);
    s = buf + strlen(buf);
    *s++ = '.';
    strcpy(s, e);

    return PL_unify_atom_chars(full, buf);
  }

  if ( !b )
    return PL_error("file_name_extension", 3, NULL, ERR_TYPE,
		    ATOM_atom, base);
  return PL_error("file_name_extension", 3, NULL, ERR_TYPE,
		  ATOM_atom, ext);
}


word
pl_prolog_to_os_filename(term_t pl, term_t os)
{
#ifdef O_XOS
  char *n;
  char buf[MAXPATHLEN];

  if ( PL_get_chars(pl, &n, CVT_ALL) )
  { _xos_os_filename(n, buf);
    return PL_unify_atom_chars(os, buf);
  }
  if ( !PL_is_variable(pl) )
    return PL_error("prolog_to_os_filename", 2, NULL, ERR_TYPE,
		    ATOM_atom, pl);

  if ( PL_get_chars(os, &n, CVT_ALL) )
  { _xos_canonical_filename(n, buf);
    return PL_unify_atom_chars(pl, buf);
  }

  return PL_error("prolog_to_os_filename", 2, NULL, ERR_TYPE,
		  ATOM_atom, os);
#else /*O_XOS*/
  return PL_unify(pl, os);
#endif /*O_XOS*/
}


foreign_t
pl_mark_executable(term_t path)
{ char name[MAXPATHLEN];

  if ( !PL_get_filename(path, name, sizeof(name)) )
    return PL_error(NULL, 0, NULL, ERR_DOMAIN, ATOM_source_sink, path);

  return MarkExecutable(name);
}


#if defined(O_XOS) && defined(__WIN32__)
word
pl_make_fat_filemap(term_t dir)
{ char *n;

  if ( (n = PL_get_filename(dir, NULL, 0)) )
  { if ( _xos_make_filemap(n) == 0 )
      succeed;

    if ( fileerrors )
      return PL_error("make_fat_filemap", 1, NULL, ERR_FILE_OPERATION,
		      ATOM_write, ATOM_file, dir);

    fail;
  }
  
  fail;
}
#endif