File: tree_tcl.tcl

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

package require Tcl 8.5 9
package require struct::list

namespace eval ::struct::tree {
    # Data storage in the tree module
    # -------------------------------
    #
    # There's a lot of bits to keep track of for each tree:
    #	nodes
    #	node values
    #	node relationships
    #
    # It would quickly become unwieldy to try to keep these in arrays or lists
    # within the tree namespace itself.  Instead, each tree structure will get
    # its own namespace.  Each namespace contains:
    #	children	array mapping nodes to their children list
    #	parent		array mapping nodes to their parent node
    #	node:$node	array mapping keys to values for the node $node

    # counter is used to give a unique name for unnamed trees
    variable counter 0

    # Only export one command, the one used to instantiate a new tree
    namespace export tree_tcl
}

# ::struct::tree::tree_tcl --
#
#	Create a new tree with a given name; if no name is given, use
#	treeX, where X is a number.
#
# Arguments:
#	name	Optional name of the tree; if null or not given, generate one.
#
# Results:
#	name	Name of the tree created

proc ::struct::tree::tree_tcl {args} {
    variable counter

    set src     {}
    set srctype {}

    switch -exact -- [llength [info level 0]] {
	1 {
	    # Missing name, generate one.
	    incr counter
	    set name "tree${counter}"
	}
	2 {
	    # Standard call. New empty tree.
	    set name [lindex $args 0]
	}
	4 {
	    # Copy construction.
	    foreach {name as src} $args break
	    switch -exact -- $as {
		= - := - as {
		    set srctype tree
		}
		deserialize {
		    set srctype serial
		}
		default {
		    return -code error \
			    "wrong # args: should be \"tree ?name ?=|:=|as|deserialize source??\""
		}
	    }
	}
	default {
	    # Error.
	    return -code error \
		    "wrong # args: should be \"tree ?name ?=|:=|as|deserialize source??\""
	}
    }

    # FIRST, qualify the name.
    if {![string match "::*" $name]} {
        # Get caller's namespace; append :: if not global namespace.
        set ns [uplevel 1 [list namespace current]]
        if {"::" != $ns} {
            append ns "::"
        }

        set name "$ns$name"
    }
    if {[llength [info commands $name]]} {
	return -code error \
		"command \"$name\" already exists, unable to create tree"
    }

    # Set up the namespace for the object,
    # identical to the object command.
    namespace eval $name {
	variable rootname
	set      rootname root

	# Set up root node's child list
	variable children
	set      children(root) [list]

	# Set root node's parent
	variable parent
	set      parent(root) [list]

	# Set up the node attribute mapping
	variable  attribute
	array set attribute {}

	# Set up a counter for use in creating unique node names
	variable nextUnusedNode
	set      nextUnusedNode 1

	# Set up a counter for use in creating node attribute arrays.
	variable nextAttr
	set      nextAttr 0
    }

    # Create the command to manipulate the tree
    interp alias {} $name {} ::struct::tree::TreeProc $name

    # Automatic execution of assignment if a source
    # is present.
    if {$src != {}} {
	switch -exact -- $srctype {
	    tree   {
		set code [catch {_= $name $src} msg]
		if {$code} {
		    namespace delete $name
		    interp alias {} $name {}
		    return -code $code -errorinfo $::errorInfo -errorcode $::errorCode $msg
		}
	    }
	    serial {
		set code [catch {_deserialize $name $src} msg]
		if {$code} {
		    namespace delete $name
		    interp alias {} $name {}
		    return -code $code -errorinfo $::errorInfo -errorcode $::errorCode $msg
		}
	    }
	    default {
		return -code error \
			"Internal error, illegal srctype \"$srctype\""
	    }
	}
    }

    # Give object to caller for use.
    return $name
}

# ::struct::tree::prune_tcl --
#
#	Abort the walk script, and ignore any children of the
#	node we are currently at.
#
# Arguments:
#	None.
#
# Results:
#	None.
#
# Sideeffects:
#
#	Stops the execution of the script and throws a signal to the
#	surrounding walker to go to the next node, and ignore the
#	children of the current node.

proc ::struct::tree::prune_tcl {} {
    return -code 5
}

##########################
# Private functions follow

# ::struct::tree::TreeProc --
#
#	Command that processes all tree object commands.
#
# Arguments:
#	name	Name of the tree object to manipulate.
#	cmd	Subcommand to invoke.
#	args	Arguments for subcommand.
#
# Results:
#	Varies based on command to perform

proc ::struct::tree::TreeProc {name {cmd ""} args} {
    # Do minimal args checks here
    if { [llength [info level 0]] == 2 } {
	return -code error "wrong # args: should be \"$name option ?arg arg ...?\""
    }

    # Split the args into command and args components
    set sub _$cmd
    if { [llength [info commands ::struct::tree::$sub]] == 0 } {
	set optlist [lsort [info commands ::struct::tree::_*]]
	set xlist {}
	foreach p $optlist {
	    set p [namespace tail $p]
	    lappend xlist [string range $p 1 end]
	}
	set optlist [linsert [join $xlist ", "] "end-1" "or"]
	return -code error \
		"bad option \"$cmd\": must be $optlist"
    }

    set code [catch {uplevel 1 [linsert $args 0 ::struct::tree::$sub $name]} result]

    if {$code == 1} {
	return -errorinfo [ErrorInfoAsCaller uplevel $sub]  \
		-errorcode $::errorCode -code error $result
    } elseif {$code == 2} {
	return -code $code $result
    }
    return $result
}

# ::struct::tree::_:= --
#
#	Assignment operator. Copies the source tree into the
#       destination, destroying the original information.
#
# Arguments:
#	name	Name of the tree object we are copying into.
#	source	Name of the tree object providing us with the
#		data to copy.
#
# Results:
#	Nothing.

proc ::struct::tree::_= {name source} {
    _deserialize $name [$source serialize]
    return
}

# ::struct::tree::_--> --
#
#	Reverse assignment operator. Copies this tree into the
#       destination, destroying the original information.
#
# Arguments:
#	name	Name of the tree object to copy
#	dest	Name of the tree object we are copying to.
#
# Results:
#	Nothing.

proc ::struct::tree::_--> {name dest} {
    $dest deserialize [_serialize $name]
    return
}

# ::struct::tree::_ancestors --
#
#	Return the list of all parent nodes of a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to look up.
#
# Results:
#	parents	List of parents of node $node.
#		Immediate ancestor (parent) first,
#		Root of tree (ancestor of all) last.

proc ::struct::tree::_ancestors {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::parent
    set a {}
    while {[info exists parent($node)]} {
	set node $parent($node)
	if {$node == {}} break
	lappend a $node
    }
    return $a
}

# ::struct::tree::_attr --
#
#	Return attribute data for one key and multiple nodes, possibly all.
#
# Arguments:
#	name	Name of the tree object.
#	key	Name of the attribute to retrieve.
#
# Results:
#	children	Dictionary mapping nodes to attribute data.

