File: bltTree.c

package info (click to toggle)
blt 2.5.3%2Bdfsg-3
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 24,864 kB
  • sloc: ansic: 133,724; tcl: 17,680; sh: 2,722; makefile: 799; cpp: 370
file content (3988 lines) | stat: -rw-r--r-- 109,511 bytes parent folder | download | duplicates (5)
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

/*
 * bltTree.c --
 *
 * Copyright 1998-1999 Lucent Technologies, Inc.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that the copyright notice and warranty
 * disclaimer appear in supporting documentation, and that the names
 * of Lucent Technologies or any of their entities not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.
 *
 * Lucent Technologies disclaims all warranties with regard to this
 * software, including all implied warranties of merchantability and
 * fitness.  In no event shall Lucent Technologies be liable for any
 * special, indirect or consequential damages or any damages
 * whatsoever resulting from loss of use, data or profits, whether in
 * an action of contract, negligence or other tortuous action, arising
 * out of or in connection with the use or performance of this
 * software.
 *
 *	The "tree" data object was created by George A. Howlett.
 *      Extensive cleanups and enhancements by Peter MacDonald.
 *
 */

#include "bltInt.h"

/* TODO:
 *	traces and notifiers should be in one list in tree object.
 *	notifier is always fired.
 *	incorporate first/next tag routines ?
 */


#ifndef NO_TREE

#include "bltTree.h"


static int IsTclDict(Tcl_Interp *interp,Tcl_Obj *objPtr) {
   static Tcl_ObjType *dictType = NULL;

   if (dictType == NULL) {
        Tcl_Obj * obj;
        obj = Tcl_NewDictObj();
        dictType = (Tcl_ObjType *)obj->typePtr;
        Tcl_DecrRefCount(obj);
   }
   return (objPtr->typePtr == dictType);
}

/* 2 = per-tree key, 1 for per-interp, 0 for global (original behavior). */
int bltTreeUseLocalKeys = 0;

static Tcl_InterpDeleteProc TreeInterpDeleteProc;
static Blt_TreeApplyProc SizeApplyProc;
static Tcl_IdleProc NotifyIdleProc;

#define TREE_THREAD_KEY		"BLT Tree Data"
#define TREE_MAGIC		((unsigned int) 0x46170277)
#define TREE_DESTROYED		(1<<0)

typedef struct Blt_TreeNodeStruct Node;
typedef struct Blt_TreeClientStruct TreeClient;
typedef struct Blt_TreeObjectStruct TreeObject;
typedef struct Blt_TreeValueStruct Value;

/*
 * Blt_TreeValue --
 *
 *	Tree nodes contain heterogeneous data fields, represented as a
 *	chain of these structures.  Each field contains the key of the
 *	field (Blt_TreeKey) and the value (Tcl_Obj) containing the
 *	actual data representations.
 * 
 */
struct Blt_TreeValueStruct {
    Blt_TreeKey key;		/* String identifying the data field */
    Tcl_Obj *objPtr;		/* Data representation. */
    Blt_Tree owner;		/* Non-NULL if privately owned. */
    Blt_TreeValue next;		/* Next value in the chain. */
};

#include <stdio.h>
#include <string.h>
/* The following header is required for LP64 compilation */
#include <stdlib.h>

#include "bltHash.h"

static void TreeDestroyValues _ANSI_ARGS_((Blt_TreeNode node));

static Value *TreeFindValue _ANSI_ARGS_((Blt_TreeNode node,
	Blt_TreeKey key));
static Value *TreeCreateValue _ANSI_ARGS_((Blt_TreeNode node,
	Blt_TreeKey key, int *newPtr));

static int TreeDeleteValue _ANSI_ARGS_((Blt_TreeNode node, 
	Blt_TreeValue value));

static Value *TreeFirstValue _ANSI_ARGS_((Blt_TreeNode, 
	Blt_TreeKeySearch *searchPtr));

static Value *TreeNextValue _ANSI_ARGS_((Blt_TreeKeySearch *srchPtr));

/*
 * When there are this many entries per bucket, on average, rebuild
 * the hash table to make it larger.
 */

#define REBUILD_MULTIPLIER	3

#if (SIZEOF_VOID_P == 8)
#define RANDOM_INDEX(i)		HashOneWord(mask, downshift, i)
#define BITSPERWORD		64
#define START_LOGSIZE		10 
#define MAX_LIST_VALUES		40 
#else 

#define START_LOGSIZE		5 /* Initial hash table size is 32. */
#define MAX_LIST_VALUES		21 /* Convert to hash table when node
				    * value list gets bigger than this
				    * many values. */

/*
 * The following macro takes a preliminary integer hash value and
 * produces an index into a hash tables bucket list.  The idea is
 * to make it so that preliminary values that are arbitrarily similar
 * will end up in different buckets.  The hash function was taken
 * from a random-number generator.
 */
#define RANDOM_INDEX(i) \
    (((((long) (i))*1103515245) >> downshift) & mask)
#define BITSPERWORD		32
#endif

#define DOWNSHIFT_START		(BITSPERWORD - 2) 

/*
 * Procedure prototypes for static procedures in this file:
 */


#if (SIZEOF_VOID_P == 8)
static Blt_Hash HashOneWord _ANSI_ARGS_((uint64_t mask, unsigned int downshift,
	CONST void *key));

#endif /* SIZEOF_VOID_P == 8 */

/*
 * The hash table below is used to keep track of all the Blt_TreeKeys
 * created so far.
 */
static Blt_HashTable keyTable;
static int keyTableInitialized = 0;

typedef struct {
    Blt_HashTable treeTable;	/* Table of trees. */
    unsigned int nextId;
    Tcl_Interp *interp;
    Blt_HashTable keyTable;
} TreeInterpData;

typedef struct {
    Tcl_Interp *interp;
    ClientData clientData;
    Blt_TreeKey key;
    unsigned int mask;
    Blt_TreeNotifyEventProc *proc;
    Blt_TreeNotifyEvent event;
    int notifyPending;
} EventHandler;

typedef struct {
    ClientData clientData;
    char *keyPattern;
    char *withTag;
    Node *nodePtr;
    unsigned int mask;
    Blt_TreeTraceProc *proc;
    TreeClient *clientPtr;
    Blt_ChainLink *linkPtr;
} TraceHandler;

/*
 * --------------------------------------------------------------
 *
 * GetTreeInterpData --
 *
 *	Creates or retrieves data associated with tree data objects
 *	for a particular thread.  We're using Tcl_GetAssocData rather
 *	than the Tcl thread routines so BLT can work with pre-8.0 
 *	Tcl versions that don't have thread support.
 *
 * Results:
 *	Returns a pointer to the tree interpreter data.
 *
 * -------------------------------------------------------------- 
 */
static TreeInterpData *
GetTreeInterpData(Tcl_Interp *interp)
{
    Tcl_InterpDeleteProc *proc;
    TreeInterpData *dataPtr;

    dataPtr = (TreeInterpData *)
	Tcl_GetAssocData(interp, TREE_THREAD_KEY, &proc);
    if (dataPtr == NULL) {
	dataPtr = Blt_Malloc(sizeof(TreeInterpData));
	assert(dataPtr);
	dataPtr->interp = interp;
	Tcl_SetAssocData(interp, TREE_THREAD_KEY, TreeInterpDeleteProc,
		 dataPtr);
	Blt_InitHashTable(&dataPtr->treeTable, BLT_STRING_KEYS);
	Blt_InitHashTable(&dataPtr->keyTable, BLT_STRING_KEYS);
    }
    return dataPtr;
}

/*
 * --------------------------------------------------------------
 *
 * NewNode --
 *
 *	Creates a new node in the tree without installing it.  The
 *	number of nodes in the tree is incremented and a unique serial
 *	number is generated for the node. 
 *
 *	Also, all nodes have a label.  If no label was provided (name
 *	is NULL) then automatically generate a serial number for the node.
 *
 * Results:
 *	Returns a pointer to the new node.
 *
 * -------------------------------------------------------------- 
 */
