File: mitab_tabview.cpp

package info (click to toggle)
gdal 1.10.1%2Bdfsg-8
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 84,320 kB
  • ctags: 74,726
  • sloc: cpp: 677,199; ansic: 162,820; python: 13,816; cs: 11,163; sh: 10,446; java: 5,279; perl: 4,429; php: 2,971; xml: 1,500; yacc: 934; makefile: 494; sql: 112
file content (2110 lines) | stat: -rw-r--r-- 73,433 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
/**********************************************************************
 * $Id: mitab_tabview.cpp,v 1.22 2010-07-07 19:00:15 aboudreault Exp $
 *
 * Name:     mitab_tabfile.cpp
 * Project:  MapInfo TAB Read/Write library
 * Language: C++
 * Purpose:  Implementation of the TABView class, used to handle .TAB
 *           datasets composed of a number of .TAB files linked through 
 *           indexed fields.
 * Author:   Daniel Morissette, dmorissette@dmsolutions.ca
 *
 **********************************************************************
 * Copyright (c) 1999-2002, 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: mitab_tabview.cpp,v $
 * Revision 1.22  2010-07-07 19:00:15  aboudreault
 * Cleanup Win32 Compile Warnings (GDAL bug #2930)
 *
 * Revision 1.21  2010-07-05 19:01:20  aboudreault
 * Reverted last SetFeature change in mitab_capi.cpp and fixed another memory leak
 *
 * Revision 1.20  2010-01-07 20:39:12  aboudreault
 * Added support to handle duplicate field names, Added validation to check if a field name start with a number (bug 2141)
 *
 * Revision 1.19  2008-03-05 20:35:39  dmorissette
 * Replace MITAB 1.x SetFeature() with a CreateFeature() for V2.x (bug 1859)
 *
 * Revision 1.18  2008/01/29 20:46:32  dmorissette
 * Added support for v9 Time and DateTime fields (byg 1754)
 *
 * Revision 1.17  2007/06/21 14:00:23  dmorissette
 * Added missing cast in isspace() calls to avoid failed assertion on Windows
 * (MITAB bug 1737, GDAL ticket 1678))
 *
 * Revision 1.16  2007/06/12 13:52:38  dmorissette
 * Added IMapInfoFile::SetCharset() method (bug 1734)
 *
 * Revision 1.15  2007/06/12 12:50:40  dmorissette
 * Use Quick Spatial Index by default until bug 1732 is fixed (broken files
 * produced by current coord block splitting technique).
 *
 * Revision 1.14  2007/03/21 21:15:56  dmorissette
 * Added SetQuickSpatialIndexMode() which generates a non-optimal spatial
 * index but results in faster write time (bug 1669)
 *
 * Revision 1.13  2004/06/30 20:29:04  dmorissette
 * Fixed refs to old address danmo@videotron.ca
 *
 * Revision 1.12  2002/02/22 20:44:51  julien
 * Prevent infinite loop with TABRelation by suppress the m_poCurFeature object
 * from the class and setting it in the calling function and add GetFeature in
 * the class. (bug 706)
 *
 * Revision 1.11  2002/01/10 05:13:22  daniel
 * Prevent crash if .IND file is deleted (but 703)
 *
 * Revision 1.10  2002/01/10 04:52:58  daniel
 * Support 'select * ...' syntax + 'open table..." directives with/without .tab
 *
 * Revision 1.9  2001/06/27 19:52:26  warmerda
 * use VSIUnlink() instead of unlink()
 *
 * Revision 1.8  2001/03/15 03:57:51  daniel
 * Added implementation for new OGRLayer::GetExtent(), returning data MBR.
 *
 * Revision 1.7  2000/09/28 16:39:44  warmerda
 * avoid warnings for unused, and unitialized variables
 *
 * Revision 1.6  2000/02/28 17:12:22  daniel
 * Write support for joined tables and indexed fields
 *
 * Revision 1.5  2000/01/15 22:30:45  daniel
 * Switch to MIT/X-Consortium OpenSource license
 *
 * Revision 1.4  1999/12/19 17:40:16  daniel
 * Init + delete m_poRelation properly
 *
 * Revision 1.3  1999/12/14 05:53:00  daniel
 * Fixed compile warnings
 *
 * Revision 1.2  1999/12/14 04:04:10  daniel
 * Added bforceFlags to GetBounds() and GetFeatureCountByType()
 *
 * Revision 1.1  1999/12/14 02:10:32  daniel
 * Initial revision
 *
 **********************************************************************/

#include "mitab.h"
#include "mitab_utils.h"

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

/*=====================================================================
 *                      class TABView
 *====================================================================*/


/**********************************************************************
 *                   TABView::TABView()
 *
 * Constructor.
 **********************************************************************/
TABView::TABView()
{
    m_pszFname = NULL;
    m_eAccessMode = TABRead;
    m_papszTABFile = NULL;
    m_pszVersion = NULL;

    m_numTABFiles = 0;
    m_papszTABFnames = NULL;
    m_papoTABFiles = NULL;
    m_nMainTableIndex = -1;

    m_papszFieldNames = NULL;
    m_papszWhereClause = NULL;

    m_poRelation = NULL;
    m_bRelFieldsCreated = FALSE;
}

/**********************************************************************
 *                   TABView::~TABView()
 *
 * Destructor.
 **********************************************************************/
TABView::~TABView()
{
    Close();
}


int TABView::GetFeatureCount (int bForce)
{

    if (m_nMainTableIndex != -1)
        return m_papoTABFiles[m_nMainTableIndex]->GetFeatureCount( bForce );

    return 0;
}

void TABView::ResetReading()
{
    if (m_nMainTableIndex != -1)
        m_papoTABFiles[m_nMainTableIndex]->ResetReading();
}


/**********************************************************************
 *                   TABView::Open()
 *
 * Open a .TAB dataset and the associated files, and initialize the 
 * structures to be ready to read features from it.
 *
 * This class is used to open .TAB files that define a view on
 * two other .TAB files.  Regular .TAB datasets should be opened using
 * the TABFile class instead.
 *
 * Set bTestOpenNoError=TRUE to silently return -1 with no error message
 * if the file cannot be opened.  This is intended to be used in the
 * context of a TestOpen() function.  The default value is FALSE which
 * means that an error is reported if the file cannot be opened.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::Open(const char *pszFname, const char *pszAccess,
                  GBool bTestOpenNoError /*= FALSE*/ )
{
    char nStatus = 0;
   
    if (m_numTABFiles > 0)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "Open() failed: object already contains an open file");
        return -1;
    }

    /*-----------------------------------------------------------------
     * Validate access mode and call the right open method
     *----------------------------------------------------------------*/
    if (EQUALN(pszAccess, "r", 1))
    {
        m_eAccessMode = TABRead;
        nStatus = (char)OpenForRead(pszFname, bTestOpenNoError);
    }
    else if (EQUALN(pszAccess, "w", 1))
    {
        m_eAccessMode = TABWrite;
        nStatus = (char)OpenForWrite(pszFname);
    }
    else
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Open() failed: access mode \"%s\" not supported", pszAccess);
        return -1;
    }

    return nStatus;
}


