File: avc_binwr.c

package info (click to toggle)
avce00 2.0.0-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 940 kB
  • sloc: ansic: 9,851; makefile: 3
file content (2335 lines) | stat: -rw-r--r-- 86,098 bytes parent folder | download | duplicates (6)
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
/* $Id: avc_binwr.c,v 1.17 2006/06/14 16:31:28 daniel Exp $
 *
 * Name:     avc_binwr.c
 * Project:  Arc/Info vector coverage (AVC)  E00->BIN conversion library
 * Language: ANSI C
 * Purpose:  Binary files access functions (write mode).
 * Author:   Daniel Morissette, dmorissette@dmsolutions.ca
 *
 **********************************************************************
 * Copyright (c) 1999-2001, Daniel Morissette
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************
 *
 * $Log: avc_binwr.c,v $
 * Revision 1.17  2006/06/14 16:31:28  daniel
 * Added support for AVCCoverPC2 type (bug 1491)
 *
 * Revision 1.16  2005/06/03 03:49:58  daniel
 * Update email address, website url, and copyright dates
 *
 * Revision 1.15  2001/07/06 05:09:33  daniel
 * Removed #ifdef around fseek to fix NT4 drive problem since ANSI-C requires
 * an fseek() between read and write operations so this applies to Unix too.
 *
 * Revision 1.14  2001/07/06 04:25:00  daniel
 * Fixed a problem writing arc.dir on NT4 networked drives in an empty dir.
 *
 * Revision 1.13  2000/10/16 16:13:29  daniel
 * Fixed sHeader.nPrecision when writing PC TXT files
 *
 * Revision 1.12  2000/09/26 21:40:18  daniel
 * Fixed writing of PC Coverage TXT... they're different from V7 TXT
 *
 * Revision 1.11  2000/09/26 20:21:04  daniel
 * Added AVCCoverPC write
 *
 * Revision 1.10  2000/09/22 19:45:20  daniel
 * Switch to MIT-style license
 *
 * Revision 1.9  2000/05/29 15:31:30  daniel
 * Added Japanese DBCS support
 *
 * Revision 1.8  2000/01/10 02:55:12  daniel
 * Added call to AVCAdjustCaseSensitiveFilename() when creating tables
 *
 * Revision 1.7  1999/12/24 07:18:34  daniel
 * Added PC Arc/Info coverages support
 *
 * Revision 1.6  1999/08/26 17:26:09  daniel
 * Removed printf() messages used in Windows tests
 *
 * Revision 1.5  1999/08/23 18:18:51  daniel
 * Fixed memory leak and some VC++ warnings
 *
 * Revision 1.4  1999/06/08 22:08:14  daniel
 * Modified CreateTable() to overwrite existing arc.dir entries if necessary
 *
 * Revision 1.3  1999/06/08 18:24:32  daniel
 * Fixed some problems with '/' vs '\\' on Windows
 *
 * Revision 1.2  1999/05/17 16:17:36  daniel
 * Added RXP + TXT/TX6/TX7 write support
 *
 * Revision 1.1  1999/05/11 02:34:46  daniel
 * Initial revision
 *
 **********************************************************************/

#include "avc.h"

#include <ctype.h>  /* tolower() */

/*=====================================================================
 * Stuff related to writing the binary coverage files
 *====================================================================*/

static void    _AVCBinWriteCloseTable(AVCBinFile *psFile);

static AVCBinFile *_AVCBinWriteCreateDBFTable(const char *pszPath, 
                                              const char *pszCoverName,
                                              AVCTableDef *psSrcTableDef,
                                              AVCCoverType eCoverType,
                                              int nPrecision, 
                                              AVCDBCSInfo *psDBCSInfo);

/**********************************************************************
 *                          AVCBinWriteCreate()
 *
 * Open a coverage file for writing, write a header if applicable, and
 * initialize the handle to be ready to write objects to the file.
 *
 * pszPath is the coverage (or info directory) path, terminated by
 *         a '/' or a '\\'
 * pszName is the name of the file to create relative to this directory.
 *
 * Note: For most file types except tables, passing pszPath="" and 
 * including the coverage path as part of pszName instead would work.
 *
 * Returns a valid AVCBinFile handle, or NULL if the file could
 * not be created.
 *
 * AVCBinClose() will eventually have to be called to release the 
 * resources used by the AVCBinFile structure.
 **********************************************************************/
AVCBinFile *AVCBinWriteCreate(const char *pszPath, const char *pszName, 
                              AVCCoverType eCoverType,
                              AVCFileType eType, int nPrecision,
                              AVCDBCSInfo *psDBCSInfo)
{
    AVCBinFile   *psFile;
    char         *pszFname = NULL, *pszExt;
    GBool        bCreateIndex = FALSE;
    int          nLen;

    /*-----------------------------------------------------------------
     * Make sure precision value is valid (AVC_DEFAULT_PREC is NOT valid)
     *----------------------------------------------------------------*/
    if (nPrecision!=AVC_SINGLE_PREC && nPrecision!=AVC_DOUBLE_PREC)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "AVCBinWriteCreate(): Invalid precision parameter "
                 "(value must be AVC_SINGLE_PREC or AVC_DOUBLE_PREC)");
        return NULL;
    }

    /*-----------------------------------------------------------------
     * The case of INFO tables is a bit different...
     * tables have to be created through a separate function.
     *----------------------------------------------------------------*/
    if (eType == AVCFileTABLE)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "AVCBinWriteCreate(): TABLEs must be created using "
                 "AVCBinWriteCreateTable()");
        return NULL;
    }

    /*-----------------------------------------------------------------
     * Alloc and init the AVCBinFile struct.
     *----------------------------------------------------------------*/
    psFile = (AVCBinFile*)CPLCalloc(1, sizeof(AVCBinFile));

    psFile->eFileType = eType;
    psFile->nPrecision = nPrecision;

    psFile->pszFilename = (char*)CPLMalloc((strlen(pszPath)+strlen(pszName)+1)*
                                           sizeof(char));
    sprintf(psFile->pszFilename, "%s%s", pszPath, pszName);

    psFile->eCoverType = eCoverType;

    /*-----------------------------------------------------------------
     * PRJ files are text files... we won't use the AVCRawBin*()
     * functions for them... the file will be created and closed
     * inside AVCBinWritePrj().
     *----------------------------------------------------------------*/
    if (eType == AVCFilePRJ)
    {
        return psFile;
    }

    /*-----------------------------------------------------------------
     * All other file types share a very similar creation method.
     *----------------------------------------------------------------*/
    psFile->psRawBinFile = AVCRawBinOpen(psFile->pszFilename, "w",
                                 AVC_COVER_BYTE_ORDER(psFile->eCoverType),
                                         psDBCSInfo);

    if (psFile->psRawBinFile == NULL)
    {
        /* Failed to open file... just return NULL since an error message
         * has already been issued by AVCRawBinOpen()
         */
        CPLFree(psFile->pszFilename);
        CPLFree(psFile);
        return NULL;
    }

    /*-----------------------------------------------------------------
     * Create an Index file if applicable for current file type.
     * Yep, we'll have a problem if filenames come in as uppercase, but
     * this should not happen in a normal situation.
     * For each type there is 3 possibilities, e.g. "pal", "pal.adf", "ttt.pal"
     *----------------------------------------------------------------*/
    pszFname = CPLStrdup(psFile->pszFilename);
    nLen = strlen(pszFname);
    if (eType == AVCFileARC &&
        ( (nLen>=3 && EQUALN((pszExt=pszFname+nLen-3), "arc", 3)) ||
          (nLen>=7 && EQUALN((pszExt=pszFname+nLen-7), "arc.adf", 7)) ) )
    {
        strncpy(pszExt, "arx", 3);
        bCreateIndex = TRUE;
    }
    else if ((eType == AVCFilePAL || eType == AVCFileRPL) &&
             ( (nLen>=3 && EQUALN((pszExt=pszFname+nLen-3), "pal", 3)) ||
               (nLen>=7 && EQUALN((pszExt=pszFname+nLen-7), "pal.adf", 7)) ) )
    {
        strncpy(pszExt, "pax", 3);
        bCreateIndex = TRUE;
    }
    else if (eType == AVCFileCNT &&
             ( (nLen>=3 && EQUALN((pszExt=pszFname+nLen-3), "cnt", 3)) ||
               (nLen>=7 && EQUALN((pszExt=pszFname+nLen-7), "cnt.adf", 7)) ) )
    {
        strncpy(pszExt, "cnx", 3);
        bCreateIndex = TRUE;
    }
    else if ((eType == AVCFileTXT || eType == AVCFileTX6) &&
             ( (nLen>=3 && EQUALN((pszExt=pszFname+nLen-3), "txt", 3)) ||
               (nLen>=7 && EQUALN((pszExt=pszFname+nLen-7), "txt.adf", 7)) ) )
    {
        strncpy(pszExt, "txx", 3);
        bCreateIndex = TRUE;
    }

    if (bCreateIndex)
    {
        psFile->psIndexFile = AVCRawBinOpen(pszFname, "w",
                                    AVC_COVER_BYTE_ORDER(psFile->eCoverType),
                                            psDBCSInfo);
    }

    CPLFree(pszFname);

    /*-----------------------------------------------------------------
     * Generate the appropriate headers for the main file and its index
     * if one was created.
     *----------------------------------------------------------------*/
    if (AVCBinWriteHeader(psFile) == -1)
    {
        /* Failed!  Return NULL */
        AVCBinWriteClose(psFile);
        psFile = NULL;
    }

    return psFile;
}