static Node *
NewNode(TreeObject *treeObjPtr, CONST char *name, int inode)
{
    Node *nodePtr;

    /* Create the node structure */
    nodePtr = Blt_PoolAllocItem(treeObjPtr->nodePool, sizeof(Node));
    nodePtr->inode = inode;
    nodePtr->treeObject = treeObjPtr;
    nodePtr->parent = NULL;
    nodePtr->depth = 0;
    nodePtr->flags = 0;
    nodePtr->next = nodePtr->prev = NULL;
    nodePtr->first = nodePtr->last = NULL;
    nodePtr->nChildren = 0;
    nodePtr->values = NULL;     
    nodePtr->logSize = 0;
    nodePtr->nValues = 0;
    nodePtr->label = NULL;
    if (name != NULL) {
	nodePtr->label = Blt_TreeKeyGet(NULL, treeObjPtr, name);
    }
    treeObjPtr->nNodes++;
    return nodePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ReleaseTagTable --
 *
 *---------------------------------------------------------------------- 
 */
static void
ReleaseTagTable(Blt_TreeTagTable *tablePtr)
{
    tablePtr->refCount--;
    if (tablePtr->refCount <= 0) {
	Blt_HashEntry *hPtr;
	Blt_HashSearch cursor;

	for(hPtr = Blt_FirstHashEntry(&tablePtr->tagTable, &cursor); 
	    hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	    Blt_TreeTagEntry *tPtr;

	    tPtr = Blt_GetHashValue(hPtr);
	    Blt_DeleteHashTable(&tPtr->nodeTable);
	    Blt_TreeTagRefDecr(tPtr);
	}
	Blt_DeleteHashTable(&tablePtr->tagTable);
	Blt_Free(tablePtr);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ResetDepths --
 *
 *	Called after moving a node, resets the depths of each node
 *	for the entire branch (node and it's decendants).  
 *
 * Results: 
 *	None.
 *
 * ---------------------------------------------------------------------- 
 */
static void
ResetDepths(
    Node *nodePtr,		/* Root node. */
    int depth)			/* Depth of the node. */
{
    nodePtr->depth = depth;
    /* Also reset the depth for each descendant node. */
    for (nodePtr = nodePtr->first; nodePtr != NULL; nodePtr = nodePtr->next) {
	ResetDepths(nodePtr, depth + 1);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * LinkBefore --
 *
 *	Inserts a link preceding a given link.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void
LinkBefore(
    Node *parentPtr,	/* Parent to hold the new entry. */
    Node *nodePtr,	/* New node to be inserted. */
    Node *beforePtr)	/* Node to link before. */
{
    if (parentPtr->first == NULL) {
	parentPtr->last = parentPtr->first = nodePtr;
    } else if (beforePtr == NULL) { /* Append onto the end of the chain */
	nodePtr->next = NULL;
	nodePtr->prev = parentPtr->last;
	parentPtr->last->next = nodePtr;
	parentPtr->last = nodePtr;
    } else {
	nodePtr->prev = beforePtr->prev;
	nodePtr->next = beforePtr;
	if (beforePtr == parentPtr->first) {
	    parentPtr->first = nodePtr;
	} else {
	    beforePtr->prev->next = nodePtr;
	}
	beforePtr->prev = nodePtr;
    }
    parentPtr->nChildren++;
    nodePtr->parent = parentPtr;
}


/*
 *----------------------------------------------------------------------
 *
 * UnlinkNode --
 *
 *	Unlinks a link from the chain. The link is not deallocated, 
 *	but only removed from the chain.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void
UnlinkNode(Node *nodePtr)
{
    Node *parentPtr;
    int unlinked;		/* Indicates if the link is actually
				 * removed from the chain. */
    parentPtr = nodePtr->parent;
    unlinked = FALSE;
    if (parentPtr->first == nodePtr) {
	parentPtr->first = nodePtr->next;
	unlinked = TRUE;
    }
    if (parentPtr->last == nodePtr) {
	parentPtr->last = nodePtr->prev;
	unlinked = TRUE;
    }
    if (nodePtr->next != NULL) {
	nodePtr->next->prev = nodePtr->prev;
	unlinked = TRUE;
    }
    if (nodePtr->prev != NULL) {
	nodePtr->prev->next = nodePtr->next;
	unlinked = TRUE;
    }
    if (unlinked) {
	parentPtr->nChildren--;
    }
    nodePtr->prev = nodePtr->next = nodePtr->parent = NULL;
}

/*
 * --------------------------------------------------------------
 *
 * FreeNode --
 *
 *	Unlinks a given node from the tree, removes its data, and
 *	frees memory allocated to the node.
 *
 * Results:
 *	None.
 *
 * -------------------------------------------------------------- 
 */
static void
FreeNode(TreeObject *treeObjPtr, Node *nodePtr)
{
    Blt_HashEntry *hPtr;

    /*
     * Destroy any data fields associated with this node.
     */
    TreeDestroyValues(nodePtr);
    UnlinkNode(nodePtr);
    treeObjPtr->nNodes--;
    hPtr = Blt_FindHashEntry(&treeObjPtr->nodeTable, (char *)(intptr_t)nodePtr->inode);
    assert(hPtr);
    Blt_DeleteHashEntry(&treeObjPtr->nodeTable, hPtr);
    nodePtr->inode = -1;
    nodePtr->flags = 0;
    Blt_PoolFreeItem(treeObjPtr->nodePool, (char *)nodePtr);
}

/*
 * --------------------------------------------------------------
 *
 * NewTreeObject --
 *
 *	Creates and initializes a new tree object. Trees always
 *	contain a root node, so one is allocated here.
 *
 * Results:
 *	Returns a pointer to the new tree object is successful, NULL
 *	otherwise.  If a tree can't be generated, interp->result will
 *	contain an error message.
 *
 * -------------------------------------------------------------- */
static TreeObject *
NewTreeObject(TreeInterpData *dataPtr, Tcl_Interp *interp, CONST char *treeName)
{
    TreeObject *treeObjPtr;
    int isNew;
    Blt_HashEntry *hPtr;

    treeObjPtr = Blt_Calloc(1, sizeof(TreeObject));
    if (treeObjPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't allocate tree", (char *)NULL);
	return NULL;
    }
    treeObjPtr->name = Blt_Strdup(treeName);
    treeObjPtr->interp = interp;
    treeObjPtr->valuePool = Blt_PoolCreate(BLT_FIXED_SIZE_ITEMS);
    treeObjPtr->nodePool = Blt_PoolCreate(BLT_FIXED_SIZE_ITEMS);
    treeObjPtr->clients = Blt_ChainCreate();
    treeObjPtr->depth = 1;
    treeObjPtr->flags = 0;
    treeObjPtr->maxKeyList = 0;
    if (bltTreeUseLocalKeys) {
        if (bltTreeUseLocalKeys>1) {
            treeObjPtr->interpKeyPtr = &treeObjPtr->keyTable;
        } else {
            treeObjPtr->interpKeyPtr = &dataPtr->keyTable;
        }
    }
    treeObjPtr->notifyFlags = 0;
    Blt_InitHashTable(&treeObjPtr->keyTable, BLT_STRING_KEYS);
    Blt_InitHashTableWithPool(&treeObjPtr->nodeTable, BLT_ONE_WORD_KEYS);

    hPtr = Blt_CreateHashEntry(&treeObjPtr->nodeTable, (char *)0, &isNew);
    treeObjPtr->root = NewNode(treeObjPtr, treeName, 0);
    Blt_SetHashValue(hPtr, treeObjPtr->root);

    treeObjPtr->tablePtr = &dataPtr->treeTable;
    treeObjPtr->hashPtr = Blt_CreateHashEntry(treeObjPtr->tablePtr, treeName, 
	&isNew);
    Blt_SetHashValue(treeObjPtr->hashPtr, treeObjPtr);

    return treeObjPtr;
}

static TreeObject *
FindTreeInNamespace(
    TreeInterpData *dataPtr,	/* Interpreter-specific data. */
    Tcl_Namespace *nsPtr,
    CONST char *treeName)
{
    Tcl_DString dString;
    char *name;
    Blt_HashEntry *hPtr;

    name = Blt_GetQualifiedName(nsPtr, treeName, &dString);
    hPtr = Blt_FindHashEntry(&dataPtr->treeTable, name);
    Tcl_DStringFree(&dString);
    if (hPtr != NULL) {
	return Blt_GetHashValue(hPtr);
    }
    return NULL;
}

/*
 * ----------------------------------------------------------------------
 *
 * GetTreeObject --
 *
 *	Searches for the tree object associated by the name given.
 *
 * Results:
 *	Returns a pointer to the tree if found, otherwise NULL.
 *
 * ----------------------------------------------------------------------
 */
static TreeObject *
GetTreeObject(Tcl_Interp *interp, CONST char *name, int flags)
{
    CONST char *treeName;
    Tcl_Namespace *nsPtr;	/* Namespace associated with the tree object.
				 * If NULL, indicates to look in first the
				 * current namespace and then the global
				 * for the tree. */
    TreeInterpData *dataPtr;	/* Interpreter-specific data. */
    TreeObject *treeObjPtr;

    treeObjPtr = NULL;
    if (Blt_ParseQualifiedName(interp, name, &nsPtr, &treeName) != TCL_OK) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't find namespace in \"", name, "\"", 
		(char *)NULL);
	return NULL;
    }
    dataPtr = GetTreeInterpData(interp);
    if (nsPtr != NULL) { 
	treeObjPtr = FindTreeInNamespace(dataPtr, nsPtr, treeName);
    } else { 
	if (flags & NS_SEARCH_CURRENT) {
	    /* Look first in the current namespace. */
	    nsPtr = Tcl_GetCurrentNamespace(interp);
	    treeObjPtr = FindTreeInNamespace(dataPtr, nsPtr, treeName);
	}
	if ((treeObjPtr == NULL) && (flags & NS_SEARCH_GLOBAL)) {
	    nsPtr = Tcl_GetGlobalNamespace(interp);
	    treeObjPtr = FindTreeInNamespace(dataPtr, nsPtr, treeName);
	}
    }
    return treeObjPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * TeardownTree --
 *
 *	Destroys an entire branch.  This is a special purpose routine
 *	used to speed up the final clean up of the tree.
 *
 * Results: 
 *	None.
 *
 * ---------------------------------------------------------------------- 
 */
static void
TeardownTree(TreeObject *treeObjPtr, Node *nodePtr)
{
    if (nodePtr->first != NULL) {
	Node *childPtr, *nextPtr;
	
	for (childPtr = nodePtr->first; childPtr != NULL; childPtr = nextPtr) {
	    nextPtr = childPtr->next;
	    TeardownTree(treeObjPtr, childPtr);
	}
    }
    if (nodePtr->values != NULL) {
	TreeDestroyValues(nodePtr);
    }
    Blt_PoolFreeItem(treeObjPtr->nodePool, (char *)nodePtr);
}

static void
DestroyTreeObject(char *treeObj)
{
    Blt_ChainLink *linkPtr;
    TreeClient *clientPtr;
    TreeObject *treeObjPtr = (TreeObject*)treeObj;
    
    if (treeObjPtr->flags & TREE_DESTROYED) return;
    treeObjPtr->flags |= TREE_DESTROYED;
    treeObjPtr->nNodes = 0;

    /* Remove the remaining clients. */
    for (linkPtr = Blt_ChainFirstLink(treeObjPtr->clients); linkPtr != NULL;
	linkPtr = Blt_ChainNextLink(linkPtr)) {
	clientPtr = Blt_ChainGetValue(linkPtr);
	Blt_ChainDestroy(clientPtr->events);
	Blt_ChainDestroy(clientPtr->traces);
	Blt_Free(clientPtr);
    }
    Blt_ChainDestroy(treeObjPtr->clients);

    TeardownTree(treeObjPtr, treeObjPtr->root);
    Blt_PoolDestroy(treeObjPtr->nodePool);
    Blt_PoolDestroy(treeObjPtr->valuePool);
    Blt_DeleteHashTable(&treeObjPtr->nodeTable);
    Blt_DeleteHashTable(&treeObjPtr->keyTable);

    if (treeObjPtr->hashPtr != NULL) {
	/* Remove the entry from the global tree table. */
	Blt_DeleteHashEntry(treeObjPtr->tablePtr, treeObjPtr->hashPtr); 
	if ((treeObjPtr->tablePtr->numEntries == 0) && (keyTableInitialized)) {
	    keyTableInitialized = FALSE;
	    Blt_DeleteHashTable(&keyTable);
	}
    }
    if (treeObjPtr->name != NULL) {
	Blt_Free(treeObjPtr->name);
    }
    Blt_Free(treeObjPtr);
}

/*
 * -----------------------------------------------------------------------
 *
 * TreeInterpDeleteProc --
 *
 *	This is called when the interpreter hosting the tree object
 *	is deleted from the interpreter.  
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Destroys all remaining trees and removes the hash table
 *	used to register tree names.
 *
 * ------------------------------------------------------------------------
 */
/* ARGSUSED */
static void
TreeInterpDeleteProc(
    ClientData clientData,	/* Interpreter-specific data. */
    Tcl_Interp *interp)
{
    TreeInterpData *dataPtr = clientData;
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    TreeObject *treeObjPtr;
    
    for (hPtr = Blt_FirstHashEntry(&dataPtr->treeTable, &cursor);
	 hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	treeObjPtr = (TreeObject *)Blt_GetHashValue(hPtr);
	treeObjPtr->hashPtr = NULL;
	treeObjPtr->delete = 1;
        Tcl_EventuallyFree(treeObjPtr, DestroyTreeObject);
         /*DestroyTreeObject(treeObjPtr); */
    }
    if (keyTableInitialized) {
	keyTableInitialized = FALSE;
	Blt_DeleteHashTable(&keyTable);
    }
    Blt_DeleteHashTable(&dataPtr->treeTable);
    Blt_DeleteHashTable(&dataPtr->keyTable);
    Tcl_DeleteAssocData(interp, TREE_THREAD_KEY);
    Blt_Free(dataPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * NotifyIdleProc --
 *
 *	Used to invoke event handler routines at some idle point.
 *	This routine is called from the Tcl event loop.  Errors
 *	generated by the event handler routines are backgrounded.
 *	
 * Results:
 *	None.
 *
 *---------------------------------------------------------------------- 
 */
static void
NotifyIdleProc(ClientData clientData)
{
    EventHandler *notifyPtr = clientData;
    int result;

    notifyPtr->notifyPending = FALSE;
    notifyPtr->mask |= TREE_NOTIFY_ACTIVE;
    result = (*notifyPtr->proc)(notifyPtr->clientData, &notifyPtr->event);
    notifyPtr->mask &= ~TREE_NOTIFY_ACTIVE;
    if (result != TCL_OK) {
	Tcl_BackgroundError(notifyPtr->interp);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * CheckEventHandlers --
 *
 *	Traverses the list of client event callbacks and checks
 *	if one matches the given event.  A client may trigger an
 *	action that causes the tree to notify it.  The can be
 *	prevented by setting the TREE_NOTIFY_FOREIGN_ONLY bit in
 *	the event handler.
 *
 *	If a matching handler is found, a callback may be called either
 *	immediately or at the next idle time depending upon the
 *	TREE_NOTIFY_WHENIDLE bit.  
 *
 *	Since a handler routine may trigger yet another call to
 *	itself, callbacks are ignored while the event handler is
 *	executing.
 *	
 * Results:
 *	None.
 *
 *---------------------------------------------------------------------- 
 */
static int
CheckEventHandlers(
    TreeClient *clientPtr,
    int isSource,		/* Indicates if the client is the source
				 * of the event. */
    Blt_TreeNotifyEvent *eventPtr)
{
    Blt_ChainLink *linkPtr, *nextPtr;
    EventHandler *notifyPtr;

    eventPtr->tree = clientPtr;
    for (linkPtr = Blt_ChainFirstLink(clientPtr->events); 
	linkPtr != NULL; linkPtr = nextPtr) {
	nextPtr = Blt_ChainNextLink(linkPtr);
	notifyPtr = Blt_ChainGetValue(linkPtr);
	if ((notifyPtr->mask & TREE_NOTIFY_ACTIVE) ||
	    (notifyPtr->mask & eventPtr->type) == 0) {
	    continue;		/* Ignore callbacks that are generated
				 * inside of a notify handler routine. */
	}
	if ((isSource) && (notifyPtr->mask & TREE_NOTIFY_FOREIGN_ONLY)) {
	    continue;		/* Don't notify yourself. */
	}
	if (notifyPtr->mask & TREE_NOTIFY_WHENIDLE) {
	    if (!notifyPtr->notifyPending) {
		notifyPtr->notifyPending = TRUE;
		notifyPtr->event = *eventPtr;
		Tcl_DoWhenIdle(NotifyIdleProc, notifyPtr);
	    }
	} else {
	    int result;

	    notifyPtr->mask |= TREE_NOTIFY_ACTIVE;
	    result = (*notifyPtr->proc) (notifyPtr->clientData, eventPtr);
	    notifyPtr->mask &= ~TREE_NOTIFY_ACTIVE;
	    if (result != TCL_OK) {
	        if (notifyPtr->mask & TREE_NOTIFY_BGERROR) {
		     Tcl_BackgroundError(notifyPtr->interp);
		}
	        return result;
	    }
	}
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NotifyClients --
 *
 *	Traverses the list of clients for a particular tree and
 *	notifies each client that an event occurred.  Clients 
 *	indicate interest in a particular event through a bit
 *	flag.  
 *
 *---------------------------------------------------------------------- 
 */
static int
NotifyClients(
    TreeClient *sourcePtr,
    TreeObject *treeObjPtr,
    Node *nodePtr,
    int eventFlag)
{
    Blt_ChainLink *linkPtr;
    Blt_TreeNotifyEvent event;
    TreeClient *clientPtr;
    int isSource, result;

    if (Tcl_InterpDeleted(treeObjPtr->interp) ||
            Tcl_InterpDeleted(sourcePtr->root->treeObject->interp)) {
        return TCL_OK;
    }
    event.type = eventFlag;
    event.inode = nodePtr->inode;

    /* 
     * Issue callbacks to each client indicating that a new node has
     * been created.
     */
    for (linkPtr = Blt_ChainFirstLink(treeObjPtr->clients);
	linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	clientPtr = Blt_ChainGetValue(linkPtr);
	isSource = (clientPtr == sourcePtr);
	result = CheckEventHandlers(clientPtr, isSource, &event);
	if (result != TCL_OK) {
	    return TCL_ERROR;
	}
        if (Blt_TreeNodeDeleted(nodePtr) || nodePtr->inode != event.inode) {
            return TCL_BREAK;
        }
     }
    return TCL_OK;
}

static void
FreeValue(Node *nodePtr, Value *valuePtr)
{
    if (valuePtr->objPtr != NULL) {
	Tcl_DecrRefCount(valuePtr->objPtr);
    }
    Blt_PoolFreeItem(nodePtr->treeObject->valuePool, valuePtr);
}


/* Public Routines */
/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeGetKey --
 *
 *	Given a string, returns a unique identifier for the string.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeKey
Blt_TreeGetKey(string)
    CONST char *string;		/* String to convert. */
{
    Blt_HashEntry *hPtr;
    int isNew;

    if (!keyTableInitialized) {
	Blt_InitHashTable(&keyTable, BLT_STRING_KEYS);
	keyTableInitialized = 1;
    }
    hPtr = Blt_CreateHashEntry(&keyTable, string, &isNew);
    return (Blt_TreeKey)Blt_GetHashKey(&keyTable, hPtr);
}

/*
*----------------------------------------------------------------------
*
* Blt_TreeKeyGet --
*
*	tree-unique keys.
*       TODO: use per-interp keyTable rather than global one.
*
*----------------------------------------------------------------------
*/
Blt_TreeKey
Blt_TreeKeyGet(interp, treeObjPtr, string)
    Tcl_Interp *interp;
    TreeObject *treeObjPtr;
    CONST char *string;		/* String to convert. */
{
    Blt_HashTable *tablePtr;
    Blt_HashEntry *hPtr;
    int isNew;

    tablePtr = NULL;
    if (treeObjPtr != NULL && treeObjPtr->interpKeyPtr != NULL) {
        tablePtr = treeObjPtr->interpKeyPtr;
    }
    if (tablePtr == NULL && interp != NULL && bltTreeUseLocalKeys != 0) {
        TreeInterpData *dataPtr;
        dataPtr = GetTreeInterpData(interp);
        tablePtr = &dataPtr->keyTable;
    }
    if (tablePtr == NULL) {
        return Blt_TreeGetKey(string);
    }
    hPtr = Blt_CreateHashEntry(tablePtr, string, &isNew);
    return (Blt_TreeKey)Blt_GetHashKey(tablePtr, hPtr);
}

/* Clear the unmodified flag for node. */
static void SetModified(Node *nodePtr)
{
    nodePtr->flags &= ~TREE_NODE_UNMODIFIED;
    nodePtr->treeObject->flags &= ~TREE_UNMODIFIED;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeCreateNode --
 *
 *	Creates a new node in the given parent node.  The name and
 *	position in the parent are also provided.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreeCreateNode(
    TreeClient *clientPtr,	/* The tree client that is creating
				 * this node.  If NULL, indicates to
				 * trigger notify events on behalf of
				 * the initiating client also. */
    Node *parentPtr,		/* Parent node where the new node will
				 * be inserted. */
    CONST char *name,		/* Name of node. */
    int pos)			/* Position in the parent's list of children
				 * where to insert the new node. */
{
    Blt_HashEntry *hPtr;
    Node *beforePtr;
    Node *nodePtr;	/* Node to be inserted. */
    TreeObject *treeObjPtr;
    int inode;
    int isNew;

    treeObjPtr = parentPtr->treeObject;

    /* Generate an unique serial number for this node.  */
    do {
	inode = treeObjPtr->nextInode++;
	hPtr = Blt_CreateHashEntry(&treeObjPtr->nodeTable,(char *)(intptr_t)inode, 
		   &isNew);
    } while (!isNew);
    nodePtr = NewNode(treeObjPtr, name, inode);
    Blt_SetHashValue(hPtr, nodePtr);

    if ((pos == -1) || (pos >= (int)parentPtr->nChildren)) {
	beforePtr = NULL;
    } else {
	beforePtr = parentPtr->first;
	while ((pos > 0) && (beforePtr != NULL)) {
	    pos--;
	    beforePtr = beforePtr->next;
	}
    }
    LinkBefore(parentPtr, nodePtr, beforePtr);
    nodePtr->depth = parentPtr->depth + 1;
    /* 
     * Issue callbacks to each client indicating that a new node has
     * been created.
     */
    if (NotifyClients(clientPtr, treeObjPtr, nodePtr, TREE_NOTIFY_CREATE) != TCL_OK) {
        nodePtr->flags |= TREE_NODE_INSERT_FAIL;
        Blt_TreeDeleteNode(clientPtr, nodePtr);
        return NULL;
    }
    treeObjPtr->flags &= ~TREE_UNMODIFIED;
    return nodePtr;
}
/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeInsertPost --
 *
 *	Trigger notify for -insert
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreeInsertPost(
    TreeClient *clientPtr,	/* The tree client that is creating
				 * this node.  If NULL, indicates to
				 * trigger notify events on behalf of
				 * the initiating client also. */
    Node *nodePtr)		    /*  node */
{
    if (NotifyClients(clientPtr, nodePtr->treeObject, nodePtr, TREE_NOTIFY_INSERT) != TCL_OK) {
        nodePtr->flags |= TREE_NODE_INSERT_FAIL;
        Blt_TreeDeleteNode(clientPtr, nodePtr);
        return NULL;
    }
    return nodePtr;
}

int
Blt_TreeNotifyGet(
    TreeClient *clientPtr,	/* The tree client that is creating
				 * this node.  If NULL, indicates to
				 * trigger notify events on behalf of
				 * the initiating client also. */
    Node *nodePtr)		    /*  node */
{
    if (nodePtr->nValues != 0) return TCL_OK;
    return NotifyClients(clientPtr, nodePtr->treeObject, nodePtr, TREE_NOTIFY_GET);
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeCreateNodeWithId --
 *
 *	Like Blt_TreeCreateNode, but provides a specific id to use
 *	for the node.  If the tree already contains a node by that
 *	id, NULL is returned.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreeCreateNodeWithId(
    TreeClient *clientPtr,
    Node *parentPtr,		/* Parent node where the new node will
				 * be inserted. */
    CONST char *name,		/* Name of node. */
    unsigned int inode,/* Requested id of the new node. If a
				 * node by this id already exists in the
				 * tree, no node is created. */
    int position)		/* Position in the parent's list of children
				 * where to insert the new node. */
{
    Blt_HashEntry *hPtr;
    Node *beforePtr;
    Node *nodePtr;	/* Node to be inserted. */
    TreeObject *treeObjPtr;
    int isNew, result;

    treeObjPtr = parentPtr->treeObject;
    hPtr = Blt_CreateHashEntry(&treeObjPtr->nodeTable,(char *)(intptr_t)inode, &isNew);
    if (!isNew) {
	return NULL;
    }
    nodePtr = NewNode(treeObjPtr, name, inode);
    Blt_SetHashValue(hPtr, nodePtr);

    if ((position == -1) || (position >= (int)parentPtr->nChildren)) {
	beforePtr = NULL;
    } else {
	beforePtr = parentPtr->first;
	while ((position > 0) && (beforePtr != NULL)) {
	    position--;
	    beforePtr = beforePtr->next;
	}
    }
    LinkBefore(parentPtr, nodePtr, beforePtr);
    nodePtr->depth = parentPtr->depth + 1;
    /* 
     * Issue callbacks to each client indicating that a new node has
     * been created.
     */
     result=NotifyClients(clientPtr, treeObjPtr, nodePtr, TREE_NOTIFY_CREATE);
     if (result != TCL_OK) {
         if (result != TCL_BREAK) {
             nodePtr->flags |= TREE_NODE_INSERT_FAIL;
             Blt_TreeDeleteNode(clientPtr, nodePtr);
         }
         return NULL;
     }
     treeObjPtr->flags &= ~TREE_UNMODIFIED;
     return nodePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeMoveNode --
 *
 *	Move an entry into a new location in the hierarchy.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
int
Blt_TreeMoveNode(
    TreeClient *clientPtr,
    Node *nodePtr, 
    Node *parentPtr, 
    Node *beforePtr)
{
    TreeObject *treeObjPtr = nodePtr->treeObject;
    int newDepth, result;

    if (nodePtr == beforePtr) {
	return TCL_ERROR;
    }
    if ((beforePtr != NULL) && (beforePtr->parent != parentPtr)) {
	return TCL_ERROR;
    }
    if (nodePtr->parent == NULL) {
	return TCL_ERROR;	/* Can't move root. */
    }
    /* Verify that the node isn't an ancestor of the new parent. */
    if (Blt_TreeIsAncestor(nodePtr, parentPtr)) {
	return TCL_ERROR;
    }
    /* 
    * Issue callbacks to each client indicating that a node has
    * been moved.
    */
    if (NotifyClients(clientPtr, treeObjPtr, nodePtr, TREE_NOTIFY_MOVE) != TCL_OK) {
        return TCL_ERROR;
    }

    UnlinkNode(nodePtr);
    /* 
     * Relink the node as a child of the new parent.
     */
    LinkBefore(parentPtr, nodePtr, beforePtr);
    newDepth = parentPtr->depth + 1;
    if (nodePtr->depth != newDepth) { 
	/* Reset the depths of all descendant nodes. */
	ResetDepths(nodePtr, newDepth);
    }
    /* 
    * Issue callbacks to each client indicating that a node has
    * been moved.
    */
    if ((result=NotifyClients(clientPtr, treeObjPtr, nodePtr, TREE_NOTIFY_MOVEPOST)) != TCL_OK) {
        return result;
    }

    return TCL_OK;
}

int
Blt_TreeDeleteNode(TreeClient *clientPtr, Node *nodePtr)
{
    TreeObject *treeObjPtr = nodePtr->treeObject;
    Node *childPtr, *nextPtr;
    int result;

    /* 
    * Issue callbacks to each client indicating that the node can
    * no longer be used.  
    */
    if (Blt_TreeNodeDeleted(nodePtr)) {
        return TCL_OK;
    }
    if ((nodePtr->flags & TREE_NODE_INSERT_FAIL) == 0 &&
        (result=NotifyClients(clientPtr, treeObjPtr, nodePtr, TREE_NOTIFY_DELETE)) != TCL_OK) {
        return result;
    }
    nodePtr->flags &= ~TREE_NODE_FIXED_FIELDS;

    /* In depth-first order, delete each descendant node. */
    for (childPtr = nodePtr->first; childPtr != NULL; childPtr = nextPtr) {
	nextPtr = childPtr->next;
	Blt_TreeDeleteNode(clientPtr, childPtr);
    }

    /* Now remove the actual node. */
    FreeNode(treeObjPtr, nodePtr);
    if (treeObjPtr->nodeTable.numEntries <= 1) {
        treeObjPtr->nextInode = 1;
    }
    return TCL_OK;
}

Blt_TreeNode
Blt_TreeGetNode(TreeClient *clientPtr, unsigned int inode)
{
    TreeObject *treeObjPtr = clientPtr->treeObject;
    Blt_HashEntry *hPtr;

    hPtr = Blt_FindHashEntry(&treeObjPtr->nodeTable, (char *)(intptr_t)inode);
    if (hPtr != NULL) {
	return (Blt_TreeNode)Blt_GetHashValue(hPtr);
    }
    return NULL;
}

/*
static Node*
GetNode(TreeObject *treeObjPtr, unsigned int inode)
{
    Blt_HashEntry *hPtr;

    hPtr = Blt_FindHashEntry(&treeObjPtr->nodeTable, (char *)(intptr_t)inode);
    if (hPtr != NULL) {
	return (Node*)Blt_GetHashValue(hPtr);
    }
    return NULL;
}
*/

Blt_TreeTrace
Blt_TreeCreateTrace(
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *keyPattern,
    CONST char *tagName,
    unsigned int mask,
    Blt_TreeTraceProc *proc,
    ClientData clientData)
{
    TraceHandler *tracePtr;

    tracePtr = Blt_Calloc(1, sizeof (TraceHandler));
    assert(tracePtr);
    tracePtr->linkPtr = Blt_ChainAppend(clientPtr->traces, tracePtr);
    if (keyPattern != NULL) {
	tracePtr->keyPattern = Blt_Strdup(keyPattern);
    }
    if (tagName != NULL) {
	tracePtr->withTag = Blt_Strdup(tagName);
    }
    tracePtr->clientPtr = clientPtr;
    tracePtr->proc = proc;
    tracePtr->clientData = clientData;
    tracePtr->mask = mask;
    tracePtr->nodePtr = nodePtr;
    return (Blt_TreeTrace)tracePtr;
}

void
Blt_TreeDeleteTrace(Blt_TreeTrace trace)
{
    TraceHandler *tracePtr = (TraceHandler *)trace;

    Blt_ChainDeleteLink(tracePtr->clientPtr->traces, tracePtr->linkPtr);
    if (tracePtr->keyPattern != NULL) {
	Blt_Free(tracePtr->keyPattern);
    }
    if (tracePtr->withTag != NULL) {
	Blt_Free(tracePtr->withTag);
    }
    Blt_Free(tracePtr);
}

int
Blt_TreeRelabelNode(TreeClient *clientPtr, Node *nodePtr, CONST char *string)
{
    int result;
    if ((result=NotifyClients(clientPtr, clientPtr->treeObject, nodePtr, 
		  TREE_NOTIFY_RELABEL)) != TCL_OK) {
	return result;
    }
    nodePtr->label = Blt_TreeKeyGet(NULL, clientPtr->treeObject,string);
    /* 
     * Issue callbacks to each client indicating that a new node has
     * been created.
     */
    SetModified(nodePtr);
    result = NotifyClients(clientPtr, clientPtr->treeObject, nodePtr, 
		  TREE_NOTIFY_RELABELPOST);
    return result;
}

int
Blt_TreeNotifyAttach(TreeClient *clientPtr)
{
    /* return NotifyClients(clientPtr, clientPtr->treeObject, clientPtr->root, 
		  TREE_NOTIFY_ATTACH); */
    return TCL_OK;
}


int
Blt_TreeRelabelNode2(Node *nodePtr, CONST char *string)
{
    nodePtr->label = Blt_TreeKeyGet(NULL, nodePtr->treeObject,string);
    SetModified(nodePtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeFindChild --
 *
 *	Searches for the named node in a parent's chain of siblings.  
 *
 *
 * Results:
 *	If found, the child node is returned, otherwise NULL.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreeFindChild(Node *parentPtr, CONST char *string)
{
    Blt_TreeKey label;
    register Node *nodePtr;
    
    label = Blt_TreeKeyGet(NULL, parentPtr->treeObject,string);
    for (nodePtr = parentPtr->first; nodePtr != NULL; nodePtr = nodePtr->next) {
	if (label == nodePtr->label) {
	    return nodePtr;
	}
    }
    return NULL;
}
/* 
 * Like Blt_TreeFindChild above, but looks forward firstN elements
 * from front, then falls back to reverse search starting from the end.
 * This speeds up insertion at the end of really long trees in treeview.
 * If firstN is < 0, just calls Blt_TreeFindChild.
 */
Blt_TreeNode
Blt_TreeFindChildRev(Node *parentPtr, CONST char *string, int firstN)
{
    Blt_TreeKey label;
    register Node *nodePtr, *endNode;
    int n;
    
    if (firstN<0) {
        return Blt_TreeFindChild(parentPtr, string);
    }
    label = Blt_TreeKeyGet(NULL, parentPtr->treeObject,string);
    for (nodePtr = parentPtr->first, n = 0;
        nodePtr != NULL && n < firstN;
        nodePtr = nodePtr->next, n++) {
        if (label == nodePtr->label) {
            return nodePtr;
        }
    }
    if (nodePtr == NULL) {
        return NULL;
    }
    endNode = nodePtr;
    for (nodePtr = parentPtr->last; nodePtr != NULL; nodePtr = nodePtr->prev) {
	if (label == nodePtr->label) {
	    return nodePtr;
	}
	if (nodePtr == endNode) break;
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeNodePosition --
 *
 *	Returns the position of the node in its parent's list of
 *	children.  The root's position is 0.
 *
 *----------------------------------------------------------------------
 */
int
Blt_TreeNodePosition(Node *nodePtr)
{
    Node *parentPtr;
    int count;

    count = 0;
    parentPtr = nodePtr->parent;
    if (parentPtr != NULL) {
	Node *childPtr;

	for (childPtr = parentPtr->first; childPtr != NULL; 
	     childPtr = childPtr->next) {
	    if (nodePtr == childPtr) {
		break;
	    }
	    count++;
	}
    }
    return count;
}


/*
 *----------------------------------------------------------------------
 *
 * Blt_TreePrevNode --
 *
 *	Returns the "previous" node in the tree.  This node (in 
 *	depth-first order) is its parent, if the node has no siblings
 *	that are previous to it.  Otherwise it is the last descendant 
 *	of the last sibling.  In this case, descend the sibling's
 *	hierarchy, using the last child at any ancestor, with we
 *	we find a leaf.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreePrevNode(Node *rootPtr, Node *nodePtr)
{
    Node *prevPtr;

    if (nodePtr == rootPtr) {
	return NULL;		/* The root is the first node. */
    }
    prevPtr = nodePtr->prev;
    if (prevPtr == NULL) {
	/* There are no siblings previous to this one, so pick the parent. */
	return nodePtr->parent;
    }
    /*
     * Traverse down the right-most thread, in order to select the
     * next entry.  Stop when we reach a leaf.
     */
    nodePtr = prevPtr;
    while ((prevPtr = nodePtr->last) != NULL) {
	nodePtr = prevPtr;
    }
    return nodePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeNextNode --
 *
 *	Returns the "next" node in relation to the given node.  
 *	The next node (in depth-first order) is either the first 
 *	child of the given node the next sibling if the node has
 *	no children (the node is a leaf).  If the given node is the 
 *	last sibling, then try it's parent next sibling.  Continue
 *	until we either find a next sibling for some ancestor or 
 *	we reach the root node.  In this case the current node is 
 *	the last node in the tree.
 *
 *----------------------------------------------------------------------
 */
Blt_TreeNode
Blt_TreeNextNode(Node *rootPtr, Node *nodePtr)
{
    Node *nextPtr;

    /* Pick the first sub-node. */
    nextPtr = nodePtr->first;
    if (nextPtr != NULL) {
	return nextPtr;
    }
    /* 
     * Back up until we can find a level where we can pick a 
     * "next sibling".  For the last entry we'll thread our 
     * way back to the root.  
     */
    while (nodePtr != rootPtr) {
	nextPtr = nodePtr->next;
	if (nextPtr != NULL) {
	    return nextPtr;
	}
	nodePtr = nodePtr->parent;
    }
    return NULL;		/* At root, no next node. */
}


int
Blt_TreeIsBefore(Node *n1Ptr, Node *n2Ptr)
{
    int depth;
    register int i;
    Node *nodePtr;

    if (n1Ptr == n2Ptr) {
	return FALSE;
    }
    depth = MIN(n1Ptr->depth, n2Ptr->depth);
    if (depth == 0) {		/* One of the nodes is root. */
	return (n1Ptr->parent == NULL);
    }
    /* 
     * Traverse back from the deepest node, until both nodes are at
     * the same depth.  Check if this ancestor node is the same for
     * both nodes.
     */
    for (i = n1Ptr->depth; i > depth; i--) {
	n1Ptr = n1Ptr->parent;
    }
    if (n1Ptr == n2Ptr) {
	return FALSE;
    }
    for (i = n2Ptr->depth; i > depth; i--) {
	n2Ptr = n2Ptr->parent;
    }
    if (n2Ptr == n1Ptr) {
	return TRUE;
    }

    /* 
     * First find the mutual ancestor of both nodes.  Look at each
     * preceding ancestor level-by-level for both nodes.  Eventually
     * we'll find a node that's the parent of both ancestors.  Then
     * find the first ancestor in the parent's list of subnodes.  
     */
    for (i = depth; i > 0; i--) {
	if (n1Ptr->parent == n2Ptr->parent) {
	    break;
	}
	n1Ptr = n1Ptr->parent;
	n2Ptr = n2Ptr->parent;
    }
    for (nodePtr = n1Ptr->parent->first; nodePtr != NULL; 
	 nodePtr = nodePtr->next) {
	if (nodePtr == n1Ptr) {
	    return TRUE;
	} else if (nodePtr == n2Ptr) {
	    return FALSE;
	}
    }
    return FALSE;
}

static int
CallTraces(
    Tcl_Interp *interp,
    TreeClient *sourcePtr,	/* Client holding a reference to the
				 * tree.  If NULL, indicates to
				 * execute all handlers, including
				 * those of the caller. */
    TreeObject *treeObjPtr,	/* Tree that was changed. */
    Node *nodePtr,		/* Node that received the event. */
    Blt_TreeKey key,
    unsigned int flags,
    int *cnt)
{
    Blt_ChainLink *l1Ptr, *l2Ptr;
    TreeClient *clientPtr;
    TraceHandler *tracePtr;
    unsigned int inode = nodePtr->inode;
    int result;

    for(l1Ptr = Blt_ChainFirstLink(treeObjPtr->clients); 
	l1Ptr != NULL; l1Ptr = Blt_ChainNextLink(l1Ptr)) {
	clientPtr = Blt_ChainGetValue(l1Ptr);
	for(l2Ptr = Blt_ChainFirstLink(clientPtr->traces); 
	    l2Ptr != NULL; l2Ptr = Blt_ChainNextLink(l2Ptr)) {
	    tracePtr = Blt_ChainGetValue(l2Ptr);
	    if ((tracePtr->mask & flags) == 0) {
		continue;	/* Flags don't match. */
	    }
	    if ((clientPtr == sourcePtr) && 
		(tracePtr->mask & TREE_TRACE_FOREIGN_ONLY)) {
		continue;	/* This client initiated the trace. */
	    }
	    if ((tracePtr->nodePtr != NULL) && (tracePtr->nodePtr != nodePtr)) {
		continue;	/* Nodes don't match. */
	    }
	    if ((tracePtr->keyPattern != NULL) && 
		(!Tcl_StringMatch(key, tracePtr->keyPattern))) {
		continue;	/* Key pattern doesn't match. */
	    }
	    if ((tracePtr->withTag != NULL) && 
		(!Blt_TreeHasTag(clientPtr, nodePtr, tracePtr->withTag))) {
		continue;	/* Doesn't have the tag. */
	    }
	    nodePtr->flags |= TREE_TRACE_ACTIVE;
	    *cnt += 1;
	    
	    Tcl_Preserve(treeObjPtr);
	    result = (*tracePtr->proc) (tracePtr->clientData, treeObjPtr->interp, 
		nodePtr, key, flags);
            if (result != TCL_OK) {
	        Tcl_Release(treeObjPtr);
                if ((tracePtr->mask & TREE_TRACE_BGERROR) && interp != NULL) {
                    Tcl_BackgroundError(interp);
                } else {
                    nodePtr->flags &= ~TREE_TRACE_ACTIVE;
                    return TCL_ERROR;
                }
	    }
             nodePtr->flags &= ~TREE_TRACE_ACTIVE;
             if (Blt_TreeNodeDeleted(nodePtr) || nodePtr->inode != inode) {
                 Tcl_Release(treeObjPtr);
                 return TCL_ERROR;
	    }
	    if (treeObjPtr->delete) {
                 Tcl_Release(treeObjPtr);
                 if (interp != NULL) {
                     Tcl_AppendResult(interp, "tree deleted", 0);
                 }
                 return TCL_ERROR;
            }
            Tcl_Release(treeObjPtr);
	    /* nodePtr = GetNode(treeObjPtr, inode);
            if (nodePtr == NULL) {
                if (interp != NULL) {
                    Tcl_AppendResult(interp, "node deleted", 0);
                }
                return TCL_ERROR;
            }*/
	}
    }
    return TCL_OK;
}

static Value *
GetTreeValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeKey key)
{
    register Value *valuePtr;

    valuePtr = TreeFindValue(nodePtr, key); 
    if (valuePtr == NULL) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't find field \"", key, "\"", 
			     (char *)NULL);
	}
	return NULL;
    }	
    if ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't access private field \"", 
			     key, "\"", (char *)NULL);
	}
	return NULL;
    }
    return valuePtr;
}

int
Blt_TreePrivateValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeKey key)
{
    Value *valuePtr;

    valuePtr = TreeFindValue(nodePtr, key); 
    if (valuePtr == NULL) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't find field \"", key, "\"", 
			     (char *)NULL);
	}
	return TCL_ERROR;
    }
    valuePtr->owner = clientPtr;
    return TCL_OK;
}

int
Blt_TreePublicValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeKey key)
{
    Value *valuePtr;

    valuePtr = TreeFindValue(nodePtr, key); 
    if (valuePtr == NULL) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't find field \"", key, "\"", 
			     (char *)NULL);
	}
	return TCL_ERROR;
    }
    if (valuePtr->owner != clientPtr) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "not the owner of \"", key, "\"", 
		     (char *)NULL);
	}
	return TCL_ERROR;
    }
    valuePtr->owner = NULL;
    return TCL_OK;
}