/**********************************************************************
 *                   TABView::OpenForRead()
 *
 * Open for reading
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::OpenForRead(const char *pszFname, 
                         GBool bTestOpenNoError /*= FALSE*/ )
{
    char *pszPath = NULL;
    int nFnameLen = 0;
   
    m_eAccessMode = TABRead;

    /*-----------------------------------------------------------------
     * Read main .TAB (text) file
     *----------------------------------------------------------------*/
    m_pszFname = CPLStrdup(pszFname);

#ifndef _WIN32
    /*-----------------------------------------------------------------
     * On Unix, make sure extension uses the right cases
     * We do it even for write access because if a file with the same
     * extension already exists we want to overwrite it.
     *----------------------------------------------------------------*/
    TABAdjustFilenameExtension(m_pszFname);
#endif

    /*-----------------------------------------------------------------
     * Open .TAB file... since it's a small text file, we will just load
     * it as a stringlist in memory.
     *----------------------------------------------------------------*/
    m_papszTABFile = TAB_CSLLoad(m_pszFname);
    if (m_papszTABFile == NULL)
    {
        if (!bTestOpenNoError)
        {
            CPLError(CE_Failure, CPLE_FileIO,
                     "Failed opening %s.", m_pszFname);
        }
        
        CPLFree(m_pszFname);
        return -1;
    }

    /*-------------------------------------------------------------
     * Look for a line with the "create view" keyword.
     * If there is no "create view", then we may have a valid .TAB file,
     * but we do not support it in this class.
     *------------------------------------------------------------*/
    GBool bCreateViewFound = FALSE;
    for (int i=0; 
         !bCreateViewFound && m_papszTABFile && m_papszTABFile[i];
         i++)
    {
        const char *pszStr = m_papszTABFile[i];
        while(*pszStr != '\0' && isspace((unsigned char)*pszStr))
            pszStr++;
        if (EQUALN(pszStr, "create view", 11))
            bCreateViewFound = TRUE;
    }

    if ( !bCreateViewFound )
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "%s contains no table view definition.  "
                     "This type of .TAB file cannot be read by this library.",
                     m_pszFname);
        else
            CPLErrorReset();

        CPLFree(m_pszFname);

        return -1;
    }

    /*-----------------------------------------------------------------
     * OK, this appears to be a valid TAB view dataset...
     * Extract the path component from the main .TAB filename
     * to build the filename of the sub-tables
     *----------------------------------------------------------------*/
    pszPath = CPLStrdup(m_pszFname);
    nFnameLen = strlen(pszPath);
    for( ; nFnameLen > 0; nFnameLen--)
    {
        if (pszPath[nFnameLen-1] == '/' || 
            pszPath[nFnameLen-1] == '\\' )
        {
            break;
        }
        pszPath[nFnameLen-1] = '\0';
    }

    /*-----------------------------------------------------------------
     * Extract the useful info from the TAB header
     *----------------------------------------------------------------*/
    if (ParseTABFile(pszPath, bTestOpenNoError) != 0)
    {
        // Failed parsing... an error has already been produced if necessary
        CPLFree(pszPath);
        Close();
        return -1;
    }
    CPLFree(pszPath);
    pszPath = NULL;

    /*-----------------------------------------------------------------
     * __TODO__ For now, we support only 2 files linked through a single
     *          field... so we'll do some validation first to make sure
     *          that what we found in the header respects these limitations.
     *----------------------------------------------------------------*/
    if (m_numTABFiles != 2)
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Open Failed: Dataset %s defines a view on %d tables. "
                     "This is not currently supported.",
                     m_pszFname, m_numTABFiles);
        Close();
        return -1;
    }

    /*-----------------------------------------------------------------
     * Open all the tab files listed in the view
     *----------------------------------------------------------------*/
    m_papoTABFiles = (TABFile**)CPLCalloc(m_numTABFiles, sizeof(TABFile*));

    for (int iFile=0; iFile < m_numTABFiles; iFile++)
    {
#ifndef _WIN32
        TABAdjustFilenameExtension(m_papszTABFnames[iFile]);
#endif
        
        m_papoTABFiles[iFile] = new TABFile;
   
        if ( m_papoTABFiles[iFile]->Open(m_papszTABFnames[iFile],
                                         "rb", bTestOpenNoError) != 0)
        {
            // Open Failed... an error has already been reported, just return.
            if (bTestOpenNoError)
                CPLErrorReset();
            Close();
            return -1;
        }
    }

    /*-----------------------------------------------------------------
     * Create TABRelation... this will build FeatureDefn, etc.
     * __TODO__ For now this assumes only 2 tables in the view...
     *----------------------------------------------------------------*/
    m_poRelation = new TABRelation;
    
    CPLAssert(m_nMainTableIndex == 0);
    CPLAssert(CSLCount(m_papszWhereClause) == 5);
    char *pszTableName = TABGetBasename(m_pszFname);
    if ( m_poRelation->Init(pszTableName,
                            m_papoTABFiles[0], m_papoTABFiles[1],
                            m_papszWhereClause[4], m_papszWhereClause[2],
                            m_papszFieldNames)  != 0 )
    {
        // An error should already have been reported
        CPLFree(pszTableName);
        Close();
        return -1;
    }
    CPLFree(pszTableName);

    return 0;
}


/**********************************************************************
 *                   TABView::OpenForWrite()
 *
 * Create a new TABView dataset
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::OpenForWrite(const char *pszFname)
{
    int nFnameLen = 0;
   
    m_eAccessMode = TABWrite;

    /*-----------------------------------------------------------------
     * Read main .TAB (text) file
     *----------------------------------------------------------------*/
    m_pszFname = CPLStrdup(pszFname);

#ifndef _WIN32
    /*-----------------------------------------------------------------
     * On Unix, make sure extension uses the right cases
     * We do it even for write access because if a file with the same
     * extension already exists we want to overwrite it.
     *----------------------------------------------------------------*/
    TABAdjustFilenameExtension(m_pszFname);
#endif

    /*-----------------------------------------------------------------
     * Extract the path component from the main .TAB filename
     *----------------------------------------------------------------*/
    char *pszPath = CPLStrdup(m_pszFname);
    nFnameLen = strlen(pszPath);
    for( ; nFnameLen > 0; nFnameLen--)
    {
        if (pszPath[nFnameLen-1] == '/' || 
            pszPath[nFnameLen-1] == '\\' )
        {
            break;
        }
        pszPath[nFnameLen-1] = '\0';
    }

    char *pszBasename = TABGetBasename(m_pszFname);

    /*-----------------------------------------------------------------
     * Create the 2 TAB files for the view.
     *
     * __TODO__ For now, we support only 2 files linked through a single
     *          field... not sure if anything else than that can be useful
     *          anyways.
     *----------------------------------------------------------------*/
    m_numTABFiles = 2;
    m_papszTABFnames = NULL;
    m_nMainTableIndex = 0;
    m_bRelFieldsCreated = FALSE;

    m_papoTABFiles = (TABFile**)CPLCalloc(m_numTABFiles, sizeof(TABFile*));

    for (int iFile=0; iFile < m_numTABFiles; iFile++)
    {
        m_papszTABFnames = CSLAppendPrintf(m_papszTABFnames, "%s%s%d.tab", 
                                               pszPath, pszBasename, iFile+1);
#ifndef _WIN32
        TABAdjustFilenameExtension(m_papszTABFnames[iFile]);
#endif
        
        m_papoTABFiles[iFile] = new TABFile;
   
        if ( m_papoTABFiles[iFile]->Open(m_papszTABFnames[iFile], "wb") != 0)
        {
            // Open Failed... an error has already been reported, just return.
            CPLFree(pszPath);
            CPLFree(pszBasename);
            Close();
            return -1;
        }
    }

    /*-----------------------------------------------------------------
     * Create TABRelation... 
     *----------------------------------------------------------------*/
    m_poRelation = new TABRelation;
    
    if ( m_poRelation->Init(pszBasename,
                            m_papoTABFiles[0], m_papoTABFiles[1],
                            NULL, NULL, NULL)  != 0 )
    {
        // An error should already have been reported
        CPLFree(pszPath);
        CPLFree(pszBasename);
        Close();
        return -1;
    }

    CPLFree(pszPath);
    CPLFree(pszBasename);

    return 0;
}