/**********************************************************************
 *                          _AVCBinWriteHeader()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteHeader() instead)
 *
 * Generate a 100 bytes header using the info in psHeader.
 *
 * Note: PC Coverage files have an initial 256 bytes header followed by the
 * regular 100 bytes header.
 *
 * This function assumes that the file pointer is currently located at
 * the beginning of the file.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteHeader(AVCRawBinFile *psFile, AVCBinHeader *psHeader,
                       AVCCoverType eCoverType)
{
    int nStatus = 0;

    if (eCoverType == AVCCoverPC)
    {
        /* PC Coverage header starts with an initial 256 bytes header
         */
        AVCRawBinWriteInt16(psFile, 0x0400);  /* Signature??? */
        AVCRawBinWriteInt32(psFile, psHeader->nLength);

        AVCRawBinWriteZeros(psFile, 250);
    }

    AVCRawBinWriteInt32(psFile, psHeader->nSignature);
    AVCRawBinWriteInt32(psFile, psHeader->nPrecision);
    AVCRawBinWriteInt32(psFile, psHeader->nRecordSize);
    AVCRawBinWriteZeros(psFile, 12);
    AVCRawBinWriteInt32(psFile, psHeader->nLength);

    /* Pad the rest of the header with zeros
     */
    AVCRawBinWriteZeros(psFile, 72);

    if (CPLGetLastErrorNo() != 0)
        nStatus = -1;

    return nStatus;
}


/**********************************************************************
 *                          AVCBinWriteHeader()
 *
 * Write a header to the specified file using the values that apply to
 * this file's type.  The function simply does nothing if it is called
 * for a file type that requires no header.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int AVCBinWriteHeader(AVCBinFile *psFile)
{
    AVCBinHeader sHeader;
    int          nStatus=0;
    GBool        bHeader = TRUE;

    /*-----------------------------------------------------------------
     * Set the appropriate header information for this file type.
     *----------------------------------------------------------------*/
    sHeader.nPrecision = sHeader.nRecordSize = sHeader.nLength = 0;
    sHeader.nSignature = 9994;
    switch(psFile->eFileType)
    {
      case AVCFileARC:
        sHeader.nPrecision = (psFile->nPrecision == AVC_DOUBLE_PREC)? -1 : 1;
        break;
      case AVCFilePAL:
      case AVCFileRPL:
        sHeader.nPrecision = (psFile->nPrecision == AVC_DOUBLE_PREC)? -11 : 11;
        break;
      case AVCFileLAB:
        sHeader.nSignature = 9993;
        sHeader.nPrecision = (psFile->nPrecision == AVC_DOUBLE_PREC)? -2 : 2;
        sHeader.nRecordSize = (psFile->nPrecision == AVC_DOUBLE_PREC)? 28 : 16;
        break;
      case AVCFileCNT:
        sHeader.nPrecision = (psFile->nPrecision == AVC_DOUBLE_PREC)? -14 : 14;
        break;
      case AVCFileTOL:
        /* single prec: tol.adf has no header
         * double prec: par.adf has a header
         */
        if (psFile->nPrecision == AVC_DOUBLE_PREC)
        {
            sHeader.nSignature = 9993;
            sHeader.nPrecision = 40;
            sHeader.nRecordSize = 8;
        }
        else
        {
            bHeader = FALSE;
        }
        break;
      case AVCFileTXT:
      case AVCFileTX6:
        if (psFile->eCoverType == AVCCoverPC)
            sHeader.nPrecision = 1;
        else
            sHeader.nPrecision = (psFile->nPrecision==AVC_DOUBLE_PREC)? -67:67;
        break;
      default:
        /* Other file types don't need a header */
        bHeader = FALSE;
    }

    /*-----------------------------------------------------------------
     * Write a header only if applicable.
     *----------------------------------------------------------------*/
    if (bHeader)
        nStatus = _AVCBinWriteHeader(psFile->psRawBinFile, &sHeader,
                                     psFile->eCoverType);

    /*-----------------------------------------------------------------
     * Write a header for the index file... it is identical to the main
     * file's header.
     *----------------------------------------------------------------*/
    if (nStatus == 0 && bHeader && psFile->psIndexFile)
        nStatus = _AVCBinWriteHeader(psFile->psIndexFile, &sHeader,
                                     psFile->eCoverType);

    return nStatus;
}

/**********************************************************************
 *                          AVCBinWriteClose()
 *
 * Close a coverage file opened for wirting, and release all memory 
 * (object strcut., buffers, etc.) associated with this file.
 **********************************************************************/

void    AVCBinWriteClose(AVCBinFile *psFile)
{
    if (psFile->eFileType == AVCFileTABLE)
    {
        _AVCBinWriteCloseTable(psFile);
        return;
    }

    /*-----------------------------------------------------------------
     * Write the file size (nbr of 2 byte words) in the header at 
     * byte 24 in the 100 byte header (only if applicable)
     * (And write the same value at byte 2-5 in the first header of PC Cover)
     *----------------------------------------------------------------*/
    if (psFile->psRawBinFile &&
        (psFile->eFileType == AVCFileARC ||
         psFile->eFileType == AVCFilePAL ||
         psFile->eFileType == AVCFileRPL ||
         psFile->eFileType == AVCFileLAB ||
         psFile->eFileType == AVCFileCNT ||
         psFile->eFileType == AVCFileTXT ||
         psFile->eFileType == AVCFileTX6 ||
         (psFile->eFileType == AVCFileTOL && 
          psFile->nPrecision == AVC_DOUBLE_PREC) ) )
    {
        GInt32 n32Size;
        n32Size = psFile->psRawBinFile->nCurPos/2;

        if (psFile->eCoverType == AVCCoverPC)
        {
            /* PC Cover... Pad to multiple of 512 bytes and write 2 headers
             * extra bytes at EOF are not included in the size written in
             * header.
             * The first 256 bytes header is not counted in the file size 
             * written in both headers
             */
            n32Size -= 128;  /* minus 256 bytes */

            if (psFile->psRawBinFile->nCurPos%512 != 0)
                AVCRawBinWriteZeros(psFile->psRawBinFile, 
                                    512 - psFile->psRawBinFile->nCurPos%512);
                
            VSIFSeek(psFile->psRawBinFile->fp, 2, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psRawBinFile, n32Size);

            VSIFSeek(psFile->psRawBinFile->fp, 256+24, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psRawBinFile, n32Size);
        }
        else
        {
            /* V7 Cover ... only 1 header */
            VSIFSeek(psFile->psRawBinFile->fp, 24, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psRawBinFile, n32Size);
        }
    }
        
    AVCRawBinClose(psFile->psRawBinFile);
    psFile->psRawBinFile = NULL;

    /*-----------------------------------------------------------------
     * Same for the index file if it exists.
     *----------------------------------------------------------------*/
    if (psFile->psIndexFile)
    {
        GInt32 n32Size;
        n32Size = psFile->psIndexFile->nCurPos/2;

        if (psFile->eCoverType == AVCCoverPC)
        {
            /* PC Cover... Pad to multiple of 512 bytes and write 2 headers
             * extra bytes at EOF are not included in the size written in
             * header
             */
            n32Size -= 128;  /* minus 256 bytes */

            if (psFile->psIndexFile->nCurPos%512 != 0)
                AVCRawBinWriteZeros(psFile->psIndexFile, 
                                    512 - psFile->psIndexFile->nCurPos%512);
                
            VSIFSeek(psFile->psIndexFile->fp, 2, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psIndexFile, n32Size);

            VSIFSeek(psFile->psIndexFile->fp, 256+24, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psIndexFile, n32Size);
        }
        else
        {
            /* V7 Cover ... only 1 header */
            VSIFSeek(psFile->psIndexFile->fp, 24, SEEK_SET);
            AVCRawBinWriteInt32(psFile->psIndexFile, n32Size);
        }

        AVCRawBinClose(psFile->psIndexFile);
        psFile->psIndexFile = NULL;
    }

    CPLFree(psFile->pszFilename);

    CPLFree(psFile);
}



