File: table.c

package info (click to toggle)
swi-prolog 9.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 82,408 kB
  • sloc: ansic: 387,503; perl: 359,326; cpp: 6,613; lisp: 6,247; java: 5,540; sh: 3,147; javascript: 2,668; python: 1,900; ruby: 1,594; yacc: 845; makefile: 428; xml: 317; sed: 12; sql: 6
file content (2241 lines) | stat: -rw-r--r-- 51,022 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
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (c)  1999-2018, University of Amsterdam
			      CWI, Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

#include <config.h>

#define O_ORDER				/* include order.c package */

#ifndef BUILD_DATE
#define BUILD_DATE __DATE__
#endif

#include <SWI-Stream.h>

#include "table.h"
#include "error.h"
#include <stdlib.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <sys/types.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif

#ifdef HAVE_FLOATINGPOINT_H
#include <floatingpoint.h>		/* strtod() prototype */
#endif

#ifdef O_DEBUG
#define DEBUG(g) g
#else
#define DEBUG(g)
#endif

#ifdef O_ORDER
#include "order.h"
#endif

#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif

#undef offsetof
#define offsetof(t, f) ((intptr_t)&(((t*)0)->f))

#define sizeofquery(t) offsetof(query, field[t->nfields])

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SWI-Prolog management of external tables.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
open_table(+File, +Fields, +Options, -Handle)
	Open a file as a table.  Fields is a list of field-types occuring
	in the file.  A field type is one of:

		atom		read field as atom
		string		read field as SWI-Prolog string
		code_list	read field as list of ASCII codes
		integer		read field as integer
		hexadecimal	read field as hex integer
		float		read field as floating point number

	Options is a list of options.  Each option is of the form
	<Name>(<Value>>).  Defined options are:

		record_separator(Code)
				Defines the separator between two
				records.  Default is 10 (newline)

		field_separator(Code)
				Defines the separator between two
				fields in a record.  Default is
				32 (space), implying all blank
				space.

		sorted(Field)
				Defines the file is sorted in the
				specified field name.  In this
				case lookup will exploit binary
				search if possible.

		unique(Field)
				Defines the field to be unique.

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


		 /*******************************
		 *	    PROTOTYPES		*
		 *******************************/

static foreign_t unify_field_info(term_t t, Field field);


		 /*******************************
		 *	      CONSTANTS		*
		 *******************************/

#ifndef EOS
#define EOS (0)
#endif

#define isBlank(c) ((c) == ' ' || (c) == '\t' || (c) == '\r' )

static atom_t ATOM_atom;
static atom_t ATOM_code_list;
static atom_t ATOM_downcase;
static atom_t ATOM_eq;
static atom_t ATOM_escape;
static atom_t ATOM_exact;
static atom_t ATOM_field;
static atom_t ATOM_field_count;
static atom_t ATOM_field_separator;
static atom_t ATOM_file;
static atom_t ATOM_float;
static atom_t ATOM_functor;
static atom_t ATOM_integer;
static atom_t ATOM_hexadecimal;
static atom_t ATOM_key_field;
static atom_t ATOM_map_space_to_underscore;
static atom_t ATOM_prefix;
static atom_t ATOM_record;
static atom_t ATOM_record_separator;
static atom_t ATOM_size;
static atom_t ATOM_skip;
static atom_t ATOM_sorted;
static atom_t ATOM_string;
static atom_t ATOM_substring;
static atom_t ATOM_syntax;
static atom_t ATOM_unique;
static atom_t ATOM_width;
static atom_t ATOM_window;
static atom_t ATOM_arg;
static atom_t ATOM_encoding;
static atom_t ATOM_iso_latin_1;
static atom_t ATOM_utf8;
static atom_t ATOM_native;

static functor_t FUNCTOR_minus2;

static void
init_constants()
{
  ATOM_arg			= PL_new_atom("arg");
  ATOM_atom			= PL_new_atom("atom");
  ATOM_code_list		= PL_new_atom("code_list");
  ATOM_downcase			= PL_new_atom("downcase");
  ATOM_eq			= PL_new_atom("=");
  ATOM_escape			= PL_new_atom("escape");
  ATOM_exact			= PL_new_atom("exact");
  ATOM_field			= PL_new_atom("field");
  ATOM_field_count		= PL_new_atom("field_count");
  ATOM_field_separator		= PL_new_atom("field_separator");
  ATOM_file			= PL_new_atom("file");
  ATOM_float			= PL_new_atom("float");
  ATOM_functor			= PL_new_atom("functor");
  ATOM_integer			= PL_new_atom("integer");
  ATOM_hexadecimal		= PL_new_atom("hexadecimal");
  ATOM_key_field		= PL_new_atom("key_field");
  ATOM_map_space_to_underscore	= PL_new_atom("map_space_to_underscore");
  ATOM_prefix			= PL_new_atom("prefix");
  ATOM_record			= PL_new_atom("record");
  ATOM_record_separator		= PL_new_atom("record_separator");
  ATOM_size			= PL_new_atom("size");
  ATOM_skip			= PL_new_atom("skip");
  ATOM_sorted			= PL_new_atom("sorted");
  ATOM_string			= PL_new_atom("string");
  ATOM_substring		= PL_new_atom("substring");
  ATOM_syntax			= PL_new_atom("syntax");
  ATOM_unique			= PL_new_atom("unique");
  ATOM_width			= PL_new_atom("width");
  ATOM_window			= PL_new_atom("window");
  ATOM_encoding			= PL_new_atom("encoding");
  ATOM_iso_latin_1		= PL_new_atom("iso_latin_1");
  ATOM_utf8			= PL_new_atom("utf8");
  ATOM_native			= PL_new_atom("native");

  FUNCTOR_minus2		= PL_new_functor(PL_new_atom("-"), 2);
}


		 /*******************************
		 *	       ERRORS		*
		 *******************************/

static int
domain_error(term_t actual, const char *expected)
{ term_t ex;

  if ( (ex=PL_new_term_ref()) &&
       PL_unify_term(ex,
		     PL_FUNCTOR_CHARS, "error", 2,
		       PL_FUNCTOR_CHARS, "domain_error", 2,
		         PL_CHARS, expected,
		         PL_TERM, actual,
		       PL_VARIABLE) )
    return PL_raise_exception(ex);

  return FALSE;
}


static int
type_error(term_t actual, const char *expected)
{ term_t ex;

  if ( (ex=PL_new_term_ref()) &&
       PL_unify_term(ex,
		     PL_FUNCTOR_CHARS, "error", 2,
		       PL_FUNCTOR_CHARS, "type_error", 2,
		         PL_CHARS, expected,
		         PL_TERM, actual,
		       PL_VARIABLE) )
    return PL_raise_exception(ex);

  return FALSE;
}


static int
existence_error(term_t actual, const char *expected)
{ term_t ex;

  if ( (ex=PL_new_term_ref()) &&
       PL_unify_term(ex,
		     PL_FUNCTOR_CHARS, "error", 2,
		       PL_FUNCTOR_CHARS, "existence_error", 2,
		         PL_CHARS, expected,
		         PL_TERM, actual,
		       PL_VARIABLE) )
    return PL_raise_exception(ex);
  return FALSE;
}


static int
format_error(const char *pred, size_t pos, Field f)
{ char buf[1024];

  sprintf(buf, "%s: bad record, field %d (%s), char-index %ld",
	  pred, f->index, PL_atom_chars(f->name), (long)pos);

  return PL_representation_error(buf);
}



		 /*******************************
		 *	 HIGH-LEVEL GET-*	*
		 *******************************/