/**********************************************************************
 *                   TABView::ParseTABFile()
 *
 * Scan the lines of the TAB file, and store any useful information into
 * class members.  The main piece of information being the sub-table
 * names, and the list of fields to include in the view that we will
 * use to build the OGRFeatureDefn for this file.
 *
 * It is assumed that the TAB header file is already loaded in m_papszTABFile
 *
 * This private method should be used only during the Open() call.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::ParseTABFile(const char *pszDatasetPath, 
                          GBool bTestOpenNoError /*=FALSE*/)
{
    int         iLine, numLines;
    char        **papszTok=NULL;
    GBool       bInsideTableDef = FALSE;

    if (m_eAccessMode != TABRead)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "ParseTABFile() can be used only with Read access.");
        return -1;
    }

    numLines = CSLCount(m_papszTABFile);

    for(iLine=0; iLine<numLines; iLine++)
    {
        /*-------------------------------------------------------------
         * Tokenize the next .TAB line, and check first keyword
         *------------------------------------------------------------*/
        CSLDestroy(papszTok);
        papszTok = CSLTokenizeStringComplex(m_papszTABFile[iLine], " \t(),;",
                                            TRUE, FALSE);
        if (CSLCount(papszTok) < 2)
            continue;   // All interesting lines have at least 2 tokens

        if (EQUAL(papszTok[0], "!version"))
        {
            m_pszVersion = CPLStrdup(papszTok[1]);
        }
        else if (EQUAL(papszTok[0], "!charset"))
        {
            CPLFree(m_pszCharset);
            m_pszCharset = CPLStrdup(papszTok[1]);
        }
        else if (EQUAL(papszTok[0], "open") &&
                 EQUAL(papszTok[1], "table") &&
                 CSLCount(papszTok) >= 3)
        {
            // Source table name may be either "filename" or "filename.tab"
            int nLen = strlen(papszTok[2]);
            if (nLen > 4 && EQUAL(papszTok[2]+nLen-4, ".tab"))
                papszTok[2][nLen-4] = '\0';

            m_papszTABFnames = CSLAppendPrintf(m_papszTABFnames, 
                                               "%s%s.tab", 
                                               pszDatasetPath, papszTok[2]);
        }
        else if (EQUAL(papszTok[0], "create") &&
                 EQUAL(papszTok[1], "view") )
        {
            bInsideTableDef = TRUE;
        }
        else if (bInsideTableDef &&
                 (EQUAL(papszTok[0],"Select")))
        {
            /*---------------------------------------------------------
             * We found the list of table fields (comma-delimited list)
             *--------------------------------------------------------*/
            int iTok;
            for(iTok=1; papszTok[iTok] != NULL; iTok++)
                m_papszFieldNames = CSLAddString(m_papszFieldNames, 
                                                 papszTok[iTok]);

        }
        else if (bInsideTableDef &&
                 (EQUAL(papszTok[0],"where")))
        {
            /*---------------------------------------------------------
             * We found the where clause that relates the 2 tables
             * Something in the form:
             *   where table1.field1=table2.field2
             * The tokenized array will contain:
             *  {"where", "table1", "field1", "table2", "field2"}
             *--------------------------------------------------------*/
            m_papszWhereClause =CSLTokenizeStringComplex(m_papszTABFile[iLine],
                                                         " \t(),;=.",
                                                         TRUE, FALSE);

            /*---------------------------------------------------------
             * For now we are very limiting on the format of the WHERE
             * clause... we will be more permitting as we learn more about
             * what it can contain... (I don't want to implement a full SQL 
             * parser here!!!).  If you encountered this error,
             * (and are reading this!) please report the test dataset 
             * that produced the error and I'll see if we can support it.
             *--------------------------------------------------------*/
            if (CSLCount( m_papszWhereClause ) != 5)
            {
                if (!bTestOpenNoError)
                    CPLError(CE_Failure, CPLE_NotSupported,
                     "WHERE clause in %s is not in a supported format: \"%s\"",
                             m_pszFname, m_papszTABFile[iLine]);
                return -1;
            }
        }
        else
        {
            // Simply Ignore unrecognized lines
        }
    }

    CSLDestroy(papszTok);

    /*-----------------------------------------------------------------
     * The main table is the one from which we read the geometries, etc...
     * For now we assume it is always the first one in the list
     *----------------------------------------------------------------*/
    m_nMainTableIndex = 0;

    /*-----------------------------------------------------------------
     * Make sure all required class members are set
     *----------------------------------------------------------------*/
    m_numTABFiles = CSLCount(m_papszTABFnames);

    if (m_pszCharset == NULL)
        m_pszCharset = CPLStrdup("Neutral");
    if (m_pszVersion == NULL)
        m_pszVersion = CPLStrdup("100");

    if (CSLCount(m_papszFieldNames) == 0 )
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "%s: header contains no table field definition.  "
                     "This type of .TAB file cannot be read by this library.",
                     m_pszFname);
        return -1;
    }

    if (CSLCount(m_papszWhereClause) == 0 )
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "%s: WHERE clause not found or missing in header.  "
                     "This type of .TAB file cannot be read by this library.",
                     m_pszFname);
        return -1;
    }
    return 0;
}


/**********************************************************************
 *                   TABView::WriteTABFile()
 *
 * Generate the TAB header file.  This is usually done during the 
 * Close() call.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::WriteTABFile()
{
    FILE *fp;

    CPLAssert(m_eAccessMode == TABWrite);
    CPLAssert(m_numTABFiles == 2);
    CPLAssert(GetLayerDefn());

    char *pszTable  = TABGetBasename(m_pszFname);
    char *pszTable1 = TABGetBasename(m_papszTABFnames[0]);
    char *pszTable2 = TABGetBasename(m_papszTABFnames[1]);

    if ( (fp = VSIFOpen(m_pszFname, "wt")) != NULL)
    {
        // Version is always 100, no matter what the sub-table's version is
        fprintf(fp, "!Table\n");
        fprintf(fp, "!Version 100\n");

        fprintf(fp, "Open Table \"%s\" Hide\n", pszTable1);
        fprintf(fp, "Open Table \"%s\" Hide\n", pszTable2);
        fprintf(fp, "\n");
        fprintf(fp, "Create View %s As\n", pszTable);
        fprintf(fp, "Select ");

        OGRFeatureDefn *poDefn = GetLayerDefn();
        for(int iField=0; iField<poDefn->GetFieldCount(); iField++)
        {
            OGRFieldDefn *poFieldDefn = poDefn->GetFieldDefn(iField);
            if (iField == 0)
                fprintf(fp, "%s", poFieldDefn->GetNameRef());
            else
                fprintf(fp, ",%s", poFieldDefn->GetNameRef());
        }
        fprintf(fp, "\n");

        fprintf(fp, "From %s, %s\n", pszTable2, pszTable1);
        fprintf(fp, "Where %s.%s=%s.%s\n", pszTable2, 
                                           m_poRelation->GetRelFieldName(),
                                           pszTable1, 
                                           m_poRelation->GetMainFieldName());


        VSIFClose(fp);
    }
    else
    {
        CPLFree(pszTable);
        CPLFree(pszTable1);
        CPLFree(pszTable2);
        
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to create file `%s'", m_pszFname);
        return -1;
    }

    CPLFree(pszTable);
    CPLFree(pszTable1);
    CPLFree(pszTable2);

    return 0;
}


/**********************************************************************
 *                   TABView::Close()
 *
 * Close current file, and release all memory used.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::Close()
{
    // In write access, the main .TAB file has not been written yet.
    if (m_eAccessMode == TABWrite && m_poRelation)
        WriteTABFile();

    for(int i=0; m_papoTABFiles && i<m_numTABFiles; i++)
    {
        if (m_papoTABFiles[i])
            delete m_papoTABFiles[i];  // Automatically closes.
    }
    CPLFree(m_papoTABFiles);
    m_papoTABFiles = NULL;
    m_numTABFiles = 0;

    
    /*-----------------------------------------------------------------
     * __TODO__ OK, MapInfo does not like to see a .map and .id file
     * attached to the second table, even if they're empty.
     * We'll use a little hack to delete them now, but eventually we
     * should avoid creating them at all.
     *----------------------------------------------------------------*/
    if (m_eAccessMode == TABWrite && m_pszFname)
    {
        m_pszFname[strlen(m_pszFname)-4] = '\0';
        char *pszFile = CPLStrdup(CPLSPrintf("%s2.map", m_pszFname));
        TABAdjustFilenameExtension(pszFile);
        VSIUnlink(pszFile);

        sprintf(pszFile, "%s2.id", m_pszFname);
        TABAdjustFilenameExtension(pszFile);
        VSIUnlink(pszFile);

        CPLFree(pszFile);
    }
    // End of hack!


    CPLFree(m_pszFname);
    m_pszFname = NULL;

    CSLDestroy(m_papszTABFile);
    m_papszTABFile = NULL;

    CPLFree(m_pszVersion);
    m_pszVersion = NULL;
    CPLFree(m_pszCharset);
    m_pszCharset = NULL;

    CSLDestroy(m_papszTABFnames);
    m_papszTABFnames = NULL;

    CSLDestroy(m_papszFieldNames);
    m_papszFieldNames = NULL;
    CSLDestroy(m_papszWhereClause);
    m_papszWhereClause = NULL;

    m_nMainTableIndex = -1;

    if (m_poRelation)
        delete m_poRelation;
    m_poRelation = NULL;

    m_bRelFieldsCreated = FALSE;

    return 0;
}