proc ::struct::tree::_attr {name key args} {
    # Syntax:
    #
    # t attr key
    # t attr key -nodes {nodelist}
    # t attr key -glob nodepattern
    # t attr key -regexp nodepattern

    variable ${name}::attribute

    set usage "wrong # args: should be \"[list $name] attr key ?-nodes list|-glob pattern|-regexp pattern?\""
    if {([llength $args] != 0) && ([llength $args] != 2)} {
	return -code error $usage
    } elseif {[llength $args] == 0} {
	# This automatically restricts the list
	# to nodes which can have the attribute
	# in question.

	set nodes [array names attribute]
    } else {
	# Determine a list of nodes to look at
	# based on the chosen restriction.

	foreach {mode value} $args break
	switch -exact -- $mode {
	    -nodes {
		# This is the only branch where we have to
		# perform an explicit restriction to the
		# nodes which have attributes.
		set nodes {}
		foreach n $value {
		    if {![info exists attribute($n)]} continue
		    lappend nodes $n
		}
	    }
	    -glob {
		set nodes [array names attribute $value]
	    }
	    -regexp {
		set nodes {}
		foreach n [array names attribute] {
		    if {![regexp -- $value $n]} continue
		    lappend nodes $n
		}
	    }
	    default {
		return -code error $usage
	    }
	}
    }

    # Without possibly matching nodes
    # the result has to be empty.

    if {![llength $nodes]} {
	return {}
    }

    # Now locate matching keys and their values.

    set result {}
    foreach n $nodes {
	upvar ${name}::$attribute($n) data
	if {[info exists data($key)]} {
	    lappend result $n $data($key)
	}
    }

    return $result
}

# ::struct::tree::_deserialize --
#
#	Assignment operator. Copies a serialization into the
#       destination, destroying the original information.
#
# Arguments:
#	name	Name of the tree object we are copying into.
#	serial	Serialized tree to copy from.
#
# Results:
#	Nothing.

proc ::struct::tree::_deserialize {name serial} {
    # As we destroy the original tree as part of
    # the copying process we don't have to deal
    # with issues like node names from the new tree
    # interfering with the old ...

    # I. Get the serialization of the source tree
    #    and check it for validity.

    CheckSerialization $serial attr p c rn

    # Get all the relevant data into the scope

    variable ${name}::rootname
    variable ${name}::children
    variable ${name}::parent
    variable ${name}::attribute
    variable ${name}::nextAttr

    # Kill the existing parent/children information and insert the new
    # data in their place.

    foreach n [array names parent] {
	unset parent($n) children($n)
    }
    array set parent   [array get p]
    array set children [array get c]
    unset p c

    set nextAttr 0
    foreach a [array names attribute] {
	unset ${name}::$attribute($a)
    }
    foreach n [array names attr] {
	GenAttributeStorage $name $n
	array set ${name}::$attribute($n) $attr($n)
    }

    set rootname $rn

    ## Debug ## Dump internals ...
    if {0} {
	puts "___________________________________ $name"
	puts $rootname
	parray children
	parray parent
	parray attribute
	puts ___________________________________
    }
    return
}

# ::struct::tree::_children --
#
#	Return the list of children for a given node of a tree.
#
# Arguments:
#	name	Name of the tree object.
#	node	Node to look up.
#
# Results:
#	children	List of children for the node.

proc ::struct::tree::_children {name args} {
    # args := ?-all? node ?filter cmdprefix?

    # '-all' implies that not only the direct children of the
    # node, but all their children, and so on, are returned.
    #
    # 'filter cmd' implies that only those nodes in the result list
    # which pass the test 'cmd' are placed into the final result. 

    set usage "wrong # args: should be \"[list $name] children ?-all? node ?filter cmd?\""

    if {([llength $args] < 1) || ([llength $args] > 4)} {
	return -code error $usage
    }
    if {[string equal [lindex $args 0] -all]} {
	set all 1
	set args [lrange $args 1 end]
    } else {
	set all 0
    }

    # args := node ?filter cmdprefix?

    if {([llength $args] != 1) && ([llength $args] != 3)} {
	return -code error $usage
    }
    if {[llength $args] == 3} {
	foreach {node _const_ cmd} $args break
	if {![string equal $_const_ filter] || ![llength $cmd]} {
	    return -code error $usage
	}
    } else {
	set node [lindex $args 0]
	set cmd {}
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    if {$all} {
	set result [DescendantsCore $name $node]
    } else {
	variable ${name}::children
	set result $children($node)
    }

    if {[llength $cmd]} {
	lappend cmd $name
	set result [uplevel 1 [list ::struct::list filter $result $cmd]]
    }

    return $result
}

# ::struct::tree::_cut --
#
#	Destroys the specified node of a tree, but not its children.
#	These children are made into children of the parent of the
#	destroyed node at the index of the destroyed node.
#
# Arguments:
#	name	Name of the tree object.
#	node	Node to look up and cut.
#
# Results:
#	None.

proc ::struct::tree::_cut {name node} {
    variable ${name}::rootname

    if { [string equal $node $rootname] } {
	# Can't delete the special root node
	return -code error "cannot cut root node"
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::parent
    variable ${name}::children

    # Locate our parent, children and our location in the parent
    set parentNode $parent($node)
    set childNodes $children($node)

    set index [lsearch -exact $children($parentNode) $node]

    # Excise this node from the parent list,
    set newChildren [lreplace $children($parentNode) $index $index]

    # Put each of the children of $node into the parent's children list,
    # in the place of $node, and update the parent pointer of those nodes.
    foreach child $childNodes {
	set newChildren [linsert $newChildren $index $child]
	set parent($child) $parentNode
	incr index
    }
    set children($parentNode) $newChildren

    KillNode $name $node
    return
}

# ::struct::tree::_delete --
#
#	Remove a node from a tree, including all of its values.  Recursively
#	removes the node's children.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to delete.
#
# Results:
#	None.

proc ::struct::tree::_delete {name node} {
    variable ${name}::rootname
    if { [string equal $node $rootname] } {
	# Can't delete the special root node
	return -code error "cannot delete root node"
    }
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::children
    variable ${name}::parent

    # Remove this node from its parent's children list
    set parentNode $parent($node)
    set index [lsearch -exact $children($parentNode) $node]
    ldelete children($parentNode) $index

    # Yes, we could use the stack structure implemented in ::struct::stack,
    # but it's slower than inlining it.  Since we don't need a sophisticated
    # stack, don't bother.
    set st [list]
    foreach child $children($node) {
	lappend st $child
    }

    KillNode $name $node

    while {[llength $st] > 0} {
	set node [lindex $st end]
	ldelete           st end
	foreach child $children($node) {
	    lappend st $child
	}

	KillNode $name $node
    }
    return
}

# ::struct::tree::_depth --
#
#	Return the depth (distance from the root node) of a given node.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to find.
#
# Results:
#	depth	Number of steps from node to the root node.

proc ::struct::tree::_depth {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }
    variable ${name}::parent
    variable ${name}::rootname
    set depth 0
    while { ![string equal $node $rootname] } {
	incr depth
	set node $parent($node)
    }
    return $depth
}

# ::struct::tree::_descendants --
#
#	Return the list containing all descendants of a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to look at.
#
# Results:
#	desc	(filtered) List of nodes descending from 'node'.

proc ::struct::tree::_descendants {name node args} {
    # children -all sucessor, allows filtering.

    set usage "wrong # args: should be \"[list $name] descendants node ?filter cmd?\""

    if {[llength $args] > 2} {
	return -code error $usage
    } elseif {[llength $args] == 2} {
	foreach {_const_ cmd} $args break
	if {![string equal $_const_ filter] || ![llength $cmd]} {
	    return -code error $usage
	}
    } else {
	set cmd {}
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    set result [DescendantsCore $name $node]

    if {[llength $cmd]} {
	lappend cmd $name
	set result [uplevel 1 [list ::struct::list filter $result $cmd]]
    }

    return $result
}

proc ::struct::tree::DescendantsCore {name node} {
    # CORE for listing of node descendants.
    # No checks ...
    # No filtering ...

    variable ${name}::children

    # New implementation. Instead of keeping a second, and explicit,
    # list of pending nodes to shift through (= copying of array data
    # around), we reuse the result list for that, using a counter and
    # direct access to list elements to keep track of what nodes have
    # not been handled yet. This eliminates a whole lot of array
    # copying within the list implementation in the Tcl core. The
    # result is unchanged, i.e. the nodes are in the same order as
    # before.

    set result  $children($node)
    set at      0

    while {$at < [llength $result]} {
	set n [lindex $result $at]
	incr at
	foreach c $children($n) {
	    lappend result $c
	}
    }

    return $result
}

# ::struct::tree::_destroy --
#
#	Destroy a tree, including its associated command and data storage.
#
# Arguments:
#	name	Name of the tree to destroy.
#
# Results:
#	None.

proc ::struct::tree::_destroy {name} {
    namespace delete $name
    interp alias {} $name {}
}

# ::struct::tree::_exists --
#
#	Test for existence of a given node in a tree.
#
# Arguments:
#	name	Name of the tree to query.
#	node	Node to look for.
#
# Results:
#	1 if the node exists, 0 else.

proc ::struct::tree::_exists {name node} {
    return [info exists ${name}::parent($node)]
}

# ::struct::tree::_get --
#
#	Get a keyed value from a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to query.
#	key	Key to lookup.
#
# Results:
#	value	Value associated with the key given.

proc ::struct::tree::_get {name node key} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node, key has to be invalid.
	return -code error "invalid key \"$key\" for node \"$node\""
    }

    upvar ${name}::$attribute($node) data
    if {![info exists data($key)]} {
	return -code error "invalid key \"$key\" for node \"$node\""
    }
    return $data($key)
}