/**********************************************************************
 *                          _AVCBinWriteIndexEntry()
 *
 * (This function is for internal library use... the index entries
 * are automatically handled by the AVCBinWrite*() functions)
 *
 * Write an Index Entry at the current position in the file.
 *
 * Position is relative to the beginning of the file, including the header.
 * Both position and size are specified in number of 2 byte words.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteIndexEntry(AVCRawBinFile *psFile, 
                           int nPosition, int nSize)
{
    AVCRawBinWriteInt32(psFile, nPosition);
    AVCRawBinWriteInt32(psFile, nSize);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteObject()
 *
 * Write a CNT (Polygon Centroid) structure to the fin object to a 
 * coverage file.
 *
 * Simply redirects the call to the right function based on the value
 * of psFile->eFileType.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteObject(AVCBinFile *psFile, void *psObj)
{
    int nStatus = 0;
    switch(psFile->eFileType)
    {
      case AVCFileARC:
        nStatus = AVCBinWriteArc(psFile, (AVCArc *)psObj);
        break;
      case AVCFilePAL:
      case AVCFileRPL:
        nStatus = AVCBinWritePal(psFile, (AVCPal *)psObj);
        break;
      case AVCFileCNT:
        nStatus = AVCBinWriteCnt(psFile, (AVCCnt *)psObj);
        break;
      case AVCFileLAB:
        nStatus = AVCBinWriteLab(psFile, (AVCLab *)psObj);
        break;
      case AVCFileTOL:
        nStatus = AVCBinWriteTol(psFile, (AVCTol *)psObj);
        break;
      case AVCFilePRJ:
        nStatus = AVCBinWritePrj(psFile, (char **)psObj);
        break;
      case AVCFileTXT:
      case AVCFileTX6:
        nStatus = AVCBinWriteTxt(psFile, (AVCTxt *)psObj);
        break;
      case AVCFileRXP:
        nStatus = AVCBinWriteRxp(psFile, (AVCRxp *)psObj);
        break;
      case AVCFileTABLE:
        nStatus = AVCBinWriteTableRec(psFile, (AVCField *)psObj);
        break;
      default:
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "AVCBinWriteObject(): Unsupported file type!");
        nStatus = -1;
    }

    return nStatus;
}


/*=====================================================================
 *                              ARC
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteArc()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteNextArc() instead)
 *
 * Write an Arc structure to the file.
 *
 * The contents of the psArc structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteArc(AVCRawBinFile *psFile, AVCArc *psArc,
                    int nPrecision, AVCRawBinFile *psIndexFile)
{
    int         i, nRecSize, nCurPos;

    nCurPos = psFile->nCurPos/2;  /* Value in 2 byte words */

    AVCRawBinWriteInt32(psFile, psArc->nArcId);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    /*-----------------------------------------------------------------
     * Record size is expressed in 2 byte words, and does not count the
     * first 8 bytes of the ARC entry.
     *----------------------------------------------------------------*/
    nRecSize = (6 * 4 + psArc->numVertices*2 * 
                ((nPrecision == AVC_SINGLE_PREC)? 4 : 8)) / 2;
    AVCRawBinWriteInt32(psFile, nRecSize);
    AVCRawBinWriteInt32(psFile, psArc->nUserId);
    AVCRawBinWriteInt32(psFile, psArc->nFNode);
    AVCRawBinWriteInt32(psFile, psArc->nTNode);
    AVCRawBinWriteInt32(psFile, psArc->nLPoly);
    AVCRawBinWriteInt32(psFile, psArc->nRPoly);
    AVCRawBinWriteInt32(psFile, psArc->numVertices);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        for(i=0; i<psArc->numVertices; i++)
        {
            AVCRawBinWriteFloat(psFile, (float)psArc->pasVertices[i].x);
            AVCRawBinWriteFloat(psFile, (float)psArc->pasVertices[i].y);
        }
    }
    else
    {
        for(i=0; i<psArc->numVertices; i++)
        {
            AVCRawBinWriteDouble(psFile, psArc->pasVertices[i].x);
            AVCRawBinWriteDouble(psFile, psArc->pasVertices[i].y);
        }

    }

    /*-----------------------------------------------------------------
     * Write index entry (arx.adf)
     *----------------------------------------------------------------*/
    if (psIndexFile)
    {
        _AVCBinWriteIndexEntry(psIndexFile, nCurPos, nRecSize);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteArc()
 *
 * Write the next Arc structure to the file.
 *
 * The contents of the psArc structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteArc(AVCBinFile *psFile, AVCArc *psArc)
{
    if (psFile->eFileType != AVCFileARC)
        return -1;

    return _AVCBinWriteArc(psFile->psRawBinFile, psArc,
                           psFile->nPrecision, psFile->psIndexFile);
}


/*=====================================================================
 *                              PAL
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWritePal()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWritePal() instead)
 *
 * Write a PAL (Polygon Arc List) structure to the file.
 *
 * The contents of the psPal structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWritePal(AVCRawBinFile *psFile, AVCPal *psPal, 
                    int nPrecision, AVCRawBinFile *psIndexFile)
{
    int i, nRecSize, nCurPos;

    nCurPos = psFile->nCurPos/2;  /* Value in 2 byte words */

    AVCRawBinWriteInt32(psFile, psPal->nPolyId);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    /*-----------------------------------------------------------------
     * Record size is expressed in 2 byte words, and does not count the
     * first 8 bytes of the PAL entry.
     *----------------------------------------------------------------*/
    nRecSize = ( 4 + psPal->numArcs*3 * 4 + 
                4 * ((nPrecision == AVC_SINGLE_PREC)? 4 : 8)) / 2;

    AVCRawBinWriteInt32(psFile, nRecSize);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        AVCRawBinWriteFloat(psFile, (float)psPal->sMin.x);
        AVCRawBinWriteFloat(psFile, (float)psPal->sMin.y);
        AVCRawBinWriteFloat(psFile, (float)psPal->sMax.x);
        AVCRawBinWriteFloat(psFile, (float)psPal->sMax.y);
    }
    else
    {
        AVCRawBinWriteDouble(psFile, psPal->sMin.x);
        AVCRawBinWriteDouble(psFile, psPal->sMin.y);
        AVCRawBinWriteDouble(psFile, psPal->sMax.x);
        AVCRawBinWriteDouble(psFile, psPal->sMax.y);
    }

    AVCRawBinWriteInt32(psFile, psPal->numArcs);

    for(i=0; i<psPal->numArcs; i++)
    {
        AVCRawBinWriteInt32(psFile, psPal->pasArcs[i].nArcId);
        AVCRawBinWriteInt32(psFile, psPal->pasArcs[i].nFNode);
        AVCRawBinWriteInt32(psFile, psPal->pasArcs[i].nAdjPoly);
    }

    /*-----------------------------------------------------------------
     * Write index entry (pax.adf)
     *----------------------------------------------------------------*/
    if (psIndexFile)
    {
        _AVCBinWriteIndexEntry(psIndexFile, nCurPos, nRecSize);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWritePal()
 *
 * Write a PAL (Polygon Arc List) structure to the file.
 *
 * The contents of the psPal structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWritePal(AVCBinFile *psFile, AVCPal *psPal)
{
    if (psFile->eFileType != AVCFilePAL && psFile->eFileType != AVCFileRPL)
        return -1;

    return _AVCBinWritePal(psFile->psRawBinFile, psPal,
                           psFile->nPrecision, psFile->psIndexFile);
}

/*=====================================================================
 *                              CNT
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteCnt()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteCnt() instead)
 *
 * Write a CNT (Polygon Centroid) structure to the file.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteCnt(AVCRawBinFile *psFile, AVCCnt *psCnt, 
                              int nPrecision, AVCRawBinFile *psIndexFile)
{
    int i, nRecSize, nCurPos;

    nCurPos = psFile->nCurPos/2;  /* Value in 2 byte words */

    AVCRawBinWriteInt32(psFile, psCnt->nPolyId);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    /*-----------------------------------------------------------------
     * Record size is expressed in 2 byte words, and does not count the
     * first 8 bytes of the CNT entry.
     *----------------------------------------------------------------*/
    nRecSize = ( 4 + psCnt->numLabels * 4 + 
                 2 * ((nPrecision == AVC_SINGLE_PREC)? 4 : 8)) / 2;

    AVCRawBinWriteInt32(psFile, nRecSize);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        AVCRawBinWriteFloat(psFile, (float)psCnt->sCoord.x);
        AVCRawBinWriteFloat(psFile, (float)psCnt->sCoord.y);
    }
    else
    {
        AVCRawBinWriteDouble(psFile, psCnt->sCoord.x);
        AVCRawBinWriteDouble(psFile, psCnt->sCoord.y);
    }

    AVCRawBinWriteInt32(psFile, psCnt->numLabels);

    for(i=0; i<psCnt->numLabels; i++)
    {
        AVCRawBinWriteInt32(psFile, psCnt->panLabelIds[i]);
    }

    /*-----------------------------------------------------------------
     * Write index entry (cnx.adf)
     *----------------------------------------------------------------*/
    if (psIndexFile)
    {
        _AVCBinWriteIndexEntry(psIndexFile, nCurPos, nRecSize);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteCnt()
 *
 * Write a CNT (Polygon Centroid) structure to the file.
 *
 * The contents of the psCnt structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteCnt(AVCBinFile *psFile, AVCCnt *psCnt)
{
    if (psFile->eFileType != AVCFileCNT)
        return -1;

    return _AVCBinWriteCnt(psFile->psRawBinFile, psCnt,
                           psFile->nPrecision, psFile->psIndexFile);
}

/*=====================================================================
 *                              LAB
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteLab()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteLab() instead)
 *
 * Write a LAB (Centroid Label) structure to the file.
 *
 * The contents of the psLab structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteLab(AVCRawBinFile *psFile, AVCLab *psLab, 
                    int nPrecision)
{

    AVCRawBinWriteInt32(psFile, psLab->nValue);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    AVCRawBinWriteInt32(psFile, psLab->nPolyId);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord1.x);
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord1.y);
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord2.x);
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord2.y);
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord3.x);
        AVCRawBinWriteFloat(psFile, (float)psLab->sCoord3.y);
    }
    else
    {
        AVCRawBinWriteDouble(psFile, psLab->sCoord1.x);
        AVCRawBinWriteDouble(psFile, psLab->sCoord1.y);
        AVCRawBinWriteDouble(psFile, psLab->sCoord2.x);
        AVCRawBinWriteDouble(psFile, psLab->sCoord2.y);
        AVCRawBinWriteDouble(psFile, psLab->sCoord3.x);
        AVCRawBinWriteDouble(psFile, psLab->sCoord3.y);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}


/**********************************************************************
 *                          AVCBinWriteLab()
 *
 * Write a LAB (Centroid Label) structure to the file.
 *
 * The contents of the psLab structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteLab(AVCBinFile *psFile, AVCLab *psLab)
{
    if (psFile->eFileType != AVCFileLAB)
        return -1;

    return _AVCBinWriteLab(psFile->psRawBinFile, psLab,
                           psFile->nPrecision);
}

/*=====================================================================
 *                              TOL
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteTol()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteTol() instead)
 *
 * Write a TOL (tolerance) structure to the file.
 *
 * The contents of the psTol structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteTol(AVCRawBinFile *psFile, AVCTol *psTol, 
                    int nPrecision)
{

    AVCRawBinWriteInt32(psFile, psTol->nIndex);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    AVCRawBinWriteInt32(psFile, psTol->nFlag);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        AVCRawBinWriteFloat(psFile, (float)psTol->dValue);
    }
    else
    {
        AVCRawBinWriteDouble(psFile, psTol->dValue);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteTol()
 *
 * Write a TOL (tolerance) structure to the file.
 *
 * The contents of the psTol structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteTol(AVCBinFile *psFile, AVCTol *psTol)
{
    if (psFile->eFileType != AVCFileTOL)
        return -1;

    return _AVCBinWriteTol(psFile->psRawBinFile, psTol,
                           psFile->nPrecision);
}

/*=====================================================================
 *                              PRJ
 *====================================================================*/

/**********************************************************************
 *                          AVCBinWritePrj()
 *
 * Write a PRJ (Projection info) to the file.
 *
 * Since a PRJ file is a simple text file and there is only ONE projection
 * info per prj.adf file, this function behaves differently from the 
 * other ones... all the job is done here, including creating and closing
 * the output file.
 *
 * The contents of the papszPrj is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWritePrj(AVCBinFile *psFile, char **papszPrj)
{
    if (psFile->eFileType != AVCFilePRJ)
        return -1;

    CSLSave(papszPrj, psFile->pszFilename);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}


/*=====================================================================
 *                              TXT/TX6/TX7
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteTxt()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteTxt() instead)
 *
 * Write a TXT/TX6/TX7 (Annotation) structure to the file.
 *
 * The contents of the psTxt structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteTxt(AVCRawBinFile *psFile, AVCTxt *psTxt, 
                              int nPrecision, AVCRawBinFile *psIndexFile)
{
    int i, nRecSize, nCurPos, nStrLen, numVertices;

    nCurPos = psFile->nCurPos/2;  /* Value in 2 byte words */

    AVCRawBinWriteInt32(psFile, psTxt->nTxtId);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    /*-----------------------------------------------------------------
     * Record size is expressed in 2 byte words, and does not count the
     * first 8 bytes of the TXT entry.
     *----------------------------------------------------------------*/
    /* String uses a multiple of 4 bytes of storage */
    if (psTxt->pszText)
        nStrLen = ((strlen(psTxt->pszText) + 3)/4)*4;
    else
        nStrLen = 0;

    numVertices = ABS(psTxt->numVerticesLine) + ABS(psTxt->numVerticesArrow);
    nRecSize = (112 + 8 + nStrLen + 
                (numVertices*2+3)* ((nPrecision == AVC_SINGLE_PREC)?4:8)) / 2;

    AVCRawBinWriteInt32(psFile, nRecSize);

    AVCRawBinWriteInt32(psFile, psTxt->nUserId );
    AVCRawBinWriteInt32(psFile, psTxt->nLevel );
    AVCRawBinWriteFloat(psFile, psTxt->f_1e2 );
    AVCRawBinWriteInt32(psFile, psTxt->nSymbol );
    AVCRawBinWriteInt32(psFile, psTxt->numVerticesLine );
    AVCRawBinWriteInt32(psFile, psTxt->n28 );
    AVCRawBinWriteInt32(psFile, psTxt->numChars );
    AVCRawBinWriteInt32(psFile, psTxt->numVerticesArrow );

    for(i=0; i<20; i++)
    {
        AVCRawBinWriteInt16(psFile, psTxt->anJust1[i] );
    }
    for(i=0; i<20; i++)
    {
        AVCRawBinWriteInt16(psFile, psTxt->anJust2[i] );
    }

    if (nPrecision == AVC_SINGLE_PREC)
    {
        AVCRawBinWriteFloat(psFile, (float)psTxt->dHeight);
        AVCRawBinWriteFloat(psFile, (float)psTxt->dV2);
        AVCRawBinWriteFloat(psFile, (float)psTxt->dV3);
    }
    else
    {
        AVCRawBinWriteDouble(psFile, psTxt->dHeight);
        AVCRawBinWriteDouble(psFile, psTxt->dV2);
        AVCRawBinWriteDouble(psFile, psTxt->dV3);
    }

    if (nStrLen > 0)
        AVCRawBinWritePaddedString(psFile, nStrLen, psTxt->pszText);

    if (nPrecision == AVC_SINGLE_PREC)
    {
        for(i=0; i<numVertices; i++)
        {
            AVCRawBinWriteFloat(psFile, (float)psTxt->pasVertices[i].x);
            AVCRawBinWriteFloat(psFile, (float)psTxt->pasVertices[i].y);
        }
    }
    else
    {
        for(i=0; i<numVertices; i++)
        {
            AVCRawBinWriteDouble(psFile, psTxt->pasVertices[i].x);
            AVCRawBinWriteDouble(psFile, psTxt->pasVertices[i].y);
        }
    }

    AVCRawBinWriteZeros(psFile, 8);

    /*-----------------------------------------------------------------
     * Write index entry (cnx.adf)
     *----------------------------------------------------------------*/
    if (psIndexFile)
    {
        _AVCBinWriteIndexEntry(psIndexFile, nCurPos, nRecSize);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          _AVCBinWritePCCoverageTxt()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteTxt() instead)
 *
 * Write a TXT (Annotation) structure to a AVCCoverPC file.
 *
 * The contents of the psTxt structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * This function assumes that PC Coverages are always single precision.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWritePCCoverageTxt(AVCRawBinFile *psFile, AVCTxt *psTxt, 
                              int nPrecision, AVCRawBinFile *psIndexFile)
{
    int i, nRecSize, nCurPos, nStrLen, numVertices;

    CPLAssert(nPrecision == AVC_SINGLE_PREC);

    nCurPos = psFile->nCurPos/2;  /* Value in 2 byte words */

    AVCRawBinWriteInt32(psFile, psTxt->nTxtId);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    /*-----------------------------------------------------------------
     * Record size is expressed in 2 byte words, and does not count the
     * first 8 bytes of the TXT entry.
     *----------------------------------------------------------------*/
    /* String uses a multiple of 4 bytes of storage,
     * And if text is already a multiple of 4 bytes then we include 4 extra 
     * spaces anyways (was probably a bug in the software!).
     */
    if (psTxt->pszText)
        nStrLen = ((strlen(psTxt->pszText) + 4)/4)*4;
    else
        nStrLen = 4;

    nRecSize = (92 - 8 + nStrLen) / 2;

    AVCRawBinWriteInt32(psFile, nRecSize);
    AVCRawBinWriteInt32(psFile, psTxt->nLevel );

    /*-----------------------------------------------------------------
     * Number of vertices to write:
     * Note that because of the way V7 binary TXT files work, the rest of the
     * lib expects to receive duplicate coords for the first vertex, so
     * we will also receive an additional vertex for that but we won't write
     * it.  We also ignore the arrow vertices if there is any.
     *----------------------------------------------------------------*/
    numVertices = ABS(psTxt->numVerticesLine) -1;
    numVertices = MIN(4, numVertices);  /* Maximum of 4 points */

    AVCRawBinWriteInt32(psFile, numVertices );

    for(i=0; i<numVertices; i++)
    {
        AVCRawBinWriteFloat(psFile, (float)psTxt->pasVertices[i+1].x);
        AVCRawBinWriteFloat(psFile, (float)psTxt->pasVertices[i+1].y);
    }

    AVCRawBinWriteZeros(psFile, (4-numVertices)*4*2 + 28);

    AVCRawBinWriteFloat(psFile, (float)psTxt->dHeight);
    AVCRawBinWriteFloat(psFile, psTxt->f_1e2 );
    AVCRawBinWriteInt32(psFile, psTxt->nSymbol );
    AVCRawBinWriteInt32(psFile, psTxt->numChars );

    if (nStrLen > 0)
        AVCRawBinWritePaddedString(psFile, nStrLen, psTxt->pszText);

    /*-----------------------------------------------------------------
     * Write index entry (cnx.adf)
     *----------------------------------------------------------------*/
    if (psIndexFile)
    {
        _AVCBinWriteIndexEntry(psIndexFile, nCurPos, nRecSize);
    }

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}


/**********************************************************************
 *                          AVCBinWriteTxt()
 *
 * Write a TXT/TX6/TX7 (Annotation) structure to the file.
 *
 * The contents of the psTxt structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteTxt(AVCBinFile *psFile, AVCTxt *psTxt)
{
    if (psFile->eFileType != AVCFileTXT && psFile->eFileType != AVCFileTX6)
        return -1;

    /* AVCCoverPC and AVCCoverWeird have a different TXT format than AVCCoverV7
     */
    if (psFile->eCoverType == AVCCoverPC || 
        psFile->eCoverType == AVCCoverWeird)
    {
        return _AVCBinWritePCCoverageTxt(psFile->psRawBinFile, psTxt,
                                         psFile->nPrecision, 
                                         psFile->psIndexFile);
    }
    else
    {
        return _AVCBinWriteTxt(psFile->psRawBinFile, psTxt,
                               psFile->nPrecision, psFile->psIndexFile);
    }
}