/**********************************************************************
 *                   TABView::SetQuickSpatialIndexMode()
 *
 * Select "quick spatial index mode". 
 *
 * The default behavior of MITAB is to generate an optimized spatial index,
 * but this results in slower write speed. 
 *
 * Applications that want faster write speed and do not care
 * about the performance of spatial queries on the resulting file can
 * use SetQuickSpatialIndexMode() to require the creation of a non-optimal
 * spatial index (actually emulating the type of spatial index produced
 * by MITAB before version 1.6.0). In this mode writing files can be 
 * about 5 times faster, but spatial queries can be up to 30 times slower.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::SetQuickSpatialIndexMode(GBool bQuickSpatialIndexMode/*=TRUE*/)
{
    if (m_eAccessMode != TABWrite || m_numTABFiles == 0)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "SetQuickSpatialIndexMode() failed: file not opened for write access.");
        return -1;
    }

    for (int iFile=0; iFile < m_numTABFiles; iFile++)
    {
        if ( m_papoTABFiles[iFile]->SetQuickSpatialIndexMode(bQuickSpatialIndexMode) != 0)
        {
            // An error has already been reported, just return.
            return -1;
        }
    }

    return 0;
}


/**********************************************************************
 *                   TABView::GetNextFeatureId()
 *
 * Returns feature id that follows nPrevId, or -1 if it is the
 * last feature id.  Pass nPrevId=-1 to fetch the first valid feature id.
 **********************************************************************/
int TABView::GetNextFeatureId(int nPrevId)
{
    if (m_nMainTableIndex != -1)
        return m_papoTABFiles[m_nMainTableIndex]->GetNextFeatureId(nPrevId);

    return -1;
}

/**********************************************************************
 *                   TABView::GetFeatureRef()
 *
 * Fill and return a TABFeature object for the specified feature id.
 *
 * The retruned pointer is a reference to an object owned and maintained
 * by this TABView object.  It should not be altered or freed by the 
 * caller and its contents is guaranteed to be valid only until the next
 * call to GetFeatureRef() or Close().
 *
 * Returns NULL if the specified feature id does not exist of if an
 * error happened.  In any case, CPLError() will have been called to
 * report the reason of the failure.
 **********************************************************************/
TABFeature *TABView::GetFeatureRef(int nFeatureId)
{
    
    /*-----------------------------------------------------------------
     * Make sure file is opened 
     *----------------------------------------------------------------*/
    if (m_poRelation == NULL)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "GetFeatureRef() failed: file is not opened!");
        return NULL;
    }

    if(m_poCurFeature)
    {
        delete m_poCurFeature;
        m_poCurFeature = NULL;
    }

    m_poCurFeature = m_poRelation->GetFeature(nFeatureId);
    m_nCurFeatureId = nFeatureId;
    m_poCurFeature->SetFID(m_nCurFeatureId);
    return m_poCurFeature;
}


/**********************************************************************
 *                   TABView::CreateFeature()
 *
 * Write a new feature to this dataset. The passed in feature is updated 
 * with the new feature id.
 *
 * Returns OGRERR_NONE on success, or an appropriate OGRERR_ code if an
 * error happened in which case, CPLError() will have been called to
 * report the reason of the failure.
 **********************************************************************/
OGRErr TABView::CreateFeature(TABFeature *poFeature)
{
    if (m_eAccessMode != TABWrite)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "CreateFeature() can be used only with Write access.");
        return OGRERR_UNSUPPORTED_OPERATION;
    }

    if (m_poRelation == NULL)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "CreateFeature() failed: file is not opened!");
        return OGRERR_FAILURE;
    }

    /*-----------------------------------------------------------------
     * If we're about to write the first feature, then we must finish
     * the initialization of the view first by creating the MI_refnum fields
     *----------------------------------------------------------------*/
    if (!m_bRelFieldsCreated)
    {
        if (m_poRelation->CreateRelFields() != 0)
            return OGRERR_FAILURE;
        m_bRelFieldsCreated = TRUE;
    }

    int nFeatureId = m_poRelation->WriteFeature(poFeature);
    if (nFeatureId < 0)
        return OGRERR_FAILURE;

    poFeature->SetFID(nFeatureId);

    return OGRERR_NONE;
}



/**********************************************************************
 *                   TABView::GetLayerDefn()
 *
 * Returns a reference to the OGRFeatureDefn that will be used to create
 * features in this dataset.
 *
 * Returns a reference to an object that is maintained by this TABView
 * object (and thus should not be modified or freed by the caller) or
 * NULL if the OGRFeatureDefn has not been initialized yet (i.e. no file
 * opened yet)
 **********************************************************************/
OGRFeatureDefn *TABView::GetLayerDefn()
{
    if (m_poRelation)
        return m_poRelation->GetFeatureDefn();

    return NULL;
}

/**********************************************************************
 *                   TABView::SetFeatureDefn()
 *
 * Set the FeatureDefn for this dataset.
 *
 * For now, fields passed through SetFeatureDefn will not be mapped
 * properly, so this function can be used only with an empty feature defn.
 **********************************************************************/
int TABView::SetFeatureDefn(OGRFeatureDefn *poFeatureDefn,
                         TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
{
    if (m_poRelation)
        return m_poRelation->SetFeatureDefn(poFeatureDefn);

    return -1;
}


/**********************************************************************
 *                   TABView::GetNativeFieldType()
 *
 * Returns the native MapInfo field type for the specified field.
 *
 * Returns TABFUnknown if file is not opened, or if specified field index is
 * invalid.
 *
 * Note that field ids are positive and start at 0.
 **********************************************************************/
TABFieldType TABView::GetNativeFieldType(int nFieldId)
{
    if (m_poRelation)
        return m_poRelation->GetNativeFieldType(nFieldId);

    return TABFUnknown;
}


/**********************************************************************
 *                   TABView::AddFieldNative()
 *
 * Create a new field using a native mapinfo data type... this is an 
 * alternative to defining fields through the OGR interface.
 * This function should be called after creating a new dataset, but before 
 * writing the first feature.
 *
 * This function will build/update the OGRFeatureDefn that will have to be
 * used when writing features to this dataset.
 *
 * A reference to the OGRFeatureDefn can be obtained using GetLayerDefn().
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::AddFieldNative(const char *pszName, TABFieldType eMapInfoType,
                            int nWidth /*=0*/, int nPrecision /*=0*/,
                            GBool bIndexed /*=FALSE*/, GBool bUnique/*=FALSE*/, int bApproxOK)
{
    if (m_poRelation)
        return m_poRelation->AddFieldNative(pszName, eMapInfoType,
                                            nWidth, nPrecision,
                                            bIndexed, bUnique, bApproxOK);

    return -1;
}

/**********************************************************************
 *                   TABView::SetFieldIndexed()
 *
 * Request that a field be indexed.  This will create the .IND file if
 * necessary, etc.
 *
 * Note that field ids are positive and start at 0.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::SetFieldIndexed(int nFieldId)
{
    if (m_poRelation)
        return m_poRelation->SetFieldIndexed(nFieldId);

    return -1;
}

/**********************************************************************
 *                   TABView::IsFieldIndexed()
 *
 * Returns TRUE if field is indexed, or FALSE otherwise.
 **********************************************************************/
GBool TABView::IsFieldIndexed(int nFieldId)
{
    if (m_poRelation)
        return m_poRelation->IsFieldIndexed(nFieldId);

    return FALSE;
}

/**********************************************************************
 *                   TABView::IsFieldUnique()
 *
 * Returns TRUE if field is in the Unique table, or FALSE otherwise.
 **********************************************************************/
GBool TABView::IsFieldUnique(int nFieldId)
{
    if (m_poRelation)
        return m_poRelation->IsFieldUnique(nFieldId);

    return FALSE;
}