# ::struct::tree::_getall --
#
#	Get a serialized list of key/value pairs from a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to query.
#
# Results:
#	value	A serialized list of key/value pairs.

proc ::struct::tree::_getall {name node {pattern *}} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attributes ...
	return {}
    }

    upvar ${name}::$attribute($node) data
    return [array get data $pattern]
}

# ::struct::tree::_height --
#
#	Return the height (distance from the given node to its deepest child)
#
# Arguments:
#	name	Name of the tree.
#	node	Node we wish to know the height for..
#
# Results:
#	height	Distance to deepest child of the node.

proc ::struct::tree::_height {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::children
    variable ${name}::parent

    if {[llength $children($node)] == 0} {
	# No children, is a leaf, height is 0.
	return 0
    }

    # New implementation. We iteratively compute the height for each
    # node under the specified one, from the bottom up. The previous
    # implementation, using recursion will fail if the encountered
    # subtree has a height greater than the currently set recursion
    # limit.

    array set h {}

    # NOTE: Check out if a for loop doing direct access, i.e. without
    #       list reversal, is faster.

    foreach n [struct::list reverse [DescendantsCore $name $node]] {
	# Height of leafs
	if {![llength $children($n)]} {set h($n) 0}

	# Height of our parent is max of our and previous height.
	set p $parent($n)
	if {![info exists h($p)] || ($h($n) >= $h($p))} {
	    set h($p) [expr {$h($n) + 1}]
	}
    }

    # NOTE: Check out how much we gain by caching the result.
    #       For all nodes we have this computed. Use cache here
    #       as well to cut the inspection of descendants down.
    #       This may degenerate into a recursive solution again
    #       however.

    return $h($node)
}

# ::struct::tree::_keys --
#
#	Get a list of keys from a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to query.
#
# Results:
#	value	A serialized list of key/value pairs.

proc ::struct::tree::_keys {name node {pattern *}} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node.
	return {}
    }

    upvar ${name}::$attribute($node) data
    return [array names data $pattern]
}

# ::struct::tree::_keyexists --
#
#	Test for existence of a given key for a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to query.
#	key	Key to lookup.
#
# Results:
#	1 if the key exists, 0 else.

proc ::struct::tree::_keyexists {name node key} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node, key cannot exist
	return 0
    }

    upvar ${name}::$attribute($node) data
    return [info exists data($key)]
}

# ::struct::tree::_index --
#
#	Determine the index of node with in its parent's list of children.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to look up.
#
# Results:
#	index	The index of the node in its parent