static int
get_size_ex(term_t t, size_t *v)
{ int64_t i;

  if ( PL_get_int64(t, &i) )
  { if ( i < 0 )
      return domain_error(t, "nonneg"),FALSE;

    *v = (size_t)i;			/* TBD: Check on 32-bit systems */
    return TRUE;
  }

  return type_error(t, "integer"),FALSE;
}


static int
get_offset_ex(term_t t, table_offset_t *v)
{ int64_t i;

  if ( PL_get_int64(t, &i) )
  { if ( i < 0 )
      return domain_error(t, "nonneg"),FALSE;

    *v = (table_offset_t)i;		/* TBD: Check on 32-bit systems */
    return TRUE;
  }

  return type_error(t, "integer"),FALSE;
}


static int
get_table_ex(term_t handle, Table *table)
{ int64_t l;

  if ( PL_get_int64(handle, &l) )
  { Table t = (Table)(intptr_t)l;

    if ( t->magic == TABLE_MAGIC )
    { *table = t;
      return TRUE;
    }

    return existence_error(handle, "table");
  }

  return type_error(handle, "table");
}


static int
get_type(atom_t typename, int *type)
{      if ( typename == ATOM_atom )
    *type = FIELD_ATOM;
  else if ( typename == ATOM_string )
    *type = FIELD_STRING;
  else if ( typename == ATOM_code_list )
    *type = FIELD_CODELIST;
  else if ( typename == ATOM_integer )
    *type = FIELD_INTEGER;
  else if ( typename == ATOM_hexadecimal )
    *type = FIELD_HEX;
  else if ( typename == ATOM_float )
    *type = FIELD_FLOAT;
  else
    return FALSE;

  return TRUE;
}


static int
get_field_flag(atom_t name, term_t arg, Field field)
{ if ( name == ATOM_sorted )
  { field->flags |= FIELD_SORTED;
    if ( arg )
    { atom_t tab;

      if ( !PL_get_atom(arg, &tab) ||
	   !(field->ord = findOrdTable(tab)) )
	return FALSE;
    }
  } else if ( name == ATOM_unique && arg == 0 )
    field->flags |= FIELD_UNIQUE;
  else if ( name == ATOM_downcase && arg == 0 )
    field->flags |= FIELD_DOWNCASE;
  else if ( name == ATOM_syntax && arg == 0 )
    field->flags |= FIELD_ALLOWBADNUM;
  else if ( name == ATOM_map_space_to_underscore && arg == 0 )
    field->flags |= FIELD_MAPSPACETOUNDERSCORE;
  else if ( name == ATOM_width && arg )
    return PL_get_integer(arg, &field->width);
  else if ( name == ATOM_arg && arg )
    return PL_get_integer(arg, &field->arg);
  else if ( name == ATOM_skip && !arg )
    field->arg = 0;
  else
    return FALSE;

  return TRUE;
}


static int
default_escape_table(Table t)
{ int i;

  if ( !(t->escape_table = malloc(256)) )
    return PL_resource_error("memory");

  for(i=0; i<256; i++)
    t->escape_table[i] = i;

  if ( t->escape == '\\' )
  { t->escape_table['b'] = '\b';
    t->escape_table['e'] = 27;
    t->escape_table['n'] = '\n';
    t->escape_table['r'] = '\r';
    t->escape_table['t'] = '\t';
  }

  return TRUE;
}


static int
get_char(term_t t, int *chr)
{ int i;

  if ( !PL_get_integer(t, &i) || i < 0 || i > 255 )
    return FALSE;
  *chr = i;

  return TRUE;
}


static foreign_t
pl_new_table(term_t file, term_t columns, term_t options, term_t handle)
{ Table table = malloc(sizeof(*table));	/* table to create */
  field fields[MAXFIELDS];		/* scratch field structures */
  int   nfields=0;			/* # collected fields */
  int   defarg=1;			/* default argument */
  term_t tail = PL_copy_term_ref(columns); /* for enumerating lists */
  term_t head = PL_new_term_ref();	/* scratch list-head */
  term_t arg  = PL_new_term_ref();	/* scratch argument */

  memset(table, 0, sizeof(*table));

  table->record_functor = 0;		/* not filled */
  table->keyfield = -1;
  table->escape = -1;
  table->escape_table = NULL;
  table->encoding = REP_ISO_LATIN_1;

  if ( !PL_get_atom(file, &table->file) )
  { free(table);
    return error(ERR_INSTANTIATION, "open_table/4", 1, file);
  }

  while(PL_get_list(tail, head, tail))
  { size_t arity;
    atom_t typename;

    if ( !PL_get_name_arity(head, &fields[nfields].name, &arity) ||
	 arity < 1 || arity > 2 ||
	 !PL_get_arg(1, head, arg) ||
	 !PL_get_atom(arg, &typename) ||
	 !get_type(typename, &fields[nfields].type) )
    { free(table);
      return error(ERR_INSTANTIATION, "new_table/4", 2, columns);
    }

    fields[nfields].index = nfields;	/* index number (0..) */
    fields[nfields].width = 0;		/* variable-width field */
    fields[nfields].flags = 0;		/* default */
    fields[nfields].arg   = defarg;	/* default field identifier */
    fields[nfields].ord   = NULL;	/* ordering table */

    if ( arity == 2 )
    { fid_t fid = PL_open_foreign_frame();
      term_t tail2 = PL_new_term_ref();
      term_t head2 = PL_new_term_ref();
      term_t arg2  = PL_new_term_ref();

      _PL_get_arg(2, head, tail2);
      while(PL_get_list(tail2, head2, tail2))
      { atom_t a;
	size_t optarity;

	if ( PL_get_name_arity(head2, &a, &optarity) )
	{ if ( optarity == 1 )
	  { _PL_get_arg(1, head2, arg2);

	    if ( !get_field_flag(a, arg2, &fields[nfields]) )
	      goto colerr;
	  } else
	  { if ( !get_field_flag(a, 0, &fields[nfields]) )
	      goto colerr;
	  }
	} else
	{ colerr:
	  free(table);
	  return error(ERR_INSTANTIATION, "new_table/4", 2, columns);
	}
      }
      if ( !PL_get_nil(tail2) )
      { free(table);
	return error(ERR_INSTANTIATION, "new_table/4", 2, columns);
      }

      if ( fields[nfields].flags & FIELD_SORTED )
	table->keyfield = nfields;

      PL_close_foreign_frame(fid);
    }

    if ( fields[nfields].arg > 0 )
      defarg = fields[nfields].arg + 1;

    nfields++;
  }
  if ( !PL_get_nil(tail) )
  { free(table);
    return error(ERR_INSTANTIATION, "new_table/4", 2, columns);
  }

  table->record_sep = '\n';
  table->field_sep  = ' ';

  if ( !PL_put_term(tail, options) )
    return FALSE;
  while(PL_get_list(tail, head, tail))
  { atom_t name;
    size_t arity;

    if ( !PL_get_name_arity(head, &name, &arity) )
      goto err3;
    if ( name == ATOM_escape && arity == 2 )
    { term_t head2 = PL_new_term_ref();
      term_t tail2 = PL_new_term_ref();

      _PL_get_arg(1, head, arg);

      if ( !PL_get_integer(arg, &table->escape) )
	goto err3;

      if ( !default_escape_table(table) )
      { free(table);
	return FALSE;
      }
      _PL_get_arg(2, head, tail2);
      while(PL_get_list(tail2, head2, tail2))
      { atom_t name;
	size_t arity;
	int f, t;

	if ( !PL_get_name_arity(head2, &name, &arity) ||
	     name != ATOM_eq || arity != 2 )
	  goto err3;
	if ( !PL_get_arg(1, head2, arg) ||
	     !get_char(arg, &f) ||
	     !PL_get_arg(2, head2, arg) ||
	     !get_char(arg, &t) )
	  goto err3;

	table->escape_table[f] = t;
      }
      if ( PL_get_nil(tail2) )
	continue;
      goto err3;
    }

    if ( arity != 1 )
      goto err3;
    _PL_get_arg(1, head, arg);
    if ( name == ATOM_record_separator )
    { if ( !PL_get_integer(arg, &table->record_sep) )
	goto err3;
    } else if ( name == ATOM_field_separator )
    { if ( !PL_get_integer(arg, &table->field_sep) )
	goto err3;
    } else if ( name == ATOM_functor )
    { if ( !PL_get_functor(arg, &table->record_functor) )
	goto err3;
    } else if ( name == ATOM_encoding )
    { atom_t enc;

      if ( !PL_get_atom_ex(arg, &enc) )
	goto err3;
      if ( enc == ATOM_iso_latin_1 )
	table->encoding = REP_ISO_LATIN_1;
      else if ( enc == ATOM_utf8 )
	table->encoding = REP_UTF8;
      else if ( enc == ATOM_native )
	table->encoding = REP_MB;
      else
      { PL_domain_error("encoding", arg);
	goto err3;
      }
    } else
      goto err3;
  }
  if ( !PL_get_nil(tail) )
  { err3:
    free(table);
    return error(ERR_INSTANTIATION, "new_table/4", 3, options);
  }

  table->nfields = nfields;
  table->fields = malloc(sizeof(struct fieldtag)*nfields);
  memcpy(&table->fields[0], fields, sizeof(struct fieldtag)*nfields);

  if ( !table->record_functor )
  { int	maxarg=0;
    int i;

    for(i=0; i<nfields; i++)
      maxarg = max(maxarg, fields[i].arg);

    table->record_functor = PL_new_functor(ATOM_record, maxarg);
  }

  table->magic  = TABLE_MAGIC;
  table->size   = -1;
  table->buffer = NULL;
  table->window = NULL;
#ifdef __WINDOWS__
  table->hfile  = NULL;
  table->hmap   = NULL;
#endif
#ifdef HAVE_MMAP
  table->fd     = -1;
#endif

  return PL_unify_integer(handle, (intptr_t)table);
}