int
Blt_TreeValueExistsByKey(clientPtr, nodePtr, key)
    TreeClient *clientPtr;
    Node *nodePtr;
    Blt_TreeKey key;
{
    register Value *valuePtr;
    int cnt;
    TreeObject *treeObjPtr = nodePtr->treeObject;
    Tcl_Interp *interp = treeObjPtr->interp;

    valuePtr = GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key);
    if (valuePtr == NULL && (!(nodePtr->flags & TREE_TRACE_ACTIVE))) {
        if (CallTraces(interp, clientPtr, treeObjPtr, nodePtr, key, 
            TREE_TRACE_EXISTS, &cnt) != TCL_OK) {
            Tcl_ResetResult(interp);
        } else {
            valuePtr = GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key);
        }
    }
    if (valuePtr == NULL) {
	return FALSE;
    }
    return TRUE;
}

int
Blt_TreeGetValueByKey(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeKey key,
    Tcl_Obj **objPtrPtr)
{
    register Value *valuePtr;
    TreeObject *treeObjPtr = nodePtr->treeObject;
    int cnt = 0;

    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
	if (CallTraces(interp, clientPtr, treeObjPtr, nodePtr, key, 
		   TREE_TRACE_READ, &cnt) != TCL_OK) {
	    return TCL_ERROR;
        }
    }
    valuePtr = GetTreeValue(interp, clientPtr, nodePtr, key);
    if (valuePtr == NULL) {
        return TCL_ERROR;
    }
    *objPtrPtr = valuePtr->objPtr;
    return TCL_OK;
}