proc ::struct::tree::_index {name node} {
    variable ${name}::rootname
    if { [string equal $node $rootname] } {
	# The special root node has no parent, thus no index in it either.
	return -code error "cannot determine index of root node"
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::children
    variable ${name}::parent

    # Locate the parent and ourself in its list of children
    set parentNode $parent($node)

    return [lsearch -exact $children($parentNode) $node]
}

# ::struct::tree::_insert --
#
#	Add a node to a tree; if the node(s) specified already exist, they
#	will be moved to the given location.
#
# Arguments:
#	name		Name of the tree.
#	parentNode	Parent to add the node to.
#	index		Index at which to insert.
#	args		Node(s) to insert.  If none is given, the routine
#			will insert a single node with a unique name.
#
# Results:
#	nodes		List of nodes inserted.

proc ::struct::tree::_insert {name parentNode index args} {
    if { [llength $args] == 0 } {
	# No node name was given; generate a unique one
	set args [list [GenerateUniqueNodeName $name]]
    }
    if { ![_exists $name $parentNode] } {
	return -code error "parent node \"$parentNode\" does not exist in tree \"$name\""
    }

    variable ${name}::parent
    variable ${name}::children
    variable ${name}::rootname

    # Make sure the index is numeric

    if {[string equal $index "end"]} {
	set index [llength $children($parentNode)]
    } elseif {[regexp {^end-([0-9]+)$} $index -> n]} {
	set index [expr {[llength $children($parentNode)] - $n}]
    }

    foreach node $args {
	if {[_exists $name $node] } {
	    # Move the node to its new home
	    if { [string equal $node $rootname] } {
		return -code error "cannot move root node"
	    }
	
	    # Cannot make a node its own descendant (I'm my own grandpa...)
	    set ancestor $parentNode
	    while { ![string equal $ancestor $rootname] } {
		if { [string equal $ancestor $node] } {
		    return -code error "node \"$node\" cannot be its own descendant"
		}
		set ancestor $parent($ancestor)
	    }
	    # Remove this node from its parent's children list
	    set oldParent $parent($node)
	    set ind [lsearch -exact $children($oldParent) $node]
	    ldelete children($oldParent) $ind
	
	    # If the node is moving within its parent, and its old location
	    # was before the new location, decrement the new location, so that
	    # it gets put in the right spot
	    if { [string equal $oldParent $parentNode] && $ind < $index } {
		incr index -1
	    }
	} else {
	    # Set up the new node
	    set children($node) [list]
	}

	# Add this node to its parent's children list
	set children($parentNode) [linsert $children($parentNode) $index $node]

	# Update the parent pointer for this node
	set parent($node) $parentNode
	incr index
    }

    return $args
}

# ::struct::tree::_isleaf --
#
#	Return whether the given node of a tree is a leaf or not.
#
# Arguments:
#	name	Name of the tree object.
#	node	Node to look up.
#
# Results:
#	isleaf	True if the node is a leaf; false otherwise.

proc ::struct::tree::_isleaf {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::children
    return [expr {[llength $children($node)] == 0}]
}

# ::struct::tree::_move --
#
#	Move a node (and all its subnodes) from where ever it is to a new
#	location in the tree.
#
# Arguments:
#	name		Name of the tree
#	parentNode	Parent to add the node to.
#	index		Index at which to insert.
#	node		Node to move; the node must exist in the tree.
#	args		Additional nodes to move; these nodes must exist
#			in the tree.
#
# Results:
#	None.

proc ::struct::tree::_move {name parentNode index node args} {
    set args [linsert $args 0 $node]

    # Can only move a node to a real location in the tree
    if { ![_exists $name $parentNode] } {
	return -code error "parent node \"$parentNode\" does not exist in tree \"$name\""
    }

    variable ${name}::parent
    variable ${name}::children
    variable ${name}::rootname

    # Make sure the index is numeric

    if {[string equal $index "end"]} {
	set index [llength $children($parentNode)]
    } elseif {[regexp {^end-([0-9]+)$} $index -> n]} {
	set index [expr {[llength $children($parentNode)] - $n}]
    }

    # Validate all nodes to move before trying to move any.
    foreach node $args {
	if { [string equal $node $rootname] } {
	    return -code error "cannot move root node"
	}

	# Can only move real nodes
	if { ![_exists $name $node] } {
	    return -code error "node \"$node\" does not exist in tree \"$name\""
	}

	# Cannot move a node to be a descendant of itself
	set ancestor $parentNode
	while { ![string equal $ancestor $rootname] } {
	    if { [string equal $ancestor $node] } {
		return -code error "node \"$node\" cannot be its own descendant"
	    }
	    set ancestor $parent($ancestor)
	}
    }

    # Remove all nodes from their current parent's children list
    foreach node $args {
	set oldParent $parent($node)
	set ind [lsearch -exact $children($oldParent) $node]

	ldelete children($oldParent) $ind

	# Update the nodes parent value
	set parent($node) $parentNode
    }

    # Add all nodes to their new parent's children list
    set children($parentNode) \
	[eval [list linsert $children($parentNode) $index] $args]

    return
}

# ::struct::tree::_next --
#
#	Return the right sibling for a given node of a tree.
#
# Arguments:
#	name		Name of the tree object.
#	node		Node to retrieve right sibling for.
#
# Results:
#	sibling		The right sibling for the node, or null if node was
#			the rightmost child of its parent.

proc ::struct::tree::_next {name node} {
    # The 'root' has no siblings.
    variable ${name}::rootname
    if { [string equal $node $rootname] } {
	return {}
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    # Locate the parent and our place in its list of children.
    variable ${name}::parent
    variable ${name}::children

    set parentNode $parent($node)
    set  index [lsearch -exact $children($parentNode) $node]

    # Go to the node to the right and return its name.
    return [lindex $children($parentNode) [incr index]]
}

# ::struct::tree::_numchildren --
#
#	Return the number of immediate children for a given node of a tree.
#
# Arguments:
#	name		Name of the tree object.
#	node		Node to look up.
#
# Results:
#	numchildren	Number of immediate children for the node.

proc ::struct::tree::_numchildren {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::children
    return [llength $children($node)]
}

# ::struct::tree::_nodes --
#
#	Return a list containing all nodes known to the tree.
#
# Arguments:
#	name		Name of the tree object.
#
# Results:
#	nodes	List of nodes in the tree.

proc ::struct::tree::_nodes {name} {
    variable ${name}::children
    return [array names children]
}

# ::struct::tree::_parent --
#
#	Return the name of the parent node of a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to look up.
#
# Results:
#	parent	Parent of node $node

proc ::struct::tree::_parent {name node} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }
    # FRINK: nocheck
    return [set ${name}::parent($node)]
}

# ::struct::tree::_previous --
#
#	Return the left sibling for a given node of a tree.
#
# Arguments:
#	name		Name of the tree object.
#	node		Node to look up.
#
# Results:
#	sibling		The left sibling for the node, or null if node was
#			the leftmost child of its parent.

proc ::struct::tree::_previous {name node} {
    # The 'root' has no siblings.
    variable ${name}::rootname
    if { [string equal $node $rootname] } {
	return {}
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    # Locate the parent and our place in its list of children.
    variable ${name}::parent
    variable ${name}::children

    set parentNode $parent($node)
    set  index [lsearch -exact $children($parentNode) $node]

    # Go to the node to the right and return its name.
    return [lindex $children($parentNode) [incr index -1]]
}

# ::struct::tree::_rootname --
#
#	Query or change the name of the root node.
#
# Arguments:
#	name	Name of the tree.
#
# Results:
#	The name of the root node

proc ::struct::tree::_rootname {name} {
    variable ${name}::rootname
    return $rootname
}

# ::struct::tree::_rename --
#
#	Change the name of any node.
#
# Arguments:
#	name	Name of the tree.
#	node	Name of node to be renamed
#	newname	New name for the node.
#
# Results:
#	The new name of the node.

proc ::struct::tree::_rename {name node newname} {
    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }
    if {[_exists $name $newname]} {
	return -code error "unable to rename node to \"$newname\",\
		node of that name already present in the tree \"$name\""
    }

    set oldname  $node

    # Perform the rename in the internal
    # data structures.

    variable ${name}::rootname
    variable ${name}::children
    variable ${name}::parent
    variable ${name}::attribute

    set children($newname) $children($oldname)
    unset                   children($oldname)
    set parent($newname)     $parent($oldname)
    unset                     parent($oldname)

    foreach c $children($newname) {
	set parent($c) $newname
    }

    if {[string equal $oldname $rootname]} {
	set rootname $newname
    } else {
	set p $parent($newname)
	set pos  [lsearch -exact $children($p) $oldname]
	lset children($p) $pos $newname
    }

    if {[info exists attribute($oldname)]} {
	set attribute($newname) $attribute($oldname)
	unset                    attribute($oldname)
    }

    return $newname
}