/**********************************************************************
 *                   TABView::GetBounds()
 *
 * Fetch projection coordinates bounds of a dataset.
 *
 * The bForce flag has no effect on TAB files since the bounds are
 * always in the header.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABView::GetBounds(double &dXMin, double &dYMin, 
                       double &dXMax, double &dYMax,
                       GBool bForce /*= TRUE*/)
{
    if (m_nMainTableIndex == -1)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
             "GetBounds() can be called only after dataset has been opened.");
        return -1;
    }

    return m_papoTABFiles[m_nMainTableIndex]->GetBounds(dXMin, dYMin,
                                                        dXMax, dYMax,
                                                        bForce);
}

/**********************************************************************
 *                   TABView::GetExtent()
 *
 * Fetch extent of the data currently stored in the dataset.
 *
 * The bForce flag has no effect on TAB files since that value is
 * always in the header.
 *
 * Returns OGRERR_NONE/OGRRERR_FAILURE.
 **********************************************************************/
OGRErr TABView::GetExtent (OGREnvelope *psExtent, int bForce)
{
    if (m_nMainTableIndex == -1)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
             "GetExtent() can be called only after dataset has been opened.");
        return -1;
    }

    return m_papoTABFiles[m_nMainTableIndex]->GetExtent(psExtent, bForce);

}

/**********************************************************************
 *                   TABView::GetFeatureCountByType()
 *
 * Return number of features of each type.
 *
 * Note that the sum of the 4 returned values may be different from
 * the total number of features since features with NONE geometry
 * are not taken into account here.
 *
 * Note: the bForce flag has nmo effect on .TAB files since the info
 * is always in the header.
 *
 * Returns 0 on success, or silently returns -1 (with no error) if this
 * information is not available.
 **********************************************************************/
int TABView::GetFeatureCountByType(int &numPoints, int &numLines,
                                   int &numRegions, int &numTexts,
                                   GBool bForce /*= TRUE*/)
{
    if (m_nMainTableIndex == -1)
        return -1;

    return m_papoTABFiles[m_nMainTableIndex]->GetFeatureCountByType(numPoints,
                                                                    numLines,
                                                                    numRegions,
                                                                    numTexts,
                                                                    bForce);
}


/**********************************************************************
 *                   TABView::GetSpatialRef()
 *
 * Returns a reference to an OGRSpatialReference for this dataset.
 * If the projection parameters have not been parsed yet, then we will
 * parse them before returning.
 *
 * The returned object is owned and maintained by this TABFile and
 * should not be modified or freed by the caller.
 *
 * Returns NULL if the SpatialRef cannot be accessed.
 **********************************************************************/
OGRSpatialReference *TABView::GetSpatialRef()
{
    if (m_nMainTableIndex == -1)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "GetSpatialRef() failed: file has not been opened yet.");
        return NULL;
    }

    return m_papoTABFiles[m_nMainTableIndex]->GetSpatialRef();
}

/**********************************************************************
 *                   TABView::SetSpatialRef()
 **********************************************************************/
int TABView::SetSpatialRef(OGRSpatialReference *poSpatialRef)
{
    if (m_nMainTableIndex == -1)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "SetSpatialRef() failed: file has not been opened yet.");
        return -1;
    }

    return m_papoTABFiles[m_nMainTableIndex]->SetSpatialRef(poSpatialRef);
}



/**********************************************************************
 *                   TABView::SetBounds()
 **********************************************************************/
int TABView::SetBounds(double dXMin, double dYMin, 
                       double dXMax, double dYMax)
{
    if (m_nMainTableIndex == -1)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "SetBounds() failed: file has not been opened yet.");
        return -1;
    }

    return m_papoTABFiles[m_nMainTableIndex]->SetBounds(dXMin, dYMin,
                                                        dXMax, dYMax);
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int TABView::TestCapability( const char * pszCap )

{
    if( EQUAL(pszCap,OLCRandomRead) )
        return TRUE;

    else if( EQUAL(pszCap,OLCSequentialWrite))
        return TRUE;

    else if( EQUAL(pszCap,OLCRandomWrite))
        return FALSE;

    else if( EQUAL(pszCap,OLCFastFeatureCount) )
        return m_poFilterGeom == NULL;

    else if( EQUAL(pszCap,OLCFastSpatialFilter) )
        return FALSE;

    else if( EQUAL(pszCap,OLCFastGetExtent) )
        return TRUE;

    else 
        return FALSE;
}






/**********************************************************************
 *                   TABView::Dump()
 *
 * Dump block contents... available only in DEBUG mode.
 **********************************************************************/
#ifdef DEBUG

void TABView::Dump(FILE *fpOut /*=NULL*/)
{
    if (fpOut == NULL)
        fpOut = stdout;

    fprintf(fpOut, "----- TABView::Dump() -----\n");

    if (m_numTABFiles > 0)
    {
        fprintf(fpOut, "File is not opened.\n");
    }
    else
    {
        fprintf(fpOut, "File is opened: %s\n", m_pszFname);
        fprintf(fpOut, "View contains %d tables\n", m_numTABFiles);

    }

    fflush(fpOut);
}

#endif // DEBUG



/*=====================================================================
 *                      class TABRelation
 *====================================================================*/


/**********************************************************************
 *                   TABRelation::TABRelation()
 *
 * Constructor.
 **********************************************************************/
TABRelation::TABRelation()
{
    m_poMainTable = NULL;
    m_pszMainFieldName = NULL;
    m_nMainFieldNo = -1;

    m_poRelTable = NULL;
    m_pszRelFieldName = NULL;
    m_nRelFieldNo = -1;
    m_nRelFieldIndexNo = -1;
    m_poRelINDFileRef = NULL;

    m_nUniqueRecordNo = 0;

    m_panMainTableFieldMap = NULL;
    m_panRelTableFieldMap = NULL;

    m_poDefn = NULL;
}

/**********************************************************************
 *                   TABRelation::~TABRelation()
 *
 * Destructor.
 **********************************************************************/
TABRelation::~TABRelation()
{
    ResetAllMembers();
}

/**********************************************************************
 *                   TABRelation::ResetAllMembers()
 *
 * Reset all class members.
 **********************************************************************/
void TABRelation::ResetAllMembers()
{
    m_poMainTable = NULL;
    CPLFree(m_pszMainFieldName);
    m_pszMainFieldName = NULL;
    m_nMainFieldNo = -1;

    m_poRelTable = NULL;
    CPLFree(m_pszRelFieldName);
    m_pszRelFieldName = NULL;
    m_nRelFieldNo = -1;
    m_nRelFieldIndexNo = -1;

    m_nUniqueRecordNo = 0;

    // No need to close m_poRelINDFileRef since we only got a ref. to it
    m_poRelINDFileRef = NULL;

    CPLFree(m_panMainTableFieldMap);
    m_panMainTableFieldMap = NULL;
    CPLFree(m_panRelTableFieldMap);
    m_panRelTableFieldMap = NULL;

    /*-----------------------------------------------------------------
     * Note: we have to check the reference count before deleting m_poDefn
     *----------------------------------------------------------------*/
    if (m_poDefn && m_poDefn->Dereference() == 0)
        delete m_poDefn;
    m_poDefn = NULL;

}

/**********************************************************************
 *                   TABRelation::Init()
 *
 * Set the details of the relation: the main and related tables, the fields
 * through which they will be connected, and the list of fields to select.
 * After this call, we are ready to read data records.
 *
 * For write access, Init() is called with pszMain/RelFieldName and
 * **papszSelectedFields passed as NULL.  They will have to be set through
 * other methods before a first feature can be written.
 *
 * A new OGRFeatureDefn is also built for the combined tables.
 *
 * Returns 0 on success, or -1 or error.
 **********************************************************************/