int
bltTreeGetValueByKey(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeKey key,
    Value** valuePtrPtr)
{
    register Value *valuePtr;
    TreeObject *treeObjPtr = nodePtr->treeObject;
    int cnt = 0;

    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
	if (CallTraces(interp, clientPtr, treeObjPtr, nodePtr, key, 
		   TREE_TRACE_READ, &cnt) != TCL_OK) {
	    return TCL_ERROR;
        }
    }
    valuePtr = GetTreeValue(interp, clientPtr, nodePtr, key);
    if (valuePtr == NULL) {
        return TCL_ERROR;
    }
    *valuePtrPtr = valuePtr;
    return TCL_OK;
}

static void
UpdateOldValue(
    TreeClient *clientPtr,
    Tcl_Obj *objPtr)
{
    if (clientPtr->oldValue != NULL) {
        Tcl_DecrRefCount(clientPtr->oldValue);
    }
    clientPtr->oldValue = objPtr;
}

void
Blt_TreeOldValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Tcl_Obj **oldPtr,
    Tcl_Obj *newPtr)
{
    if (newPtr) {
        if (clientPtr->oldValue != NULL) {
            Tcl_DecrRefCount(clientPtr->oldValue);
        }
        clientPtr->oldValue = newPtr;
        Tcl_IncrRefCount(clientPtr->oldValue);
    } else if (oldPtr != NULL) {
        *oldPtr = clientPtr->oldValue;
    }
}

int
Blt_TreeSetValueByKey(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    Blt_TreeKey key,		/* Identifies the field key. */
    Tcl_Obj *objPtr)		/* New value of field. */
{
    TreeObject *treeObjPtr;
    Value *valuePtr;
    unsigned int flags;
    int isNew = 0, cnt = 0;
    
    if (nodePtr == NULL) {
        return TCL_ERROR;
    }
    treeObjPtr = nodePtr->treeObject;
    assert(objPtr != NULL);
    if (nodePtr->flags & TREE_NODE_FIXED_FIELDS) {
        valuePtr = TreeFindValue(nodePtr, key); 
        if (valuePtr == NULL) {
            if (interp != NULL) {
                Tcl_AppendResult(interp, "fixed field \"", key, "\"", 
                    (char *)NULL);
            }
            return TCL_ERROR;
        }
    } else {
        valuePtr = TreeCreateValue(nodePtr, key, &isNew);
    }
    if ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't set private field \"", 
			     key, "\"", (char *)NULL);
	}
	return TCL_ERROR;
    }
    SetModified(nodePtr);
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
        UpdateOldValue(clientPtr, valuePtr->objPtr);
        valuePtr->objPtr = NULL;
    }
    if (objPtr != valuePtr->objPtr) {
	Tcl_IncrRefCount(objPtr);
	if (valuePtr->objPtr != NULL) {
	    Tcl_DecrRefCount(valuePtr->objPtr);
	}
	valuePtr->objPtr = objPtr;
    }
    flags = TREE_TRACE_WRITE;
    if (isNew) {
	flags |= TREE_TRACE_CREATE;
    }
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
	return CallTraces(interp, clientPtr, treeObjPtr, nodePtr, valuePtr->key, 
		flags, &cnt);
    }
    return TCL_OK;
}

int
Blt_TreeUnsetValueByKey(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    Blt_TreeKey key)		/* Name of field in node. */
{
    TreeObject *treeObjPtr = nodePtr->treeObject;
    Value *valuePtr;
    int cnt = 0;

    if (nodePtr->flags & TREE_NODE_FIXED_FIELDS) {
        if (interp != NULL) {
            Tcl_AppendResult(interp, "fixed field", 0);
        }
        return TCL_ERROR;
    }
    valuePtr = TreeFindValue(nodePtr, key);
    if (valuePtr == NULL) {
	return TCL_OK;		/* It's okay to unset values that don't
				 * exist in the node. */
    }
    if ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't unset private field \"", 
			     key, "\"", (char *)NULL);
	}
	return TCL_ERROR;
    }
    SetModified(nodePtr);
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
        UpdateOldValue(clientPtr, valuePtr->objPtr);
        valuePtr->objPtr = NULL;
    }
    TreeDeleteValue(nodePtr, valuePtr);
    return CallTraces(interp, clientPtr, treeObjPtr, nodePtr, key, TREE_TRACE_UNSET, &cnt);
}

static int
ParseParentheses(
    Tcl_Interp *interp,
    CONST char *string,
    char **leftPtr, 
    char **rightPtr)
{
    register char *p;
    char *left, *right;

    left = right = NULL;
    for (p = (char *)string; *p != '\0'; p++) {
	if (*p == '(') {
	    left = p;
	} else if (*p == ')') {
	    right = p;
	}
    }
    if (left != right) {
	if (((left != NULL) && (right == NULL)) ||
	    ((left == NULL) && (right != NULL)) ||
	    (left > right) || (right != (p - 1))) {
	    if (interp != NULL) {
		Tcl_AppendResult(interp, "bad array specification \"", string,
			     "\"", (char *)NULL);
	    }
	    return TCL_ERROR;
	}
    }
    *leftPtr = left;
    *rightPtr = right;
    return TCL_OK;
}

int
Blt_TreeGetValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *string,		/* String identifying the field in node. */
    Tcl_Obj **objPtrPtr)
{
    char *left, *right;
    int result;

    if (ParseParentheses(interp, string, &left, &right) != TCL_OK) {
	return TCL_ERROR;
    }
    if (left != NULL) {
        Tcl_DString kStr, iStr;
        Tcl_DStringInit(&kStr);
        Tcl_DStringInit(&iStr);
        Tcl_DStringAppend(&kStr, left+1, right-left-1);
        Tcl_DStringAppend(&iStr, string, left-string);
	result = Blt_TreeGetArrayValue(interp, clientPtr, nodePtr,
	   Tcl_DStringValue(&iStr), Tcl_DStringValue(&kStr), objPtrPtr);
	Tcl_DStringFree(&kStr);
	Tcl_DStringFree(&iStr);
    } else {
	result = Blt_TreeGetValueByKey(interp, clientPtr, nodePtr, 
		Blt_TreeKeyGet(NULL, clientPtr->treeObject,string), objPtrPtr);
    }
    return result;
}

int
Blt_TreeSetValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *string,		/* String identifying the field in node. */
    Tcl_Obj *valueObjPtr)	/* New value of field. If NULL, field
				 * is deleted. */
{
    char *left, *right;
    int result;

    if (nodePtr->flags & TREE_NODE_FIXED_FIELDS) {
        return Blt_TreeUpdateValue( interp, clientPtr, nodePtr, string, valueObjPtr);
    }
    if (ParseParentheses(interp, string, &left, &right) != TCL_OK) {
	return TCL_ERROR;
    }
    if (left != NULL) {
        Tcl_DString kStr, iStr;
        Tcl_DStringInit(&kStr);
        Tcl_DStringInit(&iStr);
        Tcl_DStringAppend(&kStr, left+1, right-left-1);
        Tcl_DStringAppend(&iStr, string, left-string);
        result = Blt_TreeSetArrayValue(interp, clientPtr, nodePtr,
	   Tcl_DStringValue(&iStr), Tcl_DStringValue(&kStr), valueObjPtr);
	Tcl_DStringFree(&kStr);
	Tcl_DStringFree(&iStr);
    } else {
	result = Blt_TreeSetValueByKey(interp, clientPtr, nodePtr, 
			       Blt_TreeKeyGet(NULL, clientPtr->treeObject,string), valueObjPtr);
    }
    return result;
}

int
Blt_TreeUpdateValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *string,		/* String identifying the field in node. */
    Tcl_Obj *valueObjPtr)	/* New value of field. If NULL, field
				 * is deleted. */
{
    char *left, *right;
    int result;
    Blt_TreeKey key;

    if (ParseParentheses(interp, string, &left, &right) != TCL_OK) {
	return TCL_ERROR;
    }
    if (left != NULL) {
        Tcl_DString kStr, iStr;
        Tcl_DStringInit(&kStr);
        Tcl_DStringInit(&iStr);
        Tcl_DStringAppend(&kStr, left+1, right-left-1);
        Tcl_DStringAppend(&iStr, string, left-string);
        result = Blt_TreeUpdateArrayValue(interp, clientPtr, nodePtr,
	   Tcl_DStringValue(&iStr), Tcl_DStringValue(&kStr), valueObjPtr);
	Tcl_DStringFree(&kStr);
	Tcl_DStringFree(&iStr);
    } else {
        key = Blt_TreeKeyGet(NULL, clientPtr->treeObject,string);
        if (GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key) == NULL) {
            if (interp != NULL) {
                Tcl_AppendResult(interp, "unknown key: ", string, 0);
            }
            return TCL_ERROR;
        }
        result = Blt_TreeSetValueByKey(interp, clientPtr, nodePtr, 
            key, valueObjPtr);
    }
    return result;
}