# ::struct::tree::_serialize --
#
#	Serialize a tree object (partially) into a transportable value.
#
# Arguments:
#	name	Name of the tree.
#	node	Root node of the serialized tree.
#
# Results:
#	A list structure describing the part of the tree which was serialized.

proc ::struct::tree::_serialize {name args} {
    if {[llength $args] > 1} {
	return -code error \
		"wrong # args: should be \"[list $name] serialize ?node?\""
    } elseif {[llength $args] == 1} {
	set node [lindex $args 0]

	if {![_exists $name $node]} {
	    return -code error "node \"$node\" does not exist in tree \"$name\""
	}
    } else {
	variable ${name}::rootname
	set node $rootname
    }

    set                   tree [list]
    Serialize $name $node tree
    return               $tree
}

# ::struct::tree::_set --
#
#	Set or get a value for a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to modify or query.
#	args	Optional argument specifying a value.
#
# Results:
#	val	Value associated with the given key of the given node

proc ::struct::tree::_set {name node key args} {
    if {[llength $args] > 1} {
	return -code error "wrong # args: should be \"$name set node key\
		?value?\""
    }
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    # Process the arguments ...

    if {[llength $args] > 0} {
	# Setting the value. This may have to create
	# the attribute array for this particular
	# node

	variable ${name}::attribute
	if {![info exists attribute($node)]} {
	    # No attribute data for this node,
	    # so create it as we need it now.
	    GenAttributeStorage $name $node
	}
	upvar ${name}::$attribute($node) data

	return [set data($key) [lindex $args end]]
    } else {
	# Getting the value

	return [_get $name $node $key]
    }
}

# ::struct::tree::_append --
#
#	Append a value for a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to modify.
#	key	Name of attribute to modify.
#	value	Value to append
#
# Results:
#	val	Value associated with the given key of the given node

proc ::struct::tree::_append {name node key value} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node,
	# so create it as we need it.
	GenAttributeStorage $name $node
    }

    upvar ${name}::$attribute($node) data
    return [append data($key) $value]
}

# ::struct::tree::_lappend --
#
#	lappend a value for a node in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to modify or query.
#	key	Name of attribute to modify.
#	value	Value to append
#
# Results:
#	val	Value associated with the given key of the given node

proc ::struct::tree::_lappend {name node key value} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node,
	# so create it as we need it.
	GenAttributeStorage $name $node
    }

    upvar ${name}::$attribute($node) data
    return [lappend data($key) $value]
}

# ::struct::tree::_leaves --
#
#	Return a list containing all leaf nodes known to the tree.
#
# Arguments:
#	name		Name of the tree object.
#
# Results:
#	nodes	List of leaf nodes in the tree.

proc ::struct::tree::_leaves {name} {
    variable ${name}::children

    set res {}
    foreach n [array names children] {
	if {[llength $children($n)]} continue
	lappend res $n
    }
    return $res
}

# ::struct::tree::_size --
#
#	Return the number of descendants of a given node.  The default node
#	is the special root node.
#
# Arguments:
#	name	Name of the tree.
#	node	Optional node to start counting from (default is root).
#
# Results:
#	size	Number of descendants of the node.

proc ::struct::tree::_size {name args} {
    variable ${name}::rootname
    if {[llength $args] > 1} {
	return -code error \
		"wrong # args: should be \"[list $name] size ?node?\""
    } elseif {[llength $args] == 1} {
	set node [lindex $args 0]

	if { ![_exists $name $node] } {
	    return -code error "node \"$node\" does not exist in tree \"$name\""
	}
    } else {
	# If the node is the root, we can do the cheap thing and just count the
	# number of nodes (excluding the root node) that we have in the tree with
	# array size.

	return [expr {[array size ${name}::parent] - 1}]
    }

    # If the node is the root, we can do the cheap thing and just count the
    # number of nodes (excluding the root node) that we have in the tree with
    # array size.

    if { [string equal $node $rootname] } {
	return [expr {[array size ${name}::parent] - 1}]
    }

    # Otherwise we have to do it the hard way and do a full tree search
    variable ${name}::children
    set size 0
    set st [list ]
    foreach child $children($node) {
	lappend st $child
    }
    while { [llength $st] > 0 } {
	set node [lindex $st end]
	ldelete st end
	incr size
	foreach child $children($node) {
	    lappend st $child
	}
    }
    return $size
}

# ::struct::tree::_splice --
#
#	Add a node to a tree, making a range of children from the given
#	parent children of the new node.
#
# Arguments:
#	name		Name of the tree.
#	parentNode	Parent to add the node to.
#	from		Index at which to insert.
#	to		Optional end of the range of children to replace.
#			Defaults to 'end'.
#	args		Optional node name; if given, must be unique.  If not
#			given, a unique name will be generated.
#
# Results:
#	node		Name of the node added to the tree.

proc ::struct::tree::_splice {name parentNode from {to end} args} {

    if { ![_exists $name $parentNode] } {
	return -code error "node \"$parentNode\" does not exist in tree \"$name\""
    }

    if { [llength $args] == 0 } {
	# No node name given; generate a unique node name
	set node [GenerateUniqueNodeName $name]
    } else {
	set node [lindex $args 0]
    }

    if { [_exists $name $node] } {
	return -code error "node \"$node\" already exists in tree \"$name\""
    }

    variable ${name}::children
    variable ${name}::parent

    if {[string equal $from "end"]} {
	set from [expr {[llength $children($parentNode)] - 1}]
    } elseif {[regexp {^end-([0-9]+)$} $from -> n]} {
	set from [expr {[llength $children($parentNode)] - 1 - $n}]
    }
    if {[string equal $to "end"]} {
	set to [expr {[llength $children($parentNode)] - 1}]
    } elseif {[regexp {^end-([0-9]+)$} $to -> n]} {
	set to   [expr {[llength $children($parentNode)] - 1 - $n}]
    }

    # Save the list of children that are moving
    set moveChildren [lrange $children($parentNode) $from $to]

    # Remove those children from the parent
    ldelete children($parentNode) $from $to

    # Add the new node
    _insert $name $parentNode $from $node

    # Move the children
    set children($node) $moveChildren
    foreach child $moveChildren {
	set parent($child) $node
    }

    return $node
}

# ::struct::tree::_swap --
#
#	Swap two nodes in a tree.
#
# Arguments:
#	name	Name of the tree.
#	node1	First node to swap.
#	node2	Second node to swap.
#
# Results:
#	None.