int  TABRelation::Init(const char *pszViewName,
                       TABFile *poMainTable, TABFile *poRelTable,
                       const char *pszMainFieldName,
                       const char *pszRelFieldName,
                       char **papszSelectedFields)
{
    if (poMainTable == NULL || poRelTable == NULL)
        return -1;

    // We'll need the feature Defn later...
    OGRFeatureDefn *poMainDefn, *poRelDefn;

    poMainDefn = poMainTable->GetLayerDefn();
    poRelDefn = poRelTable->GetLayerDefn();

    /*-----------------------------------------------------------------
     * Keep info for later use about source tables, etc.
     *----------------------------------------------------------------*/
    ResetAllMembers();

    m_poMainTable = poMainTable;
    if (pszMainFieldName)
    {
        m_pszMainFieldName = CPLStrdup(pszMainFieldName);
        m_nMainFieldNo = poMainDefn->GetFieldIndex(pszMainFieldName);
    }

    m_poRelTable = poRelTable;
    if (pszRelFieldName)
    {
        m_pszRelFieldName = CPLStrdup(pszRelFieldName);
        m_nRelFieldNo = poRelDefn->GetFieldIndex(pszRelFieldName);
        m_nRelFieldIndexNo = poRelTable->GetFieldIndexNumber(m_nRelFieldNo);
        m_poRelINDFileRef = poRelTable->GetINDFileRef();

        if (m_nRelFieldIndexNo >= 0 && m_poRelINDFileRef == NULL)
        {
            CPLError(CE_Failure, CPLE_FileIO,
                     "Field %s is indexed but the .IND file is missing.",
                     pszRelFieldName);
            return -1;
        }
    }

    /*-----------------------------------------------------------------
     * Init field maps.  For each field in each table, a -1 means that
     * the field is not selected, and a value >=0 is the index of the 
     * field in the view's FeatureDefn
     *----------------------------------------------------------------*/
    int i;
    int numFields1 = (poMainDefn?poMainDefn->GetFieldCount():0);
    int numFields2 = (poRelDefn?poRelDefn->GetFieldCount():0);

    m_panMainTableFieldMap = (int*)CPLMalloc((numFields1+1)*sizeof(int));
    for(i=0; i<numFields1; i++)
        m_panMainTableFieldMap[i] = -1;
    m_panRelTableFieldMap = (int*)CPLMalloc((numFields2+1)*sizeof(int));
    for(i=0; i<numFields2; i++)
        m_panRelTableFieldMap[i] = -1;

    /*-----------------------------------------------------------------
     * If selectedFields = "*" then select all fields from both tables
     *----------------------------------------------------------------*/
    if (CSLCount(papszSelectedFields) == 1 && 
        EQUAL(papszSelectedFields[0], "*") )
    {
        CSLDestroy(papszSelectedFields);
        papszSelectedFields = NULL;

        for(i=0; i<numFields1; i++)
        {
            OGRFieldDefn *poFieldDefn = poMainDefn->GetFieldDefn(i);

            papszSelectedFields = CSLAddString(papszSelectedFields, 
                                               poFieldDefn->GetNameRef());
        }

        for(i=0; i<numFields2; i++)
        {
            OGRFieldDefn *poFieldDefn = poRelDefn->GetFieldDefn(i);

            if (CSLFindString(papszSelectedFields, 
                              poFieldDefn->GetNameRef()) != -1)
                continue;  // Avoid duplicate field name in view

            papszSelectedFields = CSLAddString(papszSelectedFields, 
                                               poFieldDefn->GetNameRef());
        }

    }

    /*-----------------------------------------------------------------
     * Create new FeatureDefn and copy selected fields definitions
     * while updating the appropriate field maps.
     *----------------------------------------------------------------*/
    int nIndex, numSelFields = CSLCount(papszSelectedFields);
    OGRFieldDefn *poFieldDefn;

    m_poDefn = new OGRFeatureDefn(pszViewName);
    // Ref count defaults to 0... set it to 1
    m_poDefn->Reference();

    for(i=0; i<numSelFields ; i++)
    {
        if (poMainDefn &&
            (nIndex=poMainDefn->GetFieldIndex(papszSelectedFields[i])) >=0)
        {
            /* Field from the main table
             */
            poFieldDefn = poMainDefn->GetFieldDefn(nIndex);
            m_poDefn->AddFieldDefn(poFieldDefn);
            m_panMainTableFieldMap[nIndex] = m_poDefn->GetFieldCount()-1;
        }
        else if (poRelDefn &&
                 (nIndex=poRelDefn->GetFieldIndex(papszSelectedFields[i]))>=0)
        {
            /* Field from the related table
             */
            poFieldDefn = poRelDefn->GetFieldDefn(nIndex);
            m_poDefn->AddFieldDefn(poFieldDefn);
            m_panRelTableFieldMap[nIndex] = m_poDefn->GetFieldCount()-1;
        }
        else
        {
            // Hummm... field does not exist... likely an unsupported feature!
            // At least send a warning and ignore the field.
            CPLError(CE_Warning, CPLE_IllegalArg,
                     "Selected Field %s not found in source tables %s and %s",
                     papszSelectedFields[i], 
                     poMainDefn->GetName(), poRelDefn->GetName());
        }
    }

    return 0;
}


/**********************************************************************
 *                   TABRelation::CreateRelFields()
 *
 * For write access, create the integer fields in each table that will
 * link them, and setup everything to be ready to write the first feature.
 *
 * This function should be called just before writing the first feature.
 *
 * Returns 0 on success, or -1 or error.
 **********************************************************************/
int  TABRelation::CreateRelFields()
{
    int i;

    /*-----------------------------------------------------------------
     * Create the field in each table.  
     * The default name is "MI_refnum" but if a field with the same name
     * already exists then we'll try to generate a unique name.
     *----------------------------------------------------------------*/
    m_pszMainFieldName = CPLStrdup("MI_Refnum      ");
    strcpy(m_pszMainFieldName, "MI_Refnum");
    i = 1;
    while(m_poDefn->GetFieldIndex(m_pszMainFieldName) >= 0)
    {
        sprintf(m_pszMainFieldName, "MI_Refnum_%d", i++);
    }
    m_pszRelFieldName = CPLStrdup(m_pszMainFieldName);

    m_nMainFieldNo = m_nRelFieldNo = -1;
    if (m_poMainTable->AddFieldNative(m_pszMainFieldName,
                                      TABFInteger, 0, 0) == 0)
        m_nMainFieldNo = m_poMainTable->GetLayerDefn()->GetFieldCount()-1;

    if (m_poRelTable->AddFieldNative(m_pszRelFieldName,
                                     TABFInteger, 0, 0) == 0)
        m_nRelFieldNo = m_poRelTable->GetLayerDefn()->GetFieldCount()-1;

    if (m_nMainFieldNo == -1 || m_nRelFieldNo == -1)
        return -1;

    if (m_poMainTable->SetFieldIndexed(m_nMainFieldNo) == -1)
        return -1;

    if ((m_nRelFieldIndexNo=m_poRelTable->SetFieldIndexed(m_nRelFieldNo)) ==-1)
        return -1;

    m_poRelINDFileRef = m_poRelTable->GetINDFileRef();

    /*-----------------------------------------------------------------
     * Update field maps
     *----------------------------------------------------------------*/
    OGRFeatureDefn *poMainDefn, *poRelDefn;

    poMainDefn = m_poMainTable->GetLayerDefn();
    poRelDefn = m_poRelTable->GetLayerDefn();

    m_panMainTableFieldMap = (int*)CPLRealloc(m_panMainTableFieldMap,
                                      poMainDefn->GetFieldCount()*sizeof(int));
    m_panMainTableFieldMap[poMainDefn->GetFieldCount()-1] = -1;

    m_panRelTableFieldMap = (int*)CPLRealloc(m_panRelTableFieldMap,
                                      poRelDefn->GetFieldCount()*sizeof(int));
    m_panRelTableFieldMap[poRelDefn->GetFieldCount()-1] = -1;

    /*-----------------------------------------------------------------
     * Make sure the first unique field (in poRelTable) is indexed since
     * it is the one against which we will try to match records.
     *----------------------------------------------------------------*/
    if ( m_poRelTable->SetFieldIndexed(0) == -1)
        return -1;

    return 0;
}

/**********************************************************************
 *                   TABRelation::GetFeature()
 *
 * Fill and return a TABFeature object for the specified feature id.
 *
 * The retuned pointer is a new TABFeature that will have to be freed
 * by the caller.
 *
 * Returns NULL if the specified feature id does not exist of if an
 * error happened.  In any case, CPLError() will have been called to
 * report the reason of the failure.
 *
 * __TODO__ The current implementation fetches the features from each table
 * and creates a 3rd feature to merge them.  There would be room for 
 * optimization, at least by avoiding the duplication of the geometry 
 * which can be big sometimes... but this would imply changes at the
 * lower-level in the lib. and we won't go there yet.
 **********************************************************************/