/*=====================================================================
 *                              RXP
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteRxp()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteRxp() instead)
 *
 * Write a RXP (Region something...) structure to the file.
 *
 * The contents of the psRxp structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteRxp(AVCRawBinFile *psFile, AVCRxp *psRxp, 
                    int nPrecision)
{

    AVCRawBinWriteInt32(psFile, psRxp->n1);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    AVCRawBinWriteInt32(psFile, psRxp->n2);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteRxp()
 *
 * Write a  RXP (Region something...) structure to the file.
 *
 * The contents of the psRxp structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteRxp(AVCBinFile *psFile, AVCRxp *psRxp)
{
    if (psFile->eFileType != AVCFileRXP)
        return -1;

    return _AVCBinWriteRxp(psFile->psRawBinFile, psRxp,
                           psFile->nPrecision);
}


/*=====================================================================
 *                              TABLES
 *====================================================================*/

/**********************************************************************
 *                          _AVCBinWriteArcDir()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteCreateTable() instead)
 *
 * Write an ARC.DIR entry at the current position in file.
 *
 * The contents of the psTableDef structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteArcDir(AVCRawBinFile *psFile, AVCTableDef *psTableDef)
{
    /* STRING values MUST be padded with spaces.
     */
    AVCRawBinWritePaddedString(psFile, 32, psTableDef->szTableName);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    AVCRawBinWritePaddedString(psFile, 8, psTableDef->szInfoFile);

    AVCRawBinWriteInt16(psFile, psTableDef->numFields);

    /* Record size must be a multiple of 2 bytes */
    AVCRawBinWriteInt16(psFile, (GInt16)(((psTableDef->nRecSize+1)/2)*2));

    /* ??? Unknown values ??? */
    AVCRawBinWritePaddedString(psFile, 16, "                    ");
    AVCRawBinWriteInt16(psFile, 132);
    AVCRawBinWriteInt16(psFile, 0);

    AVCRawBinWriteInt32(psFile, psTableDef->numRecords);

    AVCRawBinWriteZeros(psFile, 10);

    AVCRawBinWritePaddedString(psFile, 2, psTableDef->szExternal);

    AVCRawBinWriteZeros(psFile, 238);
    AVCRawBinWritePaddedString(psFile, 8, "                    ");
    AVCRawBinWriteZeros(psFile, 54);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}