proc ::struct::tree::_swap {name node1 node2} {
    # Can't swap the magic root node
    variable ${name}::rootname
    if {[string equal $node1 $rootname] || [string equal $node2 $rootname]} {
	return -code error "cannot swap root node"
    }

    # Can only swap two real nodes
    if {![_exists $name $node1]} {
	return -code error "node \"$node1\" does not exist in tree \"$name\""
    }
    if {![_exists $name $node2]} {
	return -code error "node \"$node2\" does not exist in tree \"$name\""
    }

    # Can't swap a node with itself
    if {[string equal $node1 $node2]} {
	return -code error "cannot swap node \"$node1\" with itself"
    }

    # Swapping nodes means swapping their labels and values
    variable ${name}::children
    variable ${name}::parent

    set parent1 $parent($node1)
    set parent2 $parent($node2)

    # Replace node1 with node2 in node1's parent's children list, and
    # node2 with node1 in node2's parent's children list
    set i1 [lsearch -exact $children($parent1) $node1]
    set i2 [lsearch -exact $children($parent2) $node2]

    lset children($parent1) $i1 $node2
    lset children($parent2) $i2 $node1

    # Make node1 the parent of node2's children, and vis versa
    foreach child $children($node2) {
	set parent($child) $node1
    }
    foreach child $children($node1) {
	set parent($child) $node2
    }

    # Swap the children lists
    set children1 $children($node1)
    set children($node1) $children($node2)
    set children($node2) $children1

    if { [string equal $node1 $parent2] } {
	set parent($node1) $node2
	set parent($node2) $parent1
    } elseif { [string equal $node2 $parent1] } {
	set parent($node1) $parent2
	set parent($node2) $node1
    } else {
	set parent($node1) $parent2
	set parent($node2) $parent1
    }

    return
}

# ::struct::tree::_unset --
#
#	Remove a keyed value from a node.
#
# Arguments:
#	name	Name of the tree.
#	node	Node to modify.
#	key	Name of attribute to unset.
#
# Results:
#	None.