TABFeature *TABRelation::GetFeature(int nFeatureId)
{
    TABFeature *poMainFeature;
    TABFeature *poCurFeature;

    /*-----------------------------------------------------------------
     * Make sure init() has been called
     *----------------------------------------------------------------*/
    if (m_poMainTable == NULL || m_poRelTable == NULL)
    {
        CPLError(CE_Failure, CPLE_IllegalArg,
                 "GetFeatureRef() failed: object not initialized yet!");
        return NULL;
    }

    /*-----------------------------------------------------------------
     * Read main feature and create a new one of the right type
     *----------------------------------------------------------------*/
    if ((poMainFeature = m_poMainTable->GetFeatureRef(nFeatureId)) == NULL)
    {
        // Feature cannot be read from main table... 
        // an error has already been reported.
        return NULL;
    }

    poCurFeature = poMainFeature->CloneTABFeature(m_poDefn);

    /*-----------------------------------------------------------------
     * Keep track of FID and copy the geometry 
     *----------------------------------------------------------------*/
    poCurFeature->SetFID(nFeatureId);

    if (poCurFeature->GetFeatureClass() != TABFCNoGeomFeature)
    {
        OGRGeometry *poGeom;
        poGeom = poMainFeature->GetGeometryRef();
        poCurFeature->SetGeometry(poGeom);
    }

    /*-----------------------------------------------------------------
     * Fetch feature from related table
     *
     * __TODO__ Right now we support only many-to-1 relationships, but
     *          it might be possible to have several related entries
     *          for a single key, and in this case we should return
     *          one new feature for each of them.
     *----------------------------------------------------------------*/
    TABFeature *poRelFeature=NULL;
    GByte *pKey = BuildFieldKey(poMainFeature, m_nMainFieldNo,
                            m_poMainTable->GetNativeFieldType(m_nMainFieldNo),
                                m_nRelFieldIndexNo);
    int i;
    int nRelFeatureId = m_poRelINDFileRef->FindFirst(m_nRelFieldIndexNo, pKey);
    
    if (nRelFeatureId > 0)
        poRelFeature = m_poRelTable->GetFeatureRef(nRelFeatureId);

    /*-----------------------------------------------------------------
     * Copy fields from poMainFeature
     *----------------------------------------------------------------*/
    for(i=0; i<poMainFeature->GetFieldCount(); i++)
    {
        if (m_panMainTableFieldMap[i] != -1)
        {
            poCurFeature->SetField(m_panMainTableFieldMap[i], 
                                     poMainFeature->GetRawFieldRef(i));
        }
    }

    /*-----------------------------------------------------------------
     * Copy fields from poRelFeature...
     *
     * NOTE: For now, if no corresponding feature is found in RelTable
     *       then we will just leave the corresponding fields unset.
     *----------------------------------------------------------------*/
    for(i=0; poRelFeature && i<poRelFeature->GetFieldCount(); i++)
    {
        if (m_panRelTableFieldMap[i] != -1)
        {
            poCurFeature->SetField(m_panRelTableFieldMap[i], 
                                     poRelFeature->GetRawFieldRef(i));
        }
    }

    return poCurFeature;
}



/**********************************************************************
 *                   TABRelation::BuildFieldKey()
 *
 * Return the index key for the specified field in poFeature.
 * Simply maps the call to the proper method in the TABINDFile class.
 *
 * Returns a reference to a TABINDFile internal buffer that should not
 * be freed by the caller.
 **********************************************************************/
GByte *TABRelation::BuildFieldKey(TABFeature *poFeature, int nFieldNo,
                                  TABFieldType eType, int nIndexNo)
{
    GByte *pKey = NULL;

    switch(eType)
    {
      case TABFChar:
        pKey = m_poRelINDFileRef->BuildKey(nIndexNo,
                             poFeature->GetFieldAsString(nFieldNo));
        break;

      case TABFDecimal:
      case TABFFloat:
        pKey = m_poRelINDFileRef->BuildKey(nIndexNo,
                             poFeature->GetFieldAsDouble(nFieldNo));
        break;

      // __TODO__ DateTime fields are 8 bytes long, not supported yet by
      // the indexing code (see bug #1844).
      case TABFDateTime:
        CPLError(CE_Failure, CPLE_NotSupported,
                 "TABRelation on field of type DateTime not supported yet.");
        break;

      case TABFInteger:
      case TABFSmallInt:
      case TABFDate:
      case TABFTime:
      case TABFLogical:
      default:
        pKey = m_poRelINDFileRef->BuildKey(nIndexNo,
                             poFeature->GetFieldAsInteger(nFieldNo));
        break;
    }

    return pKey;
}


/**********************************************************************
 *                   TABRelation::GetNativeFieldType()
 *
 * Returns the native MapInfo field type for the specified field.
 *
 * Returns TABFUnknown if file is not opened, or if specified field index is
 * invalid.
 *
 * Note that field ids are positive and start at 0.
 **********************************************************************/
TABFieldType TABRelation::GetNativeFieldType(int nFieldId)
{
    int i, numFields;

    if (m_poMainTable==NULL || m_poRelTable==NULL ||
        m_panMainTableFieldMap==NULL || m_panRelTableFieldMap==NULL)
        return TABFUnknown;

    /*-----------------------------------------------------------------
     * Look for nFieldId in the field maps and call the corresponding
     * TAB file's GetNativeFieldType()
     *----------------------------------------------------------------*/
    numFields = m_poMainTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panMainTableFieldMap[i] == nFieldId)
        {
            return m_poMainTable->GetNativeFieldType(i);
        }
    }

    numFields = m_poRelTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panRelTableFieldMap[i] == nFieldId)
        {
            return m_poRelTable->GetNativeFieldType(i);
        }
    }

    return TABFUnknown;
}


/**********************************************************************
 *                   TABRelation::AddFieldNative()
 *
 * Create a new field using a native mapinfo data type... this is an 
 * alternative to defining fields through the OGR interface.
 * This function should be called after creating a new dataset, but before 
 * writing the first feature.
 *
 * This function will build/update the OGRFeatureDefn that will have to be
 * used when writing features to this dataset.
 *
 * A reference to the OGRFeatureDefn can be obtained using GetLayerDefn().
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABRelation::AddFieldNative(const char *pszName, TABFieldType eMapInfoType,
                                int nWidth /*=0*/, int nPrecision /*=0*/,
                                GBool bIndexed /*=FALSE*/, GBool bUnique/*=FALSE*/, int bApproxOK)
{
    if (m_poMainTable==NULL || m_poRelTable==NULL ||
        m_panMainTableFieldMap==NULL || m_panRelTableFieldMap==NULL)
        return -1;

    if (!bUnique)
    {
        /*-------------------------------------------------------------
         * Add field to poMainTable and to m_poDefn
         *------------------------------------------------------------*/
        if (m_poMainTable->AddFieldNative(pszName, eMapInfoType,
                                          nWidth, nPrecision,
                                          bIndexed, bUnique, bApproxOK) != 0)
            return -1;

        OGRFeatureDefn *poMainDefn = m_poMainTable->GetLayerDefn();

        m_panMainTableFieldMap = (int*)CPLRealloc(m_panMainTableFieldMap,
                                      poMainDefn->GetFieldCount()*sizeof(int));

        m_poDefn->AddFieldDefn(poMainDefn->GetFieldDefn(poMainDefn->
                                                          GetFieldCount()-1));

        m_panMainTableFieldMap[poMainDefn->GetFieldCount()-1] = 
                                            m_poDefn->GetFieldCount()-1;
    }
    else
    {
        /*-------------------------------------------------------------
         * Add field to poRelTable and to m_poDefn
         *------------------------------------------------------------*/
        if (m_poRelTable->AddFieldNative(pszName, eMapInfoType,
                                         nWidth, nPrecision,
                                         bIndexed, bUnique, bApproxOK) != 0)
            return -1;

        OGRFeatureDefn *poRelDefn = m_poRelTable->GetLayerDefn();

        m_panRelTableFieldMap = (int*)CPLRealloc(m_panRelTableFieldMap,
                                      poRelDefn->GetFieldCount()*sizeof(int));

        m_poDefn->AddFieldDefn(poRelDefn->GetFieldDefn(poRelDefn->
                                                         GetFieldCount()-1));

        m_panRelTableFieldMap[poRelDefn->GetFieldCount()-1] =  
                                            m_poDefn->GetFieldCount()-1;

        // The first field in this table must be indexed.
        if (poRelDefn->GetFieldCount() == 1)
            m_poRelTable->SetFieldIndexed(0);
    }

    return 0;
}