int
Blt_TreeUnsetValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *string)		/* String identifying the field in node. */
{
    char *left, *right;
    int result;

    if (nodePtr->flags & TREE_NODE_FIXED_FIELDS) {
        if (interp != NULL) {
            Tcl_AppendResult(interp, "fixed field", 0);
        }
        return TCL_ERROR;
    }
    if (ParseParentheses(interp, string, &left, &right) != TCL_OK) {
	return TCL_ERROR;
    }
    if (left != NULL) {
        Tcl_DString kStr, iStr;
        Tcl_DStringInit(&kStr);
        Tcl_DStringInit(&iStr);
        Tcl_DStringAppend(&kStr, left+1, right-left-1);
        Tcl_DStringAppend(&iStr, string, left-string);
        result = Blt_TreeUnsetArrayValue(interp, clientPtr, nodePtr,
	   Tcl_DStringValue(&iStr), Tcl_DStringValue(&kStr));
	Tcl_DStringFree(&kStr);
	Tcl_DStringFree(&iStr);
    } else {
	result = Blt_TreeUnsetValueByKey(interp, clientPtr, nodePtr, 
		Blt_TreeKeyGet(NULL, clientPtr->treeObject,string));
    }
    return result;
}

int
Blt_TreeValueExists(TreeClient *clientPtr, Node *nodePtr, CONST char *string)
{
    char *left, *right;
    int result;

    if (ParseParentheses((Tcl_Interp *)NULL, string, &left, &right) != TCL_OK) {
	return FALSE;
    }
    if (left != NULL) {
        Tcl_DString kStr, iStr;
        Tcl_DStringInit(&kStr);
        Tcl_DStringInit(&iStr);
        Tcl_DStringAppend(&kStr, left+1, right-left-1);
        Tcl_DStringAppend(&iStr, string, left-string);
        result = Blt_TreeArrayValueExists(clientPtr, nodePtr,
	   Tcl_DStringValue(&iStr), Tcl_DStringValue(&kStr));
	Tcl_DStringFree(&kStr);
	Tcl_DStringFree(&iStr);
    } else {
	result = Blt_TreeValueExistsByKey(clientPtr, nodePtr, 
		Blt_TreeKeyGet(NULL, clientPtr->treeObject,string));
    }
    return result;
}

Blt_TreeKey
Blt_TreeFirstKey(
    TreeClient *clientPtr, 
    Node *nodePtr, 
    Blt_TreeKeySearch *iterPtr)
{
    Value *valuePtr;
    
    valuePtr = TreeFirstValue(nodePtr, iterPtr);
    if (valuePtr == NULL) {
	return NULL;
    }
    while ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	valuePtr = TreeNextValue(iterPtr);
	if (valuePtr == NULL) {
	    return NULL;
	}
    }
    return valuePtr->key;
}

Blt_TreeKey
Blt_TreeNextKey(TreeClient *clientPtr, Blt_TreeKeySearch *iterPtr)
{
    Value *valuePtr;

    valuePtr = TreeNextValue(iterPtr);
    if (valuePtr == NULL) {
	return NULL;
    }
    while ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	valuePtr = TreeNextValue(iterPtr);
	if (valuePtr == NULL) {
	    return NULL;
	}
    }
    return valuePtr->key;
}

int Blt_TreeCountKeys(TreeClient *clientPtr, Node *nodePtr) {
    int cnt = 0;
    Blt_TreeKey key;
    Blt_TreeKeySearch cursor;
    
         
    for (key = Blt_TreeFirstKey(clientPtr, nodePtr, &cursor); key != NULL;
        key = Blt_TreeNextKey(clientPtr, &cursor)) {
        cnt++;
    }
    return cnt;
}


int
Blt_TreeIsAncestor(Node *n1Ptr, Node *n2Ptr)
{
    if (n2Ptr != NULL) {
	n2Ptr = n2Ptr->parent;
	while (n2Ptr != NULL) {
	    if (n2Ptr == n1Ptr) {
		return TRUE;
	    }
	    n2Ptr = n2Ptr->parent;
	}
    }
    return FALSE;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeSortNode --
 *
 *	Sorts the subnodes at a given node.
 *
 * Results:
 *	Always returns TCL_OK.
 *
 *----------------------------------------------------------------------
 */
int
Blt_TreeSortNode(
    TreeClient *clientPtr,
    Node *nodePtr,
    Blt_TreeCompareNodesProc *proc)
{
    Node **nodeArr;
    Node *childPtr;
    int nNodes;
    register Node **p;

    nNodes = nodePtr->nChildren;
    if (nNodes < 2) {
	return TCL_OK;
    }
    nodeArr = Blt_Malloc((nNodes + 1) * sizeof(Node *));
    if (nodeArr == NULL) {
	return TCL_ERROR;	/* Out of memory. */
    }
    for (p = nodeArr, childPtr = nodePtr->first; childPtr != NULL; 
	 childPtr = childPtr->next, p++) {
	*p = childPtr;
    }
    *p = NULL;

    qsort((char *)nodeArr, nNodes, sizeof(Node *), (QSortCompareProc *)proc);
    for (p = nodeArr; *p != NULL; p++) {
	UnlinkNode(*p);
	LinkBefore(nodePtr, *p, (Blt_TreeNode)NULL);
    }
    Blt_Free(nodeArr);
    return NotifyClients(clientPtr, nodePtr->treeObject, nodePtr, TREE_NOTIFY_SORT);
}

#define TEST_RESULT(result) \
	switch (result) { \
	case TCL_CONTINUE: \
	    return TCL_OK; \
	case TCL_OK: \
	    break; \
	default: \
	    return (result); \
	}

int
Blt_TreeApply(
    Node *nodePtr,		/* Root node of subtree. */
    Blt_TreeApplyProc *proc,	/* Procedure to call for each node. */
    ClientData clientData)	/* One-word of data passed when calling
				 * proc. */
{
    Node *childPtr, *nextPtr;
    int result;

    for (childPtr = nodePtr->first; childPtr != NULL; childPtr = nextPtr) {

	/* 
	 * Get the next link in the chain before calling Blt_TreeApply
	 * recursively.  This is because the apply callback may delete
	 * the node and its link.  
	 */

	nextPtr = childPtr->next;
        if (Blt_TreeNodeDeleted(childPtr)) return TCL_OK;
	result = Blt_TreeApply(childPtr, proc, clientData);
	TEST_RESULT(result);
    }
    if (Blt_TreeNodeDeleted(nodePtr)) return TCL_OK;
    return (*proc) (nodePtr, clientData, TREE_POSTORDER);
}

int
Blt_TreeApplyDFS(
    Node *nodePtr,		/* Root node of subtree. */
    Blt_TreeApplyProc *proc,	/* Procedure to call for each node. */
    ClientData clientData,	/* One-word of data passed when calling
				 * proc. */
    int order)			/* Order of traversal. */
{
    Node *childPtr, *nextPtr;
    int result;

    if (Blt_TreeNodeDeleted(nodePtr)) return TCL_OK;
    if (order & TREE_PREORDER) {
	result = (*proc) (nodePtr, clientData, TREE_PREORDER);
	TEST_RESULT(result);
    }
    childPtr = nodePtr->first;
    if (order & TREE_INORDER) {
	if (childPtr != NULL) {
	    result = Blt_TreeApplyDFS(childPtr, proc, clientData, order);
	    TEST_RESULT(result);
	    childPtr = childPtr->next;
	}
	result = (*proc) (nodePtr, clientData, TREE_INORDER);
	TEST_RESULT(result);
    }
    for (/* empty */; childPtr != NULL; childPtr = nextPtr) {
	/* 
	 * Get the next link in the chain before calling
	 * Blt_TreeApply recursively.  This is because the 
	 * apply callback may delete the node and its link.  
	 */
	nextPtr = childPtr->next;
	if (Blt_TreeNodeDeleted(childPtr)) break;
	result = Blt_TreeApplyDFS(childPtr, proc, clientData, order);
	TEST_RESULT(result);
    }
    if (Blt_TreeNodeDeleted(nodePtr)) return TCL_OK;
    if (order & TREE_POSTORDER) {
	return (*proc) (nodePtr, clientData, TREE_POSTORDER);
    }
    return TCL_OK;
}

int
Blt_TreeApplyBFS(nodePtr, proc, clientData)
    Node *nodePtr;		/* Root node of subtree. */
    Blt_TreeApplyProc *proc;	/* Procedure to call for each node. */
    ClientData clientData;	/* One-word of data passed when calling
				 * proc. */
{
    Blt_Chain *queuePtr;
    Blt_ChainLink *linkPtr, *nextPtr;
    Node *childPtr;
    int result;

    queuePtr = Blt_ChainCreate();
    linkPtr = Blt_ChainAppend(queuePtr, nodePtr);
    while (linkPtr != NULL) {
	nodePtr = Blt_ChainGetValue(linkPtr);
	/* Add the children to the queue. */
	for (childPtr = nodePtr->first; childPtr != NULL; 
	     childPtr = childPtr->next) {
	    Blt_ChainAppend(queuePtr, childPtr);
	}
	if (Blt_TreeNodeDeleted(nodePtr)) break;
	/* Process the node. */
	result = (*proc) (nodePtr, clientData, TREE_BREADTHFIRST);
	switch (result) { 
	case TCL_CONTINUE: 
	    Blt_ChainDestroy(queuePtr);
	    return TCL_OK; 
	case TCL_OK: 
	    break; 
	default: 
	    Blt_ChainDestroy(queuePtr);
	    return result; 
	}
	/* Remove the node from the queue. */
	nextPtr = Blt_ChainNextLink(linkPtr);
	Blt_ChainDeleteLink(queuePtr, linkPtr);
	linkPtr = nextPtr;
    }
    Blt_ChainDestroy(queuePtr);
    return TCL_OK;
}

static TreeClient *
NewTreeClient(TreeObject *treeObjPtr, int sharetags)
{
    TreeClient *clientPtr;

    clientPtr = Blt_Calloc(1, sizeof(TreeClient));
    if (clientPtr != NULL) {
	Blt_TreeTagTable *tablePtr;
	int hascl = (treeObjPtr->clients->headPtr != NULL);

	clientPtr->magic = TREE_MAGIC;
	clientPtr->linkPtr = Blt_ChainAppend(treeObjPtr->clients, clientPtr);
	clientPtr->events = Blt_ChainCreate();
	clientPtr->traces = Blt_ChainCreate();
	clientPtr->treeObject = treeObjPtr;
	clientPtr->root = treeObjPtr->root;
	if (sharetags && hascl) {
             TreeClient *ctPtr;
             ctPtr = Blt_ChainGetValue(treeObjPtr->clients->headPtr);
             if (ctPtr && ctPtr->tagTablePtr) {
                 clientPtr->tagTablePtr = ctPtr->tagTablePtr;
                 clientPtr->tagTablePtr->refCount++;
             }
         }
         if (clientPtr->tagTablePtr == NULL) {
             tablePtr = Blt_Malloc(sizeof(Blt_TreeTagTable));
             Blt_InitHashTable(&tablePtr->tagTable, BLT_STRING_KEYS);
             tablePtr->refCount = 1;
             clientPtr->tagTablePtr = tablePtr;
         }
    }
    return clientPtr;
}

int
Blt_TreeCreate(
    Tcl_Interp *interp,		/* Interpreter to report errors back to. */
    CONST char *name,		/* Name of tree in namespace.  Tree
				 * must not already exist. */
    TreeClient **clientPtrPtr)	/* (out) Client token of newly created
				 * tree.  Releasing the token will
				 * free the tree.  If NULL, no token
				 * is generated. */

{
    Tcl_DString dString;
    Tcl_Namespace *nsPtr;
    TreeInterpData *dataPtr;
    TreeObject *treeObjPtr;
    CONST char *treeName;
    char string[200];

    dataPtr = GetTreeInterpData(interp);
    if (name != NULL) {
	/* Check if this tree already exists the current namespace. */
	treeObjPtr = GetTreeObject(interp, name, NS_SEARCH_CURRENT);
	if (treeObjPtr != NULL) {
            if (interp != NULL)
	       Tcl_AppendResult(interp, "a tree object \"", name,
			     "\" already exists", (char *)NULL);
	    return TCL_ERROR;
	}
    } else {
	/* Generate a unique tree name in the current namespace. */
	do  {
	    sprintf(string, "tree%d", dataPtr->nextId++);
	} while (GetTreeObject(interp, string, NS_SEARCH_CURRENT) != NULL);
	name = string;
    } 
    /* 
     * Tear apart and put back together the namespace-qualified name 
     * of the tree. This is to ensure that naming is consistent.
     */ 
    treeName = name;
    if (Blt_ParseQualifiedName(interp, name, &nsPtr, &treeName) != TCL_OK) {
        if (interp != NULL)
	   Tcl_AppendResult(interp, "can't find namespace in \"", name, "\"", 
		(char *)NULL);
	return TCL_ERROR;
    }
    if (nsPtr == NULL) {
	/* 
	 * Note: Unlike Tcl_CreateCommand, an unqualified name 
	 * doesn't imply the global namespace, but the current one.
	 */
	nsPtr = Tcl_GetCurrentNamespace(interp);
    }
    name = Blt_GetQualifiedName(nsPtr, treeName, &dString);
    treeObjPtr = NewTreeObject(dataPtr, interp, name);
    if (treeObjPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't allocate tree \"", name, "\"", 
		(char *)NULL);
	Tcl_DStringFree(&dString);
	return TCL_ERROR;
    }
    Tcl_DStringFree(&dString);
    if (clientPtrPtr != NULL) {
	TreeClient *clientPtr;
	
	clientPtr = NewTreeClient(treeObjPtr, 0);
	if (clientPtr == NULL) {
            if (interp != NULL)
	       Tcl_AppendResult(interp, "can't allocate tree token",(char *)NULL);
	    return TCL_ERROR;
	}
	*clientPtrPtr = clientPtr;
    }
    return TCL_OK;
}

int
Blt_TreeGetToken(
    Tcl_Interp *interp,		/* Interpreter to report errors back to. */
    CONST char *name,		/* Name of tree in namespace. */
    TreeClient **clientPtrPtr)
{
    TreeClient *clientPtr;
    TreeObject *treeObjPtr;

    treeObjPtr = GetTreeObject(interp, name, NS_SEARCH_BOTH);
    if (treeObjPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't find a tree object \"", name, "\"", 
			 (char *)NULL);
	return TCL_ERROR;
    }
    clientPtr = NewTreeClient(treeObjPtr, 0);
    if (clientPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't allocate token for tree \"", 
			 name, "\"", (char *)NULL);
	return TCL_ERROR;
    }
    *clientPtrPtr = clientPtr;
    return TCL_OK;
}

int
Blt_TreeGetTokenTag(
    Tcl_Interp *interp,		/* Interpreter to report errors back to. */
    CONST char *name,		/* Name of tree in namespace. */
    TreeClient **clientPtrPtr)
{
    TreeClient *clientPtr;
    TreeObject *treeObjPtr;

    treeObjPtr = GetTreeObject(interp, name, NS_SEARCH_BOTH);
    if (treeObjPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't find a tree object \"", name, "\"", 
			 (char *)NULL);
	return TCL_ERROR;
    }
    clientPtr = NewTreeClient(treeObjPtr, 1);
    if (clientPtr == NULL) {
        if (interp != NULL)
            Tcl_AppendResult(interp, "can't allocate token for tree \"", 
			 name, "\"", (char *)NULL);
	return TCL_ERROR;
    }
    *clientPtrPtr = clientPtr;
    return TCL_OK;
}

