summaryrefslogtreecommitdiff
path: root/src/core/xbixndx.cpp
blob: 097bd22b1f576eae4750aa7c245293fcdab9483a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
/* xbixndx.cpp

XBase64 Software Library

Copyright (c) 1997,2003,2014,2022 Gary A Kunkel

The xb64 software library is covered under the terms of the GPL Version 3, 2007 license.

Email Contact:

    XDB-devel@lists.sourceforge.net
    XDB-users@lists.sourceforge.net

*/

#include "xbase.h"

#ifdef XB_NDX_SUPPORT

namespace xb{


/***********************************************************************/
//! @brief Class constructor.
/*!
  \param dbf Pointer to dbf instance.
*/

xbIxNdx::xbIxNdx( xbDbf *dbf ) : xbIx( dbf ){
  ndxTag    = (xbNdxTag *) calloc( 1, sizeof( xbNdxTag ));
  SetBlockSize( XB_NDX_BLOCK_SIZE );
  cNodeBuf  = (char *) malloc( XB_NDX_BLOCK_SIZE );
}
/***********************************************************************/
//! @brief Class Destructor.
xbIxNdx::~xbIxNdx(){
  if( ndxTag ){
    ndxTag->npNodeChain  = FreeNodeChain( ndxTag->npNodeChain );
    if( ndxTag->cpKeyBuf )
      free( ndxTag->cpKeyBuf );
    if( ndxTag->cpKeyBuf2 )
      free( ndxTag->cpKeyBuf2 );
    if( ndxTag->exp ){
      delete ndxTag->exp;
      ndxTag->exp = NULL;
    }
    ndxTag->sKeyExpression.Set( NULL );
    ndxTag->sTagName.Set( NULL );
    free( ndxTag );
    ndxTag = NULL;
  }
  if( cNodeBuf )
    free( cNodeBuf );
}
/***********************************************************************/
//! @brief Add key.
/*!
  Add key. If this is a unique index, this logic assumes the duplicate 
  check logic was already done.

  \param vpTag Tag to update.
  \param ulRecNo Record number to add key for.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::AddKey( void * vpTag, xbUInt32 ulRecNo ){

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  if( GetUniqueKeyOpt() == XB_EMULATE_DBASE && npTag->bFoundSts )
    return XB_NO_ERROR;

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbInt16 iHeadNodeUpdateOpt = 2;


  try{

     if(( iRc = xbIxNdx::KeySetPosAdd( npTag, ulRecNo )) != XB_NO_ERROR ){
       iErrorStop = 100;
       throw iRc;
     }
     xbInt32 lKeyCnt = GetKeyCount( npTag->npCurNode );
     if( lKeyCnt <  npTag->iKeysPerBlock ){
        // Section A - add key to appropriate position if space available
        if(( iRc = InsertNodeL( npTag, npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->cpKeyBuf, ulRecNo )) != XB_NO_ERROR ){
          iErrorStop = 200;
          throw iRc;
        }

     } else {
       // land here with a full leaf node
       iHeadNodeUpdateOpt = 1;
       // section B - split the leaf node
       xbIxNode * npRightNode = AllocateIxNode( GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, 1 );
       if( !npRightNode ){
         iErrorStop = 100;
         iRc = XB_NO_MEMORY;
         throw iRc;
       }
       if(( iRc = SplitNodeL( npTag, npTag->npCurNode, npRightNode, npTag->npCurNode->iCurKeyNo, npTag->cpKeyBuf, ulRecNo )) != XB_NO_ERROR ){
         iErrorStop = 110;
         throw iRc;
       }
       xbUInt32 ulTempBlockNo = npRightNode->ulBlockNo;

       // section C - go up the tree, splitting nodes as necessary
       xbIxNode * npParent = npTag->npCurNode->npPrev;
       while( npParent && GetKeyCount( npParent ) >= npTag->iKeysPerBlock ){
         npRightNode = FreeNodeChain( npRightNode );
         npRightNode = AllocateIxNode( GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, 1 );
         if( !npRightNode ){
           iErrorStop = 200;
           iRc = XB_NO_MEMORY;
           throw iRc;
         }
         if(( iRc = SplitNodeI( npTag, npParent, npRightNode, npParent->iCurKeyNo, ulTempBlockNo )) != XB_NO_ERROR ){
           iErrorStop = 210;
           throw iRc;
         }
         ulTempBlockNo = npRightNode->ulBlockNo;
         npTag->npCurNode = npParent;
         npParent = npParent->npPrev;
       }

       // section D - if cur node is split root, create new root
       if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock ){
         // xbase->WriteLogMessage( "Section d" );
         if(( iRc = AddKeyNewRoot( npTag, npTag->npCurNode, npRightNode )) != XB_NO_ERROR ){
             iErrorStop = 300;
             throw iRc;
         }
         npRightNode = FreeNodeChain( npRightNode );

       } else {
         // else section E, put key in parent
         if(( iRc = InsertNodeI( vpTag, npParent, npParent->iCurKeyNo, npRightNode->ulBlockNo )) != XB_NO_ERROR ){
           iErrorStop = 400;
           throw iRc;
         }
         npRightNode = FreeNodeChain( npRightNode );
       }
     }

     // update the header
     if(( iRc = WriteHeadBlock( iHeadNodeUpdateOpt )) != XB_NO_ERROR ){
       iErrorStop = 130;
       throw iRc;
     }

     // ---- free whatever is left of the node chain here, this might not be right, might need to restore it to
     //         the point right after SetKeyPosAdd
     npTag->npNodeChain = FreeNodeChain( ndxTag->npNodeChain );
     npTag->npCurNode = NULL;

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::AddKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Add new root node.
/*!
  \param npTag Tag to update.
  \param npLeft Left node.
  \param npRight Right node.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::AddKeyNewRoot(  xbNdxTag *npTag, xbIxNode *npLeft, xbIxNode *npRight ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbString sMsg;
  char *pLastKey = NULL;

  try{
    xbIxNode *npRoot = AllocateIxNode( GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, 1 );
    if( !npRoot ){
      iErrorStop = 100;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }
    npTag->ulRootBlock = npRoot->ulBlockNo;
    pLastKey = (char *) malloc( (size_t) ndxTag->iKeyLen );
    if(( iRc = GetLastKeyForBlockNo( npTag, npLeft->ulBlockNo, pLastKey )) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }
    char * pTrg = npRoot->cpBlockData;

    // set no of keys to 1
    ePutUInt32( pTrg, 1 );

    // set the left node number
    pTrg += 4;
    ePutUInt32( pTrg, npLeft->ulBlockNo );

    // set the key
    pTrg+= 8;
    memcpy( pTrg, pLastKey, (size_t) npTag->iKeyLen );

    // set the right node number
    pTrg+= (npTag->iKeyItemLen - 8);
    ePutUInt32( pTrg, npRight->ulBlockNo );

     // write out the block
    if(( iRc = WriteBlock( npRoot->ulBlockNo, GetBlockSize(), npRoot->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 120;
      throw iRc;
    }
    if( pLastKey ) 
      free( pLastKey );
    NodeFree( npRoot );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::AddKeyNewRoot() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( pLastKey ) 
      free( pLastKey );
  }
  return iRc;
}
/***********************************************************************/
//! @brief Append node to node chain.
/*!
  Append a node to the current node chain for a given tag.

  \param vpTag Tag to update.
  \param npNode Node to add to node chain.
  \returns void
*/
void xbIxNdx::AppendNodeChain( void *vpTag, xbIxNode * npNode ){

    xbNdxTag * npTag;
    vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

    if( npTag->npNodeChain == NULL ){
      npTag->npNodeChain = npNode;
      npTag->npCurNode = npNode;
    } else {
      npNode->npPrev = npTag->npCurNode;
      npTag->npCurNode->npNext = npNode;
      npTag->npCurNode = npNode;
    }
    // time stamp the node chain
    GetFileMtime( npTag->tNodeChainTs );
}

/***********************************************************************/
//! @brief Allocate a node.
/*!
  \param ulBufSize Buffer size.
  \param iOpt 0 - Don't update the node block number on the node.
              1 - Set node block number to the next available block number.
  \returns Pointer to new node.
*/

xbIxNode * xbIxNdx::AllocateIxNode( xbUInt32 ulBufSize, xbInt16 iOpt ){
  xbIxNode *n = xbIx::AllocateIxNode( ulBufSize );
  if( n && iOpt == 1 ) n->ulBlockNo = ndxTag->ulTotalBlocks++;
  return n;
}
/***********************************************************************/
//! @brief Check for duplicate key.
/*!
  \param vpTag Tag to check.
  \returns XB_KEY_NOT_UNIQUE<br>XB_NO_ERROR
*/
xbInt16 xbIxNdx::CheckForDupKey( void *vpTag )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag *npTag = (xbNdxTag *) vpTag;
  npTag->bFoundSts = xbFalse;
  try{
    if( GetUnique()){
      if( npTag->iKeySts == XB_ADD_KEY || npTag->iKeySts == XB_UPD_KEY )
        if( KeyExists( vpTag )){
          if( GetUniqueKeyOpt() == XB_EMULATE_DBASE ){
            npTag->bFoundSts = xbTrue;
            return 0;
          } else {
            return XB_KEY_NOT_UNIQUE;
          }
       }
     }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::CheckForDupKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Check tag integrity.
/*!
  Check a tag for accuracy.

  \param vpTag Tag to create key for.
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::CheckTagIntegrity( void *vpTag, xbInt16 iOpt ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iRc2;
  xbInt16 iRc3;
  xbInt16 iErrorStop = 0;
  xbUInt32 ulIxCnt = 0;
  xbUInt32 ulThisRecNo = 0;
  xbUInt32 ulPrevRecNo = 0;
  xbBool bDone = false;
  xbString sMsg;
  char cKeyType;
  char *pPrevKeyBuf = NULL;
  xbInt16 iAutoLock = xbFalse;

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
//    xbase->WriteLogMessage( "xbIxNdx::CheckTagIntegrity()", iOpt );

    #ifdef XB_LOCKING_SUPPORT
    iAutoLock = dbf->GetAutoLock();
    if( iAutoLock && !dbf->GetTableLocked() ){
      if(( iRc = dbf->LockTable( XB_LOCK )) != XB_NO_ERROR ){
        iErrorStop = 10;
        throw iRc;
      }
    }
    #endif

    memset( npTag->cpKeyBuf2, 0x00, (size_t) npTag->iKeyLen );
    cKeyType = GetKeyType( vpTag );

    sMsg.Sprintf( "Checking index type [%c]", cKeyType );
    xbase->WriteLogMessage( sMsg, iOpt );

    pPrevKeyBuf = (char *) calloc( 1, (size_t) ndxTag->iKeyLen );

    // for each key in the index, make sure it is trending in the right direction
    iRc = GetFirstKey( vpTag, 0 );
    while( iRc == XB_NO_ERROR && !bDone ){
      ulIxCnt++;
      iRc = GetNextKey( vpTag, 0 );
      if( iRc == XB_NO_ERROR ){
        // compare this key to prev key
        iRc2 = CompareKey( cKeyType, GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ), 
                          pPrevKeyBuf, (size_t) npTag->iKeyLen );

        if( iRc2 < 0 ){
          sMsg.Sprintf( "Key sequence error at key number [%ld].", ulIxCnt );
          xbase->WriteLogMessage( sMsg, iOpt );
          iErrorStop = 100;
          iRc = XB_INVALID_INDEX;
          throw iRc;
        }

        ulThisRecNo = 0;
        if(( iRc3 = GetDbfPtr( vpTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulThisRecNo )) != XB_NO_ERROR ){
          iErrorStop = 110;
          throw iRc3;
        }

        if( iRc2 == 0 && (ulThisRecNo <= ulPrevRecNo )){
          sMsg.Sprintf( "Dbf record number sequence error at key number [%ld].", iOpt );
          xbase->WriteLogMessage( sMsg, iOpt );
          iErrorStop = 120;
          iRc = XB_INVALID_INDEX;
          throw iRc;
        }
        // save this key info to prev key
        memcpy( pPrevKeyBuf, GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ), (size_t) npTag->iKeyLen );
        ulPrevRecNo = ulThisRecNo;
      }
    }

    // verify the index count matches the tag count
    xbUInt32 ulDbfCnt = 0;
    if(( iRc = dbf->GetRecordCnt( ulDbfCnt )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }

    if( GetUniqueKeyOpt() == XB_EMULATE_DBASE && GetUnique( vpTag )){
      // Can't compare counts if using XB_EMULATE_DBASE and it's a unique index
    } else {
      if( ulDbfCnt != ulIxCnt ){
        sMsg.Sprintf( "CheckTagIntegrity()  Index entry count [%ld] does not match dbf record count [%ld]", ulIxCnt, ulDbfCnt );
        xbase->WriteLogMessage( sMsg, iOpt );
        iErrorStop = 140;
        iRc = XB_INVALID_INDEX;
        throw iRc;
      }

      // verify each record in the dbf file has a corresponding index entry
      xbUInt32 j = 0;
      while( j < ulDbfCnt ){
        if(( iRc = dbf->GetRecord( ++j )) != XB_NO_ERROR ){
          iErrorStop = 150;
         throw iRc;
        }
        if(( iRc = FindKeyForCurRec( vpTag )) != XB_NO_ERROR ){
          ulThisRecNo = j;
          iErrorStop = 160;
          throw iRc;
        }
      }
      sMsg.Sprintf( "CheckTagIntegrity()  Index entry count [%ld] matches dbf record count [%ld]", ulIxCnt, ulDbfCnt );
      xbase->WriteLogMessage( sMsg, iOpt );
    }

    #ifdef XB_LOCKING_SUPPORT
    if( iAutoLock && !dbf->GetTableLocked() ){
      if(( iRc = dbf->LockTable( XB_UNLOCK )) != XB_NO_ERROR ){
        iErrorStop = 200;
        throw iRc;
      }
    }
    #endif


    if( pPrevKeyBuf )
      free( pPrevKeyBuf );

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::CheckTagIntegrity() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg, iOpt );
    xbase->WriteLogMessage( GetErrorMessage( iRc ), iOpt );
    if( pPrevKeyBuf )
      free( pPrevKeyBuf );

    if( iErrorStop == 160 ){
      sMsg.Sprintf( "xbIxNdx::CheckTagIntegrity() Missing index entry for record [%d]", ulThisRecNo );
      xbase->WriteLogMessage( sMsg, iOpt );
    }
  }
  return iRc;

}
/***********************************************************************/
//! @brief Create key for tag.
/*!
  Append a node to the current node chain for a given tag.

  \param vpTag Tag to create key for.
  \param iOpt 0 = Build a key for FindKey usage, only rec buf 0.<br>
              1 = Append Mode, Create key for an append, only use rec buf 0, set updated switch.<br>
              2 = Update Mode, Create old version and new version keys, check if different, set update switch appropriately.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::CreateKey( void * vpTag, xbInt16 iOpt ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  try{
    xbNdxTag * npTag;
    vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

    if(( iRc = npTag->exp->ProcessExpression( 0 )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }
    if( npTag->exp->GetReturnType() == XB_EXP_CHAR ){
      npTag->exp->GetStringResult( npTag->cpKeyBuf, (xbUInt32) npTag->iKeyLen );
    }
    else if( npTag->exp->GetReturnType() == XB_EXP_NUMERIC ){
      xbDouble d;
      npTag->exp->GetNumericResult( d );
      memcpy( npTag->cpKeyBuf, &d, 8 );
    }
    else if( npTag->exp->GetReturnType() == XB_EXP_DATE ){
      xbDouble d;
      npTag->exp->GetNumericResult( d );
      memcpy( npTag->cpKeyBuf, &d, 8 );
    }

    npTag->iKeySts = 0;
    if( iOpt == 1 )
      npTag->iKeySts = XB_ADD_KEY;

    else if( iOpt == 2 ){
      if(( iRc = npTag->exp->ProcessExpression( 1 )) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
      if( npTag->exp->GetReturnType() == XB_EXP_CHAR ){
        npTag->exp->GetStringResult( npTag->cpKeyBuf2, (xbUInt32) npTag->iKeyLen );
      } else if( npTag->exp->GetReturnType() == XB_EXP_NUMERIC || npTag->exp->GetReturnType() == XB_EXP_DATE  ){
        xbDouble d;
        npTag->exp->GetNumericResult( d );
        memcpy( npTag->cpKeyBuf2, &d, 8 );
      }
      if( memcmp( npTag->cpKeyBuf, npTag->cpKeyBuf2, (size_t) npTag->iKeyLen ))
        npTag->iKeySts = XB_UPD_KEY;
    }

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::CreateKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Create new tag.
/*!
  This routine creates a new tag. Since NDX files have only one tag,
  this creates a new NDX file.

  \param sName Tag Name, including .NDX suffix
  \param sKey Key Expression
  \param sFilter Filter expression.  Not supported by NDX indices.
  \param iDescending Not supported by NDX indices.
  \param iUnique xbtrue - Unique.<br>xbFalse - Not unique.
  \param iOverLay xbTrue - Overlay if file already exists.<br>xbFalse - Don't overlay.
  \param vpTag Output from method Pointer to vptag pointer.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16  xbIxNdx::CreateTag( const xbString &sName, const xbString &sKey,
                const xbString &, xbInt16, xbInt16 iUnique, xbInt16 iOverLay, void **vpTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag *npTag = ndxTag;
  *vpTag = ndxTag;

  try{
    //xbString sMsg;
    SetFileName( sName );

    if( FileExists() && !iOverLay )
      return XB_FILE_EXISTS;

    if( FileIsOpen()){
      if(( iRc = xbTruncate(0)) != XB_NO_ERROR ){
        iErrorStop = 10;
        throw iRc;
      }
      if(( iRc = xbFclose()) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
      npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
      npTag->npCurNode = NULL;
      npTag->sKeyExpression.Set( "" );

      if( npTag->cpKeyBuf ){
        free( npTag->cpKeyBuf );
        npTag->cpKeyBuf = NULL;
      }
      if( npTag->cpKeyBuf2 ){
        free( npTag->cpKeyBuf2 );
        npTag->cpKeyBuf2 = NULL;
      }
    }

    if(( iRc = xbFopen( "w+b", dbf->GetShareMode())) != XB_NO_ERROR ){
      iErrorStop = 30;
      throw iRc;
    }

    //set up the key expression
    npTag->exp = new xbExp( dbf->GetXbasePtr());
    if(( iRc = npTag->exp->ParseExpression( dbf, sKey )) != XB_NO_ERROR ){
      iErrorStop = 40;
      throw iRc;
    }

    switch( npTag->exp->GetReturnType()){
      case XB_EXP_CHAR:
        npTag->cKeyType = 'C';
        npTag->iKeyType = 0;
        npTag->iKeyLen  = npTag->exp->GetResultLen();
        break;

      case XB_EXP_NUMERIC:
        npTag->cKeyType = 'F';
        npTag->iKeyType = 1;
        npTag->iKeyLen  = 8;
        break;

      case XB_EXP_DATE:
        npTag->cKeyType = 'D';
        npTag->iKeyType = 1;
        npTag->iKeyLen  = 8;
        break;

      default:
        iErrorStop = 50;
        iRc = XB_INVALID_INDEX;
        throw iRc;
    }

    npTag->iUnique        = iUnique;
    npTag->ulRootBlock    = 1L;
    npTag->ulTotalBlocks   = 2l;
    npTag->sKeyExpression = sKey;

    GetFileNamePart( npTag->sTagName );

    if( npTag->iKeyLen > 100 ){
      iErrorStop = 60;
      throw iRc;
    }

    npTag->iKeyItemLen    = npTag->iKeyLen + 8;
    while(( npTag->iKeyItemLen % 4 )!= 0 ) npTag->iKeyItemLen++;

    npTag->iKeysPerBlock = (xbInt16) (GetBlockSize() - 8 ) / npTag->iKeyItemLen; 
    ndxTag->cpKeyBuf  = (char *) malloc( (size_t) ndxTag->iKeyLen );
    ndxTag->cpKeyBuf2 = (char *) malloc( (size_t) ndxTag->iKeyLen );

    if(( iRc = WriteHeadBlock(0)) != XB_NO_ERROR ){
      iErrorStop = 70;
      throw iRc;
    }

    //write out block binary zeroes
    char buf[512];
    memset( buf, 0x00, 512 );
    if(( iRc = xbFwrite( buf, 1, 512 )) != XB_NO_ERROR ){
      iErrorStop = 80;
      throw iRc;
    }

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::CreateTag() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Delete a key.
/*!
  This routine deletes a key from a supplied node.
  \param vpTag Tag to delete key on.
  \param npNode Node to delete key on.
  \param iSlotNo Slot number of key to delete.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::DeleteFromNode( void *vpTag, xbIxNode * npNode, xbInt16 iSlotNo )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{

    xbInt32 lKeyCnt = GetKeyCount( npNode );
    xbInt16 iLen = (lKeyCnt - iSlotNo - 1) * npTag->iKeyItemLen;
    if( !IsLeaf( vpTag, npNode ))
        iLen += 4;

    if( iLen > 0 ){
      char *pTrg = npNode->cpBlockData;
      pTrg += (4 + (npTag->iKeyItemLen * (iSlotNo)) );  //lTrgPos;
      char *pSrc = pTrg;
      pSrc += npTag->iKeyItemLen;
      memmove( pTrg, pSrc, (size_t) iLen );
    }

    // set the new number of keys 
    ePutUInt32( npNode->cpBlockData, (xbUInt32) lKeyCnt - 1 );

     // write out the block
    if(( iRc = WriteBlock( npNode->ulBlockNo, GetBlockSize(), npNode->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::DeleteFromNode() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return XB_NO_ERROR;
}

/***********************************************************************/
//! @brief Delete a key.
/*!
  This routine deletes a key. It assumes the key to delete
  is the current key in the node chain.

  \param vpTag Tag to delete key on.

  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::DeleteKey( void *vpTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  // save copy of node chain to reset to after delete completed
  xbIxNode *npSaveNodeChain = npTag->npNodeChain;
  npTag->npNodeChain = NULL;
  xbIxNode * npSaveCurNode = npTag->npCurNode;

  try{

    xbString sMsg;

     if(( iRc = xbIxNdx::KeySetPosDel( npTag )) != XB_NO_ERROR ){
       iErrorStop = 100;
       throw iRc;
     }
     // Delete key needs to handle two scenarios
     // 1 - if the delete is on the only key of a leaf node, then traverse up the tree, trimming as needed
     // 2 - if the last key on a node is deleted, and the key value is not the same as the prev key value
     //     go up the tree looking for an interior node needing updated key value


     xbInt32 lOrigKeyCnt = GetKeyCount( npTag->npCurNode );
     if(( iRc = DeleteFromNode( npTag, npTag->npCurNode, npTag->npCurNode->iCurKeyNo )) != XB_NO_ERROR ){
       iErrorStop = 110;
       throw iRc;
     }

     if( lOrigKeyCnt == 1 ){
       // scenario 1 
       xbBool bDone = xbFalse;
       xbBool bIsLeaf = xbFalse;
       xbInt32 lKeyCnt;
       npTag->npCurNode = npTag->npCurNode->npPrev;

       while( npTag->npCurNode && !bDone ){
         lKeyCnt = GetKeyCount( npTag->npCurNode );
         bIsLeaf = IsLeaf( npTag, npTag->npCurNode );
         if( lKeyCnt > 0 ){
           if(( iRc = DeleteFromNode( npTag, npTag->npCurNode, npTag->npCurNode->iCurKeyNo )) != XB_NO_ERROR ){
             iErrorStop = 120;
             throw iRc;
           }
         }
         if( (bIsLeaf && lKeyCnt > 1) || (!bIsLeaf && lKeyCnt > 0) )
           bDone = xbTrue;
         else
           npTag->npCurNode = npTag->npCurNode->npPrev; 
      }
    } else if( npTag->npCurNode->iCurKeyNo == (xbUInt32) lOrigKeyCnt - 1 ){

      // scenario 2
      // if last two keys identical, then nothing to do, else go up looking for a key to change
      if( memcmp( GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ),
                  GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo-1, npTag->iKeyItemLen ),
                  (size_t) npTag->iKeyLen )){

        xbIxNode *pNode = npTag->npCurNode->npPrev;
        char *pSrc = GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo-1, npTag->iKeyItemLen );

        while( pNode && pNode->ulBlockNo != npTag->ulRootBlock && pNode->iCurKeyNo == (xbUInt32) GetKeyCount( pNode ) )
            pNode = pNode->npPrev;
        if( pNode ){
          if( pNode->iCurKeyNo < (xbUInt32) GetKeyCount( pNode )){
            char *pTrg  = pNode->cpBlockData;
            pTrg += 12 + (pNode->iCurKeyNo * (xbUInt32) npTag->iKeyItemLen);
            for( xbInt16 i = 0; i < npTag->iKeyLen; i++ )
              *pTrg++ = *pSrc++;

            // write out the block
            if(( iRc = WriteBlock( pNode->ulBlockNo, GetBlockSize(), pNode->cpBlockData )) != XB_NO_ERROR ){
              iErrorStop = 130;
              throw iRc;
            }
          }
        }
      }
    }

    // restore node chain to pre delete status (which should be post add status)
    npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
    npTag->npNodeChain = npSaveNodeChain;
    npTag->npCurNode = npSaveCurNode;

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::DeleteKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( npSaveNodeChain ){
      npTag->npNodeChain = npSaveNodeChain;
      npSaveNodeChain = FreeNodeChain( npSaveNodeChain );
      npTag->npCurNode = npSaveCurNode;
    }
  }
  return iRc;
}


/***********************************************************************/
//! @brief Delete tag.
/*!
  In the case of an ndx tag, it deletes the ndx file as it contains
  only one tag.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::DeleteTag( void * ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  //xbNdxTag * npTag;
  //vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{

    // if open, close it
    if( FileIsOpen()){
      if(( iRc = Close()) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
    }
    // delete file
    if(( iRc = xbRemove()) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::DeleteTag() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
#ifdef XB_DEBUG_SUPPORT

//! @brief Dump a block for a given tag.
/*!
  Dump blocks for given tag for debugging purposes.
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \param vpTag - Not required for single tag NDX files.
  \returns void
*/

//xbInt16 xbIxNdx::DumpTagBlocks( xbInt16 iOpt, void *vpTag ){

xbInt16 xbIxNdx::DumpTagBlocks( xbInt16 iOpt, void * ){

  xbInt16  iRc = 0;
  xbInt16  iErrorStop = 0;
  xbUInt32 lNoOfKeys;
  char     *p;
  xbString s;
  xbBool   bIsLeaf = false;

  try{
    if( !FileIsOpen()){
      iRc = XB_NOT_OPEN;
      iErrorStop = 10;
      throw iRc;
    }

    xbUInt32 ulStartBlock;
    xbUInt32 ulEndBlock;
    ulStartBlock = 1;
    ulEndBlock = ndxTag->ulTotalBlocks;

    for( xbUInt32 lBlk = ulStartBlock; lBlk < ulEndBlock; lBlk++ ){

      memset( cNodeBuf, 0x00, XB_NDX_BLOCK_SIZE );
      if(( iRc = ReadBlock( lBlk, XB_NDX_BLOCK_SIZE, cNodeBuf )) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
      p = cNodeBuf;
      lNoOfKeys = eGetUInt32( p );

      if( eGetUInt32( p + 4 ) > 0 ){
        bIsLeaf = false;
        s.Sprintf( "Node # %ld - Interior Node - Key Type [%c] Key Count [%ld]", lBlk, ndxTag->cKeyType, lNoOfKeys );
      } else {
        bIsLeaf = true;
        s.Sprintf( "Node # %ld - Leaf Node - Key Type [%c] Key count [%ld]", lBlk, ndxTag->cKeyType, lNoOfKeys );
      }
      xbase->WriteLogMessage( s, iOpt );
      xbase->WriteLogMessage( "Key      Child    Dbf Rec  Key", iOpt );
      p += 4;
      xbUInt32 ulLeftBranch;
      xbUInt32 ulRecNo;
      xbString sKey;
      xbDouble d;

      xbUInt32 l;
      for( l = 0; l < lNoOfKeys; l++ ){
        ulLeftBranch = eGetUInt32( p );
        p+= 4;
        ulRecNo = eGetUInt32( p );
        p+= 4;
        if( ndxTag->cKeyType == 'C' ){
          sKey.Assign( p, 1, (xbUInt32) ndxTag->iKeyLen );
        } else if( ndxTag->cKeyType == 'D' ){
          xbInt32 lDate = (xbInt32) eGetDouble( p );
          xbDate dt( lDate );
          //xbString s2;
          //dt.JulToDate8( lDate, s2 );
          sKey.Sprintf( "%ld - %s", lDate, dt.Str());
        } else {
          d = eGetDouble( p );
          sKey.Sprintf( "%f", d );
        }
        p+= (ndxTag->iKeyItemLen-8);

        s.Sprintf( "%3d  %9d  %9d  %s", l+1, ulLeftBranch, ulRecNo, sKey.Str() );
        xbase->WriteLogMessage( s, iOpt );
      }
      if( !bIsLeaf ){
        ulLeftBranch = eGetUInt32( p );
        s.Sprintf( "%3d  %9d", l+1, ulLeftBranch );
        xbase->WriteLogMessage( s, iOpt );
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::DumpTagBlocks() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Dump index file header.
/*!
  Dump a index file header for debugging purposes.
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::DumpHeader( xbInt16 iOpt, xbInt16 ){
  xbString s;
  xbInt16 iRc;

  if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR )
    return iRc;

  s.Sprintf( "Index Header Node for %s", GetFileName().Str());
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "--------------------------------" );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Root block      = %ld",   ndxTag->ulRootBlock );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Total blocks    = %ld",   ndxTag->ulTotalBlocks );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Key types       = %c,%d", ndxTag->cKeyType, ndxTag->iKeyType );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Key Length      = %d",    ndxTag->iKeyLen );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Keys Per Block  = %d",    ndxTag->iKeysPerBlock );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "Key Item Len    = %ld",   ndxTag->iKeyItemLen );
  xbase->WriteLogMessage( s, iOpt);
  s.Sprintf( "Serial No       = %d",    ndxTag->cSerNo );
  xbase->WriteLogMessage( s, iOpt);
  s.Sprintf( "Unique          = %d",    ndxTag->iUnique );
  xbase->WriteLogMessage( s, iOpt );
  s.Sprintf( "KeyExpression   = %s",    ndxTag->sKeyExpression.Str() );
  xbase->WriteLogMessage( s, iOpt );
  return XB_NO_ERROR;
}
/***********************************************************************/
//! @brief Dump the index for a tag.
/*!
  Stub.
  \returns XB_NO_ERROR
*/
xbInt16 xbIxNdx::DumpIxForTag( void *, xbInt16 )
{
  return XB_NO_ERROR;
}
/***********************************************************************/
//! @brief Dump the index node chain.
/*!
  Dump the index node chain for debugging purposes.
  \param vpTag Tag of node chain to dump.
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \returns void
*/
void xbIxNdx::DumpIxNodeChain( void *vpTag, xbInt16 iOpt ) const
{

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  xbString s( "Dump Node Chain" );
  xbase->WriteLogMessage( s, iOpt );

  if( npTag->npNodeChain ){
    xbIxNode *n = npTag->npNodeChain;
    xbInt16 iCtr = 0;
    char cLeaf;
    s.Sprintf( "Cnt\tThis     Prev     Next     CurKeyNo  BlockNo  NoOfKeys  Type" );
    xbase->WriteLogMessage( s, iOpt );
    while( n ){
      IsLeaf( vpTag, n ) ? cLeaf = 'L' : cLeaf = 'I';
      s.Sprintf( "%d\t%08x %08x %08x %08d  %08d %08d  %c", 
                 iCtr++, n, n->npPrev, n->npNext, n->iCurKeyNo, 
                 n->ulBlockNo, eGetUInt32( n->cpBlockData ), cLeaf );
      xbase->WriteLogMessage( s, iOpt );
      n = n->npNext;
    }
  } else {
    s = "Empty Node Chain";
    xbase->WriteLogMessage( s, iOpt );
  }
}
/***********************************************************************/
//! @brief Dump node.
/*!
  Dump a node for debugging purposes.
  \param vpTag Tag of node chain to dump.
  \param pNode Node to dump.
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \returns XB_NVALID_OBJECT<br>XB_NO_ERROR
*/

xbInt16 xbIxNdx::DumpNode( void *vpTag, xbIxNode *pNode, xbInt16 iOpt ) const
{
  xbString s;
  xbString sKey;
  xbUInt32 lLeftBranch;
  xbUInt32 lRecNo;
  xbDouble d;

  if( !pNode )
    return XB_INVALID_OBJECT;

  xbIx::DumpNode( vpTag, pNode, iOpt );

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  xbUInt32 lNoOfKeys = eGetUInt32( pNode->cpBlockData );
  xbBool bIsLeaf = IsLeaf( vpTag, pNode );

  if( bIsLeaf )
    xbase->WriteLogMessage( "Leaf node", iOpt );
  else
    xbase->WriteLogMessage( "Interior node", iOpt );

  s.Sprintf( "Key type = [%c] No Of Keys =[%d] Prev =[%x] Next =[%x]", npTag->cKeyType, lNoOfKeys, pNode->npPrev, pNode->npNext );
  xbase->WriteLogMessage( s, iOpt );

  char *p = pNode->cpBlockData;
  p += 4;

  xbUInt32 l;
  for( l = 0; l < lNoOfKeys; l++ ){

    lLeftBranch = eGetUInt32( p );
    p+= 4;
    lRecNo = eGetUInt32( p );
    p+= 4;

    if( npTag->cKeyType == 'C' ){
      sKey.Assign( p, 1, (xbUInt32) npTag->iKeyLen );
    } else if( npTag->cKeyType == 'D' ){
      xbInt32 lDate = (xbInt32) eGetDouble( p );
      xbDate dt( lDate );
      sKey.Sprintf( "%ld - %s", lDate, dt.Str());
    } else {
      d = eGetDouble( p );
      sKey.Sprintf( "%f", d );
    }
    p+= (npTag->iKeyItemLen-8);
    s.Sprintf( "%3d  %9d  %9d  %s", l+1, lLeftBranch, lRecNo, sKey.Str() );
    xbase->WriteLogMessage( s, iOpt );
  }
  if( !bIsLeaf ){
    lLeftBranch = eGetUInt32( p );
    s.Sprintf( "%3d  %9d", l+1,  lLeftBranch );
    xbase->WriteLogMessage( s.Str(), iOpt );
  }
  return XB_NO_ERROR;
}
#endif
/***********************************************************************/
//! @brief Find key
/*!
  \param vpTag  Pointer to tag to search.
  \param vpKey Void pointer to key data to search on.
  \param lSearchKeyLen Length of key to search for.
  \param iRetrieveSw xbTrue - Retrieve the record if key found.<br>
                     xbFalse - Don't retrieve record, check for key existence only.
  \returns XB_NO_ERROR - Key found.<br>
             XB_NOT_FOUND - Key not found.<br>
             <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::FindKey( void *vpTag, const void *vpKey, xbInt32 lSearchKeyLen,
                          xbInt16 iRetrieveSw ){


  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;
  xbString sMsg;
  // xbInt16 iFindSts;
  try{
    // clean  up any previous table updates before moving on
    if( iRetrieveSw ){
      if( dbf->GetDbfStatus() == XB_UPDATED ){
        if(  dbf->GetAutoCommit() == 1 ){
          if(( iRc = dbf->Commit()) != XB_NO_ERROR ){
            iErrorStop = 10;
            throw iRc;
          }
        } else {
          if(( iRc = dbf->Abort()) != XB_NO_ERROR ){
            iErrorStop = 20;
            throw iRc;
          }
        }
      }
    }

    xbUInt32 ulNoOfKeys;
    xbNdxTag * npTag;
    vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
    char cKeyType = npTag->cKeyType;

    if( npTag->npNodeChain ){

      // determine if the index has been updated since the last time it was used
      time_t tFileTs;
      if(( iRc = GetFileMtime( tFileTs )) != XB_NO_ERROR ){
        iErrorStop = 30;
        throw iRc;
      }
      if( npTag->tNodeChainTs < tFileTs ){
        npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
        npTag->npCurNode = NULL;
        if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR ){
          iErrorStop = 40;
          throw iRc;
        }
        if(( iRc = GetBlock( npTag, (npTag->ulRootBlock ), 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
          iErrorStop = 50;
          throw iRc;
        }
      } else {
        //  pop up the chain looking for appropriate starting point
        xbBool  bDone = false;
        xbIxNode * TempIxNode;
        while( npTag->npCurNode && !bDone && npTag->npCurNode->ulBlockNo != npTag->ulRootBlock ){ // not root node
            iRc = CompareKey( cKeyType, vpKey, GetKeyData( npTag->npCurNode, 0, npTag->iKeyItemLen ), (size_t) lSearchKeyLen );
            if( iRc <= 0 ){
              TempIxNode = npTag->npCurNode;
              npTag->npCurNode = npTag->npCurNode->npPrev;
              TempIxNode = FreeNodeChain( TempIxNode );
            } else {
              // get the number of keys on the block and compare the key to the rightmost key
              xbUInt32 ulKeyCtr = eGetUInt32( npTag->npCurNode->cpBlockData ) - 1;
              iRc = CompareKey( cKeyType, vpKey, GetKeyData( npTag->npCurNode, ulKeyCtr, npTag->iKeyItemLen), (size_t) lSearchKeyLen );

              if( iRc > 0 ){
                TempIxNode = npTag->npCurNode;
                npTag->npCurNode = npTag->npCurNode->npPrev;
                TempIxNode = FreeNodeChain( TempIxNode );
              } else {
                bDone = true;
              }
            }
          }
       }
    } else {
      if(( iRc = GetBlock( npTag, (npTag->ulRootBlock ), 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
    }


    // if cur node is the base node and no keys on this node, then the index is empty
    if( npTag->ulRootBlock == npTag->npCurNode->ulBlockNo ){
      ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
      if( ulNoOfKeys == 0 && IsLeaf( npTag, npTag->npCurNode )){
        // iRc = XB_EMPTY;

        iRc = XB_NOT_FOUND;
        return iRc;
      }
    }

    // should be in the appropriate position in the node chain to continue the search from here
    // run down through the interior nodes
    xbInt16 iSearchRc = 0;
    xbUInt32 ulKeyPtr = 0;

    while( !IsLeaf( npTag, npTag->npCurNode ) ){

      // get the number of keys on the block and compare the key to the rightmost key
      ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
      if( ulNoOfKeys == 0 )   // interior nodes can have zero keys, just a link to the next lower node
        npTag->npCurNode->iCurKeyNo = 0;
      else
      {
        iRc = CompareKey( cKeyType, vpKey, GetKeyData( npTag->npCurNode, ulNoOfKeys - 1, npTag->iKeyItemLen), (size_t) lSearchKeyLen );
        if( iRc > 0 ){
          npTag->npCurNode->iCurKeyNo = ulNoOfKeys;
        } else {
          npTag->npCurNode->iCurKeyNo = (xbUInt32) BSearchBlock( cKeyType, npTag->npCurNode, 
             (xbInt32) npTag->iKeyItemLen, vpKey, (xbInt32) lSearchKeyLen, iSearchRc );
        }
      }

      if(( iRc = GetKeyPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 80;
        throw iRc;
      }

      if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 90;
        throw iRc;
      }
    }

    // should be on a the correct leaf node, it may or may not contain the actual key
    ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
    xbInt16 iCompRc = 0;

    if( ulNoOfKeys == 0 ){
      iRc = XB_NOT_FOUND;
      return iRc;
    } else {

      iRc = BSearchBlock( cKeyType, npTag->npCurNode, npTag->iKeyItemLen, vpKey, lSearchKeyLen, iCompRc );

      // iCompRc 
      //    0 found
      //  < 0 eof encountered, search key > last key in file
      //  > 0 not found, positioned to next key


      // std::cout << "xbIxNdx::FindKey -Rc = " << iRc << " CompRc = " << iCompRc << " NoOfKeys = " << ulNoOfKeys << " blk no = " << npTag->npCurNode->ulBlockNo << "\n";

      if( iCompRc >= 0 ){
        npTag->npCurNode->iCurKeyNo = (xbUInt32) iRc;
        if( iRetrieveSw ){
          xbUInt32 ulKey = npTag->npCurNode->iCurKeyNo;
          if( ulKey >= ulNoOfKeys )   // if position past end of keys, need to go back one and position to last key
            ulKey--;

          if(( iRc = GetDbfPtr( vpTag, ulKey, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
            iErrorStop = 100;
            throw iRc;
          }
          if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
            iErrorStop = 110;
            throw iRc;
          }
        }
      }
    }

    if( iCompRc == 0 )
      return XB_NO_ERROR;
    else if( iCompRc > 0 )
      return XB_NOT_FOUND;
    else
      return XB_EOF;
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::FindKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Find key for current record
/*!
  This routine is called when updating a key.

  \param vpTag  Pointer to tag to search.
             XB_NOT_FOUND Key not found.<br>
             <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::FindKeyForCurRec( void * vpTag )
{

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    if(( iRc = CreateKey( vpTag, 0 )) < XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }

    // find key
    iRc = FindKey( vpTag, npTag->cpKeyBuf, npTag->iKeyLen, 0 );
    if( iRc == XB_NOT_FOUND || iRc == XB_EMPTY || iRc == XB_EOF )
       return iRc;

    if( iRc != XB_NO_ERROR ){
      iErrorStop = 20;
      throw iRc;
    }

    // if keys are unique, and the recrd number matches, then we are good
    if( GetUnique() )
      return XB_NO_ERROR;

    // get here if key found and not unique, need to move forward looking for correct rec no
    xbUInt32 ulDbfRecNo = dbf->GetCurRecNo();
    xbBool bKeysMatch  = true;     // keys match?
    xbBool bCurRecsMatch = false;  // cur recod number matches?
    xbUInt32 ulIxRecNo = 0;
    char cKeyType = GetKeyType( vpTag );

    if(( iRc = GetDbfPtr( vpTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulIxRecNo )) != XB_NO_ERROR ){
      iErrorStop = 30;
      throw iRc;
    }
    if( ulIxRecNo == ulDbfRecNo )
      bCurRecsMatch = true;

    xbInt16 iCompRc;
    while( !bCurRecsMatch && bKeysMatch ){

      if(( iRc = GetNextKey( vpTag, 0 )) != XB_NO_ERROR ){
        iErrorStop = 40;
        throw iRc;
      }

      // do compare key here
      iCompRc = CompareKey( cKeyType, npTag->cpKeyBuf, GetKeyData( npTag->npCurNode, 0, npTag->iKeyItemLen ), (size_t) npTag->iKeyLen );
      if( iCompRc != 0 )
        bKeysMatch = false;
      else{
        if(( iRc = GetDbfPtr( vpTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulIxRecNo )) != XB_NO_ERROR ){
          iErrorStop = 50;
          throw iRc;
        }
        if( ulIxRecNo == ulDbfRecNo )
          bCurRecsMatch = true;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::FindKeyForCurRec() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return XB_NO_ERROR;
}

/***********************************************************************/
//! @brief Get dbf record number for given key number.
/*!
  \param vpTag Tag to retrieve dbf rec number on.
  \param iKeyNo Key number for retrieval
  \param np Pointer to node
  \param ulDbfPtr- Output dbf record number
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::GetDbfPtr( void *vpTag, xbInt16 iKeyNo, xbIxNode *np, xbUInt32 &ulDbfPtr ) const {

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;

  try{
    #ifdef XB_DEBUG_SUPPORT
    // turn this off in production mode for better performance
    xbUInt32 ulNoOfKeys = eGetUInt32 ( np->cpBlockData );
    if( iKeyNo < 0 || iKeyNo > (xbInt16) --ulNoOfKeys ){
      iErrorStop = 10;
      throw XB_INVALID_KEYNO;
    }
    #endif

    xbNdxTag * npTag;
    vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
    char *p = ( np->cpBlockData);
    p += (8 + (iKeyNo * npTag->iKeyItemLen));
    ulDbfPtr = eGetUInt32 ( p );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetDbfPtr() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Get the first key for the given tag.
/*!
  \param vpTag Tag to retrieve first key on.
  \param iRetrieveSw xbTrue - Retrieve the record on success.<br>
                     xbFalse - Don't retrieve record.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::GetFirstKey( void *vpTag, xbInt16 iRetrieveSw ){
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    // clear out any history
    if( npTag->npNodeChain ){
      npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
      npTag->npCurNode = NULL;
    }
    if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }
    // lRootBlock is now available
    if(( iRc = GetBlock( npTag, npTag->ulRootBlock, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
      iErrorStop = 20;
      throw iRc;
    }
    // if no keys on this node, and it's a leaf node then the index is empty
    xbUInt32 ulKeyPtr = eGetUInt32( npTag->npCurNode->cpBlockData );
    if( ulKeyPtr == 0 && IsLeaf( npTag, npTag->npCurNode )){
      iRc = XB_EMPTY;
      return iRc;
    }
    while( !IsLeaf( npTag, npTag->npCurNode ))   // go down the chain looking for a leaf node
    {
      if(( iRc = GetKeyPtr( npTag, 0, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 30;
        throw iRc;
      }
      if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 40;
        throw iRc;
      }
    }
    if( iRetrieveSw ){
      if(( iRc = GetDbfPtr( npTag, 0, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 50;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
    }
  }
  catch( xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetFirstKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Get the key expression for the given tag.
/*!
  \param vpTag Tag to retrieve expression from.
  \returns Key expression.
*/

xbString &xbIxNdx::GetKeyExpression( const void * vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->sKeyExpression;
}


/***********************************************************************/
//! @brief Get the key filter for the given tag.
/*!
  NDX index files do not support filters. This returns NULL.
  \returns NULL.
*/

xbString &xbIxNdx::GetKeyFilter( const void * ) const{
  return sNullString;
}
/***********************************************************************/
//! @brief Get the key length for the given tag.
/*!
  \param vpTag Tag to retrieve key length for.
  \returns Length of key.
*/
xbInt32 xbIxNdx::GetKeyLen( const void * vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->iKeyLen;
}
/***********************************************************************/
//! @brief Get child node number for given key number.
/*!
  \param vpTag Tag to retrieve dbf rec number on.
  \param iKeyNo Key number for retrieval
  \param np Pointer to node
  \param ulKeyPtr Output node number
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::GetKeyPtr( void *vpTag, xbInt16 iKeyNo, xbIxNode *np, xbUInt32 &ulKeyPtr ) const {

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;
  try{
    #ifdef XB_DEBUG_SUPPORT
    // turn this off in production mode for better performance
    xbUInt32 ulNoOfKeys = eGetUInt32 ( np->cpBlockData );
    if( iKeyNo < 0 || iKeyNo > (xbInt16) ulNoOfKeys ){
      iErrorStop = 10;
      throw XB_INVALID_KEYNO;
    }
    #endif
    xbNdxTag * npTag;
    vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
    char *p = ( np->cpBlockData);
    p += (4 + (iKeyNo * npTag->iKeyItemLen));
    ulKeyPtr = eGetUInt32 ( p );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetKeyPtr() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Returns key update status.
/*!
  \param vpTag Tag to check status on.
  \returns XB_UPD_KEY  Key updated.<br>
           XB_DEL_KEY  Key deleted.<br>
           XB_ADD_KEY  Key added.<br>
           0           No key updates

*/
xbInt16 xbIxNdx::GetKeySts( void *vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->iKeySts;
}
/***********************************************************************/
//! @brief Get character key type for given tag.
/*!
  \param vpTag Tag to retrieve key type for.
  \returns Char key type.
*/

char xbIxNdx::GetKeyType( const void * vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->cKeyType;
}

/***********************************************************************/
//! @brief Get numeric key type for given tag.
/*!
  \param vpTag Tag to retrieve first key for.
  \returns Numeric key type.
*/
xbInt16 xbIxNdx::GetKeyTypeN( const void * vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->iKeyType;
}
/***********************************************************************/
//! @brief Get the last key for the given tag.
/*!
  \param vpTag Tag to retrieve last key on.
  \param iRetrieveSw xbTrue - Retrieve the record on success.<br>
                     xbFalse - Don't retrieve record.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::GetLastKey( void *vpTag, xbInt16 iRetrieveSw ){
  return GetLastKey( 0, vpTag, iRetrieveSw );
//  return GetLastKey( 0, vpTag, 1 );
  
}
/***********************************************************************/
//! @brief Get the last key for the given tag and starting node.
/*!
  \param ulNodeNo Starting node
  \param vpTag Tag to retrieve last key on.
  \param iRetrieveSw xbTrue - Retrieve the record if key found.<br>
                     xbFalse - Don't retrieve record.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::GetLastKey( xbUInt32 ulNodeNo, void *vpTag, xbInt16 iRetrieveSw ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbUInt32 ulKeyPtr = 0;
  xbUInt32 ulNoOfKeys = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    // clear out any history
    if( npTag->npNodeChain ){
      npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
      npTag->npCurNode = NULL;
    }
    if( ulNodeNo == 0 ){
      if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR ){
        iErrorStop = 10;
        throw iRc;
      }
       // lRootBlock is now available
      if(( iRc = GetBlock( npTag, npTag->ulRootBlock, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
    } else {
      if(( iRc = GetBlock( npTag, ulNodeNo, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
    }
    // if no keys on this node, then the index is empty
    ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
    if( ulNoOfKeys == 0 && IsLeaf( npTag, npTag->npCurNode )){
      iRc = XB_EMPTY;
      return iRc;
    }
    npTag->npCurNode->iCurKeyNo = ulNoOfKeys;
    while( !IsLeaf( npTag, npTag->npCurNode ) ){   // go down the chain looking for a leaf node
      npTag->npCurNode->iCurKeyNo = eGetUInt32( npTag->npCurNode->cpBlockData );
      if(( iRc = GetKeyPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 40;
        throw iRc;
      }
      if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 50;
        throw iRc;
      }
      ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
      npTag->npCurNode->iCurKeyNo = ulNoOfKeys;
    }
    // get here on a leaf node, it has one fewer iCurKeyNo
    npTag->npCurNode->iCurKeyNo--;
    if( iRetrieveSw ){
      ulNoOfKeys = eGetUInt32( npTag->npCurNode->cpBlockData );
      if(( iRc = GetDbfPtr( npTag, ulNoOfKeys - 1, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 70;
        throw iRc;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetLastKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Get the last key for a block number.
/*!
  \param vpTag Tag to retrieve first key on.
  \param ulBlockNo Block number for key retrieval.
  \param cpBuf output buffer for key placement
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::GetLastKeyForBlockNo( void *vpTag, xbUInt32 ulBlockNo, char *cpBuf ){

  // returns the last key for a given block number
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    xbIxNode * npSaveNodeChain = npTag->npNodeChain;
    xbIxNode * npSaveCurNode = npTag->npCurNode;
    npTag->npNodeChain = NULL;

    if(( iRc = GetLastKey( ulBlockNo, npTag, 0 )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
    // set the key
    memcpy( cpBuf, GetKeyData( npTag->npCurNode, GetKeyCount( npTag->npCurNode ) - 1, npTag->iKeyItemLen ), (size_t) npTag->iKeyLen );

     // free memory
    npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
    npTag->npNodeChain = npSaveNodeChain;
    npTag->npCurNode   = npSaveCurNode;
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetLastKeyForBlockNo() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ) );
  }
  return iRc;
}
/***********************************************************************/
//! @brief Get the next key for the given tag.
/*!
  \param vpTag Tag to retrieve next key on.
  \param iRetrieveSw xbTrue - Retrieve the record on success.<br>
                     xbFalse - Don't retrieve record.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::GetNextKey( void * vpTag, xbInt16 iRetrieveSw ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    if( !npTag->npNodeChain )
      return GetFirstKey( vpTag, iRetrieveSw );

    // more keys on this node?  if yes, get the next one to the right
    xbUInt32 ulKeyPtr;
    if((eGetUInt32( npTag->npCurNode->cpBlockData ) -1) > npTag->npCurNode->iCurKeyNo ){
      npTag->npCurNode->iCurKeyNo++;
      if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 20;
        throw iRc;
      }
      if( iRetrieveSw ){
        if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
          iErrorStop = 30;
          throw iRc;
        } else {
          return iRc;
        }
      } else {
        return iRc;
      }
    }
    // if at end of head node, then eof
    if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock )
      return XB_EOF;

    // This logic assumes that interior nodes have n+1 left node no's where n is he the number of keys in the node
    xbIxNode * TempIxNode = npTag->npCurNode;
    npTag->npCurNode = npTag->npCurNode->npPrev;
    TempIxNode = FreeNodeChain( TempIxNode );

    while( npTag->npCurNode->iCurKeyNo >= eGetUInt32( npTag->npCurNode->cpBlockData ) &&
           (npTag->npCurNode->ulBlockNo != npTag->ulRootBlock )){
      TempIxNode = npTag->npCurNode;
      npTag->npCurNode = npTag->npCurNode->npPrev;
      TempIxNode = FreeNodeChain( TempIxNode );
    }

    // head node and at end of head node, then eof
    if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock && 
        npTag->npCurNode->iCurKeyNo == eGetUInt32( npTag->npCurNode->cpBlockData ))
      return XB_EOF;

    // move one to the right
    npTag->npCurNode->iCurKeyNo++;

    if(( iRc = GetKeyPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
      iErrorStop = 40;
      throw iRc;
    }

    if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
      iErrorStop = 50;
      throw iRc;
    }
    while( !IsLeaf( npTag, npTag->npCurNode ))   // go down the chain looking for a leaf node
    {
      if(( iRc = GetKeyPtr( npTag, 0, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
      if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 70;
        throw iRc;
      }
    }
    if( iRetrieveSw ){
      if(( iRc = GetDbfPtr( npTag, 0, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 80;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 90;
        throw iRc;
      }
    }
  }
  catch( xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetNextKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Get the previous key for the given tag.
/*!
  \param vpTag Tag to retrieve previous key on.
  \param iRetrieveSw xbTrue - Retrieve the record on success.<br>
                     xbFalse - Don't retrieve record.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::GetPrevKey( void * vpTag, xbInt16 iRetrieveSw ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  // This method assumes last index call landed on a valid key.
  // If last call resulted in an error, this method will returns XB_BOF

  try{
    if( !npTag->npNodeChain )
      return GetLastKey( 0, vpTag, iRetrieveSw );

    xbUInt32 ulKeyPtr;
    if( npTag->npCurNode->iCurKeyNo > 0 ){
      npTag->npCurNode->iCurKeyNo--;

      if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 10;
        throw iRc;
      }
      if( iRetrieveSw ){
        if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
          iErrorStop = 20;
          throw iRc;
        } else {
          return iRc;
        }
      }
    }

    // next two lines might have been an issue
    if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock && GetKeyCount( npTag->npCurNode ) == 0  && IsLeaf( npTag, npTag->npCurNode ))
      return XB_EMPTY;

    if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock )
      return XB_BOF;

    // This logic assumes that interior nodes have n+1 left node no's where n is he the number of keys in the node
    xbIxNode * TempIxNode = npTag->npCurNode;
    npTag->npCurNode = npTag->npCurNode->npPrev;
    TempIxNode = FreeNodeChain( TempIxNode );

    while( npTag->npCurNode->iCurKeyNo == 0 &&
           (npTag->npCurNode->ulBlockNo != npTag->ulRootBlock )){
      TempIxNode = npTag->npCurNode;
      npTag->npCurNode = npTag->npCurNode->npPrev;
      TempIxNode = FreeNodeChain( TempIxNode );
    }

    // head node and at end of head node, then bof
    if( npTag->npCurNode->ulBlockNo == npTag->ulRootBlock && 
        npTag->npCurNode->iCurKeyNo == 0 )
      return XB_BOF;

    // move one to the left
    npTag->npCurNode->iCurKeyNo--;

    if(( iRc = GetKeyPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
      iErrorStop = 30;
      throw iRc;
    }

    if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
      iErrorStop = 40;
      throw iRc;
    }

    while( !IsLeaf( npTag, npTag->npCurNode )){   // go down the chain looking for a leaf node
      npTag->npCurNode->iCurKeyNo = eGetUInt32( npTag->npCurNode->cpBlockData );
      if(( iRc = GetKeyPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
      if(( iRc = GetBlock( npTag, ulKeyPtr, 1, (xbUInt32) npTag->iKeyItemLen )) != XB_NO_ERROR ){
        iErrorStop = 70;
        throw iRc;
      }
    }

    npTag->npCurNode->iCurKeyNo = eGetUInt32( npTag->npCurNode->cpBlockData ) - 1;
    if( iRetrieveSw ){
      if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 80;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 90;
        throw iRc;
      }
    }
  }

  catch( xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::GetPrevKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Get the sort order for given tag.
/*!
  Ndx indices only support ascending keys.
  \returns 0
*/
xbBool xbIxNdx::GetSortOrder( void * ) const{
  return 0;
}
/***********************************************************************/
//! @brief Get tag for tag number.
/*!
  \returns Pointer to ndx tag.
*/
void * xbIxNdx::GetTag( xbInt16 ) const{
  return ndxTag;
}
/***********************************************************************/
//! @brief Get tag for tag name.
/*!
  \returns Pointer to ndx tag.
*/
void * xbIxNdx::GetTag( xbString & ) const{
  return ndxTag;
}

/***********************************************************************/
//! @brief Get tag count.
/*!
  NDX index files contain one tag.
  \returns 1
*/

xbInt16 xbIxNdx::GetTagCount() const{
  return 1;
}
/***********************************************************************/
//! @brief Get tag name.
/*!
  \returns Tag name.
*/
xbString &xbIxNdx::GetTagName( void * ) const {
// char * xbIxNdx::GetTagName( void * ) const {

  return ndxTag->sTagName;

}
/***********************************************************************/
//! @brief Get tag name.
/*!
  \returns Tag name.
*/
const char * xbIxNdx::GetTagName( void *, xbInt16 ) const {
  return ndxTag->sTagName;
}

/***********************************************************************/
//! @brief Get the unique setting for given tag.
/*!
  \param vpTag Tag to unique setting on.
  \returns xbTrue - Unique index.<br> xbFalse - Not unique index.
*/
xbBool xbIxNdx::GetUnique( void * vpTag ) const{
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  return npTag->iUnique;
}

/***********************************************************************/
//! @brief Insert key into interior node.
/*!
  Insert key into non-full interior node.<br>
  Assumes valid inputs

  \param vpTag Tag in play.
  \param npNode Node for insertion.
  \param iSlotNo Slot number to insert key.
  \param ulPtr Pointer number to insert.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::InsertNodeI( void *vpTag, xbIxNode *npNode, xbInt16 iSlotNo, xbUInt32 ulPtr ){
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char *pTrg;
  xbInt16 iSrcPos;
  char *pLastKey = NULL;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    // update number of keys on the node
    xbInt32 lKeyCnt = GetKeyCount( npNode ); 
    iSrcPos = 12 + (iSlotNo * npTag->iKeyItemLen);

    char *pSrc = npNode->cpBlockData;
    pSrc += iSrcPos;

    // if not appending to the end of the node, make some room, move things to the right
    if( iSlotNo < lKeyCnt ) {
      xbInt16 iCopyLen = ((lKeyCnt - iSlotNo) * npTag->iKeyItemLen) - 4;
      pTrg = pSrc;
      pTrg += npTag->iKeyItemLen;
      memmove( pTrg, pSrc, (size_t) iCopyLen );
    }

    // get the right most key for the left part of the split node
    xbUInt32 ulKeyPtr2;
    if(( iRc = GetKeyPtr( vpTag, npNode->iCurKeyNo, npNode, ulKeyPtr2 )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
    // get the new right key value for the freshly split node
    pLastKey = (char *) malloc((size_t) ndxTag->iKeyLen);
    if(( iRc = GetLastKeyForBlockNo( vpTag, ulKeyPtr2, pLastKey )) != XB_NO_ERROR ){
      iRc = 110;
      throw iRc;
    }
    // write the key value
    pTrg = pSrc;
    char *pTrg2 = pSrc;
    pSrc = pLastKey;
    for( xbInt16 i = 0; i < npTag->iKeyLen; i++ )
      *pTrg++ = *pSrc++;

    pTrg2 += (npTag->iKeyItemLen - 8);
    ePutUInt32( pTrg2, ulPtr );
    ePutInt32( npNode->cpBlockData, ++lKeyCnt );

    // write out the updated block to disk
    if(( iRc = WriteBlock( npNode->ulBlockNo, GetBlockSize(), npNode->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }
    if( pLastKey )
      free( pLastKey );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::InsertNodeI() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( pLastKey )
      free( pLastKey );
  }
  return iRc;
}
/***********************************************************************/
//! @brief Insert key into leaf node.
/*!
  Insert key into non-full leaf node.<br>
  Assumes valid inputs

  \param vpTag Tag in play.
  \param npNode Node for insertion.
  \param iSlotNo Slot number to insert key.
  \param ulPtr Pointer number to insert.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::InsertNodeL( void *vpTag, xbIxNode *npNode, xbInt16 iSlotNo, 
                                char * cpKeyBuf, xbUInt32 ulPtr ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char *pSrc;
  char *pTrg;
  char *pKeyPos;
  xbString sMsg;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    xbInt32 lKeyCnt = GetKeyCount( npNode ); 
    xbInt16 iKeyPos = 4 + iSlotNo * npTag->iKeyItemLen;
    pKeyPos = npNode->cpBlockData;
    pKeyPos += iKeyPos;

    // if not appending to end, make space, move things right
    if( iSlotNo < lKeyCnt ) {
      xbInt16 iCopyLen = (lKeyCnt - iSlotNo) * npTag->iKeyItemLen;
      pTrg = pKeyPos;
      pTrg += npTag->iKeyItemLen;
      memmove( pTrg, pKeyPos, (size_t) iCopyLen );
    }
    // if leaf, write rec number
    pTrg = pKeyPos;
    memset( pTrg, 0x00, 4 );
    pTrg += 4;
    ePutUInt32( pTrg, ulPtr );
    pTrg += 4;

    // write the key value
    pSrc = cpKeyBuf;
    for( xbInt16 i = 0; i < npTag->iKeyLen; i++ )
      *pTrg++ = *pSrc++;

    // update number of keys on the node
    ePutInt32( npNode->cpBlockData, ++lKeyCnt );

    // write out the updated block to disk
    if(( iRc = WriteBlock( npNode->ulBlockNo, GetBlockSize(), npNode->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::InsertNodeL() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Determine node leaf status
/*!
  \param npNode Node to examine.
  \returns xbTrue - Leaf node.<br> xbFalse - Interior node.
*/
xbBool xbIxNdx::IsLeaf( void *, xbIxNode *npNode ) const {
  xbUInt32 ulBlock = eGetUInt32 ( npNode->cpBlockData+4 );
  if( ulBlock > 0 )    // if the second four bytes are a number, it's an interior node
    return false;
  else
    return true;
}
/***********************************************************************/
//! @brief Determine if key exists.
/*!
  This method assumes the key has already been built and is in either 
  cpKeyBuf or dKey.

  \param vpTag - Pointer to tag.
  \returns xbTrue - Key exists.<br> xbFalse - Key does not exist.
*/
xbInt16 xbIxNdx::KeyExists( void * vpTag ){

  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  xbInt16 iRc = FindKey( vpTag, npTag->cpKeyBuf, npTag->iKeyLen, 0 );
  if( iRc == 0 )
    return 1;
  else
    return 0;
}

/***********************************************************************/
//! @brief Set position for key add.
/*!
  This routine is called by the AddKey() method and is used to position 
  the node chain to the position the new key should be added to the index.

  \param npTag Pointer to npTag.
  \param ulAddRecNo Record number to add.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::KeySetPosAdd( xbNdxTag *npTag, xbUInt32 ulAddRecNo ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  try{

     iRc = FindKey( npTag, npTag->cpKeyBuf, npTag->iKeyLen, 0 );
     if( iRc == XB_NOT_FOUND || iRc == XB_EMPTY )
       return XB_NO_ERROR;  // good position

     else if( iRc != XB_NO_ERROR ){
       iErrorStop = 10;
       throw iRc;
     }
     // get here if key was found, get the right most instance of any non unique key for append, find correct spot for update 
     if( GetUnique() == 0 ){
       xbUInt32 ulCurRecNo;
       if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulCurRecNo )) != XB_NO_ERROR ){
         iErrorStop = 20;
         throw iRc;
       }
       xbBool bKeysMatch = xbTrue;
       while( bKeysMatch && ulAddRecNo > ulCurRecNo && iRc == XB_NO_ERROR ){
         if(( iRc = GetNextKey( npTag, 0 )) == XB_NO_ERROR ){
           if( memcmp( GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ), npTag->cpKeyBuf, (size_t) npTag->iKeyLen ))
             bKeysMatch = xbFalse;
           else{
             if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulCurRecNo )) != XB_NO_ERROR ){
               iErrorStop = 30;
               throw iRc;
             }
           }
         }
       }
     }
     if( iRc == XB_EOF ){   // eof condition
       if(( iRc = GetLastKey( 0, npTag, 0 )) != XB_NO_ERROR ){
         iErrorStop = 130;
         throw iRc;
       }
       npTag->npCurNode->iCurKeyNo++;
       return XB_NO_ERROR;
     }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::KeySetPos() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Set position for key add.
/*!
  This routine is called by the DeleteKey() method and is used to position 
  the node chain to the position the old key should be deleted from the index.

  \param npTag Pointer to npTag.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::KeySetPosDel( xbNdxTag *npTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbString sMsg;

  try{
     iRc = FindKey( NULL, npTag->cpKeyBuf2, npTag->iKeyLen, 0 );
     if( iRc == XB_NOT_FOUND || iRc == XB_EMPTY )
       return XB_NO_ERROR;  // good position
     else if( iRc != XB_NO_ERROR ){
       iErrorStop = 20;
       throw iRc;
     }
     xbUInt32 ulIxRecNo;
     if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulIxRecNo )) != XB_NO_ERROR ){
       iErrorStop = 30;
       throw iRc;
     }
     if( ulIxRecNo == dbf->GetCurRecNo()) 
       return XB_NO_ERROR;
     if( GetUnique() == 1 ){
       iErrorStop = 40;
       iRc = XB_NOT_FOUND;
       throw iRc;
     }
     xbBool bFound = xbFalse;
     xbBool bKeysMatch = xbTrue;
     while( bKeysMatch && !bFound && iRc == XB_NO_ERROR ){
       if(( iRc =  GetNextKey( npTag, 0 )) != XB_NO_ERROR ){
         iErrorStop = 50;
         throw iRc;
       }
       if( memcmp( GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ), npTag->cpKeyBuf2, (size_t) npTag->iKeyLen )){
         bKeysMatch = xbFalse;
       } else {
         if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulIxRecNo )) != XB_NO_ERROR ){
           iErrorStop = 60;
           throw iRc;
         }
         if( ulIxRecNo == dbf->GetCurRecNo())
           bFound = xbTrue;
       }
     }
     if( bFound )
       return XB_NO_ERROR;
     else
       return XB_NOT_FOUND;
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::KeySetPosDel() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Returns key filter status.
/*!
  \param vpTag Tag to check status on.
  \returns xbtrue - Key was updated.<br>xbFalse - Key not updated.

  Always true for NDX style indices.
*/
//inline xbBool xbIxNdx::KeyFiltered( void *vpTag ) const{
//  return xbTrue;
//}

/***********************************************************************/
//! @brief Read head block of index file.
/*!
  \param iOpt 0 - Read in entire block
              1 - Read in only dynamic section of block
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxNdx::ReadHeadBlock( xbInt16 iOpt = 0 ) {

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;
  try{
    if( !FileIsOpen()){
      iRc = XB_NOT_OPEN;
      iErrorStop = 10;
      throw iRc;
    }
    xbInt16 iLen;
    iOpt == 0 ? iLen = 512 : iLen = 21;

    if(( iRc = ReadBlock( (xbUInt32) 0, (size_t) iLen, cNodeBuf )) != XB_NO_ERROR ){
      iErrorStop = 20;
      throw iRc;
    }
    char *p        = cNodeBuf;
    ndxTag->ulRootBlock      = eGetUInt32( p ); p+=4;
    ndxTag->ulTotalBlocks    = eGetUInt32( p ); p+=5;
    if( iOpt == 0 ){
      ndxTag->cKeyType       = *p;              p+=3;
      ndxTag->iKeyLen        = eGetInt16( p );  p+=2;
      ndxTag->iKeysPerBlock   = eGetInt16( p ); p+=2;
      ndxTag->iKeyType       = eGetInt16( p );  p+=2;
      ndxTag->iKeyItemLen    = eGetInt16( p );  p+=2;
      ndxTag->cSerNo         = *p;              p+=3;
      ndxTag->iUnique        = *p;              p++;
      ndxTag->sKeyExpression.Set( p );

      if( ndxTag->exp )
        delete ndxTag->exp;

      ndxTag->exp = new xbExp( xbase, dbf );
      if(( iRc = ndxTag->exp->ParseExpression( ndxTag->sKeyExpression.Str() )) != XB_NO_ERROR ){
        iErrorStop = 30;
        throw iRc;
      }

      if( ndxTag->cpKeyBuf )
        free( ndxTag->cpKeyBuf );
      if( ndxTag->cpKeyBuf2 )
        free( ndxTag->cpKeyBuf2 );

      ndxTag->cpKeyBuf  = (char *) malloc( (size_t) ndxTag->iKeyLen );
      ndxTag->cpKeyBuf2 = (char *) malloc( (size_t) ndxTag->iKeyLen );

      if( ndxTag->sTagName == "" )
        GetFileNamePart( ndxTag->sTagName );

    } else {
      p+= 11;
      ndxTag->cSerNo  = *p;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::ReadHeadBlock() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Reindex a tag.
/*!
  \param vpTag Pointer to tag pointer.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxNdx::Reindex( void **vpTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  //xbNdxTag * npTag;
  //vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  try{
    xbString sFileName = GetFqFileName();
    xbString sKey;    //       = GetKeyExpression( vpTag );
    sKey.Set( GetKeyExpression( *vpTag ));
    xbInt16  iUnique   = GetUnique( *vpTag );
    xbString sFilter   = "";

    void *vpTag2;
    if(( iRc = CreateTag( sFileName, sKey, sFilter, 0, iUnique, xbTrue, &vpTag2 )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }

    xbUInt32 ulRecCnt = 0;
    if(( iRc = dbf->GetRecordCnt( ulRecCnt )) != XB_NO_ERROR ){
      iErrorStop = 20;
      throw iRc;
    }

    for( xbUInt32 l = 1; l <= ulRecCnt; l++ ){
      if(( iRc = dbf->GetRecord( l )) != XB_NO_ERROR ){
        iErrorStop = 30;
        throw iRc;
      }

      if(( iRc = CreateKey( vpTag2, 1 )) != XB_NO_ERROR ){
        iErrorStop = 40;
        throw iRc;
      }

      if( iUnique ){
        iRc = CheckForDupKey( vpTag2 );
        if( iRc != 0 ){
          if( iRc < 0 ){
            iErrorStop = 50;
            throw iRc;
          }
          return XB_KEY_NOT_UNIQUE;
        }
      }

      if(( iRc = AddKey( vpTag2, l )) != XB_NO_ERROR ){
        iErrorStop = 60;
        throw iRc;
      }
    }
    *vpTag = vpTag2;
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::Reindex() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }

  return iRc;
}


/***********************************************************************/
//! @brief Set current tag.
/*!
  For ndx indices, there is only one tag.
  \returns XB_NO_ERROR.
*/
xbInt16 xbIxNdx::SetCurTag( xbInt16 ) {
  xbIx::SetCurTag( ndxTag );
  return XB_NO_ERROR;
}
/***********************************************************************/
//! @brief Set current tag.
/*!
  For ndx indices, there is only one tag.
  \returns XB_NO_ERROR.
*/
xbInt16 xbIxNdx::SetCurTag( xbString & ) {
  xbIx::SetCurTag( ndxTag );
  dbf->SetCurTag( "NDX", this, GetTag(0) );
  return XB_NO_ERROR;
}

/***********************************************************************/
//! @brief Split an interior node
/*!

  This routine splits an interior node into two nodes, divided by dSplitFactor.<br>
  This behaves differently than V7 Dbase. V7 does not balance the nodes.<br>
  For V7, if adding a key to the end of a node, it will create a right node 
  with only one key, and the left node is still full.<br><br>

  Possible performance improvement options.<br>
  Two modes when splitting:<br>
  a)  Split nodes in the middle - good for random access applications<br>
  b)  Split off right node with only one key - good for applications with
      expectation of ascending keys added moving forward.<br>

  This routine first inserts the key into the left node in the appropriate location
  then splits the node based on the split factor setting.

  \param vpTag Tag in play.
  \param npLeft Left node to split.
  \param npRight Right node to split.
  \param iSlotNo Slot number for split.
  \param ulPtr Pointer number to insert.
  \returns <a href="xbretcod_8h.html">Return Codes</a>  
*/

xbInt16 xbIxNdx::SplitNodeI( void *vpTag, xbIxNode * npLeft, xbIxNode *npRight, xbInt16 iSlotNo, xbUInt32 ulPtr ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbNdxTag * npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;
  xbDouble dSplitFactor = .5;                           // split the nodes 50/50
  xbString sMsg;

  try{
    xbInt32 lKeyCnt = GetKeyCount( npLeft );
    xbInt32 lNewLeftKeyCnt = (xbInt32) ((lKeyCnt + 1) * dSplitFactor) + 1;
    xbInt32 lNewRightKeyCnt = lKeyCnt - lNewLeftKeyCnt;
    xbInt16 iSrcPos;
    xbInt16 iCopyLen;
    char    *pSrc;
    char    *pTrg;

    // insert the key into the left node
    if(( iRc = InsertNodeI( vpTag, npLeft, iSlotNo, ulPtr )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }

    // move the right half of the left node to the right node
    iSrcPos  = ((lNewLeftKeyCnt + 1) * npTag->iKeyItemLen) + 4;
    iCopyLen = (lNewRightKeyCnt * npTag->iKeyItemLen) + 4;
    pSrc = npLeft->cpBlockData;
    pSrc += iSrcPos;
    pTrg = npRight->cpBlockData;
    pTrg += 4;
    memmove( pTrg, pSrc, (size_t) iCopyLen );

    // write the new key counts into the nodes
    pTrg = npLeft->cpBlockData;
    ePutInt32( pTrg, lNewLeftKeyCnt );
    pTrg = npRight->cpBlockData;
    ePutInt32( pTrg, lNewRightKeyCnt );

    // write the new key counts into the nodes
    pTrg = npLeft->cpBlockData;
    ePutInt32( pTrg, lNewLeftKeyCnt );
    pTrg = npRight->cpBlockData;
    ePutInt32( pTrg, lNewRightKeyCnt );

    // write out the block 
    if(( iRc = WriteBlock( npLeft->ulBlockNo, GetBlockSize(), npLeft->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
    // write out the block 
    if(( iRc = WriteBlock( npRight->ulBlockNo, GetBlockSize(), npRight->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 200;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::SplitNodeI() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Split a leaf node.
/*!
  This routine splits an index leaf into two nodes, divided by dSplitFactor.<br>
  This behaves differently than V7 Dbase. V7 does not balance the nodes.<br>
  For V7, if adding a key to the end of a node, it will create a right node 
  with only one key, and the left node is still full.<br><br>

  Possible performance improvement options.<br>
  Two modes when splitting:<br>
  a)  Split nodes in the middle - good for random access applications<br>
  b)  Split off right node with only one key - good for applications with 
      expectation of ascending keys added moving forward.<br>

  This routine first inserts the key into the left node in the appropriate location
  then splits the node based on the split factor setting.

  \param vpTag Tag in play.
  \param npLeft Left node to split.
  \param npRight Right node to split.
  \param iSlotNo Slot number for split.
  \param ulPtr Pointer number to insert.
  \returns <a href="xbretcod_8h.html">Return Codes</a>  
*/

xbInt16 xbIxNdx::SplitNodeL( void *vpTag, xbIxNode * npLeft, xbIxNode *npRight, 
    xbInt16 iSlotNo, char * cpKeyBuf, xbUInt32 ulPtr ){

  xbInt16  iRc = XB_NO_ERROR;
  xbInt16  iErrorStop = 0;
  xbDouble dSplitFactor = .5;
  xbNdxTag *npTag;
  vpTag ? npTag = (xbNdxTag *) vpTag : npTag = ndxTag;

  xbString sMsg;
  try{
    xbInt32 lKeyCnt = GetKeyCount( npLeft );
    xbInt32 lNewLeftKeyCnt = (xbInt32) ((lKeyCnt + 1) * dSplitFactor) + 1;
    xbInt32 lNewRightKeyCnt = lKeyCnt + 1 - lNewLeftKeyCnt;

    // xbInt16 iSrcPos;
    xbInt16 iLen;
    char *pSrc = npLeft->cpBlockData;
    char *pTrg;

    if(( iRc = InsertNodeL( vpTag, npLeft, iSlotNo, cpKeyBuf, ulPtr )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }

    // move right half off of left node to the right node
    pSrc = npLeft->cpBlockData;
    pSrc += ((lNewLeftKeyCnt * npTag->iKeyItemLen)+4);
    pTrg = npRight->cpBlockData;
    pTrg += 4;
    iLen = lNewRightKeyCnt * npTag->iKeyItemLen;
    memmove( pTrg, pSrc, (size_t) iLen );

    // write the new key counts into the nodes
    pTrg = npLeft->cpBlockData;
    ePutInt32( pTrg, lNewLeftKeyCnt );
    pTrg = npRight->cpBlockData;
    ePutInt32( pTrg, lNewRightKeyCnt );

    // write out the block 
    if(( iRc = WriteBlock( npLeft->ulBlockNo, GetBlockSize(), npLeft->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }

    // write out the block 
    if(( iRc = WriteBlock( npRight->ulBlockNo, GetBlockSize(), npRight->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 120;
      throw iRc;
    }

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::SplitNodeL() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief UpdateTagKey
/*!
  This routine updates a key or a given tag.
  The file header is considered to be the first 2048 bytes in the file.

  \param cAction A - Add a key.<br>
                 D - Delete a key.<br>
                 R - Revise a key.<br>
  \param vpTg - Pointer to tag.<br>
  \param ulRecNo - Record number association with the action.<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16  xbIxNdx::UpdateTagKey( char cAction, void *vpTag, xbUInt32 ulRecNo ){


  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  // ..xbNdxTag *npTag = (xbMdxTag *) vpTag;

  try{
    // save off any needed fileds for updating
    // xbUInt32 ulTagSizeSave    = mpTag->ulTagSize;
    //xbUInt32 ulLeftChildSave  = mpTag->ulLeftChild;
    //xbUInt32 ulRightChildSave = mpTag->ulRightChild;


    if( cAction == 'D' || cAction == 'R' ){
//      std::cout << "UpdateTagKey delete\n";
      if(( iRc = DeleteKey( vpTag )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
    }

    if( cAction == 'A' || cAction == 'R' ){
//      std::cout << "UpdateTagKey add\n";
      if(( iRc = AddKey( vpTag, ulRecNo )) != XB_NO_ERROR ){
        iErrorStop = 200;
        throw iRc;
      }
    }

//    if( ulTagSizeSave != mpTag->ulTagSize ){
//       std::cout << "UpdateTagKey - tag size was updated need to do something here\n";
//    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::UpdateTagKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Write head block.
/*!
  Commit the index head node to disk.
  \param iOpt 0 - Entire header.<br>
              1 - Update root block, number of blocks and seq number.<br>
              2 - Update sequence number only<br>
  \returns <a href="xbretcod_8h.html">
*/

xbInt16 xbIxNdx::WriteHeadBlock( xbInt16 iOpt ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{
    if( iOpt == 2 ){

     // increment the serial number
      if( ndxTag->cSerNo >= 0 && ndxTag->cSerNo < 127 )
        ndxTag->cSerNo++;
      else
        ndxTag->cSerNo = 0;

      if(( iRc = xbFseek( 20, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
      if(( iRc = xbFputc( ndxTag->cSerNo )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
    } else if( iOpt == 1 ){
      xbRewind();
      char buf[8];
      ePutUInt32( &buf[0], ndxTag->ulRootBlock );
      ePutUInt32( &buf[4], ndxTag->ulTotalBlocks );
      if(( iRc = xbFwrite( buf, 8, 1 )) != XB_NO_ERROR ){
        iErrorStop = 200;
        throw iRc;
      }
      return WriteHeadBlock( 2 );

    } else if ( iOpt == 0 ){

      char buf[512];
      memset( buf, 0x00, 512 );
      ePutUInt32( &buf[0], ndxTag->ulRootBlock );
      ePutUInt32( &buf[4], ndxTag->ulTotalBlocks );
      buf[9]  = ndxTag->cKeyType;
      buf[11] = 0x1B;
      ePutInt16( &buf[12], ndxTag->iKeyLen );
      ePutInt16( &buf[14], ndxTag->iKeysPerBlock );
      ePutInt16( &buf[16], ndxTag->iKeyType );
      ePutInt16( &buf[18], ndxTag->iKeyItemLen );
      if( ndxTag-> iUnique ) buf[23] = 0x01;

      for( xbUInt32 i = 0; i < ndxTag->sKeyExpression.Len(); i++ )
        buf[i+24] = ndxTag->sKeyExpression.GetCharacter(i+1);

      xbRewind();
      if(( iRc = xbFwrite( buf, 512, 1 )) != XB_NO_ERROR ){
        iErrorStop = 300;
        throw iRc;
      }
    } else {
      iRc = XB_INVALID_OPTION;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxNdx::WriteHeadBlock() Exception Caught. Error Stop = [%d] iRc = [%d] option = [%d] ser=[%d]", iErrorStop, iRc, iOpt, ndxTag->cSerNo );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
}              /* namespace       */
#endif         /*  XB_NDX_SUPPORT */