static int
open_table(Table table)
{ if ( !table->opened )
  {
#ifdef __WINDOWS__
    BY_HANDLE_FILE_INFORMATION info;

    table->hfile = CreateFile(PL_atom_chars(table->file),
			      GENERIC_READ,
			      FILE_SHARE_READ,
			      NULL,
			      OPEN_EXISTING,
			      FILE_ATTRIBUTE_NORMAL,
			      NULL);
    if ( !table->hfile )
      goto errio;

    if ( !GetFileInformationByHandle(table->hfile, &info) )
      goto errio;

    table->size = info.nFileSizeLow;

    if ( table->size > 0 )
    { table->hmap = CreateFileMapping(table->hfile,
				      NULL,
				      PAGE_READONLY,
				      0L,
				      (DWORD)table->size, /* Truncated? */
				      NULL);
      if ( !table->hmap )
	goto errio;

      table->buffer = MapViewOfFile(table->hmap,
				    FILE_MAP_READ,
				    0L, 0L, /* offset */
				    0L);	/* size (0=all) */

      if ( !table->buffer )
	goto errio;
    }

    table->window      = table->buffer;
    table->window_size = table->size;
    table->opened      = TRUE;

    return TRUE;

					/* error happened */
  errio:
  { int id = GetLastError();

    if ( table->hmap )
      CloseHandle(table->hmap);
    if ( table->hfile )
      CloseHandle(table->hfile);
    table->buffer = NULL;
    table->window = NULL;
    table->hfile  = NULL;
    table->hmap   = NULL;

    return error(ERR_IO, "open_table/1", id, NULL);
  }
#elif defined(HAVE_MMAP)

    struct stat buf;

#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

    if ( (table->fd = open(PL_atom_chars(table->file), O_RDONLY)) < 0 )
      goto errio;
    if ( fstat(table->fd, &buf) < 0 )
      goto errio;

    table->size = buf.st_size;
    if ( table->size > 0 )
    { if ( (table->buffer = mmap(NULL, table->size,
				 PROT_READ, MAP_SHARED|MAP_NORESERVE,
				 table->fd, 0)) == (char *) -1 )
	goto errio;
    }
    close(table->fd);
    table->fd = -1;

    table->window      = table->buffer;
    table->window_size = table->size;
    table->opened      = TRUE;

    return TRUE;

					/* error happened */
  errio:
    if ( table->buffer )
      munmap(table->buffer, table->size);
    if ( table->fd >= 0 )
      close(table->fd);
    table->buffer = NULL;
    table->window = NULL;
    table->fd     = -1;

    return error(ERR_IO, "open_table/1", errno, NULL);
#endif
  }

  return TRUE;
}


static foreign_t
pl_table_window(term_t handle, term_t start, term_t size)
{ Table table;
  size_t from;
  size_t wsize;

  if ( !get_table_ex(handle, &table) )
    return FALSE;
  if ( !get_size_ex(start, &from) )
    return FALSE;
  if ( !get_size_ex(size, &wsize) )
    return FALSE;

  if ( from > table->size )
    from = table->size;
  table->window = table->buffer + from;

  if ( table->window + wsize > table->buffer + table->size )
    wsize = (table->buffer + table->size) - table->window;
  table->window_size = wsize;

  PL_succeed;
}


static foreign_t
pl_get_table_attribute(term_t handle, term_t name, term_t value)
{ Table table;
  atom_t n;
  size_t arity;

  if ( !get_table_ex(handle, &table) )
    return FALSE;


  if ( PL_get_name_arity(name, &n, &arity) )
  { if ( n == ATOM_file && arity == 0 )
      return PL_unify_atom(value, table->file);

    if ( n == ATOM_field && arity == 1 )
    { term_t a = PL_new_term_ref();
      int i;

      _PL_get_arg(1, name, a);
      if ( PL_get_integer(a, &i) )
      { if ( i >= 1 && i <= table->nfields )
	  return unify_field_info(value, &table->fields[i-1]);

	return FALSE;
      }

      goto ierr2;
    }

    if ( n == ATOM_field_separator && arity == 0 )
      return PL_unify_integer(value, table->field_sep);
    if ( n == ATOM_record_separator && arity == 0 )
      return PL_unify_integer(value, table->record_sep);
    if ( n == ATOM_field_count && arity == 0 )
      return PL_unify_integer(value, table->nfields);
    if ( n == ATOM_key_field && arity == 0 )
    { if ( table->keyfield >= 0 )
	return PL_unify_integer(value, table->keyfield+1);
      else
	return FALSE;
    }

    if ( !open_table(table) )
      return FALSE;

    if ( n == ATOM_size && arity == 0 )
      return PL_unify_integer(value, table->size);
    if ( n == ATOM_window && arity == 0 )
      return PL_unify_term(value,
			   PL_FUNCTOR, FUNCTOR_minus2,
			     PL_LONG, table->window - table->buffer,
			     PL_LONG, table->window_size);
  }

ierr2:
    return error(ERR_INSTANTIATION, "get_table_attribute/3", 2, name);
}