/**********************************************************************
 *                          _AVCBinWriteArcNit()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteCreateTable() instead)
 *
 * Write an ARC####.NIT entry at the current position in file.
 *
 * The contents of the psTableDef structure is assumed to be valid... this
 * function performs no validation on the consistency of what it is 
 * given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteArcNit(AVCRawBinFile *psFile, AVCFieldInfo *psField)
{
    /* STRING values MUST be padded with spaces.
     */
    AVCRawBinWritePaddedString(psFile, 16, psField->szName);
    if (CPLGetLastErrorNo() != 0)
        return -1;

    AVCRawBinWriteInt16(psFile, psField->nSize);
    AVCRawBinWriteInt16(psFile, psField->v2);
    AVCRawBinWriteInt16(psFile, psField->nOffset);
    AVCRawBinWriteInt16(psFile, psField->v4);
    AVCRawBinWriteInt16(psFile, psField->v5);
    AVCRawBinWriteInt16(psFile, psField->nFmtWidth);
    AVCRawBinWriteInt16(psFile, psField->nFmtPrec);
    AVCRawBinWriteInt16(psFile, psField->nType1);
    AVCRawBinWriteInt16(psFile, psField->nType2);
    AVCRawBinWriteInt16(psFile, psField->v10);
    AVCRawBinWriteInt16(psFile, psField->v11);
    AVCRawBinWriteInt16(psFile, psField->v12);
    AVCRawBinWriteInt16(psFile, psField->v13);

    AVCRawBinWritePaddedString(psFile, 16, psField->szAltName);

    AVCRawBinWriteZeros(psFile, 56);

    AVCRawBinWriteInt16(psFile, psField->nIndex);

    AVCRawBinWriteZeros(psFile, 28);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}


/**********************************************************************
 *                     _AVCBinWriteCreateArcDirEntry()
 *
 * Add an entry in the ARC.DIR for the table defined in psSrcTableDef.
 *
 * If an entry with the same table name already exists then this entry
 * will be reused and overwritten.
 *
 * Note: there could be a problem if 2 processes try to add an entry
 * at the exact same time... does Arc/Info do any locking on that file???
 * 
 * Returns an integer value corresponding to the new table index (ARC####)
 * or -1 if something failed.
 **********************************************************************/

/* Prototype for _AVCBinReadNextArcDir() from avc_bin.c
 */
int _AVCBinReadNextArcDir(AVCRawBinFile *psFile, AVCTableDef *psArcDir);

int _AVCBinWriteCreateArcDirEntry(const char *pszArcDirFile,
                                  AVCTableDef *psTableDef, 
                                  AVCDBCSInfo *psDBCSInfo)
{
    int          iEntry, numDirEntries=0, nTableIndex = 0;
    VSIStatBuf   sStatBuf;
    AVCRawBinFile *hRawBinFile;
    GBool        bFound;
    AVCTableDef  sEntry;

    /*-----------------------------------------------------------------
     * Open and Scan the ARC.DIR to establish the table index (ARC####)
     *----------------------------------------------------------------*/
#ifdef _WIN32
    /*-----------------------------------------------------------------
     * Note, DM, 20010507 - We used to use VSIFStat() to establish the
     * size of arc.dir, but when working on a WinNT4 networked drive, the
     * stat() information was not always right, and we sometimes ended 
     * up overwriting arc.dir entries.  The solution: open and scan arc.dir
     * until EOF to establish its size.  
     * That trick also seems to fix another network buffer problem: when 
     * writing a coverage in a new empty dir (with no info dir yet), we
     * would get an error in fwrite() while writing the 3rd arc.dir 
     * entry of the coverage.  That second problem could also have been 
     * fixed by forcing a VSIFSeek() before the first fwrite()... we've 
     * added it below.
     *----------------------------------------------------------------*/
    FILE *fp;
    if ((fp = VSIFOpen(pszArcDirFile, "r")) != NULL)
    {
        char buf[380];
        while (!VSIFEof(fp))
        {
            if (VSIFRead(buf, 380, 1, fp) == 1)
                numDirEntries++;
        }
        VSIFClose(fp);
        hRawBinFile = AVCRawBinOpen(pszArcDirFile, "r+",
                                    AVC_COVER_BYTE_ORDER(AVCCoverV7),
                                    psDBCSInfo);
    }
    else 
#endif
    /* On Unix we can still use fstat() */
    if ( VSIStat(pszArcDirFile, &sStatBuf) != -1 )
    {
        numDirEntries = sStatBuf.st_size/380;
        hRawBinFile = AVCRawBinOpen(pszArcDirFile, "r+",
                                    AVC_COVER_BYTE_ORDER(AVCCoverV7),
                                    psDBCSInfo);
    }
    else
    {
        numDirEntries = 0;
        hRawBinFile = AVCRawBinOpen(pszArcDirFile, "w", 
                                    AVC_COVER_BYTE_ORDER(AVCCoverV7), 
                                    psDBCSInfo);
    }

    if (hRawBinFile == NULL)
    {
        /* Failed to open file... just return -1 since an error message
         * has already been issued by AVCRawBinOpen()
         */
        return -1;
    }

    /* Init nTableIndex at -1 so that first table created should have 
     * index 0 
     */
    nTableIndex = -1;
    iEntry = 0;
    bFound = FALSE;
    while(!bFound && iEntry<numDirEntries &&
          _AVCBinReadNextArcDir(hRawBinFile, &sEntry) == 0)
    {
        nTableIndex = atoi(sEntry.szInfoFile+3);
        if (EQUALN(psTableDef->szTableName, sEntry.szTableName, 
                   strlen(psTableDef->szTableName)))
        {   
            bFound = TRUE;
            break;
        }
        iEntry++;
    }

    /*-----------------------------------------------------------------
     * Reposition the file pointer and write the entry.
     *
     * We use VSIFSeek() directly since the AVCRawBin*() functions do
     * not support random access yet... it is OK to do so here since the
     * ARC.DIR does not have a header and we will close it right away.
     *----------------------------------------------------------------*/
    if (bFound)
        VSIFSeek(hRawBinFile->fp, iEntry*380, SEEK_SET);
    else
    {
        /* Not found... Use the next logical table index */
        nTableIndex++;

        /* We're already at EOF so we shouldn't need to fseek here, but
         * ANSI-C requires that a file positioning function be called 
         * between read and writes... this had never been a problem before
         * on any system except with NT4 network drives.
         */
        VSIFSeek(hRawBinFile->fp, numDirEntries*380, SEEK_SET);
    }

    sprintf(psTableDef->szInfoFile, "ARC%4.4d", nTableIndex);
    _AVCBinWriteArcDir(hRawBinFile, psTableDef);

    AVCRawBinClose(hRawBinFile);

    return nTableIndex;
}