/**********************************************************************
 *                   TABRelation::IsFieldIndexed()
 *
 * Returns TRUE is specified field is indexed.
 *
 * Note that field ids are positive and start at 0.
 **********************************************************************/
GBool TABRelation::IsFieldIndexed(int nFieldId)
{
    int i, numFields;

    if (m_poMainTable==NULL || m_poRelTable==NULL ||
        m_panMainTableFieldMap==NULL || m_panRelTableFieldMap==NULL)
        return FALSE;

    /*-----------------------------------------------------------------
     * Look for nFieldId in the field maps and call the corresponding
     * TAB file's GetNativeFieldType()
     *----------------------------------------------------------------*/
    numFields = m_poMainTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panMainTableFieldMap[i] == nFieldId)
        {
            return m_poMainTable->IsFieldIndexed(i);
        }
    }

    numFields = m_poRelTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panRelTableFieldMap[i] == nFieldId)
        {
            return m_poRelTable->IsFieldIndexed(i);
        }
    }

    return FALSE;
}

/**********************************************************************
 *                   TABRelation::SetFieldIndexed()
 *
 * Request that the specified field be indexed.  This will create the .IND
 * file, etc.
 *
 * Note that field ids are positive and start at 0.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABRelation::SetFieldIndexed(int nFieldId)
{
    int i, numFields;

    if (m_poMainTable==NULL || m_poRelTable==NULL ||
        m_panMainTableFieldMap==NULL || m_panRelTableFieldMap==NULL)
        return -1;

    /*-----------------------------------------------------------------
     * Look for nFieldId in the field maps and call the corresponding
     * TAB file's GetNativeFieldType()
     *----------------------------------------------------------------*/
    numFields = m_poMainTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panMainTableFieldMap[i] == nFieldId)
        {
            return m_poMainTable->SetFieldIndexed(i);
        }
    }

    numFields = m_poRelTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panRelTableFieldMap[i] == nFieldId)
        {
            return m_poRelTable->SetFieldIndexed(i);
        }
    }

    return -1;
}

/**********************************************************************
 *                   TABRelation::IsFieldUnique()
 *
 * Returns TRUE is specified field is part of the unique table (poRelTable).
 *
 * Note that field ids are positive and start at 0.
 **********************************************************************/
GBool TABRelation::IsFieldUnique(int nFieldId)
{
    int i, numFields;

    if (m_poMainTable==NULL || m_poRelTable==NULL ||
        m_panMainTableFieldMap==NULL || m_panRelTableFieldMap==NULL)
        return FALSE;

    /*-----------------------------------------------------------------
     * Look for nFieldId in the poRelTable field map
     *----------------------------------------------------------------*/
    numFields = m_poRelTable->GetLayerDefn()->GetFieldCount();
    for(i=0; i<numFields; i++)
    {
        if (m_panRelTableFieldMap[i] == nFieldId)
        {
            return TRUE;  // If it's here then it is unique!
        }
    }

    return FALSE;
}

/**********************************************************************
 *                   TABRelation::WriteFeature()
 *
 * Write a feature to this dataset.  
 *
 * For now only sequential writes are supported (i.e. with nFeatureId=-1)
 * but eventually we should be able to do random access by specifying
 * a value through nFeatureId.
 *
 * Returns the new featureId (> 0) on success, or -1 if an
 * error happened in which case, CPLError() will have been called to
 * report the reason of the failure.
 **********************************************************************/
int TABRelation::WriteFeature(TABFeature *poFeature, int nFeatureId /*=-1*/)
{
    TABFeature *poMainFeature=NULL;

    if (nFeatureId != -1)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "WriteFeature(): random access not implemented yet.");
        return -1;
    }

    CPLAssert(m_poMainTable && m_poRelTable);

    // We'll need the feature Defn later...
    OGRFeatureDefn *poMainDefn, *poRelDefn;

    poMainDefn = m_poMainTable->GetLayerDefn();
    poRelDefn = m_poRelTable->GetLayerDefn();

    /*-----------------------------------------------------------------
     * Create one feature for each table
     * Copy the geometry only to the feature from the main table
     *----------------------------------------------------------------*/
    poMainFeature = poFeature->CloneTABFeature(poMainDefn);

    if (poFeature->GetFeatureClass() != TABFCNoGeomFeature)
    {
        OGRGeometry *poGeom;
        poGeom = poFeature->GetGeometryRef();
        poMainFeature->SetGeometry(poGeom);
    }

    /*-----------------------------------------------------------------
     * Copy fields to poMainFeature
     *----------------------------------------------------------------*/
    for(int i=0; i<poMainDefn->GetFieldCount(); i++)
    {
        if (m_panMainTableFieldMap[i] != -1)
        {
            poMainFeature->SetField(i, 
                      poFeature->GetRawFieldRef(m_panMainTableFieldMap[i]));
        }
    }

    /*-----------------------------------------------------------------
     * Look for a record id for the unique fields, and write a new 
     * record if necessary
     *----------------------------------------------------------------*/
    int nRecordNo = 0;
    int nUniqueIndexNo=-1;
    if (m_panMainTableFieldMap[0] != -1)
        nUniqueIndexNo =m_poRelTable->GetFieldIndexNumber( 0 );

    if (nUniqueIndexNo > 0)
    {
        GByte *pKey = BuildFieldKey(poFeature, 0,
                                    m_poRelTable->GetNativeFieldType(0),
                                    nUniqueIndexNo);

        if ((nRecordNo=m_poRelINDFileRef->FindFirst(nUniqueIndexNo, pKey))==-1)
            return -1;

        if (nRecordNo == 0)
        {
            /*---------------------------------------------------------
             * No record in poRelTable yet for this unique value...
             * add one now...
             *--------------------------------------------------------*/
            TABFeature *poRelFeature = new TABFeature(poRelDefn);

            for(int i=0;  i<poRelDefn->GetFieldCount(); i++)
            {
                if (m_panRelTableFieldMap[i] != -1)
                {
                    poRelFeature->SetField(i, 
                          poFeature->GetRawFieldRef(m_panRelTableFieldMap[i]));
                }
            }

            nRecordNo = ++m_nUniqueRecordNo;

            poRelFeature->SetField(m_nRelFieldNo, nRecordNo);

            if (m_poRelTable->CreateFeature(poRelFeature) == OGRERR_NONE)
                return -1;

            delete poRelFeature;
        }
    }


    /*-----------------------------------------------------------------
     * Write poMainFeature to the main table
     *----------------------------------------------------------------*/
    poMainFeature->SetField(m_nMainFieldNo, nRecordNo);

    if (m_poMainTable->CreateFeature(poMainFeature) != OGRERR_NONE)
        nFeatureId = poMainFeature->GetFID();
    else
        nFeatureId = -1;

    delete poMainFeature;

    return nFeatureId;
}


/**********************************************************************
 *                   TABFile::SetFeatureDefn()
 *
 * NOT FULLY IMPLEMENTED YET... 
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABRelation::SetFeatureDefn(OGRFeatureDefn *poFeatureDefn,
                         TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
{
    if (m_poDefn && m_poDefn->GetFieldCount() > 0)
    {
        CPLAssert(m_poDefn==NULL);
        return -1;
    }

    /*-----------------------------------------------------------------
     * Keep a reference to the OGRFeatureDefn... we'll have to take the
     * reference count into account when we are done with it.
     *----------------------------------------------------------------*/
    if (m_poDefn && m_poDefn->Dereference() == 0)
        delete m_poDefn;

    m_poDefn = poFeatureDefn;
    m_poDefn->Reference();

    return 0;
}