void
Blt_TreeReleaseToken(TreeClient *clientPtr)
{
    TreeObject *treeObjPtr;
    Blt_ChainLink *linkPtr;
    EventHandler *notifyPtr;
    TraceHandler *tracePtr;

    if (clientPtr->magic != TREE_MAGIC) {
	fprintf(stderr, "invalid tree object token 0x%lx\n", 
		(unsigned long)clientPtr);
	return;
    }
    /* Remove any traces that may be set. */
    for (linkPtr = Blt_ChainFirstLink(clientPtr->traces); linkPtr != NULL;
	 linkPtr = Blt_ChainNextLink(linkPtr)) {
	tracePtr = Blt_ChainGetValue(linkPtr);
	if (tracePtr->keyPattern != NULL) {
	    Blt_Free(tracePtr->keyPattern);
	}
	Blt_Free(tracePtr);
    }
    Blt_ChainDestroy(clientPtr->traces);
    /* And any event handlers. */
    for(linkPtr = Blt_ChainFirstLink(clientPtr->events); 
	linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	notifyPtr = Blt_ChainGetValue(linkPtr);
	if (notifyPtr->notifyPending) {
	    Tcl_CancelIdleCall(NotifyIdleProc, notifyPtr);
	}
	Blt_Free(notifyPtr);
    }
    if (clientPtr->tagTablePtr != NULL) {
	ReleaseTagTable(clientPtr->tagTablePtr);
    }
    Blt_ChainDestroy(clientPtr->events);
    treeObjPtr = clientPtr->treeObject;
    if (treeObjPtr != NULL) {
	/* Remove the client from the server's list */
	Blt_ChainDeleteLink(treeObjPtr->clients, clientPtr->linkPtr);
	if (Blt_ChainGetLength(treeObjPtr->clients) == 0) {
	    treeObjPtr->delete = 1;
            Tcl_EventuallyFree(treeObjPtr, DestroyTreeObject);
	    /* DestroyTreeObject(treeObjPtr); */
	}
    }
    clientPtr->magic = 0;
    Blt_Free(clientPtr);
}

int
Blt_TreeExists(interp, name)
    Tcl_Interp *interp;		/* Interpreter to report errors back to. */
    CONST char *name;		/* Name of tree in designated namespace. */
{
    TreeObject *treeObjPtr;

    treeObjPtr = GetTreeObject(interp, name, NS_SEARCH_BOTH);
    if (treeObjPtr == NULL) {
	Tcl_ResetResult(interp);
	return 0;
    }
    return 1;
}

/*ARGSUSED*/
static int
SizeApplyProc(
    Node *nodePtr,		/* Not used. */
    ClientData clientData,
    int order)			/* Not used. */
{
    int *sumPtr = clientData;
    *sumPtr = *sumPtr + 1;
    return TCL_OK;
}

int
Blt_TreeSize(Node *nodePtr)
{
    int sum;

    sum = 0;
    Blt_TreeApply(nodePtr, SizeApplyProc, &sum);
    return sum;
}


void
Blt_TreeCreateEventHandler(
    TreeClient *clientPtr,
    unsigned int mask,
    Blt_TreeNotifyEventProc *proc,
    ClientData clientData)
{
    Blt_ChainLink *linkPtr;
    EventHandler *notifyPtr;

    notifyPtr = NULL;		/* Suppress compiler warning. */

    /* Check if the event is already handled. */
    for(linkPtr = Blt_ChainFirstLink(clientPtr->events); 
	linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	notifyPtr = Blt_ChainGetValue(linkPtr);
	if ((notifyPtr->proc == proc) && 
	    (notifyPtr->mask == mask) &&
	    (notifyPtr->clientData == clientData)) {
	    break;
	}
    }
    if (linkPtr == NULL) {
	notifyPtr = Blt_Malloc(sizeof (EventHandler));
	assert(notifyPtr);
	linkPtr = Blt_ChainAppend(clientPtr->events, notifyPtr);
    }
    if (proc == NULL) {
	Blt_ChainDeleteLink(clientPtr->events, linkPtr);
	Blt_Free(notifyPtr);
    } else {
	notifyPtr->proc = proc;
	notifyPtr->clientData = clientData;
	notifyPtr->mask = mask;
	notifyPtr->notifyPending = FALSE;
	notifyPtr->interp = clientPtr->treeObject->interp;
    }
}

void
Blt_TreeDeleteEventHandler(
    TreeClient *clientPtr,
    unsigned int mask,
    Blt_TreeNotifyEventProc *proc,
    ClientData clientData)
{
    Blt_ChainLink *linkPtr;
    EventHandler *notifyPtr;

    if (!clientPtr) return;
    for(linkPtr = Blt_ChainFirstLink(clientPtr->events); 
	linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	notifyPtr = Blt_ChainGetValue(linkPtr);
	if ((notifyPtr->proc == proc) && (notifyPtr->mask == mask) &&
	    (notifyPtr->clientData == clientData)) {
	    if (notifyPtr->notifyPending) {
		Tcl_CancelIdleCall(NotifyIdleProc, notifyPtr);
	    }
	    Blt_ChainDeleteLink(clientPtr->events, linkPtr);
	    Blt_Free(notifyPtr);
	    return;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeNodePath --
 *
 *---------------------------------------------------------------------- 
 */
char *
Blt_TreeNodePath(Node *nodePtr, Tcl_DString *resultPtr)
{
    char **nameArr;		/* Used to stack the component names. */
    char *staticSpace[64];
    int nLevels;
    register int i;

    nLevels = nodePtr->depth;
    if (nLevels > 64) {
	nameArr = Blt_Malloc(nLevels * sizeof(char *));
	assert(nameArr);
    } else {
	nameArr = staticSpace;
    }
    for (i = nLevels - 1; i >= 0; i--) {
	/* Save the name of each ancestor in the name array. 
	 * Note that we ignore the root. */
	nameArr[i] = nodePtr->label;
	nodePtr = nodePtr->parent;
    }
    /* Append each the names in the array. */
    Tcl_DStringInit(resultPtr);
    for (i = 0; i < nLevels; i++) {
	Tcl_DStringAppendElement(resultPtr, nameArr[i]);
    }
    if (nameArr != staticSpace) {
	Blt_Free(nameArr);
    }
    return Tcl_DStringValue(resultPtr);
}

char *
Blt_TreeNodePathStr(Node *nodePtr, Tcl_DString *resultPtr, char *prefix, char *delim)
{
    char **nameArr;		/* Used to stack the component names. */
    char *staticSpace[64];
    int nLevels;
    register int i;

    nLevels = nodePtr->depth;
    if (nLevels > 64) {
	nameArr = Blt_Malloc(nLevels * sizeof(char *));
	assert(nameArr);
    } else {
	nameArr = staticSpace;
    }
    for (i = nLevels - 1; i >= 0; i--) {
	/* Save the name of each ancestor in the name array. 
	 * Note that we ignore the root. */
	nameArr[i] = nodePtr->label;
	nodePtr = nodePtr->parent;
    }
    /* Append each of the names in the array. */
    Tcl_DStringInit(resultPtr);
    if (prefix != NULL) {
        Tcl_DStringAppend(resultPtr, prefix, -1);
    }
    for (i = 0; i < nLevels; i++) {
        if (i > 0 && delim != NULL) {
            Tcl_DStringAppend(resultPtr, delim, -1);
        }
        Tcl_DStringAppend(resultPtr, nameArr[i], -1);
    }
    if (nameArr != staticSpace) {
	Blt_Free(nameArr);
    }
    return Tcl_DStringValue(resultPtr);
}

int
Blt_TreeArrayValueExists(
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *arrayName, 
    CONST char *elemName)
{
    Blt_TreeKey key;
    Blt_HashEntry *hPtr;
    Blt_HashTable *tablePtr;
    register Value *valuePtr;
    int cnt;
    TreeObject *treeObjPtr = nodePtr->treeObject;
    Tcl_Interp *interp = treeObjPtr->interp;

    key = Blt_TreeKeyGet(NULL, clientPtr->treeObject,arrayName);
    
    valuePtr = GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key);
    if (valuePtr == NULL && (!(nodePtr->flags & TREE_TRACE_ACTIVE))) {
        if (CallTraces(interp, clientPtr, treeObjPtr, nodePtr, key, 
            TREE_TRACE_EXISTS, &cnt) != TCL_OK) {
                Tcl_ResetResult(interp);
            } else {
                valuePtr = GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key);
            }
    }
    if (valuePtr == NULL) {
	return FALSE;
    }
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */
        int result;
        Tcl_Obj *keyPtr, *valueObjPtr = NULL;
        
        keyPtr = Tcl_NewStringObj(elemName, -1);
        Tcl_IncrRefCount(keyPtr);
        result = Tcl_DictObjGet(interp, valuePtr->objPtr, keyPtr, &valueObjPtr);
        Tcl_DecrRefCount(keyPtr);
        if (result != TCL_OK) {
            return FALSE;
        }
        if (valueObjPtr == NULL) {
            return FALSE;
        }            
        return TRUE;
    }

    if (Blt_IsArrayObj(valuePtr->objPtr) == 0 && Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    if (Blt_GetArrayFromObj((Tcl_Interp *)NULL, valuePtr->objPtr, &tablePtr) 
	!= TCL_OK) {
	return FALSE;
    }
    hPtr = Blt_FindHashEntry(tablePtr, elemName);
    return (hPtr != NULL);
}

int
Blt_TreeGetArrayValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *arrayName,
    CONST char *elemName,
    Tcl_Obj **valueObjPtrPtr)
{
    Blt_TreeKey key;
    Blt_HashEntry *hPtr;
    Blt_HashTable *tablePtr;
    register Value *valuePtr;
    int cnt = 0;

    key = Blt_TreeKeyGet(interp, clientPtr->treeObject,arrayName);
    
    /* Reading any element of the array can cause a trace to fire. */
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
        if (CallTraces(interp, clientPtr, nodePtr->treeObject, nodePtr, key, 
            TREE_TRACE_READ, &cnt) != TCL_OK) {
                return TCL_ERROR;
        }
    }
    valuePtr = GetTreeValue(interp, clientPtr, nodePtr, key);
    if (valuePtr == NULL) {
	return TCL_ERROR;
    }
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */
        int result;
        Tcl_Obj *keyPtr;
        keyPtr = Tcl_NewStringObj(elemName, -1);
        Tcl_IncrRefCount(keyPtr);
        result = Tcl_DictObjGet(interp, valuePtr->objPtr, keyPtr, valueObjPtrPtr);
        Tcl_DecrRefCount(keyPtr);
        if (result != TCL_OK) {
            return result;
        }
        if (*valueObjPtrPtr == NULL) {
            if (interp != NULL) {
                Tcl_AppendResult(interp, "can't find \"", arrayName, "(",
                    elemName, ")\"", (char *)NULL);
            }
            return TCL_ERROR;
        }            
        return TCL_OK;
    }
    if (Blt_IsArrayObj(valuePtr->objPtr) == 0 && Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    if (Blt_GetArrayFromObj(interp, valuePtr->objPtr, &tablePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    hPtr = Blt_FindHashEntry(tablePtr, elemName);
    if (hPtr == NULL) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't find \"", arrayName, "(",
			     elemName, ")\"", (char *)NULL);
	}
	return TCL_ERROR;
    }

    *valueObjPtrPtr = (Tcl_Obj *)Blt_GetHashValue(hPtr);
    return TCL_OK;
}

static int
TreeSetArrayValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *arrayName,
    CONST char *elemName,
    Tcl_Obj *valueObjPtr,	/* New value of element. */
    int create)           /* Create the node key if required. */
{
    Blt_TreeKey key;
    Blt_HashEntry *hPtr;
    Blt_HashTable *tablePtr;
    register Value *valuePtr;
    unsigned int flags;
    int isNew, cnt = 0;

    assert(valueObjPtr != NULL);

    /* 
     * Search for the array in the list of data fields.  If one
     * doesn't exist, create it.
     */
    key = Blt_TreeKeyGet(interp, clientPtr->treeObject,arrayName);
    valuePtr = GetTreeValue((Tcl_Interp *)NULL, clientPtr, nodePtr, key);
    if (valuePtr == NULL && create == 0) {
        return TCL_ERROR;
    }
    if (valuePtr == NULL) {
        if ((nodePtr->flags & TREE_NODE_FIXED_FIELDS)) {
            return TCL_ERROR;
        }
        valuePtr = TreeCreateValue(nodePtr, key, &isNew);
        isNew = 1;
    } else {
        isNew = 0;
    }
    if ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't set private field \"", 
			     key, "\"", (char *)NULL);
	}
	return TCL_ERROR;
    }
    flags = TREE_TRACE_WRITE;
    if (isNew) {
	valuePtr->objPtr = Blt_NewArrayObj(0, (Tcl_Obj **)NULL);
	Tcl_IncrRefCount(valuePtr->objPtr);
	flags |= TREE_TRACE_CREATE;
	
     } else if (Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    
    if ((clientPtr->treeObject->flags & TREE_DICT_KEYS) &&
        IsTclDict(interp, valuePtr->objPtr)) {
        int dSiz;
        
        if (Tcl_DictObjSize(interp, valuePtr->objPtr, &dSiz) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */
        int result;
        Tcl_Obj *keyPtr, *valObjPtr;
        
        keyPtr = Tcl_NewStringObj(elemName, -1);
        Tcl_IncrRefCount(keyPtr);
        if (!create) {
            result = Tcl_DictObjGet(interp, valuePtr->objPtr, keyPtr, &valObjPtr);
            if (result != TCL_OK || valObjPtr == NULL) {
                Tcl_AppendResult(interp, "can't find field: ", elemName, 0);
                Tcl_DecrRefCount(keyPtr);
                return TCL_ERROR;
            }
        }
        result = Tcl_DictObjPut(interp, valuePtr->objPtr, keyPtr, valueObjPtr);
        Tcl_DecrRefCount(keyPtr);
        if (result != TCL_OK) {
            return result;
        }
        goto finishset;
    }


    if (Blt_GetArrayFromObj(interp, valuePtr->objPtr, &tablePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    Tcl_InvalidateStringRep(valuePtr->objPtr);
    if (create) {
        hPtr = Blt_CreateHashEntry(tablePtr, elemName, &isNew);
        assert(hPtr);
    } else {
        hPtr = Blt_FindHashEntry(tablePtr, elemName);
        if (hPtr == NULL) {
            if (interp != NULL) {
                Tcl_AppendResult(interp, "can't find array field: ", elemName, 0);
            }
            return TCL_ERROR;
        }
        isNew = 0;
    }
    
    SetModified(nodePtr);
    Tcl_IncrRefCount(valueObjPtr);
    if (!isNew) {
	Tcl_Obj *oldValueObjPtr;

	/* An element by the same name already exists. Decrement the
	 * reference count of the old value. */

	oldValueObjPtr = (Tcl_Obj *)Blt_GetHashValue(hPtr);
        if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
            UpdateOldValue(clientPtr, oldValueObjPtr);
            oldValueObjPtr = NULL;
        }
	if (oldValueObjPtr != NULL) {
	    Tcl_DecrRefCount(oldValueObjPtr);
	}
    } else {
        if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
            UpdateOldValue(clientPtr, NULL);
        }
    }
    Blt_SetHashValue(hPtr, valueObjPtr);

finishset:
    /*
     * We don't handle traces on a per array element basis.  Setting
     * any element can fire traces for the value.
     */
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
	return CallTraces(interp, clientPtr, nodePtr->treeObject, nodePtr, 
		valuePtr->key, flags, &cnt);
    }
    return TCL_OK;
}