/**********************************************************************
 *                          AVCBinWriteCreateTable()
 *
 * Open an INFO table for writing:
 *
 *  - Add an entry for the new table in the info/arc.dir
 *  - Write the attributes definitions to the info/arc####.nit
 *  - Create the data file, ready to write data records to it
 *  - If necessary, set the arc####.dat to point to the location of
 *    the data file.
 *
 * pszInfoPath is the info directory path, terminated by a '/' or a '\\'
 * It is assumed that this 'info' directory already exists and is writable.
 *
 * psTableDef should contain a valid table definition for this coverage.
 * This function will create and maintain its own copy of the structure.
 *
 * The name of the file to create and its location will be based on the 
 * table name and the external ("XX") flag values in the psTableDef 
 * structure, so you have to make sure that these values are valid.
 *
 * If a table with the same name is already present in the arc.dir, then 
 * the same arc.dir entry will be used and overwritten.  This happens
 * when a coverage directory is deleted by hand.  The behavior implemented
 * here correspond to Arc/Info's behavior.
 *
 * For internal tables, the data file goes directly in the info directory, so
 * there is not much to worry about.
 *
 * For external tables, the table name is composed of 3 parts:
 *
 *         <COVERNAME>.<EXT><SUBCLASSNAME>
 *
 *  - <COVERNAME>:
 *    The first part of the table name (before the '.') is the
 *    name of the coverage to which the table belongs, and the data file
 *    will be created in this coverage's directory... so it is assumed that
 *    the directory "../<covername>" already exists and is writable.
 *  - <EXT>:
 *    The coverage name is followed by a 3 chars extension that will be 
 *    used to build the name of the external table to create.
 *  - <SUBCLASSNAME>:
 *    For some table types, the extension is followed by a subclass name.
 *    
 *  When <SUBCLASSNAME> is present, then the data file name will be:
 *            "../<covername>/<subclassname>.<ext>"
 *
 *    e.g. The table named "TEST.PATCOUNTY" would be stored in the file
 *         "../test/county.pat" (this path is realtive to the info directory)
 *
 *  When the <SUBCLASSNAME> is not present, then the name of the data file
 *  will be the "../<covername>/<ext>.adf"
 *
 *    e.g. The table named "TEST.PAT" would be stored in the file 
 *         "../test/pat.adf"
 *
 * Of course, it would be too easy if there were no exceptions to these
 * rules!  Single precision ".TIC" and ".BND" follow the above rules and
 * will be named "tic.adf" and "bnd.adf" but in double precision coverages,
 * they will be named "dbltic.adf" and "dblbnd.adf".
 *
 * Returns a valid AVCBinFile handle, or NULL if the table could
 * not be created.
 *
 * AVCBinClose() will eventually have to be called to release the 
 * resources used by the AVCBinFile structure.
 **********************************************************************/
AVCBinFile *AVCBinWriteCreateTable(const char *pszInfoPath, 
                                   const char *pszCoverName,
                                   AVCTableDef *psSrcTableDef,
                                   AVCCoverType eCoverType,
                                   int nPrecision, AVCDBCSInfo *psDBCSInfo)
{
    AVCBinFile   *psFile;
    AVCRawBinFile *hRawBinFile;
    AVCTableDef  *psTableDef = NULL;
    char         *pszFname = NULL, szInfoFile[8]="";
    int          i, nTableIndex = 0;

    if (eCoverType == AVCCoverPC || eCoverType == AVCCoverPC2)
        return _AVCBinWriteCreateDBFTable(pszInfoPath, pszCoverName,
                                          psSrcTableDef, eCoverType, 
                                          nPrecision, psDBCSInfo);

    /*-----------------------------------------------------------------
     * Make sure precision value is valid (AVC_DEFAULT_PREC is NOT valid)
     *----------------------------------------------------------------*/
    if (nPrecision!=AVC_SINGLE_PREC && nPrecision!=AVC_DOUBLE_PREC)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "AVCBinWriteCreateTable(): Invalid precision parameter "
                 "(value must be AVC_SINGLE_PREC or AVC_DOUBLE_PREC)");
        return NULL;
    }

    /* Alloc a buffer big enough for the longest possible filename...
     */
    pszFname = (char*)CPLMalloc((strlen(pszInfoPath)+81)*sizeof(char));


    /*-----------------------------------------------------------------
     * Alloc and init the AVCBinFile struct.
     *----------------------------------------------------------------*/
    psFile = (AVCBinFile*)CPLCalloc(1, sizeof(AVCBinFile));

    psFile->eFileType = AVCFileTABLE;
    /* Precision is not important for tables */
    psFile->nPrecision = nPrecision;
    psFile->eCoverType = eCoverType;

    psFile->hdr.psTableDef = psTableDef = _AVCDupTableDef(psSrcTableDef);

    /*-----------------------------------------------------------------
     * Add a record for this table in the "arc.dir"
     * Note: there could be a problem if 2 processes try to add an entry
     * at the exact same time... does Arc/Info do any locking on that file???
     *----------------------------------------------------------------*/
    sprintf(pszFname, "%sarc.dir", pszInfoPath);

    nTableIndex = _AVCBinWriteCreateArcDirEntry(pszFname, psTableDef, 
                                                psDBCSInfo);

    if (nTableIndex < 0)
    {
        /* Failed to add arc.dir entry... just return NULL since an error
         * message has already been issued by _AVCBinWriteCreateArcDirEntry()
         */
        _AVCDestroyTableDef(psTableDef);
        CPLFree(psFile);
        CPLFree(pszFname);
        return NULL;
    }

    sprintf(szInfoFile, "arc%4.4d", nTableIndex);

    /*-----------------------------------------------------------------
     * Create the "arc####.nit" with the attribute definitions.
     *----------------------------------------------------------------*/
    sprintf(pszFname, "%s%s.nit", pszInfoPath, szInfoFile);

    hRawBinFile = AVCRawBinOpen(pszFname, "w",
                                AVC_COVER_BYTE_ORDER(AVCCoverV7),
                                psDBCSInfo);

    if (hRawBinFile == NULL)
    {
        /* Failed to open file... just return NULL since an error message
         * has already been issued by AVCRawBinOpen()
         */
        _AVCDestroyTableDef(psTableDef);
        CPLFree(psFile);
        CPLFree(pszFname);
        return NULL;
    }

    for(i=0; i<psTableDef->numFields; i++)
    {
        _AVCBinWriteArcNit(hRawBinFile, &(psTableDef->pasFieldDef[i]));
    }

    AVCRawBinClose(hRawBinFile);
    hRawBinFile = NULL;

    /*-----------------------------------------------------------------
     * The location of the data file depends on the external flag.
     *----------------------------------------------------------------*/
    if (EQUAL(psTableDef->szExternal, "  "))
    {
        /*-------------------------------------------------------------
         * Internal table: data goes directly in "arc####.dat"
         *------------------------------------------------------------*/
        psTableDef->szDataFile[0] = '\0';
        sprintf(pszFname, "%s%s.dat", pszInfoPath, szInfoFile);
        psFile->pszFilename = CPLStrdup(pszFname);
    }
    else
    {
        /*-------------------------------------------------------------
         * External table: data stored in the coverage directory, and
         * the path to the data file is written to "arc####.dat"
         *... start by extracting the info to build the data file name...
         *------------------------------------------------------------*/
        char szCoverName[40]="", szExt[4]="", szSubclass[40]="", *pszPtr;
        int nLen;
        FILE *fpOut;

        nLen = strlen(psTableDef->szTableName);
        CPLAssert(nLen <= 32);
        if (nLen > 32) return NULL;
        pszPtr = psTableDef->szTableName;

        for(i=0; *pszPtr!='\0' && *pszPtr!='.' && *pszPtr!=' ';  i++, pszPtr++)
        {
            szCoverName[i] = tolower(*pszPtr);
        }
        szCoverName[i] = '\0';

        if (*pszPtr == '.')
            pszPtr++;

        for(i=0; i<3 && *pszPtr!='\0' && *pszPtr!=' ';  i++, pszPtr++)
        {
            szExt[i] = tolower(*pszPtr);
        }
        szExt[i] = '\0';

        for(i=0; *pszPtr!='\0' && *pszPtr!=' ';  i++, pszPtr++)
        {
            szSubclass[i] = tolower(*pszPtr);
        }
        szSubclass[i] = '\0';

        /*-------------------------------------------------------------
         * ... and build the data file name based on what we extracted
         *------------------------------------------------------------*/
        if (strlen(szSubclass) == 0)
        {
            if (nPrecision == AVC_DOUBLE_PREC &&
                (EQUAL(szExt, "TIC") || EQUAL(szExt, "BND")) )
            {
                /* "../<covername>/dbl<ext>.adf" */
                sprintf(psTableDef->szDataFile, 
                        "../%s/dbl%s.adf", szCoverName, szExt);
            }
            else
            {
                /* "../<covername>/<ext>.adf" */
                sprintf(psTableDef->szDataFile, 
                        "../%s/%s.adf", szCoverName, szExt);
            }
        }
        else
        {
            /* "../<covername>/<subclass>.<ext>" */
            sprintf(psTableDef->szDataFile, 
                    "../%s/%s.%s", szCoverName, szSubclass, szExt);
        }

        /*-------------------------------------------------------------
         * Write it to the arc####.dat
         * Note that the path that is written in the arc####.dat contains
         * '/' as a directory delimiter, even on Windows systems.
         *------------------------------------------------------------*/
        sprintf(pszFname, "%s%s.dat", pszInfoPath, szInfoFile);
        fpOut = VSIFOpen(pszFname, "wt");
        if (fpOut)
        {
            VSIFPrintf(fpOut, "%-80.80s", psTableDef->szDataFile);
            VSIFClose(fpOut);
        }
        else
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Failed creating file %s.", pszFname);
            CPLFree(pszFname);
            _AVCDestroyTableDef(psTableDef);
            CPLFree(psFile);
            return NULL;
        }

        sprintf(pszFname, "%s%s", 
                pszInfoPath, psTableDef->szDataFile);
        psFile->pszFilename = CPLStrdup(pszFname);