static foreign_t
unify_field_info(term_t t, Field field)	/* name(Type, Flags) */
{ term_t flags = PL_new_term_ref();
  term_t head = PL_new_term_ref();
  term_t tail = PL_copy_term_ref(flags);
  int options = 0;
  atom_t type;

  switch(field->type)
  { case FIELD_ATOM:
      type = ATOM_atom;
      break;
    case FIELD_STRING:
      type = ATOM_string;
      break;
    case FIELD_CODELIST:
      type = ATOM_code_list;
      break;
    case FIELD_INTEGER:
      type = ATOM_integer;
      break;
    case FIELD_HEX:
      type = ATOM_hexadecimal;
      break;
    case FIELD_FLOAT:
      type = ATOM_float;
      break;
    default:
      type = 0;
      assert(0);
  }

  if ( field->flags & FIELD_UNIQUE )
  { if ( !PL_unify_list(tail, head, tail) ||
	 !PL_unify_atom(head, ATOM_unique) )
      return FALSE;
    options++;
  }
  if ( field->flags & FIELD_DOWNCASE )
  { if ( !PL_unify_list(tail, head, tail) ||
	 !PL_unify_atom(head, ATOM_downcase) )
      return FALSE;
    options++;
  }
  if ( field->flags & FIELD_ALLOWBADNUM )
  { if ( !PL_unify_list(tail, head, tail) ||
	 !PL_unify_atom(head, ATOM_syntax) )
      return FALSE;
    options++;
  }
  if ( field->flags & FIELD_MAPSPACETOUNDERSCORE )
  { if ( !PL_unify_list(tail, head, tail) ||
	 !PL_unify_atom(head, ATOM_map_space_to_underscore) )
      return FALSE;
    options++;
  }
  if ( field->flags & FIELD_SORTED )
  { if ( !PL_unify_list(tail, head, tail) )
      return FALSE;
    if ( field->ord )
    { if ( !PL_unify_term(head, PL_FUNCTOR, PL_new_functor(ATOM_sorted, 1),
			  PL_ATOM, field->ord->name) )
	return FALSE;
    } else
    { if ( !PL_unify_atom(head, ATOM_sorted) )
	return FALSE;
    }
    options++;
  }
  if ( field->width > 0 )
  { if ( !PL_unify_term(head, PL_FUNCTOR, PL_new_functor(ATOM_width, 1),
			PL_INT, field->width) )
      return FALSE;
    options++;
  }
  if ( field->arg > 0 )
  { if ( !PL_unify_term(head, PL_FUNCTOR, PL_new_functor(ATOM_arg, 1),
			PL_INT, field->arg) )
      return FALSE;
    options++;
  }

  if ( options )
  { return (PL_unify_nil(tail) &&
	    PL_unify_term(t, PL_FUNCTOR, PL_new_functor(field->name, 2),
			  PL_ATOM, type,
			  PL_TERM, flags));
  } else
  { return PL_unify_term(t, PL_FUNCTOR, PL_new_functor(field->name, 1),
				PL_ATOM, type);

  }
}


static foreign_t
pl_open_table(term_t handle)
{ Table table;

  if ( !get_table_ex(handle, &table) )
    return FALSE;

  return open_table(table);
}


static foreign_t
pl_close_table(term_t handle)
{ Table table;

  if ( !get_table_ex(handle, &table) )
    return FALSE;

  if ( table->buffer )
  {
#ifdef __WINDOWS__
    if ( table->buffer )
      UnmapViewOfFile(table->buffer);
    if ( table->hmap )
      CloseHandle(table->hmap);
    if ( table->hfile )
      CloseHandle(table->hfile);
    table->hfile  = NULL;
    table->hmap   = NULL;
#endif
#ifdef HAVE_MMAP
    if ( table->buffer )
      munmap(table->buffer, table->size);
    if ( table->fd >= 0 )
      close(table->fd);
    table->fd     = -1;
#endif

    table->size   = -1;
    table->buffer = NULL;
    table->window = NULL;
    table->opened = FALSE;
  }

  PL_succeed;
}


static foreign_t
pl_free_table(term_t handle)
{ Table table;

  if ( !pl_close_table(handle) )
    PL_fail;

  if ( !get_table_ex(handle, &table) )
    return FALSE;

  table->magic = 0;			/* so it won't be recognised */
  if ( table->escape_table )
    free(table->escape_table);

  free(table->fields);
  free(table);

  PL_succeed;
}


		 /*******************************
		 *         POSITIONING		*
		 *******************************/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Returns the start of the next non-empty  record. Returns the argument if
the pointer is at the start of a record.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static table_offset_t
find_next_record(Table t, table_offset_t start)
{ int er = t->record_sep;
  char *s = t->window + start;
  char *e = t->window + t->window_size;

  if ( start <= 0 )
  { s = t->window;
    goto out;
  }

  if ( s[-1] == er )
    goto out;

  for( ; *s != er && s < e; s++ )
    ;

out:
  while(*s == er && s < e)
    s++;

  return s-t->window;
}


static table_offset_t
find_start_of_record(Table t, table_offset_t start)
{ char *s;
  int er = t->record_sep;

  if ( start < 0 || start >= (table_offset_t)t->window_size )
    return -1;

  if ( start == (table_offset_t)t->window_size && start > 0 )
    start--;

  s = t->window + start;

  if ( *s == er )
  { char *e = t->window + t->window_size;

    while(*s == er && s<e)
      s++;

    return s-t->window;
  } else
  { while(s>t->window && s[-1] != er)
      s--;

    return s-t->window;
  }
}


static table_offset_t
previous_record(Table t, table_offset_t start)
{ char *s;
  int er = t->record_sep;

  if ( start < 0 || start > (table_offset_t)t->window_size )
    return -1;

  s = t->window + start - 1;

  while(s>=t->window && *s == er)
    s--;

  return find_start_of_record(t, s-t->window);
}


