summaryrefslogtreecommitdiff
path: root/1Tdata/xbase/xbase64-4.1.4/src/core/xbixmdx.cpp
blob: 0eef64bce21282bf22670e38622609e44f879694 (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
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
/* xbixmdx.cpp

XBase64 Software Library

Copyright (c) 1997,2003,2014,2022,2023 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


   MDX indices are comprised of blocks and pages.
   A page is 512 bytes.
   A Block is one or more pages.
   The default block size is two 512 byte pages per block.
   Nodes are used for storing block images in memory

*/

#include "xbase.h"

#ifdef XB_MDX_SUPPORT

namespace xb{

/***********************************************************************/
xbIxMdx::xbIxMdx( xbDbf *dbf ) : xbIx( dbf ){
   Init();
}
/***********************************************************************/
//void xbIxMdx::Init( xbInt16 iOpt ){
void xbIxMdx::Init( xbInt16 ){

   cVersion          = 0;
   cCreateYY         = 0;
   cCreateMM         = 0;
   cCreateDD         = 0;
   sFileName         = "";
   iBlockFactor      = 0;
   cProdIxFlag       = 0;
   cTagEntryCnt      = 0;
   iTagLen           = 0;
   iTagUseCnt        = 0;
   cNextTag          = 0;
   c1B               = 0x0b;
   ulPageCnt         = 0;
   ulFirstFreePage   = 0;
   ulNoOfBlockAvail  = 0;
   cUpdateYY         = 0;
   cUpdateMM         = 0;
   cUpdateDD         = 0;
   mdxTagTbl         = NULL;
   cNodeBuf          = NULL;
   bReuseEmptyNodes  = xbTrue;
}
/***********************************************************************/
xbIxMdx::~xbIxMdx(){
  if( cNodeBuf )
    free( cNodeBuf );

  if( FileIsOpen())
    Close();
}
/***********************************************************************/
//! @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 xbIxMdx::AddKey( void * vpTag, xbUInt32 ulRecNo ){

  xbMdxTag * npTag = (xbMdxTag *) vpTag;
  if( GetUniqueKeyOpt() == XB_EMULATE_DBASE && npTag->bFoundSts )
    return XB_NO_ERROR;

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbInt16 iHeadNodeUpdateOpt = 2;
  xbIxNode * npRightNode = NULL;
  xbUInt32 ulNewRightChild = 0;

  try{
     if(( iRc = xbIxMdx::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
        // std::cout << "AddKey Section A begin\n";
        if(( iRc = InsertNodeL( npTag, npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->cpKeyBuf, ulRecNo )) != XB_NO_ERROR ){
          iErrorStop = 110;
          throw iRc;
        }
     } else {
       // land here with a full leaf node
       iHeadNodeUpdateOpt = 1;
       npRightNode = AllocateIxNode( npTag, GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, npTag->npCurNode->ulBlockNo * (xbUInt32) iBlockFactor );
       if( !npRightNode ){
         iErrorStop = 120;
         iRc = XB_NO_MEMORY;
         throw iRc;
       }

       if(( npTag->npCurNode->ulBlockNo * (xbUInt32) iBlockFactor ) == npTag->ulRightChild ){
         ulNewRightChild = npRightNode->ulBlockNo * (xbUInt32) iBlockFactor;
       }

       if(( iRc = xbIxMdx::SplitNodeL( npTag, npTag->npCurNode, npRightNode, npTag->npCurNode->iCurKeyNo, npTag->cpKeyBuf, ulRecNo )) != XB_NO_ERROR ){
         iErrorStop = 130;
         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 ){
         //std::cout << "Section C begin  interior node is full\n";
         npRightNode = FreeNodeChain( npRightNode );
         npRightNode = AllocateIxNode( npTag, GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, npParent->ulBlockNo * (xbUInt32) iBlockFactor );
         //std::cout << "Section C - B new right node block number for interior node split= " << npRightNode->ulBlockNo << "\n";

         if( !npRightNode ){
           iErrorStop = 140;
           iRc = XB_NO_MEMORY;
           throw iRc;
         }
         //std::cout << "Section C - going to split interior node C\n";

         if(( iRc = SplitNodeI( npTag, npParent, npRightNode, npParent->iCurKeyNo, BlockToPage( ulTempBlockNo ))) != XB_NO_ERROR ){
           iErrorStop = 150;
           throw iRc;
         }
         // std::cout << "Section C - interior node split \n";
         ulTempBlockNo = npRightNode->ulBlockNo;
         npTag->npCurNode = npParent;
         npParent = npParent->npPrev;
       }

       // section D - if cur node is split root, create new root
       if(( npTag->npCurNode->ulBlockNo * (xbUInt32) iBlockFactor ) == npTag->ulRootPage ){
         if(( iRc = AddKeyNewRoot( npTag, npTag->npCurNode, npRightNode )) != XB_NO_ERROR ){
             iErrorStop = 160;
             throw iRc;
         }
         if( npRightNode )
           npRightNode = FreeNodeChain( npRightNode );

       } else {

         // std::cout << "Section E, put key in parent\n";
         if(( iRc = InsertNodeI( (void *) vpTag, (xbIxNode *) npParent, (xbInt16) npParent->iCurKeyNo, BlockToPage( npRightNode->ulBlockNo ))) != XB_NO_ERROR ){
           iErrorStop = 170;
           throw iRc;
         }
       }
     }

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

     // if adding the first key, set the cHasKeys field
     if( !npTag->cHasKeys ){
       npTag->cHasKeys = 0x01;
       if(( iRc = xbFseek( ((npTag->ulTagHdrPageNo * 512) + 246), SEEK_SET )) != XB_NO_ERROR ){
         iErrorStop = 190;
         throw iRc;
       }
       if(( iRc = xbFwrite( &npTag->cHasKeys, 1, 1 )) != XB_NO_ERROR ){
         iErrorStop = 200;
         throw iRc;
       }
     }

     if( ulNewRightChild > 0 ){

       char cBuf[4];
       ePutUInt32( cBuf, ulNewRightChild );
       if(( iRc = xbFseek( ((npTag->ulTagHdrPageNo * 512) + 252), SEEK_SET )) != XB_NO_ERROR ){
         iErrorStop = 210;
         throw iRc;
       }
       if(( iRc = xbFwrite( &cBuf, 4, 1 )) != XB_NO_ERROR ){
         iErrorStop = 220;
         throw iRc;
       }
       npTag->ulRightChild = ulNewRightChild;
     }

     if( npRightNode )
       npRightNode = FreeNodeChain( npRightNode );
     npTag->npNodeChain = FreeNodeChain( npTag->npNodeChain );
     npTag->npCurNode = NULL;

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::AddKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
void xbIxMdx::AppendNodeChain( void *vpTag, xbIxNode * npNode ){
    xbMdxTag * mdxTag = (xbMdxTag *) vpTag;
    if( mdxTag->npNodeChain == NULL ){
      mdxTag->npNodeChain = npNode;
      mdxTag->npCurNode = npNode;
    } else {
      npNode->npPrev = mdxTag->npCurNode;
      mdxTag->npCurNode->npNext = npNode;
      mdxTag->npCurNode = npNode;
    }
    // time stamp the node chain
    GetFileMtime( mdxTag->tNodeChainTs );
}

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

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

  try{
    xbIxNode *npRoot = AllocateIxNode( npTag, GetBlockSize() + (xbUInt32) npTag->iKeyItemLen, npRight->ulBlockNo * (xbUInt32) iBlockFactor );
    if( !npRoot ){
      iErrorStop = 100;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }
    npTag->ulRootPage = npRoot->ulBlockNo;

    pLastKey = (char *) malloc( (size_t) npTag->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 += 8;
    ePutUInt32( pTrg, npLeft->ulBlockNo * (xbUInt32) iBlockFactor );

    // set the key
    pTrg+= 4;
    memcpy( pTrg, pLastKey, (size_t) npTag->iKeyLen );
    pTrg+= npTag->iKeyItemLen - 4;
    ePutUInt32( pTrg, npRight->ulBlockNo * (xbUInt32) iBlockFactor );

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

    // write out the new root node number in the tag header
    // position the file
    xbUInt32 ulPagePos = npTag->ulTagHdrPageNo * 512;

    // save the number to a buffer
    char cBuf[4];
    ePutUInt32( cBuf, npRoot->ulBlockNo * ((xbUInt32) iBlockFactor ));

    if(( iRc = xbFseek( ulPagePos, SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }
    if(( iRc = xbFwrite( &cBuf, 4, 1 )) != XB_NO_ERROR ){
      iErrorStop = 140;
      throw iRc;
    }

    if( pLastKey ) 
      free( pLastKey );

    npRoot = FreeNodeChain( npRoot );

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



/***********************************************************************/
//! @brief Allocate a node.
/*!
  \param mpTag Pointer to mdx tag
  \param ulBufSize Buffer size.
  \param ulBlock2 Value to load in ulBlock2 field, bytes 4-7 in the first page of the block
  \returns Pointer to new node.
*/
xbIxNode * xbIxMdx::AllocateIxNode( xbMdxTag * mpTag, xbUInt32 ulBufSize, xbUInt32 ulBlock2 ){

  xbInt16  iRc = XB_NO_ERROR;
  xbInt16  iErrorStop = 0;
  xbIxNode *n = NULL;

  try{
    if(( n = xbIx::AllocateIxNode( ulBufSize )) == NULL ){
      iRc = XB_NO_MEMORY;
      iErrorStop = 100;
      throw iRc;
    }
    char *p = n->cpBlockData;
    p += 4;

    if( ulFirstFreePage > 0 && bReuseEmptyNodes ){
      // have an empty node we can reuse
      n->ulBlockNo = PageToBlock( ulFirstFreePage );
      if(( iRc = ReadBlock( n->ulBlockNo, GetBlockSize(), n->cpBlockData )) != XB_NO_ERROR ){
        iRc = 110;
        throw iRc;
      }
      // update ulFirstFreePage
      ulFirstFreePage = eGetUInt32( p );
      if(( iRc = xbFseek( 36, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
      if(( iRc = xbFwrite( p, 4, 1 )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
      // memset cpBlockData to zeroes
      memset( n->cpBlockData, 0x00, GetBlockSize());

    } else {
      n->ulBlockNo     =  ulPageCnt / (xbUInt32) iBlockFactor;
      ulPageCnt        += (xbUInt32) iBlockFactor;
    }

    mpTag->ulTagSize += (xbUInt32) iBlockFactor;
    if( ulBlock2 > 0 ){
      ePutUInt32( p, ulBlock2 );
    }
  }
  catch( xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::AllocateIxNode() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( n ) 
      n = FreeNodeChain( n );
  }
  return n;
}
/***********************************************************************/
//! @brief Calculate B-tree pointers.
/*!
  Set binary tree pointer value.  The MDX tags are stored with binary 
  tree positions.  This routine calculates the value in memory.
  \returns void
*/

void xbIxMdx::CalcBtreePointers(){

  xbInt16 iaLeftChild[48];
  xbInt16 iaRightChild[48];
  xbInt16 iaParent[48];

  for( xbInt16 i = 0; i < 48; i++ ){
    iaLeftChild[i] = 0;
    iaRightChild[i] = 0;
    iaParent[i] = 0;
  }

  // anything to do?
  if( iTagUseCnt > 1 ){
    xbString sBaseTag;
    xbString sThisTag;
    xbString sWorkTag;
    xbInt16  iWorkTagNo;
    xbBool   bDone;
    sBaseTag = GetTagName( GetTag( 0 ));

    for( xbInt16 iThisTagNo = 1; iThisTagNo < iTagUseCnt; iThisTagNo++ ){
      iWorkTagNo = 0;
      sWorkTag.Set( sBaseTag );
      sThisTag = GetTagName( GetTag( iThisTagNo ));
      bDone = xbFalse;
      while( !bDone ){
        if( sThisTag < sWorkTag ){
          if( iaLeftChild[iWorkTagNo] == 0 ) {
            iaLeftChild[iWorkTagNo] = iThisTagNo + 1;
            iaParent[iThisTagNo] = iWorkTagNo + 1;
            bDone = xbTrue;
          } else {
             iWorkTagNo = iaLeftChild[iWorkTagNo]-1;
             sWorkTag = GetTagName( GetTag( iWorkTagNo));
          }
        } else {
          if( iaRightChild[iWorkTagNo] == 0 ) {
            iaRightChild[iWorkTagNo] = iThisTagNo + 1;
            iaParent[iThisTagNo] = iWorkTagNo + 1;
            bDone = xbTrue;
          } else {
             iWorkTagNo = iaRightChild[iWorkTagNo]-1;
             sWorkTag = GetTagName( GetTag( iWorkTagNo ));
          }
        }
      }
    }
  }

  xbString s;
  xbMdxTag *mpTag = mdxTagTbl;
  for( xbInt16 i = 0;  i < iTagUseCnt; i++ ){
    mpTag->cLeftChild  = (char ) iaLeftChild[i];
    mpTag->cRightChild = (char ) iaRightChild[i];
    mpTag->cParent     = (char ) iaParent[i];
    mpTag = mpTag->next;
  }
}

/**************************************************************************************************************/
//! @brief Calculate the page number for a given block
/*!
  This routine is called by any function needing to calculate the page number for a given block.
  Page numbers are stored internally in the physical file, and the library reads and writes in
  blocks of one or more pages.

  Assumes valid data input

  \param ulBlockNo  Block Number
  \returns Calculated page number.
*/

inline xbUInt32 xbIxMdx::BlockToPage( xbUInt32 ulBlockNo ){
  return ulBlockNo * (xbUInt32) iBlockFactor;
}
/***********************************************************************/
char xbIxMdx::CalcTagKeyFmt( xbExp &exp ){

  xbExpNode *n = exp.GetTreeHandle();
  if( n->GetChildCnt() == 0 && n->GetNodeType() == XB_EXP_FIELD )
    return 0x01;
  else
    return 0;
}
/***********************************************************************/
//! @brief Check for duplicate key.
/*!
  \param vpTag Tag to check.
  \returns XB_KEY_NOT_UNIQUE<br>XB_NO_ERROR
*/

xbInt16 xbIxMdx::CheckForDupKey( void *vpTag )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  mpTag->bFoundSts = xbFalse;
  try{
    if( GetUnique( mpTag )){
      if( mpTag->iKeySts == XB_ADD_KEY || mpTag->iKeySts == XB_UPD_KEY )
        if( KeyExists( mpTag )){
          if( GetUniqueKeyOpt() == XB_EMULATE_DBASE ){
            mpTag->bFoundSts = xbTrue;
            return 0;
          } else {
            return XB_KEY_NOT_UNIQUE;
          }
        }
     }
     return 0;
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::CheckForDupKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    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 xbIxMdx::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;
  xbMdxTag *npTag = (xbMdxTag *) vpTag;
  xbBool bDescending = npTag->cKeyFmt2 & 0x08;

  #ifdef XB_LOCKING_SUPPORT
  xbBool bLocked = xbFalse;
  #endif

  try{

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

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

    pPrevKeyBuf = (char *) calloc( 1, (size_t) npTag->iKeyLen );
    iRc = GetFirstKey( vpTag, 0 );

    memcpy( pPrevKeyBuf, GetKeyData( npTag->npCurNode, npTag->npCurNode->iCurKeyNo, npTag->iKeyItemLen ), (size_t) npTag->iKeyLen );

    // for each key in the index, make sure it is trending in the right direction
    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 && !bDescending ) || ( iRc2 > 0 && bDescending )){
          sMsg.Sprintf( "Key sequence error at key number [%ld].", ulIxCnt );
          xbase->WriteLogMessage( sMsg, iOpt );
          iErrorStop = 110;
          iRc = XB_INVALID_INDEX;
          throw iRc;
        }

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

        if( iRc2 == 0 && (ulThisRecNo <= ulPrevRecNo )){
          sMsg.Sprintf( "Dbf record number sequence error at key number [%ld].", iOpt );
          xbase->WriteLogMessage( sMsg, iOpt );
          iErrorStop = 130;
          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;
      }
    }

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

    xbUInt32 ulFiltCnt = 0;
    xbBool bFiltered = xbTrue;
    // 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( npTag->cHasFilter ){
        if(( iRc = npTag->filter->ProcessExpression( 0 )) != XB_NO_ERROR ){
          iErrorStop = 160;
          throw iRc;
        }
        if(( iRc = npTag->filter->GetBoolResult( bFiltered )) != XB_NO_ERROR ){
          iErrorStop = 170;
          throw iRc;
        }
      }

      if( bFiltered ){
        if(( iRc = FindKeyForCurRec( vpTag )) != XB_NO_ERROR ){
          ulThisRecNo = j;
          iErrorStop = 180;
          throw iRc;
        }
        ulFiltCnt++;
      }
    }

    if((GetUniqueKeyOpt() == XB_EMULATE_DBASE) && (GetUnique( vpTag ))){
      // can't compare counts if using XB_EMULATE_DBASE and it's a unique index
    } else {
      if( ulIxCnt != ulFiltCnt && GetUniqueKeyOpt() == XB_HALT_ON_DUPKEY ){
        if( npTag->cHasFilter )
          sMsg.Sprintf( "xbIxMdx::CheckTagIntegrity()  Filtered index entry count [%ld] does not match dbf record count [%ld] for tag [%s]", ulIxCnt, ulFiltCnt, npTag->cTagName );
        else
          sMsg.Sprintf( "xbIxMdx::CheckTagIntegrity()  Index entry count [%ld] does not match dbf record count [%ld] for tag [%s]", ulIxCnt, ulFiltCnt, npTag->cTagName );

        xbase->WriteLogMessage( sMsg, iOpt );
        iErrorStop = 190;
        iRc = XB_INVALID_INDEX;
        throw iRc;
      }
      if( npTag->cHasFilter )
        sMsg.Sprintf( "xbIxMdx::CheckTagIntegrity()  Filtered index entry count [%ld]  matches dbf record count [%ld] for tag [%s]", ulIxCnt, ulFiltCnt, npTag->cTagName );
      else
        sMsg.Sprintf( "xbIxMdx::CheckTagIntegrity()  Index entry count [%ld]  matches dbf record count [%ld] for tag [%s]", ulIxCnt, ulFiltCnt, npTag->cTagName );
      xbase->WriteLogMessage( sMsg, iOpt );
    }

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

    if( iErrorStop == 160 ){
      sMsg.Sprintf( "xbIxMdx::CheckTagIntegrity() Missing index entry for record [%d]", ulThisRecNo );
      xbase->WriteLogMessage( sMsg, iOpt );
    }
  }
  #ifdef XB_LOCKING_SUPPORT
  if( bLocked ){
    dbf->LockTable( XB_UNLOCK );
  }
  #endif

  return iRc;
}

/***********************************************************************/
xbMdxTag *xbIxMdx::ClearTagTable(){

  // clear the list of tags
  xbMdxTag *tt  = mdxTagTbl;
  xbMdxTag *tt2;
  while( tt ){
    tt2 = tt;
    tt = tt->next;
    tt2->npNodeChain = FreeNodeChain( tt2->npNodeChain );
    tt2->npCurNode = NULL;
    if( tt2->cpKeyBuf )
      free( tt2->cpKeyBuf );
    if( tt2->cpKeyBuf2 )
      free( tt2->cpKeyBuf2 );
    if( tt2->exp )
      delete tt2->exp;
    if( tt2->filter )
      delete tt2->filter;
    if( tt2->sKeyExp )
      delete tt2->sKeyExp;
    if( tt2->sTagName )
      delete tt2->sTagName;
    if( tt2->sFiltExp )
      delete tt2->sFiltExp;
    free( tt2 );
  }
  return NULL;
}
/***********************************************************************/
xbInt16 xbIxMdx::Close(){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{
    mdxTagTbl = ClearTagTable();
    if(( iRc = xbIx::Close()) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::Close() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Create key.
/*!

  \param vpTag Tag
  \param iOpt 1 = Append, 2 = Update
  \returns XB_KEY_NOT_UNIQUE<br>XB_NO_ERROR

  iKeySts     0 - No Updates
              1 - Add Key        XB_ADD_KEY
              2 - Update Key     XB_UPD_KEY
              3 - Delete Key     XB_DEL_KEY

  bKeyFiltered xbFalse - Key filtered out
               xbTrue  - Key filtered in

  cpKeyBuf  - Key buffer for add
  cpKeyBuf2 - Key buffer for delete

*/

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

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  xbBool  bFilter0 = xbFalse;   // filter against RecBuf,  updated record buffer
  xbBool  bFilter1 = xbFalse;   // filter against recBuf2, original record buffer

  try{

    xbMdxTag *npTag = (xbMdxTag *) vpTag;
    npTag->iKeySts = 0;

    // do tag filter logic
    if( npTag->cHasFilter ){
      if(( iRc = npTag->filter->ProcessExpression( 0 )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
      if(( iRc = npTag->filter->GetBoolResult( bFilter0 )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
    } else {
      bFilter0 = xbTrue;
    }

    // if add request and filtered out, we're done
    if( iOpt == 1 && !bFilter0 )
      return XB_NO_ERROR;

    if(( iRc = npTag->exp->ProcessExpression( 0 )) != XB_NO_ERROR ){
      iErrorStop = 120;
      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 );
       xbBcd bcd( d );
       bcd.ToChar( npTag->cpKeyBuf );
    }
    else if( npTag->exp->GetReturnType() == XB_EXP_DATE ){
       xbDouble d;
       npTag->exp->GetNumericResult( d );
       memcpy( npTag->cpKeyBuf, &d, 8 );
    }

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

    else if( iOpt == 2 ){           // Update
      if( npTag->cHasFilter ){
        if(( iRc = npTag->filter->ProcessExpression( 1 )) != XB_NO_ERROR ){
          iErrorStop = 130;
          throw iRc;
        }
        if(( iRc = npTag->filter->GetBoolResult( bFilter1 )) != XB_NO_ERROR ){
          iErrorStop = 140;
          throw iRc;
        }
      } else {
        bFilter1 = xbTrue;
      }

      if(( iRc = npTag->exp->ProcessExpression( 1 )) != XB_NO_ERROR ){
        iErrorStop = 150;
        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 ){
        xbDouble d;
        npTag->exp->GetNumericResult( d );
        xbBcd bcd( d );
        bcd.ToChar( npTag->cpKeyBuf2 );

      } else if( npTag->exp->GetReturnType() == XB_EXP_DATE  ){
        xbDouble d;
        npTag->exp->GetNumericResult( d );
        memcpy( npTag->cpKeyBuf2, &d, 8 );

      }

      if( bFilter1 ){     // original key was indexed
        if( bFilter0 ){   // new key s/b indexed, update it if changed
          if( memcmp( npTag->cpKeyBuf, npTag->cpKeyBuf2, (size_t) npTag->iKeyLen )){
            npTag->iKeySts = XB_UPD_KEY;
          }
        } else {          // original key indexed, new key not indexed, delete it
          npTag->iKeySts = XB_DEL_KEY;
        }
      } else {            // original key not indexed
        if( bFilter0 )
          npTag->iKeySts = XB_ADD_KEY;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::CreateKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
//! @brief Create new tag.
/*!
  This routine creates a new tag.   When complete, sets the cur tag pointer to 
  the newly created tag.


  \param sName Tag Name, including .MDX suffix
  \param sKey Key Expression
  \param sFilter Filter expression.
  \param iDescending 
  \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  xbIxMdx::CreateTag( const xbString &sName, const xbString &sKey, const xbString &sFilter, xbInt16 iDescending, xbInt16 iUnique, xbInt16 iOverlay, void **vpTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbMdxTag *tte = NULL;

  try{
    // verify room for new tag
    if( !( iTagUseCnt < 47 )){
      iErrorStop = 100;
      iRc = XB_LIMIT_REACHED;
      throw iRc;
    }

    // verify valid tag name
    xbString sWorker = sName;
    sWorker.Trim();
    if( sWorker.Len() > 10 ){
      iErrorStop = 110;
      iRc = XB_INVALID_TAG;
      throw iRc;
    }

    // verify tag not already defined
    if( iTagUseCnt > 0 ){
      if( GetTag( sWorker )){
        iErrorStop = 120;
        iRc = XB_INVALID_TAG;
        throw iRc;
      }
    }

    // allocate a tag structure here
    if(( tte = (xbMdxTag *) calloc( 1, (size_t) sizeof( xbMdxTag ))) == NULL ){
      iErrorStop = 130;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }
    *vpTag = tte;
    tte->sTagName = new xbString( sWorker );

    //set up the key expression
    sWorker = sFilter;
    sWorker.Trim();
    if( sWorker.Len() > 0 ){
      if( sWorker.Len() == 0 || sWorker.Len() > 220 ){
        iRc = XB_INVALID_TAG;
        iErrorStop = 140;
        throw iRc;
      }
      tte->sFiltExp = new xbString( sWorker );
      tte->filter = new xbExp( dbf->GetXbasePtr());
      if(( iRc = tte->filter->ParseExpression( dbf, sWorker )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }

      if((tte->filter->GetReturnType()) != 'L' ){
        iRc = XB_INVALID_TAG;
        iErrorStop = 160;
        throw iRc;
      }
      tte->cHasFilter = 0x01;
    }

    //set up the key expression
    sWorker = sKey;
    sWorker.Trim();
    if( sWorker.Len() == 0 || sWorker.Len() > 100 ){
      iRc = XB_INVALID_TAG;
      iErrorStop = 170;
      throw iRc;
    }
    tte->sKeyExp = new xbString( sWorker );
    tte->exp = new xbExp( dbf->GetXbasePtr());
    if(( iRc = tte->exp->ParseExpression( dbf, sWorker )) != XB_NO_ERROR ){
      iErrorStop = 180;
      throw iRc;
    }

    xbDate d;
    d.Sysdate();
    if( iTagUseCnt == 0 ){
      // first tag, new mdx file
      // create the file name
      xbString sIxFileName = dbf->GetFqFileName();
      sIxFileName.Trim();
      xbUInt32 lLen = sIxFileName.Len();
      sIxFileName.PutAt( lLen-2, 'M' );
      sIxFileName.PutAt( lLen-1, 'D' );
      sIxFileName.PutAt( lLen,   'X' );

      // copy the file name to the class variable
      this->SetFileName( sIxFileName );
      if( FileExists() && !iOverlay ){
        iErrorStop = 190;
        iRc = XB_FILE_EXISTS;
        throw iRc;
      }

      // first tag, need to create the file
      if(( iRc = xbFopen( "w+b", dbf->GetShareMode())) != XB_NO_ERROR ){
        iErrorStop = 200;
        throw iRc;
      }
      cVersion         = 2;
      cCreateYY        = (char) d.YearOf() - 1900;
      cCreateMM        = (char) d.MonthOf();
      cCreateDD        = (char) d.DayOf( XB_FMT_MONTH );

      GetFileNamePart( sFileName );
      sFileName.ToUpperCase();

      SetBlockSize( (xbUInt32) dbf->GetCreateMdxBlockSize());
      iBlockFactor     = GetBlockSize() / 512;

      cProdIxFlag      = 1;
      cTagEntryCnt     = 48;
      iTagLen          = 32;
      ulPageCnt        = 4;
      ulFirstFreePage  = 0;
      ulNoOfBlockAvail = 0;
      cNextTag         = 1;
      c1B              = 0x1B;
      cUpdateYY        = cCreateYY;
      cUpdateMM        = cCreateMM;
      cUpdateDD        = cCreateDD;

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

    // populate the tag table entry structure
    tte->ulTagHdrPageNo = ulPageCnt;
    ulPageCnt += (xbUInt32) iBlockFactor;
    tte->sTagName->strncpy( tte->cTagName, 10 );

    // cKeyFmt is always 0x10;
    // tested 2+ZIPCD  CITY+STATE  or just standalone field - always 0x10
    tte->cKeyFmt = 0x10;        //  = CalcTagKeyFmt( *tte->exp );

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

      case XB_EXP_NUMERIC:
        tte->cKeyType    = 'N';
        tte->iKeyLen     = 12;
        tte->iSecKeyType = 0;
        break;

      case XB_EXP_DATE:
        tte->cKeyType    = 'D';
        tte->iKeyLen     = 8;
        tte->iSecKeyType = 1;
        break;

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

    tte->cpKeyBuf  = (char *) malloc( (size_t) tte->iKeyLen + 1 );
    tte->cpKeyBuf2 = (char *) malloc( (size_t) tte->iKeyLen + 1 );

    // write the new tte entry here
    char tteBuf[21];
    memset( tteBuf, 0x00, 21 );

    ePutUInt32( &tteBuf[0], tte->ulTagHdrPageNo );
    for( xbUInt32 l = 0; l < tte->sTagName->Len() && l < 10; l++ ){
      tteBuf[l+4] = tte->sTagName->GetCharacter(l+1);
    }
    tteBuf[15] = tte->cKeyFmt;
    tteBuf[19] = 0x02;                // appears to always be a 0x02
    tteBuf[20] = tte->cKeyType;

    if(( iRc = xbFseek( (iTagUseCnt * 32) + 544, SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 210;
      throw iRc;
    }
    if(( iRc = xbFwrite( tteBuf, 21, 1 )) != XB_NO_ERROR ){
      iErrorStop = 220;
      throw iRc;
    }

    // Begin Tag Header
    tte->ulRootPage   = ulPageCnt;
    tte->ulTagSize    = (xbUInt32) iBlockFactor;
    ulPageCnt        += 2;
    tte->cKeyFmt2     = 0x10;
    if( iDescending )
      tte->cKeyFmt2  += 0x08;
    if( iUnique ){
      tte->cKeyFmt2  += 0x40;
      tte->cUnique    = 0x01;
    }

    tte->cTag11       = 0x1B;    // always 0x1b ?
    tte->cSerialNo    = 0x01;    // version incremented with each tag update
    tte->ulLeftChild  = tte->ulRootPage;
    tte->ulRightChild = tte->ulRootPage;

    tte->cTagYY       = (char) d.YearOf() - 1900;
    tte->cTagMM       = (char) d.MonthOf();
    tte->cTagDD       = (char) d.DayOf( XB_FMT_MONTH );

    tte->cKeyType2    = tte->cKeyType;
    tte->iKeyItemLen  = tte->iKeyLen + 4;
    while(( tte->iKeyItemLen % 4 ) != 0 ) tte->iKeyItemLen++;

    tte->iKeysPerBlock = (xbInt16) (GetBlockSize() - 12) / tte->iKeyItemLen;
    tte->cKeyFmt3 = CalcTagKeyFmt( *tte->exp );

    char *pBuf;
    if(( pBuf = (char *) calloc( 1, (size_t) GetBlockSize())) == NULL ){
      iErrorStop = 230;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }
    char *wPtr;
    wPtr = pBuf;
    ePutUInt32( wPtr, tte->ulRootPage );

    wPtr  += 4;
    ePutUInt32( wPtr, tte->ulTagSize );

    wPtr  += 4;
    *wPtr  = tte->cKeyFmt2;

    wPtr++;
    *wPtr  = tte->cKeyType2;

    wPtr  += 2;
    *wPtr  = tte->cTag11;

    wPtr  += 1;
    ePutInt16( wPtr, tte->iKeyLen );

    wPtr += 2;
    ePutInt16( wPtr, tte->iKeysPerBlock );

    wPtr += 2;
    ePutInt16( wPtr, tte->iSecKeyType );

    wPtr += 2;
    ePutInt16( wPtr, tte->iKeyItemLen );

    wPtr += 2;
    *wPtr = tte->cSerialNo;

    wPtr += 3;
    *wPtr = tte->cUnique;

    wPtr++;
    for( xbUInt32 l = 0; l < tte->sKeyExp->Len(); l++ )
      *wPtr++ = tte->sKeyExp->GetCharacter(l+1);

    wPtr = pBuf;

    tte->cHasKeys = 0x00;
    pBuf[246] = tte->cHasKeys;

    wPtr += 248;
    ePutUInt32( wPtr, tte->ulLeftChild );
    wPtr += 4;
    ePutUInt32( wPtr, tte->ulRightChild );

    pBuf[257] = tte->cTagYY;
    pBuf[258] = tte->cTagMM;
    pBuf[259] = tte->cTagDD;
    pBuf[480] = tte->cKeyFmt3;

    if( sFilter.Len() > 0 ){
      pBuf[245] = tte->cHasFilter;
      wPtr = pBuf;
      wPtr += 762;
      for( xbUInt32 l = 0; l < sFilter.Len(); l++ )
        *wPtr++ = sFilter.GetCharacter(l+1);
    }

    if(( iRc = xbFseek( tte->ulTagHdrPageNo * 512, SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 240;
      throw iRc;
    }

    if(( iRc = xbFwrite( pBuf, GetBlockSize(), 1 )) != XB_NO_ERROR ){
      iErrorStop = 250;
      throw iRc;
    }

    memset( pBuf, 0x00, GetBlockSize() );
    if(( iRc = xbFwrite( pBuf, GetBlockSize(), 1 )) != XB_NO_ERROR ){
      iErrorStop = 260;
      throw iRc;
    }

    iTagUseCnt++;
    cNextTag++;

    if(( iRc = WriteHeadBlock( 1 )) != XB_NO_ERROR ){
      iErrorStop = 270;
      throw iRc;
    }

    // update the dbf file if needed - discreet field, has no filter
    // 10/15/22 - dbase 7 does not update this field on index creation
    if( tte->cKeyFmt3 == 0x01 && !tte->cHasFilter ){
      // printf( "cKeyFmt3 = [%x]\n", tte->cKeyFmt3 );
      xbInt16 iFldNo;
      if(( iRc = dbf->GetFieldNo( sKey, iFldNo )) != XB_NO_ERROR ){
        iErrorStop = 280;
        throw iRc;
      }
      xbInt64 lOffset =  31 + ((iFldNo + 1) * 32 );

      if(( iRc = dbf->xbFseek( lOffset, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 290;
        iRc = XB_SEEK_ERROR;
        throw iRc;
      }
      char cBuf[2];
      cBuf[0] = 0x01;
      cBuf[1] = 0x00;

      if(( iRc = dbf->xbFwrite( cBuf, 1, 1 )) != XB_NO_ERROR ){
        iErrorStop = 300;
        throw iRc;
      }
      dbf->UpdateSchemaIxFlag( iFldNo, 0x01 );
    }

    // add the new entry to the end of the list of tags
    if( mdxTagTbl == NULL ){
      mdxTagTbl = tte;
    } else {
      xbMdxTag *tteL = mdxTagTbl;
      while( tteL->next )
        tteL = tteL->next;
      tteL->next = tte;
    }

    /* update the btree pointers */
    CalcBtreePointers();
    char bBuf[3];
    xbMdxTag *tteWork = mdxTagTbl;

    if(( iRc = xbFseek( 560, SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 310;
      throw iRc;
    }
    while( tteWork ){
      bBuf[0] = tteWork->cLeftChild;
      bBuf[1] = tteWork->cRightChild;
      bBuf[2] = tteWork->cParent;

      if(( iRc = xbFwrite( bBuf, 3, 1 )) != XB_NO_ERROR ){
        iErrorStop = 320;
        throw iRc;
      }
      if( tteWork->next ){
        if(( iRc = xbFseek( 29, SEEK_CUR )) != XB_NO_ERROR ){
          iErrorStop = 330;
          throw iRc;
        }
      }
      tteWork = tteWork->next;
    }
    free( pBuf );
  }

  catch (xbInt16 iRc ){
    if( tte ){
      if( tte->cpKeyBuf )
        free( tte->cpKeyBuf );
      if( tte->cpKeyBuf2 )
        free( tte->cpKeyBuf2 );
      if( tte->exp )
        delete tte->exp;
      if( tte->filter )
        delete tte->filter;
      if( tte->sKeyExp )
        delete tte->sKeyExp;
      if( tte->sFiltExp )
        delete tte->sFiltExp;
      if( tte->sTagName )
        delete tte->sTagName;
      free( tte );
    }
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::CreateTag() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }

  return iRc;
};

/***********************************************************************/
//! @brief Delete a key from a node.
/*!
  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 xbIxMdx::DeleteFromNode( void *vpTag, xbIxNode * npNode, xbInt16 iSlotNo )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbMdxTag * npTag = (xbMdxTag *) vpTag;

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

    char *pTrg = npNode->cpBlockData;
    if( iLen > 0 ){
      pTrg += (8 + (npTag->iKeyItemLen * (iSlotNo)) );  //lTrgPos;
      // std::cout << "TrgSpot = " << (8 + (npTag->iKeyItemLen * (iSlotNo)) ) << "\n";
      char *pSrc = pTrg;
      pSrc += npTag->iKeyItemLen;
      memmove( pTrg, pSrc, (size_t) iLen );
    }

    // zap out the right most key
    pTrg = npNode->cpBlockData;
    if( bLeaf ){
      pTrg += (8 + (npTag->iKeyItemLen * ( lKeyCnt-1 )));

    } else {
      pTrg += (12 + (npTag->iKeyItemLen * ( lKeyCnt-1 )));

    }

    for( xbInt16 i = 0; i < npTag->iKeyItemLen; i++ )
      *pTrg++ = 0x00;

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

    // if node empty, add it to the free node chain
    if( lKeyCnt < 2 ){
      if( bReuseEmptyNodes ){
        if( bLeaf && lKeyCnt == 1 ){
          if(( iRc =  HarvestEmptyNode( npTag, npNode, 0 )) != XB_NO_ERROR ){
            iErrorStop = 100;
            throw iRc;
          }
        }
      }
    }

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

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::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 xbIxMdx::DeleteKey( void *vpTag ){

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

  // 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 = xbIxMdx::KeySetPosDel( npTag )) != XB_NO_ERROR ){
       iErrorStop = 100;
       throw iRc;
     }
     // Delete key needs to handle two scenarios
     // 1 - if delete is on the only key of leaf, 
     //     traverse up tree, trim as needed
     // 2 - if last key on node is deleted, and key value is not the same 
     //     as prev key, ascend 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;
            }
         } else if(( iRc =  HarvestEmptyNode( npTag, npTag->npCurNode, 1 )) != XB_NO_ERROR ){
            iErrorStop = 130;
            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->ulRootPage && 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 = 140;
              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;

    // update the serial number
    if(( iRc = TagSerialNo( 3, npTag )) != XB_NO_ERROR ){
      iErrorStop = 150;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::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 a given tag
/*!
  \param vpTag Input tag ptr for tag to be deleted<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a><br>
            1 = Deleted entire MDX file, only had one tag

*/

xbInt16 xbIxMdx::DeleteTag( void *vpTag ){

  xbInt16  iRc        = 0;
  xbInt16  iErrorStop = 0;
  xbMdxTag * mpTag    = (xbMdxTag *) vpTag;
  xbIxNode *n         = NULL;
  xbBool   bLoneTag   = xbFalse;

  try{

    if( !vpTag ){
      iErrorStop = 100;
      iRc = XB_INVALID_TAG;
      throw iRc;
    }

    char cSaveHasFilter = mpTag->cHasFilter;
    char cSaveKeyFmt3   = mpTag->cKeyFmt3;
    xbString sSaveKey   = mpTag->sKeyExp->Str();

    if( iTagUseCnt == 1 ){
      // std::cout << "xbIxMdx::DeleteTag - one tag found, delete the mdx file\n";

      // close the mdx file
      if(( iRc = xbIxMdx::Close()) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }

      // delete the file
      xbRemove();

      // init variables - needed?
      // Init();
      // iRc > 0 defines this as the only tag in an MDX file, MDX file deleted.
      //         signals to the calling process to drop the MDX file from the
      //         list of updateable indices.
      bLoneTag = xbTrue;

    } else {

      //    harvest tag nodes

      if(( iRc = HarvestTagNodes( mpTag, xbTrue )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }

      // remove an entry from tag table
      //   which tag is this?
      xbInt16  iTagNo  = 0;
      xbMdxTag *mp     = mdxTagTbl;
      xbMdxTag *mpPrev = NULL;
      while( mp && mp->ulTagHdrPageNo != mpTag->ulTagHdrPageNo ){
        iTagNo++;
        mpPrev = mp;
        mp = mp->next;
      }

      // remove it from the linked list of tags
      if( !mpPrev ){
        mdxTagTbl = mp->next;
      } else {
        mpPrev->next = mp->next;
      }
      if( mp ){
        if( mp->cpKeyBuf )  free(  mp->cpKeyBuf );
        if( mp->cpKeyBuf2 ) free(  mp->cpKeyBuf2 );
        if( mp->exp )       delete mp->exp;
        if( mp->filter )    delete mp->filter;
        if( mp->sKeyExp )   delete mp->sKeyExp;
        if( mp->sFiltExp )  delete mp->sFiltExp;
        if( mp->sTagName )  delete mp->sTagName;
        free( mp );
      }
      xbInt32 iTarg = iTagNo * 32;
      xbInt32 iSrc  = iTarg  + 32;
      xbInt32 iLen  = (iTagUseCnt - iTagNo) * 32;

      if(( iRc = xbFseek( 544, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }
      char Buf[1536];  // 47 tags + 1 in case tag #47 is deleted
      memset( Buf, 0x00, 1536 );
      if(( iRc = xbFread( Buf, 1504, 1 )) != XB_NO_ERROR ){
        iErrorStop = 170;
        throw iRc;
      }
      char *pTrg = Buf;
      pTrg += iTarg;
      char *pSrc = Buf;
      pSrc += iSrc;
      for( xbInt32 i = 0; i < iLen; i++ )
        *pTrg++ = *pSrc++;

      if(( iRc = xbFseek( 544, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 180;
        throw iRc;
      }
      if(( iRc = xbFwrite( Buf, 1504, 1 )) != XB_NO_ERROR ){
        iErrorStop = 190;
        throw iRc;
      }

      iTagUseCnt--;
      if(( iRc = WriteHeadBlock( 1 )) != XB_NO_ERROR ){
        iErrorStop = 200;
        throw iRc;
      }

      /* update the btree pointers */
      CalcBtreePointers();
      char bBuf[3];
      xbMdxTag *tteWork = mdxTagTbl;

      if(( iRc = xbFseek( 560, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 210;
        throw iRc;
      }
      while( tteWork ){
        bBuf[0] = tteWork->cLeftChild;
        bBuf[1] = tteWork->cRightChild;
        bBuf[2] = tteWork->cParent;

        if(( iRc = xbFwrite( bBuf, 3, 1 )) != XB_NO_ERROR ){
          iErrorStop = 320;
          throw iRc;
        }
        if( tteWork->next ){
          if(( iRc = xbFseek( 29, SEEK_CUR )) != XB_NO_ERROR ){
            iErrorStop = 330;
            throw iRc;
          }
        }
        tteWork = tteWork->next;
      }
    }

    // update the dbf file if needed, if discreet field with no filter
    // printf( "cSaveKeyFmt3 = [%x] cSaveHasFilter=[%x] SaveKey = [%s]\n", cSaveKeyFmt3, cSaveHasFilter, sSaveKey.Str());

    if( cSaveKeyFmt3 == 0x01 && !cSaveHasFilter ){
      xbInt16 iFldNo;
      if(( iRc = dbf->GetFieldNo( sSaveKey, iFldNo )) != XB_NO_ERROR ){
        iErrorStop = 340;
        throw iRc;
      }
      xbInt64 lOffset =  31 + ((iFldNo + 1) * 32 );

      if(( iRc = dbf->xbFseek( lOffset, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 350;
        iRc = XB_SEEK_ERROR;
        throw iRc;
      }
      char cBuf[2];
      cBuf[0] = 0x00;
      cBuf[1] = 0x00;
      if(( iRc = dbf->xbFwrite( cBuf, 1, 1 )) != XB_NO_ERROR ){
        iErrorStop = 360;
        throw iRc;
      }
      dbf->UpdateSchemaIxFlag( iFldNo, 0x00 );
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::DeleteTag() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( n )
      free( n );
  }
  if( bLoneTag && !iRc )
    return 1;
  else
    return iRc;
}

/***********************************************************************/
#ifdef XB_DEBUG_SUPPORT

//! @brief Dump a given block for a tag
/*!
  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \param ulBlockNo Block number to dump
  \param mpTag Index tag pointer
  \returns <a href="xbretcod_8h.html">Return Codes</a>

*/

xbInt16 xbIxMdx::DumpBlock( xbInt16 iOpt, xbUInt32 ulBlockNo, xbMdxTag *mpTag ){

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;
  xbString s, s2;
  xbBool bLeaf;
  char *p;

  try{
    if(( iRc = GetBlock( mpTag, ulBlockNo, 0 )) != XB_NO_ERROR ){
      iErrorStop = 10;
      throw iRc;
    }
    p = cNodeBuf;
    xbInt32 lNoOfKeys = eGetInt32( p );
    p+=4;
    xbUInt32 ulNode2 = eGetUInt32( p );

    if( !mpTag ){
      // if no tag info, print what is available without tag info and exit
      s.Sprintf( "--- BlkNo = %ld  Page = %ld NoOfKeys = %ld Node2 (opt NextFreePage) = %ld", ulBlockNo, BlockToPage( ulBlockNo ), lNoOfKeys, ulNode2 );
      xbase->WriteLogMessage( s, iOpt );
      return XB_NO_ERROR;
    }

    p+=4;
    p+= mpTag->iKeyItemLen * lNoOfKeys;
    if( eGetUInt32( p ) == 0 ){
      bLeaf = xbTrue;
      // std::cout << "No of keys = " << lNoOfKeys << "\n";
      s.Sprintf( "--- Leaf Node      KeyCnt %d\t  Page %d\t Block %d", lNoOfKeys, BlockToPage( ulBlockNo ), ulBlockNo ); 
    } else {
      bLeaf = xbFalse;
      s.Sprintf( "--- Interior Node  KeyCnt %d\t  Page %d\t Block %d", lNoOfKeys, BlockToPage( ulBlockNo ), ulBlockNo );
    }
    if( ulNode2 > 0 )
      s.Sprintf( "%s  Node2 (opt NextFreePage) = %d", s.Str(), ulNode2 );

    xbase->WriteLogMessage( s, iOpt );

    xbInt32 l;
    for( l = 0; l < lNoOfKeys; l++ ){
      p = cNodeBuf + (8 + (l * mpTag->iKeyItemLen ));
      s.Sprintf( "%08ld\t", eGetUInt32( p ));
      p+=4;
      if( mpTag->cKeyType2 == 'C' ){         //CHAR
        for( xbInt32 l = 0; l < (mpTag->iKeyItemLen-4); l++ )
        s += *p++;
        s.Trim();
      } else if( mpTag->cKeyType2 == 'N' ){  // NUMERIC
        xbBcd bcd( p );
        bcd.ToString( s2 );
        s += s2;
      } else if( mpTag->cKeyType2 == 'D' ){  // DATE
        xbInt32 lDate = (xbInt32) eGetDouble( p );
        xbDate d( lDate );
        s.Sprintf( "%s\t%ld\t(%s)", s.Str(), lDate, d.Str());
      } else {
        s.Sprintf( "Unknown key type [%c]", mpTag->cKeyType2 );
      }
      xbase->WriteLogMessage( s, iOpt );
    }
    if( !bLeaf ){
      // interior node has one extra key at the right most position
      p = cNodeBuf + (8 + (l * mpTag->iKeyItemLen ));
      s.Sprintf( "\t%08ld", eGetUInt32( p ));
      xbase->WriteLogMessage( s, iOpt );
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::DumpBlock() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/**************************************************************************************************************/
//! @brief Dump free blocks.
/*!
  Dump free blocks for index 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 xbIxMdx::DumpFreeBlocks( xbInt16 iOpt ){

  xbInt16  iRc = XB_NO_ERROR;
  xbInt16  iErrorStop = 0;
  xbString s;
  char     *pBuf = NULL;
  char     *pNextPage;
  xbUInt32 ulNextPage;

  try{

    if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }

    xbUInt32 ulLastBlock  = PageToBlock( ulPageCnt );

    pBuf = (char *) malloc( (size_t) GetBlockSize());
    if( !pBuf ){
      iErrorStop = 110;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    if( ulFirstFreePage > 0 ){
      xbUInt32 ulThisFreePage = ulFirstFreePage;
      xbUInt32 ulNextFreePage = 0;
      xbUInt32 ulCnt = 0;
      xbase->WriteLogMessage( "*** Free Blocks ***", iOpt );
      s.Sprintf( "File Header - FirstFreePage = %ld  Block = %ld", ulFirstFreePage, PageToBlock( ulFirstFreePage ));
      xbase->WriteLogMessage( s, iOpt );
      while( ulThisFreePage > 0 ){
        if(( iRc = ReadBlock( PageToBlock( ulThisFreePage ), GetBlockSize(), pBuf )) != XB_NO_ERROR ){
          iErrorStop = 120;
          throw iRc;
        }
        pNextPage = pBuf;
        pNextPage+=4;
        ulNextFreePage = eGetUInt32( pNextPage );
        s.Sprintf( "Free Page# = %ld\t(Block# = %ld)\tNext Free Page = %ld\t(Block = %ld)", ulThisFreePage, PageToBlock( ulThisFreePage ), ulNextFreePage, PageToBlock( ulNextFreePage ));
        xbase->WriteLogMessage( s, iOpt );
        ulThisFreePage = ulNextFreePage;
        ulCnt++;
      }
      s.Sprintf( "%ld free blocks (%ld pages)", ulCnt, BlockToPage( ulCnt ));
      xbase->WriteLogMessage( s, iOpt );
      xbase->WriteLogMessage( "*** End Of Free Blocks ***", iOpt );
    }

    pNextPage = pBuf;
    pNextPage+=4;

    s = "*** Beginning of Block2 Info ***";
    xbase->WriteLogMessage( s, iOpt );
    s = "ulBlock2 info.  ulBlock2 is either one of a linked list of free nodes, or the id of the original node that this node was split from.";
    xbase->WriteLogMessage( s, iOpt );
    s = "Stored in physical file as pages, processed in blocks";
    xbase->WriteLogMessage( s, iOpt );

    xbUInt32 ulFirstBlock = 3;

    for( xbUInt32 ul = ulFirstBlock; ul < ulLastBlock; ul++ ){
      if(( iRc = ReadBlock( ul, GetBlockSize(), pBuf )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
      ulNextPage = eGetUInt32( pNextPage );
      if( ulNextPage > 0 ){
        s.Sprintf( " Block# = %ld\tPage# = %ld\tulBlock2 = %ld\tulBlock2(Page) = %ld", ul, BlockToPage( ul ), PageToBlock( ulNextPage ), ulNextPage );
        xbase->WriteLogMessage( s, iOpt );
      }
    }
    s = "*** End of Block2 Info ***";
    xbase->WriteLogMessage( s, iOpt );

    if( pBuf ) free( pBuf );
  }

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

/**************************************************************************************************************/
//! @brief Dump interior and leaf blocks for a given tag.
/*!
  Dump blocks for given tag for index debugging purposes.

  A page is 512 bytes<br>
  A block is one or more pages<br>
  The default mdx block size is 2 pages, or 1024 bytes<br>
  The first four pages or header pages<br>

  \param iOpt Output message destination<br>
              0 = stdout<br>
              1 = Syslog<br>
              2 = Both<br>
  \param vpTag Index tag pointer, defaults to all tags if null.
  \returns <a href="xbretcod_8h.html">Return Codes</a>

*/

xbInt16 xbIxMdx::DumpTagBlocks( xbInt16 iOpt, void * vpTag ){

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;
  xbInt16 iCurTag = 0;
  xbString s;
  xbInt16 iBlockCtr = 0;

  try{

    xbMdxTag * mpTag;
    if( vpTag == NULL )
      mpTag = (xbMdxTag *) GetTag( iCurTag++ );
    else
      mpTag = (xbMdxTag *) vpTag;

    if( mpTag == NULL ){
      iErrorStop = 100;
      iRc = XB_INVALID_TAG;
      throw iRc;
    }

    xbIxNode *n;
    xbString s;
    xbString s2;
    xbBool bDone = xbFalse;

    xbUInt32 ulBlkNo;
    xbLinkListOrd<xbUInt32> ll;
    xbLinkListNode<xbUInt32> * llN;

    ll.SetDupKeys( xbFalse );

    s.Sprintf( "%s Root Page %ld  (Block %ld)", mpTag->cTagName, mpTag->ulRootPage, PageToBlock( mpTag->ulRootPage ) );
    xbase->WriteLogMessage( s, iOpt );

    // for each tag
    while( !bDone ){

      // clear out any history
      ll.Clear();
      if( mpTag->npNodeChain ){
        mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
        mpTag->npCurNode   = NULL;
      }

      while( GetNextKey( mpTag, 0 ) == 0 ){
        n = mpTag->npNodeChain;

        while(n){
          ll.InsertKey( n->ulBlockNo, (xbUInt32) n->iCurKeyNo );
          n = n->npNext;
        }
      }
      llN = ll.GetHeadNode();

      while( llN ){

        ulBlkNo = llN->GetKey();
        xbIxMdx::DumpBlock( iOpt, ulBlkNo, mpTag );
        llN = llN->GetNextNode();
        iBlockCtr++;
      }

      if( vpTag || iCurTag >= GetTagCount())
        bDone = xbTrue;
      else
        mpTag = (xbMdxTag *) GetTag( iCurTag++ );
    }

    s.Sprintf( "\nTotal Blocks: %d", iBlockCtr );
    xbase->WriteLogMessage( s, iOpt );

    if( mpTag->npNodeChain ){
        mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
        mpTag->npCurNode   = NULL;
    }

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::DumpTagBlocks() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    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>
  \param iFmtOpt Output Format<br>
              0, 1 = Header info only<br>
              2 = Tag info<br>
              3 = Header && Tag info<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxMdx::DumpHeader( xbInt16 iOpt, xbInt16 iFmtOpt )
{

  xbInt16 iRc = XB_NO_ERROR;
  xbString s;
  if(( iRc = ReadHeadBlock( 1 )) != XB_NO_ERROR )
    return iRc;

  char c, tfv, cDisplayMask = 1;
  cDisplayMask = cDisplayMask << 7;
  if( iFmtOpt != 2 && iFmtOpt != 4 ){
    s = "*** MDX Index Header ***";
    xbase->WriteLogMessage( s, iOpt );
    s = "Version           = ";
    tfv = cVersion;
    for( c = 1; c<= 8; c++ ){
      //std::cout << (tfv & cDisplayMask ? '1' : '0');
      s+= (tfv & cDisplayMask ? '1' : '0');
      tfv <<= 1;
    }
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Create Date       = %d/%d/%d", (int) cCreateMM, (int) cCreateDD, (int) cCreateYY % 100 );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "File Name         = %s", sFileName.Str() );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Block Factor      = %d", iBlockFactor );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Block Size        = %d", GetBlockSize() );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Prod Ix Flag      = %d", (xbInt16) cProdIxFlag );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Tag Entry Cnt     = %d", (xbInt16) cTagEntryCnt );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Tag Len           = %d", iTagLen );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Next Tag          = %d", (xbInt16) cNextTag );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Tag Use Cnt       = %d", iTagUseCnt );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Page Cnt          = %d", ulPageCnt );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "First Free Page   = %d", ulFirstFreePage );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "No Of Block Avail = %d\n", ulNoOfBlockAvail );
    xbase->WriteLogMessage( s, iOpt );

    s.Sprintf( "Last update date  = %d/%d/%d", (int) cCreateMM, (int) cCreateDD, (int) cCreateYY % 100 );
    xbase->WriteLogMessage( s, iOpt );

    if( ulFirstFreePage > 0 ){
      xbString s;
      xbUInt32 ulNfp = ulFirstFreePage;   // next free page
      xbInt16 lc = 0;
      while( ulNfp && lc++ < 5 ){
        if( s.Len() > 0 )
          s += ",";
        s.Sprintf( "%s%ld", s.Str(), ulNfp );
        if(( iRc = GetBlock( NULL, (xbUInt32) (ulNfp / (xbUInt32) iBlockFactor), 0 )) != 0 )
          return iRc;
        ulNfp = eGetUInt32( cNodeBuf+4 );
      }
      xbase->WriteLogMessage( s, iOpt );
    }
  }
  if( iFmtOpt > 1 ){
    xbMdxTag *tt = mdxTagTbl;
    xbString s;
    xbInt16 i = 0;

    if( tt ){
      while( tt ){
        i++;
        if(( iRc = LoadTagDetail( 2, tt )) != XB_NO_ERROR )
          return iRc;

        s.Sprintf( "TTE (%d)\tName         HdrPage\tFormat\tLeftChild\tRightChild\tParent\tKeyType", i );
        xbase->WriteLogMessage( s, iOpt );
        s.Sprintf( "TTE (%d)\t%-12s %d\t\t%d\t%d\t\t%d\t\t%d\t%c\n", i, tt->cTagName,  tt->ulTagHdrPageNo, tt->cKeyFmt, tt->cLeftChild, tt->cRightChild, tt->cParent, tt->cKeyType );
        xbase->WriteLogMessage( s, iOpt );

        s.Sprintf( "TTH (%d)\tRoot\tTagSize\tKeyFmt2\tType2\tKeyLen\tKeysPerBlock\tSecType\tKeyItemLen\tSerial#\tHasKeys\tFilter\tDesc\tUnique\tLchild\tRchild\tKeyFmt3\tTagDate", i );
        xbase->WriteLogMessage( s, iOpt );

        s.Sprintf( "TTH (%d)\t%d\t%d\t%d\t%c\t%d\t%d\t\t%d\t%d\t\t%x\t%x\t%d\t%d\t%d\t%d\t%d\t%d\t%d/%d/%d", 
           i, tt->ulRootPage, tt->ulTagSize, tt->cKeyFmt2, tt->cKeyType2, tt->iKeyLen, tt->iKeysPerBlock, tt->iSecKeyType, tt->iKeyItemLen, tt->cSerialNo, tt->cHasKeys, tt->cHasFilter,
           (((tt->cKeyFmt2 & 0x08) > 0) ? 1 : 0),  // descending?
           tt->cUnique, tt->ulLeftChild, tt->ulRightChild, tt->cKeyFmt3, (int) tt->cTagMM,   (int) tt->cTagDD, (int) tt->cTagYY % 100 );

        xbase->WriteLogMessage( s, iOpt );

        s.Sprintf( "Key (%d) %s", i, tt->sKeyExp->Str());
        xbase->WriteLogMessage( s, iOpt );

        if( tt->cHasFilter ){
          s.Sprintf( "Flt (%d) %s", i, tt->sFiltExp->Str());
          xbase->WriteLogMessage( s, iOpt );
        }
        xbase->WriteLogMessage( "", iOpt );
        tt = tt->next;

      }
    }
  }
  return iRc;
}

/***********************************************************************/
xbInt16 xbIxMdx::DumpIxForTag( void *vpTag, xbInt16 iOutputOpt )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbInt16 iDepth = 0;
  xbUInt32 lKeyCtr = 0;
  xbInt32 iMinDepth = 999999;
  xbInt32 iMaxDepth = 0;

  try{
  /* 
    get first node
    while interior node  
      print the left key
      level++
      go down one on the left
  */

    xbMdxTag * mpTag = (xbMdxTag *) vpTag;
    if( mpTag->npNodeChain ){
      mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
      mpTag->npCurNode   = NULL;
    }

    // Get the root
    if(( iRc = LoadTagDetail( 2, mpTag )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
    // lRootBlock is now available
    if(( iRc = GetBlock( vpTag, (mpTag->ulRootPage / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }
    // if no keys on this node, then the index is empty
    xbUInt32 ulKeyPtr = eGetUInt32( mpTag->npCurNode->cpBlockData );
    if( ulKeyPtr == 0 ){
      iErrorStop = 120;
      iRc = XB_EMPTY;
      throw iRc;
    }
    while( !IsLeaf( vpTag, mpTag->npCurNode )){   // go down the chain looking for a leaf node
      PrintKey( vpTag, mpTag->npCurNode , 0, iDepth++,  'I', iOutputOpt );
      if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
    }
    if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
      iErrorStop = 150;
      throw iRc;
    }
    // loop through the leaf entries of left most leaf
    if( iDepth < iMinDepth ) iMinDepth = iDepth;
    if( iDepth > iMaxDepth ) iMaxDepth = iDepth;
    xbUInt32 ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
    for( xbUInt32 ul = 0; ul < ulNoOfKeys; ul++ ){
      PrintKey( vpTag, mpTag->npCurNode , ul, iDepth, 'L', iOutputOpt );
      lKeyCtr++;
    }

    // if head node = start node, return
    if( mpTag->npCurNode->ulBlockNo == ( mpTag->ulRootPage / (xbUInt32) iBlockFactor ))
      return XB_NO_ERROR;

    xbBool bEof = false;
    while( !bEof  ){

      // go up the chain, looking for an interior node with more keys on it
      xbIxNode * TempIxNode = mpTag->npCurNode;
      mpTag->npCurNode = mpTag->npCurNode->npPrev;
      mpTag->npCurNode->npNext = NULL;
      TempIxNode->npPrev = NULL;
      TempIxNode = FreeNodeChain( TempIxNode );
      iDepth--;

      while( mpTag->npCurNode->iCurKeyNo >= eGetUInt32( mpTag->npCurNode->cpBlockData ) &&
             mpTag->npCurNode->ulBlockNo != ( mpTag->ulRootPage / (xbUInt32) iBlockFactor) ){
        TempIxNode = mpTag->npCurNode;
        mpTag->npCurNode = mpTag->npCurNode->npPrev; 
        mpTag->npCurNode->npNext = NULL;
        TempIxNode->npPrev = NULL;
        TempIxNode = FreeNodeChain( TempIxNode );
        iDepth--;
      }
      // if head node && right most key, return
      if( mpTag->npCurNode->ulBlockNo == (mpTag->ulRootPage / (xbUInt32) iBlockFactor) &&
          mpTag->npCurNode->iCurKeyNo == eGetUInt32( mpTag->npCurNode->cpBlockData ))
        bEof = true;

      if( !bEof ){
        mpTag->npCurNode->iCurKeyNo++;
        if(( iRc = GetKeyPtr( vpTag,  mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
          iErrorStop = 160;
          throw iRc;
        }
        PrintKey( vpTag, mpTag->npCurNode , mpTag->npCurNode->iCurKeyNo, iDepth++,  'I', iOutputOpt );

        if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
          iErrorStop = 170;
          throw iRc;
        }

        // traverse down the left side of the tree
        while( !IsLeaf( vpTag, mpTag->npCurNode ))   // go down the chain looking for a leaf node
        {
          PrintKey( vpTag, mpTag->npCurNode , 0, iDepth++,  'I', iOutputOpt );
          if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
            iErrorStop = 180;
            throw iRc;
          }
          if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
            iErrorStop = 190;
            throw iRc;
          }
        }
        if( iDepth < iMinDepth ) iMinDepth = iDepth;
        if( iDepth > iMaxDepth ) iMaxDepth = iDepth;
        ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
        for( xbUInt32 ul = 0; ul < ulNoOfKeys; ul++ ){
          PrintKey( vpTag, mpTag->npCurNode , ul, iDepth, 'L', iOutputOpt );
          lKeyCtr++;
        }
      }
    }
    xbString s;
    s.Sprintf( "Total keys = [%ld] Min Depth = [%d] Max Depth = [%d]", lKeyCtr, iMinDepth, iMaxDepth );
    xbase->WriteLogMessage( s.Str(), 2 );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::DumpIxForTag() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/**************************************************************************************************************/
void xbIxMdx::DumpIxNodeChain( void *vpTag, xbInt16 iOutputOpt ) const
{
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;
  xbString s( "Dump Node Chain" );
  xbase->WriteLogMessage( s, 2 );

  if( mpTag->npNodeChain ){
    xbIxNode *n = mpTag->npNodeChain;
    xbInt16 iCtr = 0;
    char cLeaf;
    s.Sprintf( "Cnt\tThis     Prev     Next     CurKeyNo  BlockNo  Page      NoOfKeys    Type" );
    xbase->WriteLogMessage( s, iOutputOpt );
    while( n ){
      IsLeaf( vpTag, n ) ? cLeaf = 'L' : cLeaf = 'I';
      s.Sprintf( "%d\t%08x %08x %08x %08d  %08d %08d  %08ld    %c",
                 iCtr++, n, n->npPrev, n->npNext, n->iCurKeyNo,
                 n->ulBlockNo, n->ulBlockNo * (xbUInt32) iBlockFactor,
                 eGetUInt32( n->cpBlockData ), cLeaf );
      xbase->WriteLogMessage( s, 2 );
      n = n->npNext;
    }
  } else {
    s = "Empty Node Chain";
    xbase->WriteLogMessage( s, 2 );
  }
}
#endif

/***********************************************************************************************/
xbInt16 xbIxMdx::FindKey( void *vpTag, xbDouble dKey, xbInt16 iRetrieveSw ){

  xbMdxTag * mpTag = (xbMdxTag *) vpTag;
  if( mpTag->cKeyType2 == 'N' ){   // mdx indices store numeric keys as bcd values
    xbBcd bcd( dKey );
    return xbIx::FindKey( vpTag, bcd, iRetrieveSw );
  } else                           // this would be a julian date inquiry
    return FindKey( vpTag, &dKey, 8, iRetrieveSw );
}

/***********************************************************************************************/
// iRetrieveSw = 1 - position db file to index position
//               0 - do not position dbf file

xbInt16 xbIxMdx::FindKey( void *vpTag, const void * vpKey, 
      xbInt32 lSearchKeyLen, xbInt16 iRetrieveSw ){

  xbInt16 iRc = 0;
  xbInt16 iErrorStop = 0;

  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 = 100;
            throw iRc;
          }
        } else {
          if(( iRc = dbf->Abort()) != XB_NO_ERROR ){
            iErrorStop = 110;
            throw iRc;
          }
        }
      }
    }

    xbUInt32 ulNoOfKeys;
    xbMdxTag * mpTag = (xbMdxTag *) vpTag;
    char cKeyType = GetKeyType( vpTag );
    xbBool bDescending = mpTag->cKeyFmt2 & 0x08;

    if( mpTag->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 = 120;
        throw iRc;
      }
      if( mpTag->tNodeChainTs < tFileTs ){
        mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
        mpTag->npCurNode   = NULL;

      } else {
        //  pop up the chain looking for appropriate starting point
        xbBool  bDone = false;
        xbIxNode * TempIxNode;
        while( mpTag->npCurNode  && !bDone && 
          (mpTag->npCurNode->ulBlockNo != ( mpTag->ulRootPage / (xbUInt32) iBlockFactor ))){ // not root node
            //if no keys on the node, pop up one
            ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
            if( ulNoOfKeys == 0 ){
              TempIxNode = mpTag->npCurNode;
              mpTag->npCurNode = mpTag->npCurNode->npPrev;
              TempIxNode = FreeNodeChain( TempIxNode );

            } else {

              iRc = CompareKey( cKeyType, vpKey, GetKeyData( mpTag->npCurNode, 0, mpTag->iKeyItemLen ), (size_t) lSearchKeyLen );
              if( (!bDescending && iRc <= 0) || (bDescending && iRc >= 0 )){
                TempIxNode = mpTag->npCurNode;
                mpTag->npCurNode = mpTag->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( mpTag->npCurNode->cpBlockData ) - 1;     // IsLeaf( vpTag, mpTag->npCurNode );
                iRc = CompareKey( cKeyType, vpKey, GetKeyData( mpTag->npCurNode, ulKeyCtr, mpTag->iKeyItemLen), (size_t) lSearchKeyLen );

                if( (!bDescending && iRc > 0) || (bDescending && iRc < 0 )){
                  TempIxNode = mpTag->npCurNode;
                  mpTag->npCurNode = mpTag->npCurNode->npPrev;
                  TempIxNode = FreeNodeChain( TempIxNode );
                } else {
                  bDone = true;
                }
             }
           }
        }
      }
    } 

    // either started empty, or cleared due to file time diff
    if( !mpTag->npNodeChain ){
      // Get the root
      if(( iRc = LoadTagDetail( 2, mpTag )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
      // lRootBlock is now available
      if(( iRc = GetBlock( vpTag, (mpTag->ulRootPage / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
      // if this is a leaf node and no keys on this node, then the index is empty
      ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
      if( ulNoOfKeys == 0 && IsLeaf( vpTag, mpTag->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( vpTag && !IsLeaf( vpTag, mpTag->npCurNode ) ){
      // get the number of keys on the block and compare the key to the rightmost key
      ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );

      if( ulNoOfKeys == 0 ){
        mpTag->npCurNode->iCurKeyNo = 0;

      } else {

        iRc = CompareKey( cKeyType, vpKey, GetKeyData( mpTag->npCurNode, ulNoOfKeys - 1, mpTag->iKeyItemLen), (size_t) lSearchKeyLen );
        if( (!bDescending && iRc > 0) || (bDescending && iRc < 0)){
          mpTag->npCurNode->iCurKeyNo = ulNoOfKeys;
        }
        else
        {
          mpTag->npCurNode->iCurKeyNo = (xbUInt32) BSearchBlock( cKeyType, mpTag->npCurNode, 
              (xbInt32) mpTag->iKeyItemLen, vpKey, (xbInt32) lSearchKeyLen, iSearchRc, bDescending );
        }
      }

      if(( iRc = GetKeyPtr( vpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }

      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32)iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }
    }

    ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
    xbInt16 iCompRc = 0;

    if( ulNoOfKeys == 0 ){
      // iCompRc = -1;
      // iRc = XB_EMPTY;
      iRc = XB_NOT_FOUND;
      return iRc;

    } else {

      iRc = BSearchBlock( cKeyType, mpTag->npCurNode, mpTag->iKeyItemLen, vpKey, lSearchKeyLen, iCompRc, bDescending );
      // iCompRc 
      //    0 found
      //  < 0 eof encountered, search key > last key in file
      //  > 0 not found, positioned to next key

      if( iCompRc >= 0 ){
        mpTag->npCurNode->iCurKeyNo = (xbUInt32) iRc;


        if( iRetrieveSw ){

          xbUInt32 ulKey = mpTag->npCurNode->iCurKeyNo;
          if( ulKey >= ulNoOfKeys )   // if position past end of keys, need to go back one and position to last key
            ulKey--;

          // if(( iRc = GetKeyPtr( vpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){

          if(( iRc = GetKeyPtr( vpTag, ulKey, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
            iErrorStop = 170;
            throw iRc;
          }
          if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
            iErrorStop = 180;
            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( "xbIxMdx::FindKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
xbInt16 xbIxMdx::FindKeyForCurRec( void * vpTag )
{

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbInt16 i = 0;

  try{
    if(( iRc = CreateKey( vpTag, 0 )) < XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::FindKeyForCurRec() Exception Caught. Error Stop = [%d] iRc = [%d] Tag=[%d]", iErrorStop, iRc, i );
    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 xbIxMdx::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 = 100;
      throw XB_INVALID_KEYNO;
    }
    #endif

    xbMdxTag * mpTag = (xbMdxTag *) vpTag;
    char *p = ( np->cpBlockData);
    p += (8 + (iKeyNo * mpTag->iKeyItemLen));
    ulDbfPtr = eGetUInt32 ( p );

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

/***********************************************************************/
/*!
  \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 xbIxMdx::GetFirstKey( void *vpTag, xbInt16 iRetrieveSw = 0 ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  // convert the tag pointer to mdx tag pointer
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;


  try{
    // clear out any history
    if( mpTag->npNodeChain ){
      mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
      mpTag->npCurNode   = NULL;
    }
    // Get the root 
    if(( iRc = LoadTagDetail( 2, mpTag )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }

    // lRootPage is available
    if(( iRc = GetBlock( vpTag, (mpTag->ulRootPage / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }

    // if no keys on this node, then the index is empty
    // this is not true

    xbUInt32 ulKeyPtr = eGetUInt32( mpTag->npCurNode->cpBlockData );
    if( ulKeyPtr == 0 && IsLeaf( vpTag, mpTag->npCurNode )){
      iRc = XB_EMPTY;
      return iRc;
    }

    while( !IsLeaf( vpTag, mpTag->npCurNode )){   // go down the chain looking for a leaf node
      if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }

      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
    }

    // retrieve record to data buf 
    if( iRetrieveSw ){
      if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::GetFirstKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//xbBool xbIxMdx::GetIndexUpdated() const {
//  std::cout << "xbIxMdx::GetIndexUpdate() FIX ME \n";
//  return xbFalse;
//}

/***********************************************************************/
//! @brief Get the key expression for the given tag.
/*!
  \param vpTag Tag to retrieve key expression from tag.
  \returns Key expression.
*/

xbString &xbIxMdx::GetKeyExpression( const void * vpTag ) const{
  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  return *mpTag->sKeyExp;
}

/***********************************************************************/
//! @brief Get the key expression for the given tag.
/*!
  \param vpTag Tag to retrieve filter expression from tag (if it exists).
  \returns Key filter.
*/

xbString &xbIxMdx::GetKeyFilter( const void * vpTag ) const{

  xbMdxTag * mpTag = (xbMdxTag *) vpTag;

  if( mpTag->sFiltExp )
    return *mpTag->sFiltExp;
  else
    return sNullString;

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

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{

    xbMdxTag *mdxTag = (xbMdxTag *) vpTag;
    char *p = np->cpBlockData;
    xbUInt32 ulKeyCnt = eGetUInt32( p );
    if( iKeyNo < 0 || iKeyNo > (xbInt16) ulKeyCnt ){
      iErrorStop = 100;
      iRc = XB_INVALID_KEYNO;
      throw iRc;
    }
    p+=8;  // skip past first two four byte numeric fields
    p+= (iKeyNo * mdxTag->iKeyItemLen);
    ulKeyPtr = eGetUInt32( p );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::GetKeyPtr() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    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

*/
inline xbInt16 xbIxMdx::GetKeySts( void *vpTag ) const{

  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  return mpTag->iKeySts;
}

/***********************************************************************/
char xbIxMdx::GetKeyType( const void *vpTag ) const {
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;
  return mpTag->cKeyType;
}

/***********************************************************************/
//! @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 xbIxMdx::GetLastKey( void *vpTag, xbInt16 iRetrieveSw ){
  return GetLastKey( 0, vpTag, iRetrieveSw );
}

/***********************************************************************/
//! @brief Get the last key for the given tag and starting node.
/*!
  \param ulBlockNo 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 xbIxMdx::GetLastKey( xbUInt32 ulBlockNo, void *vpTag, xbInt16 iRetrieveSw ){

  // if UlNodeNo is zero, start at head node, otherwise start at ulNodeNo
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  // convert the tag pointer to mdx tag pointer
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;

  try{
    xbUInt32 ulNoOfKeys = 0;
    // clear out any history
    if( mpTag->npNodeChain ){
       mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
       mpTag->npCurNode   = NULL;
    }
    // Get the root 
    if( ulBlockNo == 0 ){
      if(( iRc = LoadTagDetail( 2, mpTag )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
      //if(( iRc = GetBlock( vpTag, (mpTag->ulRootPage / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
      if(( iRc = GetBlock( vpTag, PageToBlock( mpTag->ulRootPage ), 1 )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }

    } else {
      if(( iRc = GetBlock( vpTag, ulBlockNo, 1 )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
    }

    ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );

    if( ulNoOfKeys == 0 && IsLeaf( vpTag, mpTag->npCurNode )){
      iRc = XB_EMPTY;
      return iRc;
    }

    mpTag->npCurNode->iCurKeyNo = ulNoOfKeys;
    ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );

    xbUInt32 ulKeyPtr = 0;
    while( !IsLeaf( vpTag, mpTag->npCurNode )){   // go down the chain looking for a leaf node
      // std::cout << "Considered an interior node\n";
      if(( iRc = GetKeyPtr( vpTag, ulNoOfKeys, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }

      ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
      mpTag->npCurNode->iCurKeyNo = ulNoOfKeys;
    }
    // leaf node has one fewer keys than the interior node
    mpTag->npCurNode->iCurKeyNo--;
    ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );

    // retrieve record to data buf 
    if( iRetrieveSw ){
      if(( iRc = GetKeyPtr( vpTag, (ulNoOfKeys-1), mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::GetLastKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    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 xbIxMdx::GetLastKeyForBlockNo( void *vpTag, xbUInt32 ulBlockNo, char *cpBuf ){

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

  xbMdxTag * npTag = (xbMdxTag *) vpTag;

  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;
    }
    memcpy( cpBuf, GetKeyData( npTag->npCurNode, GetKeyCount( npTag->npCurNode ) - 1, npTag->iKeyItemLen ), (size_t) npTag->iKeyLen );

     // free memory
    FreeNodeChain( npTag->npNodeChain );
    npTag->npNodeChain = npSaveNodeChain;
    npTag->npCurNode = npSaveCurNode;

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::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 xbIxMdx::GetNextKey( void * vpTag, xbInt16 iRetrieveSw ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  // convert the tag pointer to mdx tag pointer
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;

  try{
    if( !mpTag->npCurNode )
      return GetFirstKey( vpTag, iRetrieveSw );

    // more keys on this node?
    xbUInt32 ulKeyPtr;
    if( (eGetUInt32( mpTag->npCurNode->cpBlockData ) - 1) > mpTag->npCurNode->iCurKeyNo ){
      mpTag->npCurNode->iCurKeyNo++;

      if(( iRc = GetKeyPtr( vpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
      if( iRetrieveSw ){
        if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
          iErrorStop = 110;
          throw iRc;
        } else {
          return iRc;
        }
      } else {
        return iRc;
      }
    }

    // if at end head node, then at eof
    if( mpTag->npCurNode->ulBlockNo == ( mpTag->ulRootPage / (xbUInt32) iBlockFactor ))
      return XB_EOF;

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

    // While no more right keys && not head node, pop up one node
    while( mpTag->npCurNode->iCurKeyNo >= eGetUInt32( mpTag->npCurNode->cpBlockData ) &&
           mpTag->npCurNode->ulBlockNo != ( mpTag->ulRootPage / (xbUInt32) iBlockFactor) ){

      TempIxNode = mpTag->npCurNode;
      mpTag->npCurNode = mpTag->npCurNode->npPrev; 
      TempIxNode = FreeNodeChain( TempIxNode );
    }

    // if head node && right most key, return eof
    if( mpTag->npCurNode->ulBlockNo == (mpTag->ulRootPage / (xbUInt32) iBlockFactor) &&  
        mpTag->npCurNode->iCurKeyNo == eGetUInt32( mpTag->npCurNode->cpBlockData ))
      return XB_EOF;

    // move one to the right
    mpTag->npCurNode->iCurKeyNo++;
    if(( iRc = GetKeyPtr( vpTag,  mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
      iErrorStop = 120;
      throw iRc;
    }

    if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }

    // traverse down the left side of the tree
    while( !IsLeaf( vpTag, mpTag->npCurNode ))   // go down the chain looking for a leaf node
    {
      if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
    }
    // retrieve record to data buf 
    if( iRetrieveSw ){
      if(( iRc = GetKeyPtr( vpTag, 0, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 170;
        throw iRc;
      }
    } else {
      return iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::GetNextKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    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 xbIxMdx::GetPrevKey( void * vpTag, xbInt16 iRetrieveSw ){

  xbString s;

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  // convert the tag pointer to mdx tag pointer
  xbMdxTag * mpTag = (xbMdxTag *) vpTag;

  try{
    if( !mpTag->npCurNode ){
      return GetLastKey( 0, vpTag, iRetrieveSw );
    }

    xbUInt32 ulKeyPtr = 0;
    // more keys on this assumed-leaf node?

    if( mpTag->npCurNode->iCurKeyNo > 0 ){
      mpTag->npCurNode->iCurKeyNo--;

      if(( iRc = GetKeyPtr( vpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }

      if( iRetrieveSw ){
        if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
          iErrorStop = 110;
          throw iRc;
        } else {
          return iRc;
        }
      } else {
        return iRc;
      }
    }

    //if head node = start node, at eof
    if( mpTag->npCurNode->ulBlockNo == ( mpTag->ulRootPage / (xbUInt32) iBlockFactor ))
      return XB_BOF;

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

    // While no more left keys && not head node, pop up one node
    while( mpTag->npCurNode->iCurKeyNo == 0 &&
           mpTag->npCurNode->ulBlockNo != ( mpTag->ulRootPage / (xbUInt32) iBlockFactor) ){
      TempIxNode = mpTag->npCurNode;
      mpTag->npCurNode = mpTag->npCurNode->npPrev; 
      TempIxNode = FreeNodeChain( TempIxNode );
    }

    //if head node && left most key, return bof
    if( mpTag->npCurNode->ulBlockNo == ( mpTag->ulRootPage / (xbUInt32) iBlockFactor) && mpTag->npCurNode->iCurKeyNo == 0 )
      return XB_BOF;

    // move one to the left
    mpTag->npCurNode->iCurKeyNo--;
    if(( iRc = GetKeyPtr( vpTag,  mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
      iErrorStop = 120;
      throw iRc;
    }

    if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }

    // traverse down the right side of the tree
    xbUInt32 ulNoOfKeys;
    while( !IsLeaf( vpTag, mpTag->npCurNode ))   // go down the chain looking for a leaf node
    {
      ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
      mpTag->npCurNode->iCurKeyNo = ulNoOfKeys;

      if(( iRc = GetKeyPtr( vpTag,  ulNoOfKeys, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
      if(( iRc = GetBlock( vpTag, (ulKeyPtr / (xbUInt32) iBlockFactor), 1 )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
    }

    // ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
    mpTag->npCurNode->iCurKeyNo = eGetUInt32( mpTag->npCurNode->cpBlockData ) - 1;

    // retrieve record to data buf 
    if( iRetrieveSw ){
      if(( iRc = GetKeyPtr( vpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }
      if(( iRc = dbf->GetRecord( ulKeyPtr )) != XB_NO_ERROR ){
        iErrorStop = 170;
        throw iRc;
      }
    } else {
      return iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::GetPrevKey() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief GetReuseEmptyNode swuitch setting.
/*!
  \returns xbFalse - Do not reuse empty MDX index nodes (Dbase 6. behavior).
           xbTrue  - Reuse empty MDX index nodes.
*/

xbBool xbIxMdx::GetReuseEmptyNodesSw() const {
  return bReuseEmptyNodes;
}
/***********************************************************************/
xbBool xbIxMdx::GetSortOrder( void *vpTag ) const {

  // return true if descending
  xbMdxTag *mTag = (xbMdxTag *) vpTag;  
  if( mTag->cKeyFmt2 & 0x08 )
    return 0x01;
  else
    return 0x00;
}

/***********************************************************************/
//! @brief Get tag for tag number.
/*!
  \param iTagNo - Zero based, which tag to retrieve.
  \returns Pointer to mdx tag for a given tag number.
*/

void * xbIxMdx::GetTag( xbInt16 iTagNo ) const {

  xbMdxTag *tt = mdxTagTbl;
  xbInt16 i = 0;

  while( i < iTagNo && tt->next ){
    tt = tt->next;
    i++;
  }
  if( i == iTagNo )
    return (void *) tt;
  else
    return NULL;
}

/***********************************************************************/
//! @brief Get tag for tag name.
/*!
  \sTagName - Tag name to retrieve.
  \returns Pointer to mdx tag for a given tag number.
*/

void * xbIxMdx::GetTag( xbString &sTagName ) const {

  xbMdxTag *tt = mdxTagTbl;

  while( sTagName != tt->cTagName && tt->next ){
    tt = tt->next;
  }

  if( sTagName == tt->cTagName )
    return (void *) tt;
  else
    return NULL;
}
/***********************************************************************/
xbInt16 xbIxMdx::GetTagCount() const {
  return iTagUseCnt;
}

/***********************************************************************/
void xbIxMdx::GetTagName( void *vpTag, xbString &sTagName ){

  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  sTagName = mpTag->sTagName->Str();
}

/***********************************************************************/
//const char *xbIxMdx::GetTagName( void *vpTag, xbInt16 iOpt ) const {

const char *xbIxMdx::GetTagName( void *vpTag, xbInt16 ) const {
  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  return mpTag->cTagName;
}

/***********************************************************************/
xbString &xbIxMdx::GetTagName( void *vpTag ) const {

  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  return *mpTag->sTagName;
}

/***********************************************************************/
void *xbIxMdx::GetTagTblPtr() const {
  return (void *) mdxTagTbl;
}

/***********************************************************************/
xbBool xbIxMdx::GetUnique( void *vpTag ) const {
//! @brief Determine unique setting for given tag.
/*!
  \param vpTag Tag to retrieve expression from.
  \returns xbTrue if unique key.
*/
  xbMdxTag *mTag = (xbMdxTag *) vpTag;
  return mTag->cUnique;
}

/***********************************************************************/
//! @brief Harvest Empty Node.
/*!
  Harvest empty MDX node and add it to the chain of link nodes

  \param mpTag Tag to harvest.
  \param iOpt - 0 Don't write the node info to disk, handled elsewhere (don't write it twice)
                1 Write the update into to disk
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/
xbInt16 xbIxMdx::HarvestEmptyNode( xbMdxTag *mpTag, xbIxNode *npNode, xbInt16 iOpt, xbBool bHarvestRoot ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbBool  bRootPage = xbFalse;
  xbInt32 iOffset = 0;

  try{

    if( mpTag->ulRootPage == BlockToPage( npNode->ulBlockNo ) && !bHarvestRoot ){
      bRootPage = xbTrue;
    }
    memset( npNode->cpBlockData, 0x00, GetBlockSize());

    char *pTrg = npNode->cpBlockData;
    if( !bRootPage ){
      pTrg += 4;
      ePutUInt32( pTrg, ulFirstFreePage );
    }

    if( bRootPage ){
      if( mpTag->cHasKeys ){

        // std::cout << "setting has keys\n";

        mpTag->cHasKeys = 0x00;
        if(( iRc = xbFseek( ((mpTag->ulTagHdrPageNo * 512) + 246), SEEK_SET )) != XB_NO_ERROR ){
          iErrorStop = 100;
          throw iRc;
        }
        if(( iRc = xbFwrite( &mpTag->cHasKeys, 1, 1 )) != XB_NO_ERROR ){
          iErrorStop = 110;
          throw iRc;
        }
        // might need to update left sibling and right sibling here.
        // Fields don't seem to be updated consistently by other xbase tools, 
        // for now, not updating
      }

    } else {

      // update header
      // seek to position byte 13
      ulFirstFreePage = BlockToPage( npNode->ulBlockNo );
      if(( iRc = xbFseek( 36, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
      // write it
      char c4[4];
      ePutUInt32( c4, ulFirstFreePage );
      if(( iRc = xbFwrite( c4, 4, 1 )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
    }

    if( iOpt == 1 ){
      if(( iRc = xbFseek( (xbInt64) ((npNode->ulBlockNo * GetBlockSize() )) + iOffset, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
      // write out the block
      if(( iRc = xbFwrite( npNode->cpBlockData, GetBlockSize(), 1 )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
    }
  }

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

/***********************************************************************/
//! @brief Harvest Tag Nodes.
/*!
  Save all nodes for a given tag into the free node chain.
  Used for reindexing or deleting a given tag.

  \param mpTag Tag for harvesting nodes
  \param bHarvestRoot Set to True when deleting tag
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxMdx::HarvestTagNodes( xbMdxTag *mpTag, xbBool bHarvestRoot ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  xbUInt32 ulBlkNo;
  xbLinkListOrd<xbUInt32> ll;
  xbLinkListNode<xbUInt32> * llN;
  xbIxNode * n;

  try{

    ll.SetDupKeys( xbFalse );

    // clear out any history
    if( mpTag->npNodeChain ){
      mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
      mpTag->npCurNode   = NULL;
    }

    while( GetNextKey( mpTag, 0 ) == 0 ){
      n = mpTag->npNodeChain;
      while(n){
        ll.InsertKey( n->ulBlockNo, (xbUInt32) n->iCurKeyNo );
        n = n->npNext;
      }
    }

    if( bHarvestRoot )
      ll.InsertKey( PageToBlock( mpTag->ulTagHdrPageNo ), 0 );

    llN = ll.GetHeadNode();
    if(( n = xbIx::AllocateIxNode( GetBlockSize())) == NULL ){
      iErrorStop = 100;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    while( llN ){
      ulBlkNo = llN->GetKey();

      // read in a block for the block number
      if(( iRc = ReadBlock( ulBlkNo, GetBlockSize(), n->cpBlockData )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
      // harvest it
      n->ulBlockNo = ulBlkNo;
      if(( iRc = HarvestEmptyNode( mpTag, n, 1, bHarvestRoot )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
      llN = llN->GetNextNode();
    }
    n = FreeNodeChain( n );
    mpTag->npNodeChain = FreeNodeChain( mpTag->npNodeChain );
    mpTag->npCurNode   = NULL;

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

/***********************************************************************/
//! @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 Page number to insert.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxMdx::InsertNodeI( void *vpTag, xbIxNode *npNode, xbInt16 iSlotNo, xbUInt32 ulPtr ){
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char *pNewKeyPos;
  char *pTrg;
  char *pLastKey = NULL;
  xbMdxTag * npTag;
  npTag = (xbMdxTag *) vpTag;
  xbInt16 iCopyLen;
  xbInt16 iNewKeyPos = 8;

  try{
    xbInt32 lKeyCnt = GetKeyCount( npNode ); 
    iNewKeyPos += (iSlotNo * npTag->iKeyItemLen);
    char *pSrc = npNode->cpBlockData;

    if( iSlotNo < lKeyCnt )
      iCopyLen = ((lKeyCnt - iSlotNo) * npTag->iKeyItemLen) + 4;
    else
      iCopyLen = 0;

    xbUInt32 ulRqdBufSize = (xbUInt32) ((lKeyCnt + 1) * npTag->iKeyItemLen) + 12;
    if( ulRqdBufSize > npNode->ulBufSize ){
      npNode->ulBufSize += (xbUInt32) npTag->iKeyItemLen;
      npNode->cpBlockData = (char *) realloc( npNode->cpBlockData, (size_t) npNode->ulBufSize );
      if( !npNode->cpBlockData ){
        iErrorStop = 100;
        iRc = XB_NO_MEMORY;
        throw iRc;
      }
    }

    // if not appending to the end of the node, make some room, move things to the right
    pNewKeyPos = npNode->cpBlockData;
    pNewKeyPos += iNewKeyPos;

    if( iSlotNo < lKeyCnt ){
      pTrg = pNewKeyPos;
      pTrg += npTag->iKeyItemLen;
      memmove( pTrg, pNewKeyPos, (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 = 110;
      throw iRc;
    }

    // get the new right key value for the freshly split node
    pLastKey = (char *) malloc((size_t) npTag->iKeyLen);
    if(( iRc = GetLastKeyForBlockNo( vpTag, PageToBlock( ulKeyPtr2 ), pLastKey )) != XB_NO_ERROR ){
      iRc = 120;
      throw iRc;
    }

    // write the key values
    pTrg = pNewKeyPos;
    pTrg += 4;
    pSrc = pLastKey;
    for( xbInt16 i = 0; i < npTag->iKeyLen; i++ )
      *pTrg++ = *pSrc++;

    pTrg = pNewKeyPos;
    //pTrg+= npTag->iKeyItemLen - 4;
    pTrg+= npTag->iKeyItemLen;

    ePutUInt32( pTrg, ulPtr);
    ePutInt32( npNode->cpBlockData, ++lKeyCnt );

    // write out the updated block to disk
    if(( iRc = WriteBlock( npNode->ulBlockNo, GetBlockSize(), npNode->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }
    if( pLastKey )
      free( pLastKey );
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::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 xbIxMdx::InsertNodeL( void *vpTag, xbIxNode *npNode, xbInt16 iSlotNo, char * cpKeyBuf, xbUInt32 ulPtr ){

  // format of block data is
  //   4 bytes number of keys on block
  //   4 bytes - next free block or split block num
  //   repeating
  //      4 bytes record number
  //      x bytes key data

  //  Special processing note:  when splitting node, new key is first inserted into full left node before
  //  the node is split.  This routine will make additional room in the buffer for that scenario


  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char *pNewKeyPos;              // pointer to position in record for new key composite
  char *pTrg;

  xbInt16 iNewKeyPos = 8;        // position in data block where new key begins.
                                 // is the position of the record number, where the fmt is 
                                 // [four byte rec number][actual key data] repeats

  xbMdxTag * npTag = (xbMdxTag *) vpTag;
  xbInt16 iCopyLen;

  try{
    xbInt32 lKeyCnt = GetKeyCount( npNode ); 
    iNewKeyPos += (iSlotNo * npTag->iKeyItemLen);

    // length of number of keys that need to be moved to the right
    if( iSlotNo < lKeyCnt )
      iCopyLen = (lKeyCnt - iSlotNo) * npTag->iKeyItemLen;
    else
      iCopyLen = 0;

    // +8 is to include the first two 4 byte fields in the block
    xbUInt32 ulRqdBufSize = (xbUInt32) ((lKeyCnt + 1) * npTag->iKeyItemLen) + 8;

    if( ulRqdBufSize > npNode->ulBufSize ){

      npNode->ulBufSize += (xbUInt32) npTag->iKeyItemLen;
      npNode->cpBlockData = (char *) realloc( npNode->cpBlockData, (size_t) npNode->ulBufSize );

      // init the newly acquired buffer space
      char *p = npNode->cpBlockData;
      p += (npNode->ulBufSize - (xbUInt32) npTag->iKeyItemLen);
      memset( p, 0x00, (size_t) npTag->iKeyItemLen );
 
      if( !npNode->cpBlockData ){
        iErrorStop = 100;
        iRc = XB_NO_MEMORY;
        throw iRc;
      }
    }

    // if not appending to end, move things right

    pNewKeyPos =  npNode->cpBlockData;
    pNewKeyPos += iNewKeyPos;

    if( iSlotNo < lKeyCnt ) {
      pTrg       =  pNewKeyPos;
      pTrg       += npTag->iKeyItemLen;
      memmove( pTrg, pNewKeyPos, (size_t) iCopyLen );

    }

    // write rec number
    ePutUInt32( pNewKeyPos, ulPtr );

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

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

    // determine length of node, zap everything to the right of it
    xbUInt32 iStartPos = 8 + ((xbUInt32) lKeyCnt * (xbUInt32) npTag->iKeyItemLen );
    xbUInt32 iClearLen = npNode->ulBufSize - iStartPos;

    char *p = npNode->cpBlockData;
    p += iStartPos;
    memset( p, 0x00, iClearLen );

    // write out the updated block to disk
    if(( iRc = WriteBlock( npNode->ulBlockNo, GetBlockSize(), npNode->cpBlockData )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::InsertNodeL() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
inline xbBool xbIxMdx::IsLeaf( void *vpTag, xbIxNode *npNode ) const{

  // for performance reasons, does no data checking
  // will result in potentially hard to find segfaults if passing invalid npNode

  xbMdxTag *mTag = (xbMdxTag *) vpTag;
  char *p = npNode->cpBlockData;

  xbInt32 lNoOfKeys = eGetInt32( p );
  // mdx interior nodes have a sibling number to the right of the right most key in the node
  p+=8;
  p+= mTag->iKeyItemLen * lNoOfKeys;

  if( eGetUInt32( p ) == 0 ){
    // std::cout << "leaf node\n";
    return true;
  } else {
    // std::cout << "interior node\n";
    return false;
  }
}

/***********************************************************************/
xbInt16 xbIxMdx::KeyExists( void * vpTag )
{
  // this method assumes the key has already been built 

  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  xbInt16 iRc = FindKey( vpTag, mpTag->cpKeyBuf, mpTag->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 xbIxMdx::KeySetPosAdd( xbMdxTag *mpTag, xbUInt32 ulAddRecNo ){

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

     iRc = FindKey( mpTag, mpTag->cpKeyBuf, mpTag->iKeyLen, 0 );
     if( iRc == XB_NOT_FOUND || iRc == XB_EMPTY )
       return XB_NO_ERROR;  // good position
     else if( iRc != XB_NO_ERROR ){
       iErrorStop = 100;
       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( mpTag ) == 0 ){

       xbUInt32 ulCurRecNo;
       if(( iRc = GetDbfPtr( mpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulCurRecNo )) != XB_NO_ERROR ){
         iErrorStop = 110;
         throw iRc;
       }
       xbBool bKeysMatch = xbTrue;

       while( bKeysMatch && ulAddRecNo > ulCurRecNo && iRc == XB_NO_ERROR ){
         if(( iRc = GetNextKey( mpTag, 0 )) == XB_NO_ERROR ){
           if( memcmp( GetKeyData( mpTag->npCurNode, mpTag->npCurNode->iCurKeyNo, mpTag->iKeyItemLen ), mpTag->cpKeyBuf, (size_t) mpTag->iKeyLen ))
             bKeysMatch = xbFalse;
           else{
             if(( iRc = GetDbfPtr( mpTag, mpTag->npCurNode->iCurKeyNo, mpTag->npCurNode, ulCurRecNo )) != XB_NO_ERROR ){
               iErrorStop = 120;
               throw iRc;
             }
           }
         }
       }
     }
     if( iRc == XB_EOF ){   // eof condition
       if(( iRc = GetLastKey( 0, mpTag, 0 )) != XB_NO_ERROR ){
         iErrorStop = 130;
         throw iRc;
       }
       mpTag->npCurNode->iCurKeyNo++;
       return XB_NO_ERROR;
     }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::KeySetPosAdd() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/***********************************************************************/
//! @brief Set position for key delete.
/*!
  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 xbIxMdx::KeySetPosDel( xbMdxTag *npTag ){

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

  try{

     iRc = FindKey( npTag, npTag->cpKeyBuf2, npTag->iKeyLen, 0 );
     if( iRc == XB_NOT_FOUND || iRc == XB_EMPTY )
       return XB_NO_ERROR;  // good pos ition
     else if( iRc != XB_NO_ERROR ){
       iErrorStop = 100;
       throw iRc;
     }

     xbUInt32 ulIxRecNo;
     if(( iRc = GetDbfPtr( npTag, npTag->npCurNode->iCurKeyNo, npTag->npCurNode, ulIxRecNo )) != XB_NO_ERROR ){
       iErrorStop = 110;
       throw iRc;
     }

     if( ulIxRecNo == dbf->GetCurRecNo()) 
       return XB_NO_ERROR;

     if( GetUnique( npTag ) == 1 ){
       iErrorStop = 120;
       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 = 130;
         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 = 140;
           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( "xbIxMdx::KeySetPosDel() 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 xbtrue - Key was updated.<br>xbFalse - Key not updated.
*/
/*
inline xbBool xbIxMdx::KeyFiltered( void *vpTag ) const{

  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  return mpTag->bKeyFiltered;
}
*/
/***********************************************************************/
xbInt16 xbIxMdx::LoadTagDetail( xbInt16 iOption, xbMdxTag *tte ){

  // option 1 - Load the entire tag detail
  // option 2 - Load the dynamic variables only

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  size_t iReadSize;
  char *buf = NULL;
  char *p;

  try{
    // set the read length based on the option
    if( iOption == 1 )
      iReadSize = 1024;

    else if( iOption == 2 )
    //  iReadSize = 4;
      iReadSize = 260;
    else{
      iRc = XB_INVALID_OPTION;
      iErrorStop = 100;
      throw iRc;
    }
    if(( buf = (char *) calloc( 1, (size_t) iReadSize )) == NULL ){
      iErrorStop = 110;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }
    if(( iRc = ReadBlock( tte->ulTagHdrPageNo,(xbUInt32) (GetBlockSize() / (xbUInt16) iBlockFactor),
        iReadSize, buf )) != XB_NO_ERROR ){
      free( buf );
      iErrorStop = 30;
      throw iRc;
    }

    p = buf;
    tte->ulRootPage = eGetUInt32( p );

    if( iOption == 1 ){
      p+=4;
      tte->ulTagSize    = eGetUInt32( p );
      p+=4;
      tte->cKeyFmt2     = *p;
      p++;
      tte->cKeyType2    = *p;
      p+=3;
      tte->iKeyLen      = eGetInt16( p );
      p+=2;
      tte->iKeysPerBlock = *p;
      p+=2;
      tte->iSecKeyType  = eGetInt16( p );
      p+=2;
      tte->iKeyItemLen  = eGetInt16( p );
      p+=2;
      tte->cSerialNo    = *p;
      p+=3;
      tte->cUnique      = *p;
      p++;

      // next line assumes expression is a null terminated string in the block
      tte->sKeyExp = new xbString();
      tte->sKeyExp->Sprintf( "%s", p );

      p+=221;
      tte->cHasFilter   = *p;
      p+=1;
      tte->cHasKeys     = *p;
      p+=2;
      tte->ulLeftChild  = eGetUInt32( p );
      p+=4;
      tte->ulRightChild = eGetUInt32( p );
      p+=5;
      tte->cTagYY       = *p;
      p++;
      tte->cTagMM       = *p;
      p++;
      tte->cTagDD       = *p;
      // p+=223;

      p+=221;
      tte->cKeyFmt3     = *p;

      if( tte->cHasFilter ){
        p+=282;
        tte->sFiltExp = new xbString();
        tte->sFiltExp->Sprintf( "%s", p );
        tte->filter = new xbExp( xbase, dbf );
        if(( iRc = tte->filter->ParseExpression( tte->sFiltExp->Str())) != XB_NO_ERROR ){
          iErrorStop = 120;
          throw iRc;
        }
      }
      tte->npNodeChain = NULL;
      tte->npCurNode   = NULL;
      tte->cpKeyBuf    = (char *) malloc( (size_t) tte->iKeyLen + 1 );
      tte->cpKeyBuf2   = (char *) malloc( (size_t) tte->iKeyLen + 1 );
      tte->exp = new xbExp( xbase, dbf );
      if(( iRc = tte->exp->ParseExpression( tte->sKeyExp->Str() )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
    } else if( iOption == 2 ){
      // refresh the dynamic tag variables
      p+=4;
      tte->ulTagSize    = eGetUInt32( p );
      p+= 16;
      tte->cSerialNo    = *p;
      p+= 226;
      tte->cHasKeys     = *p;
      p+=2;
      tte->ulLeftChild  = eGetUInt32( p );
      p+=4;
      tte->ulRightChild = eGetUInt32( p );
      p+=5;
      tte->cTagYY       = *p;
      p++;
      tte->cTagMM       = *p;
      p++;
      tte->cTagDD       = *p;
    }
    if( buf )
      free( buf );

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

/***********************************************************************/
xbInt16 xbIxMdx::LoadTagTable()
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char * buf = NULL;

  //std::cout << "xbIxMdx::LoadTagTable() tag use cnt = " << iTagUseCnt << "\n";

  try{

    if( iTagUseCnt > 46 ){
      iErrorStop = 100;
      iRc = XB_INVALID_INDEX;
      throw iRc;
    }

    xbInt16 iBufSize = (xbInt16) iTagLen * iTagUseCnt;

    if(( buf = (char *) malloc( (size_t) iBufSize )) == NULL ){
      iErrorStop = 110;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    if(( iRc = xbFseek( 544, SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 120;
      throw iRc;
    }

    if(( iRc = xbFread( buf, (size_t) iBufSize, 1 )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }

    xbInt16 iPos;
    char    *p;
    xbMdxTag *tte;
    xbMdxTag *ttel = NULL;

    for( xbInt16 i = 0; i < iTagUseCnt; i++ ){
      iPos = i * iTagLen;
      p = buf + iPos;

      if(( tte = (xbMdxTag *) calloc( 1, (size_t) sizeof( xbMdxTag ))) == NULL ){
        iErrorStop = 140;
        iRc = XB_NO_MEMORY;
        throw iRc;
      }

      // set the current tag to the first tag in the table
      if( !vpCurTag )
        xbIx::SetCurTag( (void *) tte );

      if( mdxTagTbl )
        ttel->next = tte;
      else
        mdxTagTbl = tte;

      ttel = tte;
      tte->next = NULL;
      tte->ulTagHdrPageNo = eGetUInt32( p );

      p += 4;
      for( xbUInt32 i = 0; i < 11; i ++ )
        tte->cTagName[i] = *p++;

      tte->cTagName[11] = 0x00;
      tte->cKeyFmt        = *p++;
      tte->cLeftChild     = *p++;
      tte->cRightChild    = *p++;
      tte->cParent        = *p++;
      tte->c2             = *p++;
      tte->cKeyType       = *p;
      tte->sTagName = new xbString();
      tte->sTagName->Set( tte->cTagName );
      tte->sTagName->Trim();

      if(( iRc = LoadTagDetail( 1, tte )) != XB_NO_ERROR ){
        iErrorStop = 150;
        throw iRc;
      }
    }
    if( buf )
      free( buf );
  }
  catch (xbInt16 iRc ){
    if( buf )
      free( buf );
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::LoadTagTable() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    if( iErrorStop == 100 ){
      sMsg.Sprintf( "xbIxMdx::LoadTagTable() Invalid Tag Count: %d", iTagUseCnt );
      xbase->WriteLogMessage( sMsg.Str());
    }
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}

/**************************************************************************************************************/
//! @brief Calculate the block number for a given page.
/*!
  This routine is called by any function needing to calculate the block number for a given page.
  Page numbers are stored internally in the physical file, and the library reads and writes in
  blocks of one or more pages.

  Assumes valid data input

  \param ulPageNo Page Number
  \returns Calculated block number.
*/

inline xbUInt32 xbIxMdx::PageToBlock( xbUInt32 ulPageNo ){
  return ulPageNo / (xbUInt32) iBlockFactor;
}



/**************************************************************************************************************/
#ifdef XB_DEBUG_SUPPORT
xbInt16 xbIxMdx::PrintKey( void *vpTag, xbIxNode *npNode, xbInt16 iKeyNo, xbInt16 iDepth, char cType, xbInt16 iOutputOpt ){

  xbString sPre;
  sPre.Sprintf( "%c ", cType );
  for( xbInt16 i = 0; i < iDepth; i++ )
    sPre += "|";

  xbString sPost;
  sPost.Sprintf( "\tThisBlock=[%ld] KeyNo=[%d] Depth=[%d]", npNode->ulBlockNo, iKeyNo, iDepth );

  xbMdxTag * mpTag = (xbMdxTag *) vpTag;
  char *p = npNode->cpBlockData + (8 + (iKeyNo * mpTag->iKeyItemLen ));

  xbString sKeyPtr;
  xbUInt32 ulNoOfKeys = 0;
  if( cType == 'I' ) {       // interior
    sKeyPtr.Sprintf( " ptr=[%ld]", eGetUInt32( p ));
    ulNoOfKeys = eGetUInt32( mpTag->npCurNode->cpBlockData );
  }
  else if( cType == 'L' )   // leaf
    sKeyPtr.Sprintf( " rec=[%ld]", eGetUInt32( p ));
  p += 4;

  xbString s;
  if(( cType == 'I' && iKeyNo < (xbInt16) ulNoOfKeys) || cType == 'L' ){
    if( mpTag->cKeyType2 == 'C' ){         //CHAR
      for( xbInt32 l = 0; l < (mpTag->iKeyItemLen-4); l++ )
        s += *p++;

    } else if( mpTag->cKeyType2 == 'N' ){  // NUMERIC
      xbBcd bcd( p );
      xbString s2;
      bcd.ToString( s2 );
      s += s2;

    } else if( mpTag->cKeyType2 == 'D' ){  // DATE
      xbInt32 lDate = (xbInt32) eGetDouble( p );
      xbDate d( lDate );
      //xbString s2;
      //d.JulToDate8( lDate, s2 );
      s.Sprintf( "%s%s", s.Str(), d.Str());
    }
  } else {
    s = "Rightmost InteriorNode Pointer";
  }

  xbString sOut( sPre );
  sOut += s;
  sOut += sPost;
  sOut += sKeyPtr;

  xbase->WriteLogMessage( sOut, iOutputOpt );
  return XB_NO_ERROR;
}
#endif

/***********************************************************************/
//! @brief ReadHeadBlock.
/*!
  Read values off head block in MDX file
  \param iOpt 0 - Read entire block, initialize as needed.<br>
              1 - Read in only dynamic section of block<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>

*/

xbInt16 xbIxMdx::ReadHeadBlock( xbInt16 iOpt )
{
  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{
    if( !FileIsOpen()){
      iRc = XB_NOT_OPEN;
      iErrorStop = 100;
      throw iRc;
    }
    char sBuf[48];
    memset( sBuf, 0x00, 48 );

    if( iOpt == 0 ){
      if(( iRc = xbFseek( 0, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }

      if(( iRc = xbFread( sBuf, 47, 1 )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
    } else {

      if(( iRc = xbFseek( 28, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }

      if(( iRc = xbFread( sBuf, 19, 1 )) != XB_NO_ERROR ){
        iErrorStop = 140;
        throw iRc;
      }
    }

    char *p         = sBuf;
    if( iOpt == 0 ){
      cVersion         = *p++;
      cCreateYY        = *p++;
      cCreateMM        = *p++;
      cCreateDD        = *p++;
      sFileName.Assign( p, 1, 16 );
      p+=16;
      iBlockFactor     = eGetInt16( p );
      p+=2;
      SetBlockSize( (xbUInt32) eGetInt16( p ));
      p+=2;
      cProdIxFlag      = *p++;
      cTagEntryCnt     = *p++;
      iTagLen          = *p;
      p+=2;

      iTagUseCnt       = eGetInt16( p );
      //lTagUseCnt       = eGetInt32( p );
      //p+=4;
      p+=2;
      cNextTag         = *p++;
      c1B              = *p++;

      ulPageCnt        = eGetUInt32( p );
      p+=4;
      ulFirstFreePage  = eGetUInt32( p );
      p+=4;
      ulNoOfBlockAvail = eGetUInt32( p );
      p+=4;
      cUpdateYY        = *p++;
      cUpdateMM        = *p++;
      cUpdateDD        = *p;

      if( cNodeBuf )
        free( cNodeBuf );

      if(( cNodeBuf = (char *) malloc( (size_t) GetBlockSize())) == NULL ){
        iErrorStop = 150;
        throw XB_NO_MEMORY;
      }

      if(( iRc = xbIxMdx::LoadTagTable()) != XB_NO_ERROR ){
        iErrorStop = 160;
        throw iRc;
      }

    } else {
      iTagUseCnt       = eGetInt16( p );
      p+=4;
      ulPageCnt        = eGetUInt32( p );
      p+=4;
      ulFirstFreePage  = eGetUInt32( p );
      p+=4;
      ulNoOfBlockAvail = eGetUInt32( p );
      p+=4;
      cUpdateYY        = *p++;
      cUpdateMM        = *p++;
      cUpdateDD        = *p;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::ReadHeadBlock() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    if( cNodeBuf )
      free( cNodeBuf );
  }
  return iRc;
}

/***********************************************************************/
//! @brief Reindex
/*!
  Reindex specifed tag or all tags 
  \param **vpTag &tag - Tag to reindex.<br>
                 NULL - Reindex all tags<br>
  \returns <a href="xbretcod_8h.html">Return Codes</a>

  If this method fails, the index is left in an undefined state

*/

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

  xbInt16 iRc        = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbMdxTag * mpTag;
  #ifdef XB_LOCKING_SUPPORT
  xbBool  bLocked = xbFalse;
  #endif

  if( vpTag )
    mpTag = (xbMdxTag *) *vpTag;
  else
    mpTag = NULL;

  struct tagInfo{
    xbBool   bUnique;
    xbBool   bDesc;
    char     sTagName[11];
    xbString *sKeyExp;
    xbString *sFiltExp;
    tagInfo  *next;
  };
  tagInfo *ti = NULL;

  try{

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

    if( mpTag == NULL ){
      // do all tags
      xbMdxTag *tt = mdxTagTbl;
      tagInfo *pHead = NULL;
      tagInfo *pEnd  = NULL;

      if( tt ){
        while( tt ){
          ti = (tagInfo *) calloc( 1, sizeof( tagInfo ));
          ti->bUnique = tt->cUnique ? 1 : 0;
          ti->bDesc   = (((tt->cKeyFmt2 & 0x08) > 0) ? 1 : 0);
          memcpy( ti->sTagName, tt->cTagName, 11 );
          ti->sKeyExp = new xbString( tt->sKeyExp->Str());
          if( tt->cHasFilter )
            ti->sFiltExp = new xbString( tt->sFiltExp->Str());
          else
            ti->sFiltExp = new xbString( "" );
          if( !pHead )
            pHead = ti;
          else
            pEnd->next = ti;
          pEnd = ti;
          tt = tt->next;
        }
      }

      // get the file name and save it
      xbString sMdxFileName = GetFqFileName();

      // close the mdx file
      if(( iRc = xbIxMdx::Close()) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }

      // delete the file
      xbRemove();

      // init variables
      Init();

      tagInfo *p = pHead;
      tagInfo *pDel;

      // create new file & add the tags
      while( p ){

        if(( iRc = CreateTag( p->sTagName, p->sKeyExp->Str(), p->sFiltExp->Str(), p->bDesc, p->bUnique, xbTrue, vpTag )) != XB_NO_ERROR ){
          iErrorStop = 120;
          throw iRc;
        }
        delete p->sKeyExp;
        delete p->sFiltExp;
        pDel = p;
        p = p->next;
        free( pDel );
      }
    } else {
      if(( iRc = HarvestTagNodes( mpTag )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
    }

    xbUInt32 ulRecCnt = 0;
    if(( iRc = dbf->GetRecordCnt( ulRecCnt )) != XB_NO_ERROR ){
      iErrorStop = 140;
      throw iRc;
    }
    xbInt16  iCurTag = 0;
    xbBool   bDone = xbFalse;

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

      bDone   = xbFalse;
      iCurTag = 0;
      if( !vpTag )
        mpTag = (xbMdxTag *) GetTag( iCurTag++ );

      while( !bDone ){
        // do the tag things
        // CreateKey
        if(( iRc = CreateKey( mpTag, 1 )) != XB_NO_ERROR ){
          iErrorStop = 160;
          throw iRc;
        }
        if( mpTag->iKeySts == XB_ADD_KEY ){
          if( mpTag->cUnique ){
            if(( iRc = CheckForDupKey( mpTag )) != XB_NO_ERROR ){
              iErrorStop = 170;
              throw iRc;
            }
          }
          if(( iRc = AddKey( mpTag, ulRec )) != XB_NO_ERROR ){
            iErrorStop = 180;
            throw iRc;
          }
        }
        if( vpTag || iCurTag >= GetTagCount())
          bDone = xbTrue;
        else
          mpTag = (xbMdxTag *) GetTag( iCurTag++ );
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::ReIndex() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg.Str() );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    this->DeleteTag( mpTag );
  }

  #ifdef XB_LOCKING_SUPPORT
  if( bLocked ){
    dbf->LockTable( XB_UNLOCK );
  }
  #endif
  return iRc;
}

/***********************************************************************/
xbInt16 xbIxMdx::SetCurTag( xbString &sTagName ) {

  xbMdxTag *tt = (xbMdxTag *) GetTag( sTagName );
  if( tt ){
      xbIx::SetCurTag((void *) tt );
      return XB_NO_ERROR;
  } else
    return XB_INVALID_TAG;
}

/***********************************************************************/
xbInt16 xbIxMdx::SetCurTag( xbInt16 iTagNo ) {

  xbMdxTag *tt = (xbMdxTag *) GetTag( iTagNo );
  if( tt ){
      xbIx::SetCurTag((void *) tt );
      return XB_NO_ERROR;
  } else
    return XB_INVALID_TAG;
}

/***********************************************************************/
//! @brief SetReuseEmptyNode switch setting.
/*!
  \param  bEmptyNodeSw  xbFalse - Do not reuse empty MDX index nodes (Dbase 6. behavior).
                        xbTrue  - Reuse empty MDX index nodes.
*/

void xbIxMdx::SetReuseEmptyNodesSw( xbBool bEmptyNodesSw ) {
  bReuseEmptyNodes = bEmptyNodesSw;
}

/***********************************************************************/
//! @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 xbIxMdx::SplitNodeI( void *vpTag, xbIxNode * npLeft, xbIxNode *npRight, xbInt16 iSlotNo, xbUInt32 ulPtr ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  xbMdxTag * npTag = (xbMdxTag *) vpTag;
  xbDouble dSplitFactor = .5;                           // split the nodes 50/50
  xbInt16 iLen;
  char    *pSrc;
  char    *pTrg;

  try{
    xbInt32 lKeyCnt = GetKeyCount( npLeft );
    xbInt32 lNewLeftKeyCnt = (xbInt32) ((lKeyCnt + 1) * dSplitFactor);
    xbInt32 lNewRightKeyCnt = lKeyCnt - lNewLeftKeyCnt;
    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
    pSrc = npLeft->cpBlockData;
    pSrc += 8 + ((lNewLeftKeyCnt+1) * npTag->iKeyItemLen);
    pTrg = npRight->cpBlockData;
    pTrg += 8;
    iLen = (lNewRightKeyCnt * npTag->iKeyItemLen) + 4;
    memmove( pTrg, pSrc, (size_t) iLen );

    // eliminate chattle on the right
    iLen = 12 + (lNewLeftKeyCnt * npTag->iKeyItemLen);
    pSrc = npLeft->cpBlockData;
    pSrc += iLen;
    memset( pSrc, 0x00, npLeft->ulBufSize - (xbUInt32) 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( "xbIxMdx::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>
  
  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 xbIxMdx::SplitNodeL( void *vpTag, xbIxNode * npLeft, xbIxNode *npRight,
    xbInt16 iSlotNo, char * cpKeyBuf, xbUInt32 ulPtr ){

  xbInt16  iRc = XB_NO_ERROR;
  xbInt16  iErrorStop = 0;
  xbDouble dSplitFactor = .5;             // can adjust performance with this number
  xbMdxTag *mpTag = (xbMdxTag *) vpTag;
  xbString sMsg;

  xbInt16 iLen;
  char *pSrc;
  char *pTrg;

  // std::cout << "In xbIxMdx::SplitNodeL()\n";
  try{
    xbInt32 lKeyCnt = GetKeyCount( npLeft );
    xbInt32 lNewLeftKeyCnt = (xbInt32) ((lKeyCnt + 1) * dSplitFactor) + 1;
    xbInt32 lNewRightKeyCnt = lKeyCnt + 1 - lNewLeftKeyCnt;

    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 += 8 + (lNewLeftKeyCnt * mpTag->iKeyItemLen);
    pTrg = npRight->cpBlockData;
    pTrg += 8;
    iLen = lNewRightKeyCnt * mpTag->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 );

    // zero out the next key number so this node is not confused with interior node
    iLen = 8 + (lNewLeftKeyCnt * mpTag->iKeyItemLen);
    pSrc = npLeft->cpBlockData;
    pSrc += iLen;
    memset( pSrc, 0x00, npLeft->ulBufSize - (xbUInt32) iLen );

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

  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::SplitNodeL() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/**************************************************************************************************************/
//! @brief TagSerialNo.
/*!
  This routine is used internally for reading or updating the serial number on a given tag when the tag.

  \param iOption 1 - Read tag serial number off disk, save in structure<br>
                 2 - Write serial number from memory to disk<br>
                 3 - Read serial number off disk, increment, write updated number to disk<br>
         mpTag - Pointer to tag for serial number update
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbIxMdx::TagSerialNo( xbInt16 iOption, xbMdxTag * mpTag ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{
    xbInt64 lPos = (mpTag->ulTagHdrPageNo * 512) + 20;

    if( iOption != 2 ){
      if(( iRc = xbFseek( lPos, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }
      if(( iRc = xbFgetc( mpTag->cSerialNo )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
    }

    if( iOption == 3 )
      mpTag->cSerialNo++;

    if( iOption != 1 ){
      if(( iRc = xbFseek( lPos, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
      if(( iRc = xbFwrite( &mpTag->cSerialNo, 1, 1 )) != XB_NO_ERROR ){
        iErrorStop = 130;
        throw iRc;
      }
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::UpdateSerialNo() 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  xbIxMdx::UpdateTagKey( char cAction, void *vpTag, xbUInt32 ulRecNo ){


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

  try{
    // save off any needed fields for updating
    xbUInt32 ulTagSizeSave    = npTag->ulTagSize;

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

    if( cAction == 'A' || cAction == 'R' ){
      if(( iRc = AddKey( vpTag, ulRecNo )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
    }
    if( ulTagSizeSave != npTag->ulTagSize ){
      if(( iRc = UpdateTagSize( npTag, npTag->ulTagSize )) != XB_NO_ERROR) {
        iErrorStop = 120;
        throw iRc;
      }
    }
    // update the serial number
    if(( iRc = TagSerialNo( 3, npTag )) != XB_NO_ERROR ){
      iErrorStop = 130;
      throw iRc;
    }

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

/**************************************************************************************************************/
//! @brief Write head block.
/*!
  This routine updates the MDX file header and commits changes to disk.
  The file header is considered to be the first 2048 bytes in the file.

  \param iOption 0 - Entire 2048 byte header, used for creating a new mdx file.<br>
                 1 - Bytes 28 through 46, used when adding or deleting a tag.<br>
                 2 - Bytes 32 through 46, used after updating keys in the file.
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/


xbInt16 xbIxMdx::WriteHeadBlock( xbInt16 iOption ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;

  try{
    xbDate d;
    d.Sysdate();   // set to system date, today
    cUpdateYY = (char) d.YearOf() - 1900;
    cUpdateMM = (char) d.MonthOf();
    cUpdateDD = (char) d.DayOf( XB_FMT_MONTH );

    if( iOption >  0 ){
      char buf[48];
      memset( buf, 0x00, 48 );
      xbUInt32 ulStartPos = 0;
      xbUInt32 ulLen = 0;

      if( iOption == 1 ){
        ePutInt16( &buf[28], iTagUseCnt );
        buf[30] = cNextTag;
        buf[31] = 0x1b;
        ulStartPos = 28;
        ulLen = 19;
      } else {
        ulStartPos = 32;
        ulLen = 16;
      }

      ePutUInt32( &buf[32], ulPageCnt );
      ePutUInt32( &buf[36], ulFirstFreePage );
      ePutUInt32( &buf[40], ulNoOfBlockAvail );
      buf[44]   = cUpdateYY;
      buf[45]   = cUpdateMM;
      buf[46]   = cUpdateDD;

      if(( iRc = xbFseek( ulStartPos, SEEK_SET )) != XB_NO_ERROR ){
        iErrorStop = 100;
        throw iRc;
      }

      if(( iRc = xbFwrite( &buf[ulStartPos], ulLen, 1 )) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }

    } else if( iOption == 0 ){
      char buf[2048];
      memset( buf, 0x00, 2048 );

      buf[0] = cVersion;
      cCreateYY = cUpdateYY;
      cCreateMM = cUpdateMM;
      cCreateDD = cUpdateDD;
      buf[1] = cCreateYY;
      buf[2] = cCreateMM;
      buf[3] = cCreateDD;


      for( xbUInt32 l = 0; l < sFileName.Len() && l < 10; l++ ){
        buf[l+4] = sFileName[l+1];
      }

      ePutInt16( &buf[20], iBlockFactor );
      ePutInt16( &buf[22], (xbInt16) GetBlockSize() );

      buf[24]   = cProdIxFlag;
      buf[25]   = cTagEntryCnt;
      ePutInt16 ( &buf[26], iTagLen );
      ePutInt16 ( &buf[28], iTagUseCnt );
      buf[30]   = cNextTag;
      buf[31]   = c1B;
      ePutUInt32( &buf[32], ulPageCnt );
      ePutUInt32( &buf[36], ulFirstFreePage );
      ePutUInt32( &buf[40], ulNoOfBlockAvail );
      buf[44]   = cUpdateYY;
      buf[45]   = cUpdateMM;
      buf[46]   = cUpdateDD;

      // not sure what the following "1" is for in a sea of zeroes....
      // maybe it's current tag or default tag or something along those lines?
      buf[529]  = 0x01;

      xbRewind();
      if(( iRc = xbFwrite( buf, 2048, 1 )) != XB_NO_ERROR ){
        iErrorStop = 120;
        throw iRc;
      }
    } else {
      iErrorStop = 130;
      iRc = XB_INVALID_OPTION;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::WriteHeadBlock() Exception Caught. Error Stop = [%d] iRc = [%d] option = [%d]", iErrorStop, iRc, iOption );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}
/***********************************************************************/
xbInt16 xbIxMdx::UpdateTagSize( xbMdxTag *mpTag, xbUInt32 ulTagSz ){

  xbInt16 iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char    buf[4];
  try{
    ePutUInt32( &buf[0], ulTagSz );
    if(( iRc = xbFseek( (xbInt64) ((mpTag->ulTagHdrPageNo *512 )+ 4), SEEK_SET )) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }
    if(( iRc = xbFwrite( &buf[0], 4, 1 )) != XB_NO_ERROR ){
      iErrorStop = 110;
      throw iRc;
    }
  }
  catch (xbInt16 iRc ){
    xbString sMsg;
    sMsg.Sprintf( "xbIxMdx::UpdateTagSize() Exception Caught. Error Stop = [%d] iRc = [%d]", iErrorStop, iRc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
  }
  return iRc;
}


/***********************************************************************/
//void xbIxMdx::TestStub( char *s, void *vpTag ){
void xbIxMdx::TestStub( char *, void * ){
}
/***********************************************************************/
}              /* namespace       */
#endif         /*  XB_MDX_SUPPORT */