#ifdef WIN32
        /*-------------------------------------------------------------
         * On a Windows system, we have to change the '/' to '\\' in the
         * data file path.
         *------------------------------------------------------------*/
        for(i=0; psFile->pszFilename[i] != '\0'; i++)
            if (psFile->pszFilename[i] == '/')
                psFile->pszFilename[i] = '\\';
#endif /* WIN32 */

    }/* if "XX" */

    /*-----------------------------------------------------------------
     * OK, now we're ready to create the actual data file.
     *----------------------------------------------------------------*/
    AVCAdjustCaseSensitiveFilename(psFile->pszFilename);
    psFile->psRawBinFile = AVCRawBinOpen(psFile->pszFilename, "w",
                                         AVC_COVER_BYTE_ORDER(AVCCoverV7),
                                         psDBCSInfo);

    if (psFile->psRawBinFile == NULL)
    {
        /* Failed to open file... just return NULL since an error message
         * has already been issued by AVCRawBinOpen()
         */
        CPLFree(pszFname);
        CPLFree(psFile->pszFilename);
        _AVCDestroyTableDef(psTableDef);
        CPLFree(psFile);
        return NULL;
    }

    CPLFree(pszFname);

    return psFile;
}


/**********************************************************************
 *                          _AVCBinWriteCreateDBFTable()
 *
 * Create a table (DBF file) in a PC Coverage and write the attribute defns to
 * the file.  The file will then be ready to write records to.
 *
 * In PC Coverages, only the following tables appear to be supported:
 *    - TEST.AAT -> AAT.DBF
 *    - TEST.PAT -> PAT.DBF
 *    - TEST.BND -> BND.DBF
 *    - TEST.TIC -> TIC.DBF
 *
 * However, this function will not fail if it is passed a table name not 
 * supported by PC Arc/Info. 
 * e.g. TEST.PATCOUNTY would be written as PATCOUNTY.DBF even if PC Arc/Info
 * would probably not recognize that name.
 *
 * Returns a valid AVCBinFile handle, or NULL if the table could
 * not be created.
 *
 * AVCBinClose() will eventually have to be called to release the 
 * resources used by the AVCBinFile structure.
 **********************************************************************/
AVCBinFile *_AVCBinWriteCreateDBFTable(const char *pszPath, 
                                       const char *pszCoverName,
                                       AVCTableDef *psSrcTableDef,
                                       AVCCoverType eCoverType,
                                       int nPrecision, AVCDBCSInfo *psDBCSInfo)
{
    AVCBinFile    *psFile;
    AVCTableDef   *psTableDef = NULL;
    AVCFieldInfo  *pasDef;
    char          *pszDBFBasename, szFieldName[12];
    int           i, j, nType;

    /*-----------------------------------------------------------------
     * Alloc and init the AVCBinFile struct.
     *----------------------------------------------------------------*/
    psFile = (AVCBinFile*)CPLCalloc(1, sizeof(AVCBinFile));

    psFile->eFileType = AVCFileTABLE;
    /* Precision is not important for tables */
    psFile->nPrecision = nPrecision;
    psFile->eCoverType = eCoverType;

    psFile->hdr.psTableDef = psTableDef = _AVCDupTableDef(psSrcTableDef);

    /* nCurDBFRecord is used to keep track of the 0-based index of the
     * last record we read from the DBF file... this is to emulate 
     * sequential access which is assumed by the rest of the lib.
     * Since the first record (record 0) has not been written yet, then
     * we init the index at -1.
     */
    psFile->nCurDBFRecord = -1;

    /*-----------------------------------------------------------------
     * Establish name of file to create.
     *----------------------------------------------------------------*/
    psFile->pszFilename = (char*)CPLCalloc(strlen(psSrcTableDef->szTableName)+
                                           strlen(pszPath)+10, sizeof(char));

    if (EQUALN(psSrcTableDef->szTableName, pszCoverName, strlen(pszCoverName))
        && psSrcTableDef->szTableName[strlen(pszCoverName)] == '.')
    {
        pszDBFBasename = psSrcTableDef->szTableName + strlen(pszCoverName)+1;
    }
    else
    {
        pszDBFBasename = psSrcTableDef->szTableName;
    }

    strcpy(psFile->pszFilename, pszPath);

    for(i=strlen(psFile->pszFilename); *pszDBFBasename; i++, pszDBFBasename++)
    {
        psFile->pszFilename[i] = tolower(*pszDBFBasename);
    }

    strcat(psFile->pszFilename, ".dbf");

    /*-----------------------------------------------------------------
     * OK, let's try to create the DBF file.
     *----------------------------------------------------------------*/
    AVCAdjustCaseSensitiveFilename(psFile->pszFilename);
    psFile->hDBFFile = DBFCreate(psFile->pszFilename);

    if (psFile->hDBFFile == NULL)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Failed creating file %s.", psFile->pszFilename);
        CPLFree(psFile->pszFilename);
        _AVCDestroyTableDef(psTableDef);
        CPLFree(psFile);
        return NULL;
    }

    /*-----------------------------------------------------------------
     * Create fields.
     *----------------------------------------------------------------*/
    pasDef = psTableDef->pasFieldDef;
    for(i=0; i<psTableDef->numFields; i++)
    {
        nType = pasDef[i].nType1*10;

        /*-------------------------------------------------------------
         * Special characters '#' and '-' in field names have to be replaced 
         * with '_'.  PC Field names are limited to 10 chars.
         *------------------------------------------------------------*/
        strncpy(szFieldName, pasDef[i].szName, 10);
        szFieldName[10] = '\0';
        for(j=0; szFieldName[j]; j++)
        {
            if (szFieldName[j] == '#' || szFieldName[j] == '-')
                szFieldName[j] = '_';
        }

        if (nType ==  AVC_FT_DATE || nType == AVC_FT_CHAR)
        {
            /*---------------------------------------------------------
             * Values stored as strings
             *--------------------------------------------------------*/
            DBFAddField(psFile->hDBFFile, szFieldName, FTString, 
                        pasDef[i].nSize, 0);
        }
        else if (nType == AVC_FT_FIXINT || nType == AVC_FT_FIXNUM)
        {
            /*---------------------------------------------------------
             * Numerics (internally stored as strings)
             *--------------------------------------------------------*/
            DBFAddField(psFile->hDBFFile, szFieldName, FTDouble, 
                        pasDef[i].nSize, pasDef[i].nFmtPrec);
        }
        else if (nType == AVC_FT_BININT)
        {
            /*---------------------------------------------------------
             * Integers (16 and 32 bits)
             *--------------------------------------------------------*/
            DBFAddField(psFile->hDBFFile, szFieldName, FTInteger, 11, 0);
        }
        else if (nType == AVC_FT_BINFLOAT)
        {
            /*---------------------------------------------------------
             * Single + Double precision floats
             * Set them as width=13, prec=6 in the header like PC/Arc does
             *--------------------------------------------------------*/
            DBFAddField(psFile->hDBFFile, szFieldName, FTDouble, 
                        13, 6);
        }
        else
        {
            /*---------------------------------------------------------
             * Hummm... unsupported field type...
             *--------------------------------------------------------*/
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Unsupported field type: (field=%s, type=%d, size=%d)",
                     szFieldName, nType, pasDef[i].nSize);
            _AVCBinWriteCloseTable(psFile);
            return NULL;
        }
    }

    return psFile;
}


/**********************************************************************
 *                          _AVCBinWriteCloseTable()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteClose() instead)
 *
 * Close an info table opened for wirting, and release all memory 
 * (object struct., buffers, etc.) associated with this file.
 **********************************************************************/