proc ::struct::tree::_unset {name node key} {
    if {![_exists $name $node]} {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    variable ${name}::attribute
    if {![info exists attribute($node)]} {
	# No attribute data for this node,
	# nothing to do.
	return
    }

    upvar ${name}::$attribute($node) data
    catch {unset data($key)}

    if {[array size data] == 0} {
	# No attributes stored for this node, squash the whole array.
	unset attribute($node)
	unset data
    }
    return
}

# ::struct::tree::_walk --
#
#	Walk a tree using a pre-order depth or breadth first
#	search. Pre-order DFS is the default.  At each node that is visited,
#	a command will be called with the name of the tree and the node.
#
# Arguments:
#	name	Name of the tree.
#	node	Node at which to start.
#	args	Optional additional arguments specifying the type and order of
#		the tree walk, and the command to execute at each node.
#		Format is
#		    ?-type {bfs|dfs}? ?-order {pre|post|in|both}? a n script
#
# Results:
#	None.

proc ::struct::tree::_walk {name node args} {
    set usage "$name walk node ?-type {bfs|dfs}? ?-order {pre|post|in|both}? ?--? loopvar script"

    if {[llength $args] > 7 || [llength $args] < 2} {
	return -code error "wrong # args: should be \"$usage\""
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    set args [WalkOptions $args 2 $usage]
    # Remainder is 'a n script'

    foreach {loopvariables script} $args break

    if {[llength $loopvariables] > 2} {
	return -code error "too many loop variables, at most two allowed"
    } elseif {[llength $loopvariables] == 2} {
	foreach {avar nvar} $loopvariables break
    } else {
	set nvar [lindex $loopvariables 0]
	set avar {}
    }

    # Make sure we have a script to run, otherwise what's the point?
    if { [string equal $script ""] } {
	return -code error "no script specified, or empty"
    }

    # Do the walk
    variable ${name}::children
    set st [list ]
    lappend st $node

    # Compute some flags for the possible places of command evaluation
    set leave [expr {[string equal $order post] || [string equal $order both]}]
    set enter [expr {[string equal $order pre]  || [string equal $order both]}]
    set touch [string equal $order in]

    if {$leave} {
	set lvlabel leave
    } elseif {$touch} {
	# in-order does not provide a sense
	# of nesting for the parent, hence
	# no enter/leave, just 'visit'.
	set lvlabel visit
    }

    set rcode 0
    set rvalue {}

    if {[string equal $type "dfs"]} {
	# Depth-first walk, several orders of visiting nodes
	# (pre, post, both, in)

	array set visited {}

	while { [llength $st] > 0 } {
	    set node [lindex $st end]

	    if {[info exists visited($node)]} {
		# Second time we are looking at this 'node'.
		# Pop it, then evaluate the command (post, both, in).

		ldelete st end

		if {$leave || $touch} {
		    # Evaluate the script at this node
		    WalkCall $avar $nvar $name $node $lvlabel $script
		    # prune stops execution of loop here.
		}
	    } else {
		# First visit of this 'node'.
		# Do *not* pop it from the stack so that we are able
		# to visit again after its children

		# Remember it.
		set visited($node) .

		if {$enter} {
		    # Evaluate the script at this node (pre, both).
		    #
		    # Note: As this is done before the children are
		    # looked at the script may change the children of
		    # this node and thus affect the walk.

		    WalkCall $avar $nvar $name $node "enter" $script
		    # prune stops execution of loop here.
		}

		# Add the children of this node to the stack.
		# The exact behaviour depends on the chosen
		# order. For pre, post, both-order we just
		# have to add them in reverse-order so that
		# they will be popped left-to-right. For in-order
		# we have rearrange the stack so that the parent
		# is revisited immediately after the first child.
		# (but only if there is ore than one child,)

		set clist        $children($node)
		set len [llength $clist]

		if {$touch && ($len > 1)} {
		    # Pop node from stack, insert into list of children
		    ldelete st end
		    set clist [linsert $clist 1 $node]
		    incr len
		}

		for {set i [expr {$len - 1}]} {$i >= 0} {incr i -1} {
		    lappend st [lindex $clist $i]
		}
	    }
	}
    } else {
	# Breadth first walk (pre, post, both)
	# No in-order possible. Already captured.

	if {$leave} {
	    set backward $st
	}

	while { [llength $st] > 0 } {
	    set node [lindex   $st 0]
	    ldelete st 0

	    if {$enter} {
		# Evaluate the script at this node
		WalkCall $avar $nvar $name $node "enter" $script
		# prune stops execution of loop here.
	    }

	    # Add this node's children
	    # And create a mirrored version in case of post/both order.

	    foreach child $children($node) {
		lappend st $child
		if {$leave} {
		    set backward [linsert $backward 0 $child]
		}
	    }
	}

	if {$leave} {
	    foreach node $backward {
		# Evaluate the script at this node
		WalkCall $avar $nvar $name $node "leave" $script
	    }
	}
    }

    if {$rcode != 0} {
	return -code $rcode $rvalue
    }
    return
}

proc ::struct::tree::_walkproc {name node args} {
    set usage "$name walkproc node ?-type {bfs|dfs}? ?-order {pre|post|in|both}? ?--? cmdprefix"

    if {[llength $args] > 6 || [llength $args] < 1} {
	return -code error "wrong # args: should be \"$usage\""
    }

    if { ![_exists $name $node] } {
	return -code error "node \"$node\" does not exist in tree \"$name\""
    }

    set args [WalkOptions $args 1 $usage]
    # Remainder is 'n cmdprefix'

    set script [lindex $args 0]

    # Make sure we have a script to run, otherwise what's the point?
    if { ![llength $script] } {
	return -code error "no script specified, or empty"
    }

    # Do the walk
    variable ${name}::children
    set st [list ]
    lappend st $node

    # Compute some flags for the possible places of command evaluation
    set leave [expr {[string equal $order post] || [string equal $order both]}]
    set enter [expr {[string equal $order pre]  || [string equal $order both]}]
    set touch [string equal $order in]

    if {$leave} {
	set lvlabel leave
    } elseif {$touch} {
	# in-order does not provide a sense
	# of nesting for the parent, hence
	# no enter/leave, just 'visit'.
	set lvlabel visit
    }

    set rcode 0
    set rvalue {}

    if {[string equal $type "dfs"]} {
	# Depth-first walk, several orders of visiting nodes
	# (pre, post, both, in)

	array set visited {}

	while { [llength $st] > 0 } {
	    set node [lindex $st end]

	    if {[info exists visited($node)]} {
		# Second time we are looking at this 'node'.
		# Pop it, then evaluate the command (post, both, in).

		ldelete st end

		if {$leave || $touch} {
		    # Evaluate the script at this node
		    WalkCallProc $name $node $lvlabel $script
		    # prune stops execution of loop here.
		}
	    } else {
		# First visit of this 'node'.
		# Do *not* pop it from the stack so that we are able
		# to visit again after its children

		# Remember it.
		set visited($node) .

		if {$enter} {
		    # Evaluate the script at this node (pre, both).
		    #
		    # Note: As this is done before the children are
		    # looked at the script may change the children of
		    # this node and thus affect the walk.

		    WalkCallProc $name $node "enter" $script
		    # prune stops execution of loop here.
		}

		# Add the children of this node to the stack.
		# The exact behaviour depends on the chosen
		# order. For pre, post, both-order we just
		# have to add them in reverse-order so that
		# they will be popped left-to-right. For in-order
		# we have rearrange the stack so that the parent
		# is revisited immediately after the first child.
		# (but only if there is ore than one child,)

		set clist        $children($node)
		set len [llength $clist]

		if {$touch && ($len > 1)} {
		    # Pop node from stack, insert into list of children
		    ldelete st end
		    set clist [linsert $clist 1 $node]
		    incr len
		}

		for {set i [expr {$len - 1}]} {$i >= 0} {incr i -1} {
		    lappend st [lindex $clist $i]
		}
	    }
	}
    } else {
	# Breadth first walk (pre, post, both)
	# No in-order possible. Already captured.

	if {$leave} {
	    set backward $st
	}

	while { [llength $st] > 0 } {
	    set node [lindex   $st 0]
	    ldelete st 0

	    if {$enter} {
		# Evaluate the script at this node
		WalkCallProc $name $node "enter" $script
		# prune stops execution of loop here.
	    }

	    # Add this node's children
	    # And create a mirrored version in case of post/both order.

	    foreach child $children($node) {
		lappend st $child
		if {$leave} {
		    set backward [linsert $backward 0 $child]
		}
	    }
	}

	if {$leave} {
	    foreach node $backward {
		# Evaluate the script at this node
		WalkCallProc $name $node "leave" $script
	    }
	}
    }

    if {$rcode != 0} {
	return -code $rcode $rvalue
    }
    return
}

proc ::struct::tree::WalkOptions {theargs n usage} {
    upvar 1 type type order order

    # Set defaults
    set type dfs
    set order pre

    while {[llength $theargs]} {
	set flag [lindex $theargs 0]
	switch -exact -- $flag {
	    "-type" {
		if {[llength $theargs] < 2} {
		    return -code error "value for \"$flag\" missing"
		}
		set type [string tolower [lindex $theargs 1]]
		set theargs [lrange $theargs 2 end]
	    }
	    "-order" {
		if {[llength $theargs] < 2} {
		    return -code error "value for \"$flag\" missing"
		}
		set order [string tolower [lindex $theargs 1]]
		set theargs [lrange $theargs 2 end]
	    }
	    "--" {
		set theargs [lrange $theargs 1 end]
		break
	    }
	    default {
		break
	    }
	}
    }

    if {[llength $theargs] == 0} {
	return -code error "wrong # args: should be \"$usage\""
    }
    if {[llength $theargs] != $n} {
	return -code error "unknown option \"$flag\""
    }

    # Validate that the given type is good
    switch -exact -- $type {
	"dfs" - "bfs" {
	    set type $type
	}
	default {
	    return -code error "bad search type \"$type\": must be bfs or dfs"
	}
    }

    # Validate that the given order is good
    switch -exact -- $order {
	"pre" - "post" - "in" - "both" {
	    set order $order
	}
	default {
	    return -code error "bad search order \"$order\":\
		    must be both, in, pre, or post"
	}
    }

    if {[string equal $order "in"] && [string equal $type "bfs"]} {
	return -code error "unable to do a ${order}-order breadth first walk"
    }

    return $theargs
}

# ::struct::tree::WalkCall --
#
#	Helper command to 'walk' handling the evaluation
#	of the user-specified command. Information about
#	the tree, node and current action are substituted
#	into the command before it evaluation.
#
# Arguments:
#	tree	Tree we are walking
#	node	Node we are at.
#	action	The current action.
#	cmd	The command to call, already partially substituted.
#
# Results:
#	None.

proc ::struct::tree::WalkCall {avar nvar tree node action cmd} {

    if {$avar != {}} {
	upvar 2 $avar a ; set a $action
    }
    upvar 2 $nvar n ; set n $node

    set code [catch {uplevel 2 $cmd} result]

    # decide what to do upon the return code:
    #
    #               0 - the body executed successfully
    #               1 - the body raised an error
    #               2 - the body invoked [return]
    #               3 - the body invoked [break]
    #               4 - the body invoked [continue]
    #               5 - the body invoked [struct::tree::prune]
    # everything else - return and pass on the results
    #
    switch -exact -- $code {
	0 {}
	1 {
	    return -errorinfo [ErrorInfoAsCaller uplevel WalkCall]  \
		    -errorcode $::errorCode -code error $result
	}
	3 {
	    # FRINK: nocheck
	    return -code break
	}
	4 {}
	5 {
	    upvar order order
	    if {[string equal $order post] || [string equal $order in]} {
		return -code error "Illegal attempt to prune ${order}-order walking"
	    }
	    return -code continue
	}
	default {
	    upvar 1 rcode rcode rvalue rvalue
	    set rcode $code
	    set rvalue $result
	    return -code break
	    #return -code $code $result
	}
    }
    return {}
}

proc ::struct::tree::WalkCallProc {tree node action cmd} {

    lappend cmd $tree $node $action
    set code [catch {uplevel 2 $cmd} result]

    # decide what to do upon the return code:
    #
    #               0 - the body executed successfully
    #               1 - the body raised an error
    #               2 - the body invoked [return]
    #               3 - the body invoked [break]
    #               4 - the body invoked [continue]
    #               5 - the body invoked [struct::tree::prune]
    # everything else - return and pass on the results
    #
    switch -exact -- $code {
	0 {}
	1 {
	    return -errorinfo [ErrorInfoAsCaller uplevel WalkCallProc]  \
		    -errorcode $::errorCode -code error $result
	}
	3 {
	    # FRINK: nocheck
	    return -code break
	}
	4 {}
	5 {
	    upvar order order
	    if {[string equal $order post] || [string equal $order in]} {
		return -code error "Illegal attempt to prune ${order}-order walking"
	    }
	    return -code continue
	}
	default {
	    upvar 1 rcode rcode rvalue rvalue
	    set rcode $code
	    set rvalue $result
	    return -code break
	}
    }
    return {}
}

proc ::struct::tree::ErrorInfoAsCaller {find replace} {
    set info $::errorInfo
    set i [string last "\n    (\"$find" $info]
    if {$i == -1} {return $info}
    set result [string range $info 0 [incr i 6]]	;# keep "\n    (\""
    append result $replace			;# $find -> $replace
    incr i [string length $find]
    set j [string first ) $info [incr i]]	;# keep rest of parenthetical
    append result [string range $info $i $j]
    return $result
}

# ::struct::tree::GenerateUniqueNodeName --
#
#	Generate a unique node name for the given tree.
#
# Arguments:
#	name	Name of the tree to generate a unique node name for.
#
# Results:
#	node	Name of a node guaranteed to not exist in the tree.

proc ::struct::tree::GenerateUniqueNodeName {name} {
    variable ${name}::nextUnusedNode
    while {[_exists $name "node${nextUnusedNode}"]} {
	incr nextUnusedNode
    }
    return "node${nextUnusedNode}"
}

# ::struct::tree::KillNode --
#
#	Delete all data of a node.
#
# Arguments:
#	name	Name of the tree containing the node
#	node	Name of the node to delete.
#
# Results:
#	none

proc ::struct::tree::KillNode {name node} {
    variable ${name}::parent
    variable ${name}::children
    variable ${name}::attribute

    # Remove all record of $node
    unset parent($node)
    unset children($node)

    if {[info exists attribute($node)]} {
	# FRINK: nocheck
	unset ${name}::$attribute($node)
	unset attribute($node)
    }
    return
}

# ::struct::tree::GenAttributeStorage --
#
#	Create an array to store the attributes of a node in.
#
# Arguments:
#	name	Name of the tree containing the node
#	node	Name of the node which got attributes.
#
# Results:
#	none

proc ::struct::tree::GenAttributeStorage {name node} {
    variable ${name}::nextAttr
    variable ${name}::attribute

    set   attr "a[incr nextAttr]"
    set   attribute($node) $attr
    return
}

# ::struct::tree::Serialize --
#
#	Serialize a tree object (partially) into a transportable value.
#
# Arguments:
#	name	Name of the tree.
#	node	Root node of the serialized tree.
#
# Results:
#	None

proc ::struct::tree::Serialize {name node tvar} {
    upvar 1 $tvar tree

    variable ${name}::attribute
    variable ${name}::parent

    # 'node' is the root of the tree to serialize. The precondition
    # for the call is that this node is already stored in the list
    # 'tvar', at index 'rootidx'.

    # The attribute data for 'node' goes immediately after the 'node'
    # data. the node information is _not_ yet stored, and this command
    # has to do this.


    array set r {}
    set loc($node) 0

    lappend tree $node {}
    if {[info exists attribute($node)]} {
	upvar ${name}::$attribute($node) data
	lappend tree [array get data]
    } else {
	# Encode nodes without attributes.
	lappend tree {}
    }

    foreach n [DescendantsCore $name $node] {
	set loc($n) [llength $tree]
	lappend tree $n $loc($parent($n))

	if {[info exists attribute($n)]} {
	    upvar ${name}::$attribute($n) data
	    lappend tree [array get data]
	} else {
	    # Encode nodes without attributes.
	    lappend tree {}
	}
    }

    return $tree
}


proc ::struct::tree::CheckSerialization {ser avar pvar cvar rnvar} {
    upvar 1 $avar attr $pvar p $cvar ch $rnvar rn

    # Overall length ok ?

    if {[llength $ser] % 3} {
	return -code error \
		"error in serialization: list length not a multiple of 3."
    }

    set rn {}
    array set p    {}
    array set ch   {}
    array set attr {}

    # Basic decoder pass

    foreach {node parent nattr} $ser {

	# Initialize children data, if not already done
	if {![info exists ch($node)]} {
	    set ch($node) {}
	}
	# Attribute length ok ? Dictionary!
	if {[llength $nattr] % 2} {
	    return -code error \
		    "error in serialization: malformed attribute dictionary."
	}
	# Remember attribute data only for non-empty nodes
	if {[llength $nattr]} {
	    set attr($node) $nattr
	}
	# Remember root
	if {$parent == {}} {
	    lappend rn $node
	    set p($node) {}
	    continue
	}
	# Parent reference ok ?
	##nagelfar ignore
	if {
	    ![string is integer -strict $parent] ||
	    ($parent % 3) ||
	    ($parent < 0) ||
	    ($parent >= [llength $ser])
	} {
	    return -code error \
		    "error in serialization: bad parent reference \"$parent\"."
	}
	# Remember parent, and reconstruct children

	set p($node) [lindex $ser $parent]
	lappend ch($p($node)) $node
    }

    # Root node information ok ?

    if {[llength $rn] < 1} {
	return -code error \
		"error in serialization: no root specified."
    } elseif {[llength $rn] > 1} {
	return -code error \
		"error in serialization: multiple root nodes."
    }
    set rn [lindex $rn 0]

    # Duplicate node names ?

    if {[array size ch] < ([llength $ser] / 3)} {
	return -code error \
		"error in serialization: duplicate node names."
    }

    # Cycles in the parent relationship ?

    array set visited {}
    foreach n [array names p] {
	if {[info exists visited($n)]} {continue}
	array set _ {}
	while {$n != {}} {
	    if {[info exists _($n)]} {
		# Node already converted, cycle.
		return -code error \
			"error in serialization: cycle detected."
	    }
	    set _($n)       .
	    # root ?
	    if {$p($n) == {}} {break}
	    set n $p($n)
	    if {[info exists visited($n)]} {break}
	    set visited($n) .
	}
	unset _
    }
    # Ok. The data is now ready for the caller.

    return
}

##########################
# Private functions follow
#
# Do a compatibility version of [lset] for pre-8.4 versions of Tcl.
# This version does not do multi-arg [lset]!

proc ::struct::tree::K { x y } { set x }

if { [package vcompare [package provide Tcl] 8.4] < 0 } {
    proc ::struct::tree::lset { var index arg } {
	upvar 1 $var list
	set list [::lreplace [K $list [set list {}]] $index $index $arg]
    }
}

proc ::struct::tree::ldelete {var index {end {}}} {
    upvar 1 $var list
    if {$end == {}} {set end $index}
    set list [lreplace [K $list [set list {}]] $index $end]
    return
}

# ### ### ### ######### ######### #########
## Ready

namespace eval ::struct {
    # Put 'tree::tree' into the general structure namespace
    # for pickup by the main management.

    namespace import -force tree::tree_tcl
}