static foreign_t
pl_previous_record(term_t handle, term_t here, term_t prev)
{ Table t;
  table_offset_t start;

  if ( !get_table_ex(handle, &t) )
    return FALSE;
  if ( !get_offset_ex(here, &start) )
    return FALSE;

  if ( !open_table(t) )
    PL_fail;

  if ( start <= 0 )
    PL_fail;

  if ( (start = previous_record(t, start)) < 0 )
    PL_fail;

  return PL_unify_integer(prev, start);
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
start_of_record(+Table, +From, +To, -StartOfRecord)
	Enumerates all start-positions of records in the interval
	[from, to).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static foreign_t
pl_start_of_record(term_t handle,		/* table */
		   term_t from, term_t to,	/* range  */
		   term_t recstart,		/* return */
		   control_t control)		/* backtracking control */
{ Table table;
  size_t n, f;
  table_offset_t t;
  char *end;				/* pointer to end of search */
  char *start;				/* start of search */
  int er;

  switch(PL_foreign_control(control))
  { case PL_FIRST_CALL:
      if ( !get_size_ex(from, &f) )
	return FALSE;
      break;
    case PL_REDO:
      f = PL_foreign_context(control);
      break;
    case PL_PRUNED:
    default:
      PL_succeed;
  }

  if ( !get_table_ex(handle, &table) )
    return FALSE;
  if ( !get_offset_ex(to, &t) )
    return FALSE;

  if ( !open_table(table) )
    return FALSE;
					/* find end of search */
  if ( t < 0 || (size_t)t > table->window_size )
    end = table->window + table->window_size;
  else
    end = table->window + t;

					/* find start of search */
  if ( f <= 0 )
    start = table->window;
  else
    start = table->window + f;

  if ( start > end )
    PL_fail;

  er = table->record_sep;

  if ( start == table->window || start[-1] == er )
    goto found;
  while( *start != er && start < end )
    start++;

  if ( start >= end )
    PL_fail;

found:
  while(*start == er && start < end )
    start++;

  n = start-table->window;

  if ( PL_unify_integer(recstart, n) )
    PL_retry(n+1);

  PL_fail;
}


		 /*******************************
		 *       READING RECORDS	*
		 *******************************/

static int
field_boundaries(Table t, Field f, table_offset_t start,
		 char **sf, char **zf, table_offset_t *next)
{ char *s = t->window + start;
  char *e = t->window + t->window_size;
  char *z;
  int ef = t->field_sep;
  int er = t->record_sep;

  if ( f->width > 0 )			/* fixed-width field */
  { z = s + f->width;
    if ( z > e )
      return FALSE;
    if ( next )
      *next = z - t->window;
  } else
  { if ( ef == ' ' )
    { for( ; isBlank(*s); s++ )		/* skip leading blanks */
      { if ( s >= e )
	  return FALSE;
      }
					/* record to next blank */
      for(z=s+1; !isBlank(*z) && *z != er; z++)
      { if ( z >= e )
	  return FALSE;
      }
    } else
    { for(z=s; *z != ef && *z != er; z++)
      { if ( z >= e )
	  return FALSE;
      }
      if ( *z == er && er == '\n' && z[-1] == '\r' )
      { if ( next )
	  *next = z - t->window + 1;
	z--;
	goto out;
      }
    }

    if ( next )
      *next = z - t->window + 1;
  }

out:
  *sf = s;
  *zf = z;

  return TRUE;
}


static int
digitval(int chr, int base)
{ if ( chr >= '0' && chr <= '9' )
    return chr - '0';
  if ( base == 16 )
  { if ( chr >= 'a' && chr <= 'f' )
      return chr + 10 - 'a';
    if ( chr >= 'A' && chr <= 'F' )
      return chr + 10 - 'A';
  }

  return -1;
}


static void
tab_memcpy(Table table, int flags, char *to, const char *from, size_t len)
{ size_t i = len;
  char *t = to;

  if ( flags & FIELD_DOWNCASE )
  { for( ; i-- > 0; t++, from++)
    { int c = *from & 0xff;

      if ( c == table->escape && i > 0 )
      { int c2 = *++from & 0xff;
	c = table->escape_table[c2];
	i--;
      }
      *t = (isupper(c) ? tolower(c) : c);
    }
    *t = EOS;
  } else if ( table->escape >= 0 )
  { for( ; i-- > 0; from++)
    { int c = *from & 0xff;

      if ( c == table->escape && i > 0 )
      { int c2 = *++from & 0xff;
	c = table->escape_table[c2];
	i--;
      }
      *t++ = c;
    }
    *t = EOS;
  } else
  { strncpy(to, from, len);
    to[len] = EOS;
  }

  if ( flags & FIELD_MAPSPACETOUNDERSCORE )
  { char *q;

    for(q=to; *q; q++)
    { if ( *q == ' ' )
	*q = '_';
    }
  }
}


static int
unify_field_text(Table t, int flags, int type,
		 term_t arg, const char *s, size_t len)
{ char *tmp;
  int rval = FALSE;
  char buf[1024];
  int chflags = t->encoding;

  if ( (flags&(FIELD_DOWNCASE|FIELD_MAPSPACETOUNDERSCORE)) ||
       t->escape >= 0 )
  { if ( len < 256 )
      tmp = buf;
    else
      tmp = malloc(len+1);
    tab_memcpy(t, flags, tmp, s, len);
    len = strlen(tmp);
    s = tmp;
  } else
  { tmp = buf;
  }

  switch(type)
  { case FIELD_ATOM:     chflags |= PL_ATOM;      break;
    case FIELD_STRING:   chflags |= PL_STRING;    break;
    case FIELD_CODELIST: chflags |= PL_CODE_LIST; break;
  }
  rval = PL_unify_chars(arg, chflags, len, s);

  if ( buf != tmp )
    free(tmp);

  return rval;
}



static int
read_field(Table t, Field f, table_offset_t start, table_offset_t *end, term_t arg)
{ char *s, *z;
  int type;

  if ( !field_boundaries(t, f, start, &s, &z, end) )
    return FALSE;

  if ( !arg )
    return TRUE;			/* just skipping */

  switch((type=f->type))
  { case FIELD_ATOM:
    case_atom:;
    case FIELD_STRING:
    case FIELD_CODELIST:
      return unify_field_text(t, f->flags, type, arg, s, z-s);
    { int base;
    case FIELD_HEX:
      base = 16;
      goto case_int;
    case FIELD_INTEGER:
    { long l;
      char *a;
      int digits;

      base=10;
    case_int:

      for(l=0,digits=0,a=s; a<z; a++)
      { int code;

	if ( (code = digitval(*a, base)) >= 0 )
	{ digits++;
	  l = l*base+code;
	}
	else if ( !isBlank(*a) )
	{ if ( f->flags & FIELD_ALLOWBADNUM )
	  { type = FIELD_ATOM;
	    goto case_atom;
	  }
	  return format_error("read_record", s-t->window, f);
	}
      }

      if ( !digits )
      { if ( f->flags & FIELD_ALLOWBADNUM )
	{ type = FIELD_ATOM;
	  goto case_atom;
	}
	return format_error("read_record", s-t->window, f);
      }

      return PL_unify_integer(arg, l);
    }
    }
    case FIELD_FLOAT:
    { char *e;
      double g;

      g = strtod(s, &e);
      while( e < z && isBlank(*e) )
	e++;
      if ( z == e )
	return PL_unify_float(arg, g);
      else if ( f->flags & FIELD_ALLOWBADNUM )
      { type = FIELD_ATOM;
	goto case_atom;
      } else
	return format_error("read_record", s-t->window, f);
    }
  }


  return TRUE;
}


static int
read_record(Table t, table_offset_t start, table_offset_t *end, term_t record)
{ int n;
  Field f;
  term_t arg = PL_new_term_ref();

  if ( !open_table(t) )			/* just make sure */
    return FALSE;

  if ( !PL_unify_functor(record, t->record_functor) )
    return FALSE;

  f = t->fields;
  for(n=1; n<=t->nfields; n++, f++)
  { if ( f->arg > 0 )
    { if ( !PL_get_arg(f->arg, record, arg) ||
	   !read_field(t, f, start, &start, arg) )
	return FALSE;
    } else
    { if ( !read_field(t, f, start, &start, 0) )
	return FALSE;
    }
  }

  if ( end )
    *end = find_next_record(t, start);

  return TRUE;
}


foreign_t
pl_read_record(term_t handle, term_t from, term_t to, term_t record)
{ Table table;
  table_offset_t start, end;

  if ( !get_table_ex(handle, &table) )
    return FALSE;
  if ( !get_offset_ex(from, &start) )
    return FALSE;

  if ( !open_table(table) )
    return FALSE;

  if ( (start = find_start_of_record(table, start)) < 0 )
    PL_fail;

  if ( read_record(table, start, &end, record) )
    return PL_unify_integer(to, end);

  PL_fail;
}


foreign_t
pl_read_record_data(term_t handle, term_t from, term_t to, term_t record)
{ Table table;
  table_offset_t start, end;
  size_t len;

  if ( !get_table_ex(handle, &table) )
    return FALSE;
  if ( !get_offset_ex(from, &start) )
    return FALSE;

  if ( !open_table(table) )
    return FALSE;

  if ( (start = find_start_of_record(table, start)) < 0 )
    PL_fail;
  end = find_next_record(table, start+1);

  if ( end <= start || !PL_unify_integer(to, end) )
    return FALSE;

  len = end-start-1;

  return PL_unify_string_nchars(record, len, start+table->window);
}


foreign_t
pl_read_fields(term_t handle, term_t from, term_t to, term_t fields)
{ Table table;
  Field f;
  table_offset_t start;
  term_t tail = PL_copy_term_ref(fields);
  term_t head = PL_new_term_ref();
  int i;
#ifdef HAVE_ALLOCA
  term_t *argv;
#else
  term_t argv[MAXFIELDS*sizeof(term_t)];
#endif

  if ( !get_table_ex(handle, &table) )
    return FALSE;
  if ( !get_offset_ex(from, &start) )
    return FALSE;

  if ( !open_table(table) ||
       (start = find_start_of_record(table, start)) < 0 )
    return FALSE;

#ifdef HAVE_ALLOCA
  argv = alloca(sizeof(term_t) * table->nfields);
#endif
  for(i=0; i<table->nfields; i++)
    argv[i] = 0;

  while(PL_get_list(tail, head, tail))
  { atom_t a;
    size_t arity;

    if ( !PL_get_name_arity(head, &a, &arity) || arity != 1 )
      return error(ERR_INSTANTIATION, "read_fields/4", 4, fields);

    for(i=0; i<table->nfields; i++)
    { if ( table->fields[i].name == a )
      { argv[i] = PL_new_term_ref();
	if ( !PL_get_arg(1, head, argv[i]) )
	  return FALSE;
	goto cont;
      }
    }

					/* no such record */
    return error(ERR_INSTANTIATION, "read_fields/4", 4, fields);

  cont:
    ;
  }
  if ( !PL_get_nil(tail) )
    return error(ERR_INSTANTIATION, "read_fields/4", 4, fields);

  f = table->fields;
  for(i=0; i<table->nfields; i++, f++)
  { if ( argv[i] )
    { if ( !read_field(table, f, start, &start, argv[i]) )
	return FALSE;
    } else
    { if ( !read_field(table, f, start, &start, 0) )
	return FALSE;
    }
  }

  return PL_unify_integer(to, find_next_record(table, start));
}


		 /*******************************
		 *	      SEARCH		*
		 *******************************/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	-1: query before field
	 0: equal
	 1: query after field
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#define MR_BIND		0x01		/* bind results */
#define MR_KEY_ONLY	0x02		/* only compare the key (=sorted) */
					/* field */

#define MATCH_ERROR    -3		/* Prolog (resource) error */
#define MATCH_NORECORD -2		/* bad record */
#define MATCH_LT       -1		/* < */
#define MATCH_EQ	0		/* == */
#define MATCH_GT	1		/* > */
#define MATCH_NE	2		/* != */

static int
match_field(Table t, Field f, QueryField q, table_offset_t start, table_offset_t *end, int bind)
{ char *a, *z;

  if ( !field_boundaries(t, f, start, &a, &z, end) )
    return MATCH_NORECORD;

  if ( ((q->flags & QUERY_DONTCARE) && !bind) ||
       (q->flags == QUERY_DONTCARE) )
    return MATCH_EQ;

  switch(f->type)
  { case FIELD_ATOM:
    case FIELD_STRING:
    case FIELD_CODELIST:
    { size_t len = z-a;
#ifdef HAVE_ALLOCA
      char *tmp = alloca(len+1);
#define DEALLOC()
#else
      char buf[1024];
      char *tmp;

      if ( len+1<1024 )
	tmp = buf;
      else
	tmp = malloc(len+1);
#define DEALLOC() do { if ( tmp != buf ) free(tmp); } while(0)
#endif

      tab_memcpy(t, f->flags, tmp, a, len);

      if ( q->flags & QUERY_READ )
      { switch(f->type)
	{ case FIELD_ATOM:
	    if ( !PL_unify_atom_chars(q->value.term, tmp) )
	    { DEALLOC();
	      return MATCH_ERROR;
	    }
	    break;
	  case FIELD_STRING:
	    if ( !PL_unify_string_chars(q->value.term, tmp) )
	    { DEALLOC();
	      return MATCH_ERROR;
	    }
	    break;
	  case FIELD_CODELIST:
	    if ( !PL_unify_list_chars(q->value.term, tmp) )
	    { DEALLOC();
	      return MATCH_ERROR;
	    }
	    break;
	}

	DEALLOC();
	return MATCH_EQ;
      }

      if ( q->flags & QUERY_EXACT )
      { if ( q->ord )
	{ int r = compare_strings(q->value.s, tmp, -1, q->ord);

	  DEBUG(Sdprintf("Using ord %s for '%s' <-> '%s'\n",
			 PL_atom_chars(q->ord->name),
			 q->value.s, tmp));
	  DEALLOC();
	  return r;
	} else
	{ int r = strcmp(q->value.s, tmp);
	  DEALLOC();
	  return r < 0 ? MATCH_LT : r > 0 ? MATCH_GT : MATCH_EQ;
	}
      } else if ( q->flags & QUERY_PREFIX )
      { if ( q->ord )
	{ int r = compare_strings(q->value.s, tmp, q->length, q->ord);
	  DEALLOC();
	  return r;
	} else
	{ int r = strncmp(q->value.s, tmp, q->length);
	  DEALLOC();
	  return r < 0 ? MATCH_LT : r > 0 ? MATCH_GT : MATCH_EQ;
	}
      } else if ( q->flags & QUERY_SUBSTRING ) /* Use Boyle Moore */
      { if ( q->ord )
	{ size_t ls = q->length;
	  int i;

	  for(i=0; i+ls<=len; i++)
	  { if ( compare_strings(q->value.s, &tmp[i], ls, q->ord) == 0 )
	    { DEALLOC();
	      return MATCH_EQ;
	    }
	  }
          DEALLOC();
	  return MATCH_NE;
	} else
	{ size_t ls = q->length;
	  size_t i;

	  for(i=0; i+ls<=len; i++)
	  { if ( strncmp(q->value.s, &tmp[i], ls) == 0 )
	    { DEALLOC();
	      return MATCH_EQ;
	    }
	  }
	  DEALLOC();
	  return MATCH_NE;
	}
      }
    }

    { int base;
    case FIELD_HEX:
      base = 16;
      goto case_int;
    case FIELD_INTEGER:
    { long l;
      int digits;

      base = 10;
    case_int:

      for(l=0, digits=0; a<z; a++)
      { int code;

	if ( (code = digitval(*a, base)) >= 0 )
	{ digits++;
	  l = l*base+code;
	}
	else if ( !isBlank(*a) )
	{ if ( f->flags & FIELD_ALLOWBADNUM )
	    return MATCH_NE;
	  format_error("match_record", a-t->window, f);
	  return MATCH_NORECORD;
	}
      }

      if ( !digits )
      { if ( f->flags & FIELD_ALLOWBADNUM )
	  return MATCH_NE;
	format_error("match_record", a-t->window, f);
      }

      if ( q->flags & QUERY_READ )
      { if ( !PL_unify_integer(q->value.term, l) )
	  return MATCH_ERROR;
	return MATCH_EQ;
      }

      return q->value.i == l ? MATCH_EQ : q->value.i < l ? MATCH_LT : MATCH_GT;
    }
    }

    case FIELD_FLOAT:
    { char *e;
      double x;

      x = strtod(a, &e);
      while( e < z && isBlank(*e) )
	e++;
      if ( z != e )
      { if ( f->flags & FIELD_ALLOWBADNUM )
	  return MATCH_NE;
	format_error("match_record", a-t->window, f);
	return MATCH_NORECORD;
      }

      if ( q->flags & QUERY_READ )
      { if ( !PL_unify_float(q->value.term, x) )
	  return MATCH_ERROR;
	return MATCH_EQ;
      }

      return q->value.f == x ? MATCH_EQ : q->value.f < x ? MATCH_LT : MATCH_GT;
    }
    default:
      return MATCH_NORECORD;
  }
}


static int
match_record(Query q, table_offset_t start, table_offset_t *end, int flags)
{ int n;
  Field f;
  int rval = MATCH_EQ;
  Table t = q->table;
  QueryField qf = q->field;
  table_offset_t orgstart = start;

  f = t->fields;
  for(n=1; n<=t->nfields; n++, f++, qf++)
  { int match;

    if ( (flags & MR_KEY_ONLY) && !(f->flags & FIELD_SORTED) )
      continue;

    match = match_field(t, f, qf, start, &start, (flags&MR_BIND));

    switch(match)
    { case MATCH_NORECORD:
      case MATCH_ERROR:
	rval = match;
        goto out;
      case MATCH_EQ:
	continue;
      case MATCH_LT:
      case MATCH_GT:
      case MATCH_NE:
      default:
	if ( rval == MATCH_EQ || (f->flags & FIELD_SORTED) )
	  rval = match;
    }
  }

  out:
  if ( end )
  { if ( start <= orgstart )
      start = orgstart+1;		/* avoid being trapped! */
    *end = find_next_record(t, start);
  }

  return rval;
}


static table_offset_t
execute_binary_search(Query q)
{ Table t       = q->table;
  table_offset_t low     = 0;
  table_offset_t high    = t->window_size;
  table_offset_t here    = find_start_of_record(t, (low+high)/2);

  for(;;)
  { table_offset_t next;

    switch( match_record(q, here, &next, MR_KEY_ONLY) )
    { case MATCH_ERROR:
	return -1;
      case MATCH_NORECORD:
      { if ( here >= (table_offset_t)t->window_size )
	  return FALSE;
	here = next;
	continue;
      }
      case MATCH_LT:
      { table_offset_t rc;
	table_offset_t mid;

	high = here;
	mid = (low+high)/2;
	while((rc=find_start_of_record(t, mid)) == here && mid > low)
	  mid--;
	here = rc;
	DEBUG(Sdprintf("<, %ld %ld %ld\n", (long)low, (long)here, (long)high));
	goto next;
      }
      case MATCH_GT:
      { low = here;
	here = find_start_of_record(t, (low+high)/2);
	DEBUG(Sdprintf(">, %ld %ld %ld\n", (long)low, (long)here, (long)high));
	goto next;
      }
      case MATCH_EQ:
	DEBUG(Sdprintf("=, %ld\n", (long)here));
	if ( t->fields[t->keyfield].flags & FIELD_UNIQUE )
	{ q->technique |= TECH_UNIQUE;
	  return here;
	} else
	{ table_offset_t first = here, prev = here;

	  while(prev > 0)		/* find the first */
	  { prev = previous_record(t, prev);
	    switch( match_record(q, prev, &next, MR_KEY_ONLY) )
	    { case MATCH_EQ:
		first = prev;
	        continue;
	      case MATCH_ERROR:
		return -1;
	    }
	    break;
	  }
	  return first;
	}
      default:
      case MATCH_NE:
	return -1;
    }

  next:
    if ( low == here )
    { while(here <= high && here < (table_offset_t)t->window_size)
      { switch( match_record(q, here, &next, MR_KEY_ONLY) )
	{ case MATCH_EQ:
	    return here;
	  case MATCH_ERROR:
	    return -1;
	}
	here = next;
      }
      return -1;
    }
  }
}


static void
free_query(Query q)
{ int t = q->table->nfields;
  int n;

  for(n=0; n<t; n++)
  { if ( q->field[n].flags & QUERY_MALLOCVAL )
      free(q->field[n].value.ptr);
  }

  free(q);
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rebind_query_vars() refills the invalidated  value.term   slots  of  the
field structures for a redo in pl_in_table().   No  checking needs to be
done as the initial call has already done that.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static int
rebind_query_vars(Query q, term_t from)
{ if ( q->nvars > 0 )
  { term_t tail = PL_copy_term_ref(from);
    term_t head = PL_new_term_ref();
    term_t arg  = PL_new_term_ref();
    int varsleft = q->nvars;

    while(PL_get_list(tail, head, tail))
    { if ( !PL_get_arg(1, head, arg) )
	return FALSE;

      if ( PL_is_variable(arg) )
      { atom_t name;
	size_t arity;
	int i;

	if ( !PL_get_name_arity(head, &name, &arity) )
	  return FALSE;
	for(i=0; i<q->table->nfields; i++)
	{ if ( q->table->fields[i].name == name )
	  { QueryField qf = &q->field[i];
	    qf->value.term = PL_copy_term_ref(arg);
	    if ( --varsleft == 0 )
	      return TRUE;
	    break;
	  }
	}
      }
    }
  }

  return TRUE;
}


static Query
make_query(Table t, term_t from)
{ size_t sizeq = sizeofquery(t);
  Query q = malloc(sizeq);
  term_t tail = PL_copy_term_ref(from);
  term_t head = PL_new_term_ref();
  term_t arg  = PL_new_term_ref();
  int i;

  q->table     = t;
  q->offset    = 0L;
  q->nvars     = 0;
  q->technique = 0;
  for(i=0; i<t->nfields; i++)
    q->field[i].flags = QUERY_DONTCARE;

  while(PL_get_list(tail, head, tail))
  { atom_t name;
    size_t arity;

    if ( !PL_get_name_arity(head, &name, &arity) || arity < 1 || arity > 2 )
      goto err2;
    _PL_get_arg(1, head, arg);

    for(i=0; i<t->nfields; i++)
    { if ( t->fields[i].name == name )
      { QueryField qf = &q->field[i];

	if ( PL_is_variable(arg) )
	{ qf->flags |= QUERY_READ;
	  qf->value.term = PL_copy_term_ref(arg);
	  q->nvars++;
	  goto cont;
	}

	qf->flags &= ~QUERY_DONTCARE;
	assert(qf->flags == 0);

	switch(t->fields[i].type)	/* get value to search for */
	{ case FIELD_ATOM:
	  case FIELD_STRING:
	  case FIELD_CODELIST:
	    if ( !PL_get_atom_chars(arg, &qf->value.s) )
	    { char *tmp;
	      if ( !PL_get_chars(arg, &tmp, CVT_ALL) )
		goto err2;
	      qf->value.s = malloc(strlen(tmp)+1);
	      strcpy(qf->value.s, tmp);
	      qf->flags |= QUERY_MALLOCVAL;
	    }
	    qf->length = strlen(qf->value.s);
	    break;
	  case FIELD_HEX:
	  case FIELD_INTEGER:
	    if ( !PL_get_long(arg, &qf->value.i) )
	      goto err2;
	    break;
	  case FIELD_FLOAT:
	    if ( !PL_get_float(arg, &qf->value.f) )
	      goto err2;
	    break;
	}

	qf->ord = t->fields[i].ord;

	if ( arity == 1 )
	{ qf->flags |= QUERY_EXACT;	/* default; */
	} else
	{ atom_t opt;
	  atom_t tab;
	  size_t a;

	  _PL_get_arg(2, head, arg);
	  if ( !PL_get_name_arity(arg, &opt, &a) || a > 1 )
	    goto err2;
	  if ( opt == ATOM_prefix )
	    qf->flags |= QUERY_PREFIX;
	  else if ( opt == ATOM_substring )
	    qf->flags |= QUERY_SUBSTRING;
	  else if ( opt == ATOM_eq )
	    qf->flags |= QUERY_EXACT;
	  else
	    goto err2;

	  if ( PL_get_arg(1, arg, arg) )
	  { if ( !PL_get_atom(arg, &tab) ||
		 !(tab == ATOM_exact || (qf->ord = findOrdTable(tab))) )
	      goto err2;
	  }
	}

	goto cont;
      }
    }
    goto err2;

    cont:;
  }

  if ( !PL_get_nil(tail) )
  { err2:
    free_query(q);
    return NULL;
  }

  if ( t->keyfield >= 0 &&
       (q->field[t->keyfield].flags == QUERY_EXACT ||
	q->field[t->keyfield].flags == QUERY_PREFIX) &&
       q->field[t->keyfield].ord   == t->fields[t->keyfield].ord )
    q->technique |= TECH_BINARY;
  else
    q->technique |= TECH_LINEAR;

  return q;
}


static int
unique_match(Query q)
{ int i;
  QueryField qf = q->field;
  Field f = q->table->fields;

  for(i=0; i<q->table->nfields; i++, qf++, f++)
  { if ( !(qf->flags & QUERY_DONTCARE) && f->flags & FIELD_UNIQUE )
      return TRUE;
  }

  return FALSE;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
in_table(+Handle, [ +Field(?Spec), ... ], -RecordId)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static foreign_t
pl_in_table(term_t handle, term_t spec, term_t record, control_t control)
{ Query q;

  switch(PL_foreign_control(control))
  { case PL_FIRST_CALL:
    { Table t;

      if ( !get_table_ex(handle, &t) )
	return FALSE;
      if ( !open_table(t) )
	PL_fail;
      if ( !(q=make_query(t, spec)) )
	return error(ERR_INSTANTIATION, "in_table/3", 2, handle);
      if ( !PL_is_variable(record) )
	return error(ERR_INSTANTIATION, "in_table/3", 3, record);

      if ( q->technique & TECH_BINARY )
      { if ( (q->offset = execute_binary_search(q)) == -1 )
	{ free_query(q);
	  return FALSE;
	}
      }

      break;
    }
    case PL_REDO:
      q = PL_foreign_context_address(control);
      rebind_query_vars(q, spec);
      break;
    case PL_PRUNED:
    default:
      q = PL_foreign_context_address(control);
      if ( q )
	free_query(q);
      PL_succeed;
  }


  if ( q->technique & TECH_BINARY )
  { table_offset_t next;

    DEBUG(Sdprintf("Binary search, match at offset=%ld\n", (long)q->offset));

    if ( q->technique & TECH_UNIQUE )
    { int rc;

      if ( (rc=match_record(q, q->offset, &next, MR_BIND)) == MATCH_EQ )
      { if ( !PL_unify_integer(record, q->offset) )
	  return FALSE;
	if ( unique_match(q) )
	{ free_query(q);
	  return TRUE;
	}
	q->offset = next;

	PL_retry_address(q);
      } else if ( rc == MATCH_ERROR )
      { free_query(q);
	return FALSE;
      }
    } else
    { DEBUG(Sdprintf("Non-unique match\n"));

      do
      { int rc;

	DEBUG(Sdprintf("Trying offset %ld\n", (long)q->offset));

	if ( (rc=match_record(q, q->offset, &next, 0)) == MATCH_EQ )
	{ if ( (match_record(q, q->offset, &next, MR_BIND) == MATCH_ERROR) ||
	       !PL_unify_integer(record, q->offset) )
	  { free_query(q);
	    return FALSE;
	  }
	  if ( unique_match(q) )
	  { free_query(q);
	    return TRUE;
	  }
	  q->offset = next;

	  PL_retry_address(q);
	} else if ( rc == MATCH_ERROR )
	{ free_query(q);
	  return FALSE;
	}

	q->offset = next;
      } while( match_record(q, q->offset, &next, MR_KEY_ONLY) == MATCH_EQ );
    }

    free_query(q);
    return FALSE;
  }


  while(q->offset < (table_offset_t)q->table->window_size)
  { table_offset_t next;

    if ( match_record(q, q->offset, &next, 0) == MATCH_EQ )
    { match_record(q, q->offset, &next, MR_BIND);
      if ( !PL_unify_integer(record, q->offset) )
	return FALSE;
      if ( unique_match(q) )
      { free_query(q);
	return TRUE;
      }
      q->offset = next;

      PL_retry_address(q);
    }

    q->offset = next;
  }

  free_query(q);
  PL_fail;
}

		 /*******************************
		 *	       VERSION		*
		 *******************************/

static foreign_t
pl_table_version(term_t version, term_t date)
{ if ( PL_unify_atom_chars(version, TABLE_VERSION) &&
       PL_unify_atom_chars(date, BUILD_DATE) )
    return TRUE;

  return FALSE;
}


		 /*******************************
		 *         INSTALLATION		*
		 *******************************/

install_t
install_table()
{ init_constants();

#ifdef O_ORDER
  install_order();
#endif

  PL_register_foreign("table_version",         2, pl_table_version,       0);
  PL_register_foreign("new_table",             4, pl_new_table,           0);
  PL_register_foreign("open_table",            1, pl_open_table,          0);
  PL_register_foreign("close_table",           1, pl_close_table,         0);
  PL_register_foreign("free_table",	       1, pl_free_table,	  0);
  PL_register_foreign("table_window",	       3, pl_table_window,	  0);
  PL_register_foreign("read_table_record",     4, pl_read_record,         0);
  PL_register_foreign("read_table_record_data",4, pl_read_record_data,    0);
  PL_register_foreign("read_table_fields",     4, pl_read_fields,         0);
  PL_register_foreign("get_table_attribute",   3, pl_get_table_attribute, 0);
  PL_register_foreign("table_previous_record", 3, pl_previous_record,	  0);
  PL_register_foreign("table_start_of_record", 4, pl_start_of_record,
		      PL_FA_NONDETERMINISTIC);
  PL_register_foreign("in_table",	       3, pl_in_table,
		      PL_FA_NONDETERMINISTIC);
}


install_t
install()
{ install_table();
}