static void    _AVCBinWriteCloseTable(AVCBinFile *psFile)
{
    if (psFile->eFileType != AVCFileTABLE)
        return;

    /*-----------------------------------------------------------------
     * Close the data file
     *----------------------------------------------------------------*/
    if (psFile->hDBFFile)
    {
        /*-------------------------------------------------------------
         * The case of DBF files is simple!
         *------------------------------------------------------------*/
        DBFClose(psFile->hDBFFile);
        psFile->hDBFFile = NULL;
    }
    else if (psFile->psRawBinFile)
    {
        /*-------------------------------------------------------------
         * __TODO__ make sure ARC.DIR entry contains accurate info about the 
         * number of records written, etc.
         *------------------------------------------------------------*/
        AVCRawBinClose(psFile->psRawBinFile);
        psFile->psRawBinFile = NULL;
    }

    /*-----------------------------------------------------------------
     * Release other memory
     *----------------------------------------------------------------*/
    _AVCDestroyTableDef(psFile->hdr.psTableDef);

    CPLFree(psFile->pszFilename);

    CPLFree(psFile);
}


/**********************************************************************
 *                          _AVCBinWriteTableRec()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteTableRec() instead)
 *
 * Write a table data record at the current position in file.
 *
 * The contents of the pasDef and pasFields structures is assumed to 
 * be valid... this function performs no validation on the consistency 
 * of what it is given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteTableRec(AVCRawBinFile *psFile, int nFields,
                         AVCFieldInfo *pasDef, AVCField *pasFields,
                         int nRecordSize, const char *pszFname)
{
    int i, nType, nBytesWritten=0;

    if (psFile == NULL)
        return -1;

    for(i=0; i<nFields; i++)
    {
        if (CPLGetLastErrorNo() != 0)
            return -1;

        nType = pasDef[i].nType1*10;

        if (nType ==  AVC_FT_DATE || nType == AVC_FT_CHAR ||
            nType == AVC_FT_FIXINT || nType == AVC_FT_FIXNUM)
        {
            /*---------------------------------------------------------
             * Values stored as strings (MUST be padded with spaces)
             *--------------------------------------------------------*/
            AVCRawBinWritePaddedString(psFile, pasDef[i].nSize,
                                       pasFields[i].pszStr);
        }
        else if (nType == AVC_FT_BININT && pasDef[i].nSize == 4)
        {
            /*---------------------------------------------------------
             * 32 bit binary integers
             *--------------------------------------------------------*/
            AVCRawBinWriteInt32(psFile, pasFields[i].nInt32);
        }
        else if (nType == AVC_FT_BININT && pasDef[i].nSize == 2)
        {
            /*---------------------------------------------------------
             * 16 bit binary integers
             *--------------------------------------------------------*/
            AVCRawBinWriteInt16(psFile, pasFields[i].nInt16);
        }
        else if (nType == AVC_FT_BINFLOAT && pasDef[i].nSize == 4)
        {
            /*---------------------------------------------------------
             * Single precision floats
             *--------------------------------------------------------*/
            AVCRawBinWriteFloat(psFile, pasFields[i].fFloat);
        }
        else if (nType == AVC_FT_BINFLOAT && pasDef[i].nSize == 8)
        {
            /*---------------------------------------------------------
             * Double precision floats
             *--------------------------------------------------------*/
            AVCRawBinWriteDouble(psFile, pasFields[i].dDouble);
        }
        else
        {
            /*---------------------------------------------------------
             * Hummm... unsupported field type...
             *--------------------------------------------------------*/
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Unsupported field type in %s: (type=%d, size=%d)",
                     pszFname, nType, pasDef[i].nSize);
            return -1;
        }

        nBytesWritten += pasDef[i].nSize;
    }

    /*-----------------------------------------------------------------
     * Record size is rounded to a multiple of 2 bytes.
     * Check the number of bytes written, and pad with zeros if 
     * necessary.
     *----------------------------------------------------------------*/
    nRecordSize = ((nRecordSize+1)/2)*2;
    if (nBytesWritten < nRecordSize)
        AVCRawBinWriteZeros(psFile, nRecordSize - nBytesWritten);

    if (CPLGetLastErrorNo() != 0)
        return -1;

    return 0;
}

/**********************************************************************
 *                          _AVCBinWriteDBFTableRec()
 *
 * (This function is for internal library use... external calls should
 * go to AVCBinWriteTableRec() instead)
 *
 * Write a table data record at the current position in DBF file.
 *
 * The contents of the pasDef and pasFields structures is assumed to 
 * be valid... this function performs no validation on the consistency 
 * of what it is given as input.
 *
 * Returns 0 on success or -1 on error.
 **********************************************************************/
int _AVCBinWriteDBFTableRec(DBFHandle hDBFFile, int nFields,
                            AVCFieldInfo *pasDef, AVCField *pasFields,
                            int *nCurDBFRecord, const char *pszFname)
{
    int i, nType, nStatus = FALSE;

    if (hDBFFile == NULL)
        return -1;

    (*nCurDBFRecord)++;

    for(i=0; i<nFields; i++)
    {
        if (CPLGetLastErrorNo() != 0)
            return -1;

        nType = pasDef[i].nType1*10;

        if (nType ==  AVC_FT_DATE || nType == AVC_FT_CHAR)
        {
            /*---------------------------------------------------------
             * Values stored as strings
             *--------------------------------------------------------*/
            nStatus = DBFWriteStringAttribute(hDBFFile, *nCurDBFRecord, i, 
                                              pasFields[i].pszStr);
        }
        else if (nType == AVC_FT_FIXINT || nType == AVC_FT_FIXNUM)
        {
            /*---------------------------------------------------------
             * Numbers stored as strings
             *--------------------------------------------------------*/
            nStatus = DBFWriteAttributeDirectly(hDBFFile, *nCurDBFRecord, i, 
                                                pasFields[i].pszStr);
        }
        else if (nType == AVC_FT_BININT && pasDef[i].nSize == 4)
        {
            /*---------------------------------------------------------
             * 32 bit binary integers
             *--------------------------------------------------------*/
            nStatus = DBFWriteIntegerAttribute(hDBFFile, *nCurDBFRecord, i, 
                                               pasFields[i].nInt32);
        }
        else if (nType == AVC_FT_BININT && pasDef[i].nSize == 2)
        {
            /*---------------------------------------------------------
             * 16 bit binary integers
             *--------------------------------------------------------*/
            nStatus = DBFWriteIntegerAttribute(hDBFFile, *nCurDBFRecord, i, 
                                               pasFields[i].nInt16);
        }
        else if (nType == AVC_FT_BINFLOAT)
        {
            /*---------------------------------------------------------
             * Single+double precision floats
             *--------------------------------------------------------*/
            char szBuf[32] = "";
            int nLen;

            if (pasDef[i].nSize == 4)
                nLen = AVCPrintRealValue(szBuf, AVC_FORMAT_DBF_FLOAT,
                                         AVCFileTABLE, pasFields[i].fFloat);
            else
                nLen = AVCPrintRealValue(szBuf, AVC_FORMAT_DBF_FLOAT,
                                         AVCFileTABLE, pasFields[i].dDouble);

            szBuf[nLen] = '\0';

            nStatus = DBFWriteAttributeDirectly(hDBFFile, *nCurDBFRecord, i, 
                                                szBuf);
        }
        else
        {
            /*---------------------------------------------------------
             * Hummm... unsupported field type...
             *--------------------------------------------------------*/
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Unsupported field type in %s: (type=%d, size=%d)",
                     pszFname, nType, pasDef[i].nSize);
            return -1;
        }

        if (nStatus != TRUE)
        {
            CPLError(CE_Failure, CPLE_FileIO,
                     "Failed writing table field %d to record %d in %s",
                     i, *nCurDBFRecord, pszFname);
            return -1;
        }

    }

    return 0;
}

/**********************************************************************
 *                          AVCBinWriteTableRec()
 *
 * Write a table data record at the current position in file.
 *
 * The contents of the pasDef and pasFields structures is assumed to 
 * be valid... this function performs no validation on the consistency 
 * of what it is given as input.
 *
 * Returns 0 on success or -1 on error.
 *
 * If a problem happens, then CPLError() will be called by the lower-level
 * functions and CPLGetLastErrorNo() can be used to find out what happened.
 **********************************************************************/
int AVCBinWriteTableRec(AVCBinFile *psFile, AVCField *pasFields)
{
    if (psFile->eFileType != AVCFileTABLE||
        psFile->hdr.psTableDef->numRecords == 0)
        return -1;

    if (psFile->eCoverType == AVCCoverPC || psFile->eCoverType == AVCCoverPC2)
        return _AVCBinWriteDBFTableRec(psFile->hDBFFile, 
                                       psFile->hdr.psTableDef->numFields,
                                       psFile->hdr.psTableDef->pasFieldDef,
                                       pasFields,
                                       &(psFile->nCurDBFRecord),
                                       psFile->pszFilename);
    else
        return _AVCBinWriteTableRec(psFile->psRawBinFile, 
                                    psFile->hdr.psTableDef->numFields,
                                    psFile->hdr.psTableDef->pasFieldDef,
                                    pasFields,
                                    psFile->hdr.psTableDef->nRecSize,
                                    psFile->pszFilename);
}