int
Blt_TreeSetArrayValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *arrayName,
    CONST char *elemName,
    Tcl_Obj *valueObjPtr)	/* New value of element. */
{
    return TreeSetArrayValue(interp, clientPtr, nodePtr, arrayName, elemName, valueObjPtr, 1);
}

int
Blt_TreeUpdateArrayValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *arrayName,
    CONST char *elemName,
    Tcl_Obj *valueObjPtr)	/* New value of element. */
{
    return TreeSetArrayValue(interp, clientPtr, nodePtr, arrayName, elemName, valueObjPtr, 0);
}

int
Blt_TreeUnsetArrayValue(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,		/* Node to be updated. */
    CONST char *arrayName,
    CONST char *elemName)
{
    Blt_TreeKey key;		/* Name of field in node. */
    Blt_HashEntry *hPtr;
    Blt_HashTable *tablePtr;
    Tcl_Obj *valueObjPtr;
    Value *valuePtr;
    int cnt = 0;

    key = Blt_TreeKeyGet(interp, clientPtr->treeObject,arrayName);
    valuePtr = TreeFindValue(nodePtr, key);
    if (valuePtr == NULL) {
	return TCL_OK;
    }
    if ((valuePtr->owner != NULL) && (valuePtr->owner != clientPtr)) {
	if (interp != NULL) {
	    Tcl_AppendResult(interp, "can't unset private field \"", 
			     key, "\"", (char *)NULL);
	}
	return TCL_ERROR;
    }
        
    if (Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */
        int result;
        Tcl_Obj *keyPtr;
        keyPtr = Tcl_NewStringObj(elemName, -1);
        Tcl_IncrRefCount(keyPtr);
        result = Tcl_DictObjRemove(interp, valuePtr->objPtr, keyPtr);
        Tcl_DecrRefCount(keyPtr);
        if (result != TCL_OK) {
            return result;
        }
        goto finishrm;
    }

    if (Blt_GetArrayFromObj(interp, valuePtr->objPtr, &tablePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    hPtr = Blt_FindHashEntry(tablePtr, elemName);
    if (hPtr == NULL) {
        goto finishrm; /* Element doesn't exist, Ok. */
    }
    SetModified(nodePtr);
    valueObjPtr = (Tcl_Obj *)Blt_GetHashValue(hPtr);
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
        UpdateOldValue(clientPtr, valueObjPtr);
    } else {
        Tcl_DecrRefCount(valueObjPtr);
    }
    Blt_DeleteHashEntry(tablePtr, hPtr);
    Tcl_InvalidateStringRep(valuePtr->objPtr);

finishrm:
    /*
     * Un-setting any element in the array can cause the trace on the value
     * to fire.
     */
    if (!(nodePtr->flags & TREE_TRACE_ACTIVE)) {
	return CallTraces(interp, clientPtr, nodePtr->treeObject, nodePtr, 
		valuePtr->key, TREE_TRACE_WRITE, &cnt);
    }
    return TCL_OK;
}

int
Blt_TreeArrayNames(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *arrayName,
    Tcl_Obj *listObjPtr,
    CONST char *pattern)
{
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Blt_HashTable *tablePtr;
    Tcl_Obj *objPtr;
    Value *valuePtr;
    char *key;

    key = Blt_TreeKeyGet(interp, clientPtr->treeObject,arrayName);
    valuePtr = GetTreeValue(interp, clientPtr, nodePtr, key);
    if (valuePtr == NULL) {
	return TCL_ERROR;
    }
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */

        Tcl_DictSearch search;
        Tcl_Obj *keyPtr;
        int done;
        
        Tcl_DictObjFirst(NULL, valuePtr->objPtr, &search, &keyPtr, NULL, &done);
        for (; !done ; Tcl_DictObjNext(&search, &keyPtr, NULL, &done)) {
            if (!pattern || Tcl_StringMatch(Tcl_GetString(keyPtr), pattern)) {
                Tcl_ListObjAppendElement(NULL, listObjPtr, keyPtr);
            }
        }
        Tcl_DictObjDone(&search);
        return TCL_OK;
    }

    if (Blt_IsArrayObj(valuePtr->objPtr) == 0 && Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    if (Blt_GetArrayFromObj(interp, valuePtr->objPtr, &tablePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    /*tablePtr = (Blt_HashTable *)valuePtr->objPtr; */
    for (hPtr = Blt_FirstHashEntry(tablePtr, &cursor); hPtr != NULL; 
	 hPtr = Blt_NextHashEntry(&cursor)) {
	 char *str;
	 
	 str = Blt_GetHashKey(tablePtr, hPtr);
         if (pattern == NULL || Tcl_StringMatch(str, pattern)) {
             objPtr = Tcl_NewStringObj(str, -1);
             Tcl_ListObjAppendElement(interp, listObjPtr, objPtr);
         }
    }
    return TCL_OK;
}

int
Blt_TreeArrayValues(
    Tcl_Interp *interp,
    TreeClient *clientPtr,
    Node *nodePtr,
    CONST char *arrayName,
    Tcl_Obj *listObjPtr,
    int names)
{
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Blt_HashTable *tablePtr;
    Tcl_Obj *objPtr;
    Value *valuePtr;
    char *key;

    key = Blt_TreeKeyGet(interp, clientPtr->treeObject,arrayName);
    if ( bltTreeGetValueByKey(interp, clientPtr, nodePtr, key, &valuePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    if (IsTclDict(interp, valuePtr->objPtr)) {
        /* Preserve type if this was a dict */

        Tcl_DictSearch search;
        Tcl_Obj *keyPtr;
        int done;
        int result;
        
        Tcl_DictObjFirst(NULL, valuePtr->objPtr, &search, &keyPtr, NULL, &done);
        for (; !done ; Tcl_DictObjNext(&search, &keyPtr, NULL, &done)) {
            Tcl_Obj *valueObjPtr;
            if (names) {
                Tcl_ListObjAppendElement(NULL, listObjPtr, keyPtr);
            }
                
            valueObjPtr = NULL;
            result = Tcl_DictObjGet(interp, valuePtr->objPtr, keyPtr, &valueObjPtr);
            if (result != TCL_OK) {
                continue;
            }
            if (valueObjPtr == NULL) {
                valueObjPtr = Tcl_NewStringObj("",-1);
            }      
            Tcl_ListObjAppendElement(NULL, listObjPtr, valueObjPtr);
        }
        Tcl_DictObjDone(&search);
        return TCL_OK;
    }
    if (Blt_IsArrayObj(valuePtr->objPtr) == 0 && Tcl_IsShared(valuePtr->objPtr)) {
	Tcl_DecrRefCount(valuePtr->objPtr);
	valuePtr->objPtr = Tcl_DuplicateObj(valuePtr->objPtr);
	Tcl_IncrRefCount(valuePtr->objPtr);
    }
    if (Blt_GetArrayFromObj(interp, valuePtr->objPtr, &tablePtr) != TCL_OK) {
	return TCL_ERROR;
    }
    /*tablePtr = (Blt_HashTable *)valuePtr->objPtr; */
    for (hPtr = Blt_FirstHashEntry(tablePtr, &cursor); hPtr != NULL; 
	 hPtr = Blt_NextHashEntry(&cursor)) {
	if (names) {
             Tcl_ListObjAppendElement(interp, listObjPtr,
                Tcl_NewStringObj( Blt_GetHashKey(tablePtr, hPtr), -1));
        }
	objPtr = Blt_GetHashValue(hPtr);
	Tcl_ListObjAppendElement(interp, listObjPtr, objPtr?objPtr:Tcl_NewStringObj("",-1));
    }
    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeShareTagTable --
 *
 *---------------------------------------------------------------------- 
 */
int
Blt_TreeShareTagTable(
    TreeClient *sourcePtr,
    TreeClient *targetPtr)
{
    sourcePtr->tagTablePtr->refCount++;
    if (targetPtr->tagTablePtr != NULL) {
	ReleaseTagTable(targetPtr->tagTablePtr);
    }
    targetPtr->tagTablePtr = sourcePtr->tagTablePtr;
    return TCL_OK;
}

int
Blt_TreeTagTableIsShared(TreeClient *clientPtr)
{
    return (clientPtr->tagTablePtr->refCount > 1);
}   

void
Blt_TreeClearTags(TreeClient *clientPtr, Blt_TreeNode node)
{
    Blt_HashEntry *hPtr, *h2Ptr;
    Blt_HashSearch cursor;
    
    for (hPtr = Blt_FirstHashEntry(&clientPtr->tagTablePtr->tagTable, &cursor); 
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	Blt_TreeTagEntry *tPtr;

	tPtr = Blt_GetHashValue(hPtr);
	h2Ptr = Blt_FindHashEntry(&tPtr->nodeTable, (char *)node);
	if (h2Ptr != NULL) {
             SetModified(node);
             Blt_DeleteHashEntry(&tPtr->nodeTable, h2Ptr);
	}
    }
}

int
Blt_TreeHasTag(
    TreeClient *clientPtr,
    Blt_TreeNode node, 
    CONST char *tagName)
{
    Blt_HashEntry *hPtr;
    Blt_TreeTagEntry *tPtr;

    if (strcmp(tagName, "all") == 0) {
	return TRUE;
    }
    if (strcmp(tagName, "nonroot") == 0) {
        return TRUE;
    }
    if (strcmp(tagName, "rootchildren") == 0) {
        return TRUE;
    }
    if ((strcmp(tagName, "root") == 0) && 
	(node == Blt_TreeRootNode(clientPtr))) {
	return TRUE;
    }
    hPtr = Blt_FindHashEntry(&clientPtr->tagTablePtr->tagTable, tagName);
    if (hPtr == NULL) {
	return FALSE;
    }
    tPtr = Blt_GetHashValue(hPtr);
    hPtr = Blt_FindHashEntry(&tPtr->nodeTable, (char *)node);
    if (hPtr == NULL) {
	return FALSE;
    }
    return TRUE;
}

int
Blt_TreeAddTag(
    TreeClient *clientPtr,
    Blt_TreeNode node,
    CONST char *tagName)
{
    int isNew, isNewN, cnt = 0, flags;
    Blt_HashEntry *hPtr;
    Blt_HashTable *tablePtr;
    Blt_TreeTagEntry *tPtr;
    Tcl_Interp *interp = clientPtr->treeObject->interp;

    if ((strcmp(tagName, "all") == 0) || (strcmp(tagName, "root") == 0)
        || (strcmp(tagName, "nonroot") == 0) || (strcmp(tagName, "rootchildren") == 0)) {
        Tcl_AppendResult(interp, "reserved tag", 0);
	return TCL_ERROR;
    }
    tablePtr = &clientPtr->tagTablePtr->tagTable;
    hPtr = Blt_CreateHashEntry(tablePtr, tagName, &isNewN);
    assert(hPtr);
    if (isNewN) {

	tPtr = Blt_Calloc(sizeof(Blt_TreeTagEntry), 1);
	Blt_InitHashTable(&tPtr->nodeTable, BLT_ONE_WORD_KEYS);
	Blt_SetHashValue(hPtr, tPtr);
	tPtr->hashPtr = hPtr;
	tPtr->tagName = Blt_GetHashKey(tablePtr, hPtr);
        Blt_TreeTagRefIncr(tPtr);
     } else {
	tPtr = Blt_GetHashValue(hPtr);
    }
    if (node == NULL) {
        return TCL_OK;
    }
    if (!(node->flags & TREE_TRACE_ACTIVE)) {
        int result;
        flags = TREE_TRACE_TAGADD;
        if (tPtr->nodeTable.numEntries > 0) {
            flags |= TREE_TRACE_TAGMULTIPLE;
        }
        result = CallTraces(interp, clientPtr, node->treeObject, node, (Blt_TreeKey)tagName, 
            flags, &cnt);
        if (result == TCL_BREAK) {
            return TCL_OK;
        }
        if (result != TCL_OK) {
            return result;
        }
    }
    hPtr = Blt_CreateHashEntry(&tPtr->nodeTable, (char *)node, &isNew);
    assert(hPtr);
    if (isNew) {
        SetModified(node);
        Blt_SetHashValue(hPtr, node);
    }
    return TCL_OK;
}

/* Trigger tag delete traces. */
int
Blt_TreeTagDelTrace(
    TreeClient *clientPtr,
    Blt_TreeNode node,
    CONST char *tagName)
{
    Tcl_Interp *interp = clientPtr->treeObject->interp;
    int cnt;
    
    if (!(node->flags & TREE_TRACE_ACTIVE)) {
        return CallTraces(interp, clientPtr, node->treeObject, node, (Blt_TreeKey)tagName, 
            (TREE_TRACE_TAGDELETE), &cnt);
    }
    return TCL_OK;
}

int
Blt_TreeForgetTag(TreeClient *clientPtr, CONST char *tagName)
{
    Blt_HashEntry *hPtr;
    if ((strcmp(tagName, "all") == 0) || (strcmp(tagName, "root") == 0)
       || (strcmp(tagName, "nonroot") == 0)
       || (strcmp(tagName, "rootchildren") == 0)) {
       return TCL_OK;
    }
	
    hPtr = Blt_FindHashEntry(&clientPtr->tagTablePtr->tagTable, tagName);
    if (hPtr != NULL) {
        Blt_TreeTagEntry *tPtr;
        Blt_TreeNode node;
        Blt_HashSearch cursor;
	    
        Blt_DeleteHashEntry(&clientPtr->tagTablePtr->tagTable, hPtr);
        tPtr = Blt_GetHashValue(hPtr);
        for (hPtr = Blt_FirstHashEntry(&tPtr->nodeTable, &cursor);
            hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
                 
            node = Blt_GetHashKey(&tPtr->nodeTable, hPtr);
            if (Blt_TreeTagDelTrace(clientPtr, node, tagName) != TCL_OK) {
                return TCL_ERROR;
            }
            SetModified(node);
        }
        Blt_DeleteHashTable(&tPtr->nodeTable);
        Blt_TreeTagRefDecr(tPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeTagHashTable --
 *
 *---------------------------------------------------------------------- 
 */
Blt_HashTable *
Blt_TreeTagHashTable(TreeClient *clientPtr, CONST char *tagName)
{
    Blt_HashEntry *hPtr;
   
    hPtr = Blt_FindHashEntry(&clientPtr->tagTablePtr->tagTable, tagName);
    if (hPtr != NULL) {
	Blt_TreeTagEntry *tPtr;
	
	tPtr = Blt_GetHashValue(hPtr);
	return &tPtr->nodeTable;
    }
    return NULL;
}

Blt_TreeTagEntry *
Blt_TreeTagHashEntry(TreeClient *clientPtr, CONST char *tagName)
{
    Blt_HashEntry *hPtr;
   
    hPtr = Blt_FindHashEntry(&clientPtr->tagTablePtr->tagTable, tagName);
    if (hPtr != NULL) {
	Blt_TreeTagEntry *tPtr;
	
	tPtr = Blt_GetHashValue(hPtr);
	return tPtr;
    }
    return NULL;
}

Blt_HashEntry *
Blt_TreeFirstTag(TreeClient *clientPtr, Blt_HashSearch *cursorPtr)
{
    return Blt_FirstHashEntry(&clientPtr->tagTablePtr->tagTable, cursorPtr);
}

#if (SIZEOF_VOID_P == 8)
/*
 *----------------------------------------------------------------------
 *
 * HashOneWord --
 *
 *	Compute a one-word hash value of a 64-bit word, which then can
 *	be used to generate a hash index.
 *
 *	From Knuth, it's a multiplicative hash.  Multiplies an unsigned
 *	64-bit value with the golden ratio (sqrt(5) - 1) / 2.  The
 *	downshift value is 64 - n, when n is the log2 of the size of
 *	the hash table.
 *		
 * Results:
 *	The return value is a one-word summary of the information in
 *	64 bit word.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static Blt_Hash
HashOneWord(
    uint64_t mask,
    unsigned int downshift,	        
    CONST void *key)
{
    uint64_t a0, a1;
    uint64_t y0, y1;
    uint64_t y2, y3; 
    uint64_t p1, p2;
    uint64_t result;

    /* Compute key * GOLDEN_RATIO in 128-bit arithmetic */
    a0 = (uint64_t)key & 0x00000000FFFFFFFF; 
    a1 = (uint64_t)key >> 32;
    
    y0 = a0 * 0x000000007f4a7c13;
    y1 = a0 * 0x000000009e3779b9; 
    y2 = a1 * 0x000000007f4a7c13;
    y3 = a1 * 0x000000009e3779b9; 
    y1 += y0 >> 32;		/* Can't carry */ 
    y1 += y2;			/* Might carry */
    if (y1 < y2) {
	y3 += (1LL << 32);	/* Propagate */ 
    }

    /* 128-bit product: p1 = loword, p2 = hiword */
    p1 = ((y1 & 0x00000000FFFFFFFF) << 32) + (y0 & 0x00000000FFFFFFFF);
    p2 = y3 + (y1 >> 32);
    
    /* Left shift the value downward by the size of the table */
    if (downshift > 0) { 
	if (downshift < 64) { 
	    result = ((p2 << (64 - downshift)) | (p1 >> (downshift & 63))); 
	} else { 
	    result = p2 >> (downshift & 63); 
	} 
    } else { 
	result = p1;
    } 
    /* Finally mask off the high bits */
    return (Blt_Hash)(result & mask);
}

#endif /* SIZEOF_VOID_P == 8 */

/*
 *----------------------------------------------------------------------
 *
 * RebuildTable --
 *
 *	This procedure is invoked when the ratio of entries to hash
 *	buckets becomes too large.  It creates a new table with a
 *	larger bucket array and moves all of the entries into the
 *	new table.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory gets reallocated and entries get re-hashed to new
 *	buckets.
 *
 *----------------------------------------------------------------------
 */
static void
RebuildTable(Node *nodePtr)		/* Table to enlarge. */
{
    Value **newBucketPtr, **oldBuckets;
    register Value **bucketPtr, **endPtr;
    register Value *valuePtr, *nextPtr;
    unsigned int downshift;
    unsigned long mask;
    Value **buckets;
    size_t nBuckets;

    oldBuckets = (Value **)nodePtr->values;
    nBuckets = (1 << nodePtr->logSize);
    endPtr = oldBuckets + nBuckets;

    /*
     * Allocate and initialize the new bucket array, and set up
     * hashing constants for new array size.
     */
    nodePtr->logSize += 2;
    nBuckets = (1 << nodePtr->logSize);
    buckets = Blt_Calloc(nBuckets, sizeof(Value *));

    /*
     * Move all of the existing entries into the new bucket array,
     * based on their hash values.  
     */
    mask = nBuckets - 1;
    downshift = DOWNSHIFT_START - nodePtr->logSize;
    for (bucketPtr = oldBuckets; bucketPtr < endPtr; bucketPtr++) {
	for (valuePtr = *bucketPtr; valuePtr != NULL; valuePtr = nextPtr) {
	    nextPtr = valuePtr->next;
	    newBucketPtr = buckets + RANDOM_INDEX(valuePtr->key);
	    valuePtr->next = *newBucketPtr;
	    *newBucketPtr = valuePtr;
	}
    }
    nodePtr->values = (Value *)buckets;
    Blt_Free(oldBuckets);
}

static void
ConvertValues(Node *nodePtr)
{
    unsigned int nBuckets;
    Value **buckets;
    unsigned int mask;
    int downshift;
    Value *valuePtr, *nextPtr, **bucketPtr;

    /*
     * Convert list of values into a hash table.
     */
    nodePtr->logSize = START_LOGSIZE;
    nBuckets = 1 << nodePtr->logSize;
    buckets = Blt_Calloc(nBuckets, sizeof(Value *));
    mask = nBuckets - 1;
    downshift = DOWNSHIFT_START - nodePtr->logSize;
    for (valuePtr = nodePtr->values; valuePtr != NULL; valuePtr = nextPtr) {
	nextPtr = valuePtr->next;
	bucketPtr = buckets + RANDOM_INDEX(valuePtr->key);
	valuePtr->next = *bucketPtr;
	*bucketPtr = valuePtr;
    }
    nodePtr->values = (Value *)buckets;
}

/*
 *----------------------------------------------------------------------
 *
 * TreeDeleteValue --
 *
 *	Remove a single entry from a hash table.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The entry given by entryPtr is deleted from its table and
 *	should never again be used by the caller.  It is up to the
 *	caller to free the clientData field of the entry, if that
 *	is relevant.
 *
 *----------------------------------------------------------------------
 */
static int
TreeDeleteValue(Node *nodePtr, Blt_TreeValue value)
{
    Value *valuePtr = value;
    register Value *prevPtr;
    
    if (nodePtr->logSize > 0) {
	Value **bucketPtr;
	unsigned int downshift;
	unsigned long mask;

	mask = (1 << nodePtr->logSize) - 1;
	downshift = DOWNSHIFT_START - nodePtr->logSize;
	
	bucketPtr = (Value **)nodePtr->values + RANDOM_INDEX(valuePtr->key);
	if (*bucketPtr == valuePtr) {
	    *bucketPtr = valuePtr->next;
	} else {
	    for (prevPtr = *bucketPtr; /*empty*/; prevPtr = prevPtr->next) {
		if (prevPtr == NULL) {
		    return TCL_ERROR; /* Can't find value in hash bucket. */
		}
		if (prevPtr->next == valuePtr) {
		    prevPtr->next = valuePtr->next;
		    break;
		}
	    }
	}
    } else {
	prevPtr = NULL;
	for (valuePtr = nodePtr->values; valuePtr != NULL; 
	     valuePtr = valuePtr->next) {
	    if (valuePtr == value) {
		break;
	    }
	    prevPtr = valuePtr;
	}
	if (valuePtr == NULL) {
	    return TCL_ERROR;	/* Can't find value in list. */
	}
	if (prevPtr == NULL) {
	    nodePtr->values = valuePtr->next;
	} else {
	    prevPtr->next = valuePtr->next;
	}
    }
    nodePtr->nValues--;
    FreeValue(nodePtr, valuePtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TreeDestroyValues --
 *
 *	Free up everything associated with a hash table except for
 *	the record for the table itself.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The hash table is no longer useable.
 *
 *----------------------------------------------------------------------
 */
static void
TreeDestroyValues(Node *nodePtr)
{
    register Value *valuePtr;
    Value *nextPtr;

    /*
     * Free up all the entries in the table.
     */
    if (nodePtr->values == NULL) { 
	return;
    }
    if (nodePtr->logSize > 0) {
	Value **buckets;
	int nBuckets;
	int i;

	buckets = (Value **)nodePtr->values;
	nBuckets = (1 << nodePtr->logSize);
	for (i = 0; i < nBuckets; i++) {
	    for (valuePtr = buckets[i]; valuePtr != NULL; valuePtr = nextPtr) {
		nextPtr = valuePtr->next;
		FreeValue(nodePtr, valuePtr);
	    }
	}
	Blt_Free(buckets);
    } else {
	for (valuePtr = nodePtr->values; valuePtr != NULL; valuePtr = nextPtr) {
	    nextPtr = valuePtr->next;
	    FreeValue(nodePtr, valuePtr);
	}
    }
    nodePtr->values = NULL;
    nodePtr->nValues = 0;
    nodePtr->logSize = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TreeFirstValue --
 *
 *	Locate the first entry in a hash table and set up a record
 *	that can be used to step through all the remaining entries
 *	of the table.
 *
 * Results:
 *	The return value is a pointer to the first value in tablePtr,
 *	or NULL if tablePtr has no entries in it.  The memory at
 *	*searchPtr is initialized so that subsequent calls to
 *	Blt_TreeNextValue will return all of the values in the table,
 *	one at a time.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static Value *
TreeFirstValue(
    Node *nodePtr,
    Blt_TreeKeySearch *searchPtr) /* Place to store information about
				   * progress through the table. */
{
    searchPtr->node = nodePtr;
    searchPtr->nextIndex = 0;
    searchPtr->cnt = 1;
    if (nodePtr->logSize > 0) {
	searchPtr->nextValue = NULL;
    } else {
	searchPtr->nextValue = nodePtr->values;
    }
    return TreeNextValue(searchPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TreeNextValue --
 *
 *	Once a hash table enumeration has been initiated by calling
 *	Blt_TreeFirstValue, this procedure may be called to return
 *	successive elements of the table.
 *
 * Results:
 *	The return value is the next entry in the hash table being
 *	enumerated, or NULL if the end of the table is reached.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static Value *
TreeNextValue(
    Blt_TreeKeySearch *searchPtr) /* Place to store information about
				   * progress through the table.  Must
				   * have been initialized by calling
				   * Blt_TreeFirstValue. */
{
    Value *valuePtr;

    if (searchPtr->node->logSize > 0) {
	size_t nBuckets;
	Value **buckets;

	nBuckets = (1 << searchPtr->node->logSize);
	buckets = (Value **)searchPtr->node->values;
	while (searchPtr->nextValue == NULL) {
	    if (searchPtr->nextIndex >= nBuckets) {
		return NULL;
	    }
	    searchPtr->nextValue = buckets[searchPtr->nextIndex];
	    searchPtr->nextIndex++;
	}
    }
    searchPtr->cnt++;
    /* Sanity check. */
    if (searchPtr->cnt>100000000) return NULL;
    valuePtr = searchPtr->nextValue;
    if (valuePtr != NULL) {
        searchPtr->nextValue = valuePtr->next;
    }
    return valuePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TreeFindValue --
 *
 *	Given a hash table with one-word keys, and a one-word key, find
 *	the entry with a matching key.
 *
 * Results:
 *	The return value is a token for the matching entry in the
 *	hash table, or NULL if there was no matching entry.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static Value *
TreeFindValue(
    Node *nodePtr,
    Blt_TreeKey key)		/* Key to use to find matching entry. */
{
    register Value *valuePtr;
    Value *bucket;

    if (nodePtr->logSize > 0) {
	unsigned int downshift;
	unsigned long mask;

	mask = (1 << nodePtr->logSize) - 1;
	downshift = DOWNSHIFT_START - nodePtr->logSize;
	bucket = ((Value **)(nodePtr->values))[RANDOM_INDEX((void *)key)];
    } else {
	bucket = nodePtr->values; /* Single chain list. */
    }
    /*
     * Search all of the entries in the appropriate bucket.
     */
    for (valuePtr = bucket; valuePtr != NULL; valuePtr = valuePtr->next) {
	if (valuePtr->key == key) {
	    return valuePtr;
	}
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_TreeCreateValue --
 *
 *	Find the value with a matching key.  If there is no matching 
 *	value, then create a new one.
 *
 * Results:
 *	The return value is a pointer to the matching value.  If this
 *	is a newly-created value, then *newPtr will be set to a non-zero
 *	value;  otherwise *newPtr will be set to 0.  
 *
 * Side effects:
 *	A new value may be added to the hash table.
 *
 *----------------------------------------------------------------------
 */
static Value *
TreeCreateValue(
    Node *nodePtr,
    Blt_TreeKey key,		/* Key to use to find or create matching
				 * entry. */
    int *newPtr)		/* Store info here telling whether a new
				 * entry was created. */
{
    register Value *valuePtr;
    TreeObject *treeObjPtr = nodePtr->treeObject;
    int maxVals;
    
    if (treeObjPtr->maxKeyList>0) {
        maxVals = treeObjPtr->maxKeyList;
    } else {
        maxVals = MAX_LIST_VALUES;
    }
    /* 
     * Check if there as so many values that storage should be
     * converted from a hash table instead of a list. 
     */
    if ((nodePtr->logSize == 0) && (nodePtr->nValues >= maxVals)) {
	ConvertValues(nodePtr);
    }
    if (nodePtr->logSize > 0) {
	Value **bucketPtr;
	size_t nBuckets;
	unsigned int downshift;
	unsigned long mask;

	nBuckets = (1 << nodePtr->logSize);
	mask = nBuckets - 1;
	downshift = DOWNSHIFT_START - nodePtr->logSize;
	bucketPtr = (Value **)nodePtr->values + RANDOM_INDEX((void *)key);
	
	*newPtr = FALSE;
	for (valuePtr = *bucketPtr; valuePtr != NULL; 
	     valuePtr = valuePtr->next) {
	    if (valuePtr->key == key) {
		return valuePtr;
	    }
	}
	
	/* Value not found. Add a new value to the bucket. */
	*newPtr = TRUE;
	valuePtr = Blt_PoolAllocItem(nodePtr->treeObject->valuePool, 
		sizeof(Value));
	valuePtr->key = key;
	valuePtr->owner = NULL;
	valuePtr->next = *bucketPtr;
	valuePtr->objPtr = NULL;
	*bucketPtr = valuePtr;
	nodePtr->nValues++;
	
	/*
	 * If the table has exceeded a decent size, rebuild it with many
	 * more buckets.
	 */
	if ((unsigned int)nodePtr->nValues >= (nBuckets * 3)) {
	    RebuildTable(nodePtr);
	}
    } else {
	Value *prevPtr;

	prevPtr = NULL;
	*newPtr = FALSE;
	for (valuePtr = nodePtr->values; valuePtr != NULL; 
	     valuePtr = valuePtr->next) {
	    if (valuePtr->key == key) {
		return valuePtr;
	    }
	    prevPtr = valuePtr;
	}
	/* Value not found. Add a new value to the list. */
	*newPtr = TRUE;
	valuePtr = Blt_PoolAllocItem(nodePtr->treeObject->valuePool, 
		sizeof(Value));
	valuePtr->key = key;
	valuePtr->owner = NULL;
	valuePtr->next = NULL;
	valuePtr->objPtr = NULL;
	if (prevPtr == NULL) {
	    nodePtr->values = valuePtr;
	} else {
	    prevPtr->next = valuePtr;
	}
	nodePtr->nValues++;
    }
    return valuePtr;
}


Blt_TreeNode Blt_TreeEndNode (Blt_TreeNode node,
    unsigned int nodeFlags) {
    /* TODO: finish. */
    return NULL;
}

#undef Blt_TreeFirstChild
#undef Blt_TreeLastChild
#undef Blt_TreeNextSibling
#undef Blt_TreePrevSibling
#undef Blt_TreeChangeRoot

Blt_TreeNode Blt_TreeFirstChild (Blt_TreeNode parent) {
    return parent->first;
}

Blt_TreeNode Blt_TreeNextSibling (Blt_TreeNode node) {
    return (node == NULL ? NULL : node->next);
}

Blt_TreeNode Blt_TreeLastChild (Blt_TreeNode parent) {
    return parent->last;
}

Blt_TreeNode Blt_TreePrevSibling (Blt_TreeNode node) {
    return (node == NULL ? NULL : node->prev);
}

Blt_TreeNode Blt_TreeChangeRoot (Blt_Tree tree, Blt_TreeNode node) {
    tree->root = node;
    return node;
}

#endif /* NO_TREE */