File: htmltree.c

package info (click to toggle)
tk-html3 3.0~fossil20110109-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 6,632 kB
  • sloc: ansic: 48,994; tcl: 26,030; sh: 1,190; yacc: 161; makefile: 24
file content (3307 lines) | stat: -rw-r--r-- 94,665 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
/*
 * HtmlTree.c ---
 *
 *     This file implements the tree structure that can be used to access
 *     elements of an HTML document.
 *
 *--------------------------------------------------------------------------
 * Copyright (c) 2005 Eolas Technologies Inc.
 * All rights reserved.
 *
 * This Open Source project was made possible through the financial support
 * of Eolas Technologies Inc.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

static const char rcsid[] = "$Id: htmltree.c,v 1.161 2008/02/14 08:39:14 danielk1977 Exp $";

#include "html.h"
#include "swproc.h"
#include <assert.h>
#include <string.h>


struct HtmlFragmentContext {
  HtmlNode *pRoot;
  HtmlElementNode *pCurrent;
  Tcl_Obj *pNodeList;
};

/*
 * An HTML table is structured as follows:
 *
 *  <TABLE>                            <!-- Level 4 -->
 *    <TBODY|THEAD|TFOOT>              <!-- Level 3 -->
 *      <TR>                           <!-- Level 2 -->
 *        <TH|TD>                      <!-- Level 1 -->
 *
 * Other, non-table, elements have a level of 0. 
 *
 * Currently Tkhtml does not even parse <COL> and <COLGROUP> tags. When
 * this is fixed these two elements may need to be factored into the macro.
 */
#define TAG_TO_TABLELEVEL(eTag) (  \
    (eTag==Html_TABLE) ? 4 :       \
    (eTag==Html_TBODY) ? 3 :       \
    (eTag==Html_THEAD) ? 3 :       \
    (eTag==Html_TFOOT) ? 3 :       \
    (eTag==Html_TR)    ? 2 :       \
    (eTag==Html_TD)    ? 1 :       \
    (eTag==Html_TH)    ? 1 : 0     \
)

static void treeCloseFosterTree(HtmlTree *);

/*
 *---------------------------------------------------------------------------
 *
 * explicitCloseCount --
 *
 *
 * Results:
 *     Sets the value of *pNClose.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static void 
explicitCloseCount(pCurrent, eTag, zTag, pNClose)
    HtmlNode *pCurrent;     /* Node currently being constructed */
    int eTag;               /* Id of closing tag (i.e. "</p>" -> Html_P) */
    const char *zTag;       /* Atom of closing tag */
    int *pNClose;           /* OUT: Number of elements to close */
{
    *pNClose = 0;
    if (eTag != Html_HTML && eTag != Html_BODY && eTag != Html_HEAD) {
        HtmlNode *p;
        int nLevel = 0;

        for (p = pCurrent; p;  p = HtmlNodeParent(p)) {
            nLevel++;

            assert(zTag == p->zTag || stricmp(zTag, p->zTag));
            if (zTag == p->zTag) {
                *pNClose = nLevel;
                break;
            }

            if (
                TAG_TO_TABLELEVEL(p->eTag) &&
                TAG_TO_TABLELEVEL(eTag) <= TAG_TO_TABLELEVEL(p->eTag)
            ) break;
        }
    }
}

static void 
implicitCloseCount(pTree, pCurrent, eTag, pNClose)
    HtmlTree *pTree;
    HtmlNode *pCurrent;
    int eTag;
    int *pNClose;
{
    int nClose = 0;

    if (pCurrent) {
        int nLevel = 0;
        HtmlNode *p;
        int eCloseRes = TAG_PARENT;
        assert(HtmlNodeAsElement(pCurrent));
    
        for (p = pCurrent; p && eCloseRes != TAG_OK; p = HtmlNodeParent(p)) {
            HtmlTokenMap *pMap = HtmlMarkup(HtmlNodeTagType(p));
            nLevel++;
    
            if (pMap && pMap->xClose) {
                eCloseRes = pMap->xClose(pTree, p, eTag);
                assert(
                    eCloseRes == TAG_CLOSE || 
                    eCloseRes == TAG_OK || 
                    eCloseRes == TAG_PARENT
                );
                if (eCloseRes == TAG_CLOSE) {
                    nClose = nLevel;
                }
            }
        }
    }

    *pNClose = nClose;
}

static void
geomRequestProcCb(clientData) 
    ClientData clientData;
{
    HtmlNode *pNode = (HtmlNode *)clientData;
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    HtmlCallbackLayout(pTree, pNode);
}

static void 
geomRequestProc(clientData, widget)
    ClientData clientData;
    Tk_Window widget;
{
    HtmlNode *pNode = (HtmlNode *)clientData;
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    if (!pTree->cb.inProgress) {
        HtmlCallbackLayout(pTree, pNode);
    } else {
        Tcl_DoWhenIdle(geomRequestProcCb, (ClientData)pNode);
    }
}

static void
clearReplacement(pTree, pElem)
    HtmlTree *pTree;
    HtmlElementNode *pElem;
{
    HtmlNodeReplacement *p = pElem->pReplacement;
    pElem->pReplacement = 0;
    if (p) {

        /* Cancel any idle callback scheduled by geomRequestProc() */
        Tcl_CancelIdleCall(geomRequestProcCb, (ClientData)pElem);

        /* If there is a delete script, invoke it now. */
        if (p->pDelete) {
            int flags = TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL;
            Tcl_EvalObjEx(pTree->interp, p->pDelete, flags);
        }

        /* Remove any entry from the HtmlTree.pMapped list. */
        if (p == pTree->pMapped) {
            pTree->pMapped = p->pNext;
        } else {
            HtmlNodeReplacement *pCur = pTree->pMapped; 
            while( pCur && pCur->pNext != p ) pCur = pCur->pNext;
            if (pCur) {
                pCur->pNext = p->pNext;
            }
        }

        /* Cancel geometry management */
        if (p->win) {
            if (Tk_IsMapped(p->win)) {
                Tk_UnmapWindow(p->win);
            }
            Tk_ManageGeometry(p->win, 0, 0);
        }

        /* Delete the Tcl_Obj's and the structure itself. */
        if (p->pDelete)       { Tcl_DecrRefCount(p->pDelete); }
        if (p->pReplace)      { Tcl_DecrRefCount(p->pReplace); }
        if (p->pConfigureCmd) { Tcl_DecrRefCount(p->pConfigureCmd); }
        HtmlFree(p);
    }
}

int 
HtmlNodeClearStyle(pTree, pElem)
    HtmlTree *pTree;
    HtmlElementNode *pElem;
{
    if (pElem) {
        HtmlNodeClearGenerated(pTree, pElem);
        HtmlComputedValuesRelease(pTree, pElem->pPropertyValues);
        HtmlComputedValuesRelease(pTree, pElem->pPreviousValues);
        HtmlCssInlineFree(pElem->pStyle);
        HtmlCssFreeDynamics(pElem);
        pElem->pStyle = 0;
        pElem->pPropertyValues = 0;
        pElem->pPreviousValues = 0;
        pElem->pDynamic = 0;
        HtmlDelStackingInfo(pTree, pElem);
    }
    return 0;
}

int 
HtmlNodeDeleteCommand(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    if (pNode->pNodeCmd) {
        Tcl_Obj *pCommand = pNode->pNodeCmd->pCommand;
        Tcl_DeleteCommand(pTree->interp, Tcl_GetString(pCommand));
        Tcl_DecrRefCount(pCommand);
        HtmlFree(pNode->pNodeCmd);
        pNode->pNodeCmd = 0;
    }
    return 0;
}


/*
 *---------------------------------------------------------------------------
 *
 * freeNode --
 *
 *     Free the memory allocated for pNode and all of it's children. If the
 *     node has attached style information, either from stylesheets or an
 *     Html style attribute, this is deleted here too.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     pNode and children are made invalid.
 *
 *---------------------------------------------------------------------------
 */
static void 
freeNode(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    if( pNode ){
        int i;

        /* Invalidate the cache of the parent node before deleting any
         * child nodes. This is because invalidating a cache may involve
         * deleting primitives that correspond to descendant nodes. In
         * general, primitives must be deleted before their owner nodes.
         */
        HtmlLayoutInvalidateCache(pTree, pNode);

        if (!HtmlNodeIsText(pNode)) {
            /* Do HtmlElementNode specific destruction */
            HtmlElementNode *pElem = (HtmlElementNode *)pNode;
            HtmlFree(pElem->pAttributes);

            /* Delete the computed values caches. */
            HtmlNodeClearStyle(pTree, pElem);
            HtmlCssFreeDynamics(pElem);

            if (pElem->pOverride) {
                Tcl_DecrRefCount(pElem->pOverride);
                pElem->pOverride = 0;
            }

            /* Delete the descendant nodes. */
            for(i=0; i < pElem->nChild; i++){
                freeNode(pTree, pElem->apChildren[i]);
            }
            HtmlFree(pElem->apChildren);

            clearReplacement(pTree, pElem);

            HtmlDrawCanvasItemRelease(pTree, pElem->pBox);

        } else {
            HtmlTextNode *pTextNode = HtmlNodeAsText(pNode);
            assert(pTextNode);
            HtmlTagCleanupNode(pTextNode);
            HtmlFree(pTextNode->aToken);
        }

        /* Delete the computed values caches. */
        HtmlDelScrollbars(pTree, pNode);

        HtmlNodeDeleteCommand(pTree, pNode);

        HtmlFree(pNode);
    }
}

int
HtmlNodeClearGenerated(pTree, pElem)
    HtmlTree *pTree;
    HtmlElementNode *pElem;
{
    assert(!pElem->pBefore || !HtmlNodeIsText(pElem->pBefore));
    freeNode(pTree, pElem->pBefore);
    freeNode(pTree, pElem->pAfter);
    pElem->pBefore = 0;
    pElem->pAfter = 0;
    return 0;
}

static Tcl_Obj *
nodeGetPreText(pTextNode)
    HtmlTextNode *pTextNode;
{
    HtmlTextIter sIter;
    Tcl_Obj *pRet = Tcl_NewObj();

    for (
        HtmlTextIterFirst(pTextNode, &sIter);
        HtmlTextIterIsValid(&sIter);
        HtmlTextIterNext(&sIter)
    ) {
        char *zWhite = " ";

        int eType = HtmlTextIterType(&sIter);
        int nData = HtmlTextIterLength(&sIter);
        char const * zData = HtmlTextIterData(&sIter);

        switch (eType) {
            case HTML_TEXT_TOKEN_TEXT:
                Tcl_AppendToObj(pRet, zData, nData);
                break;

            case HTML_TEXT_TOKEN_NEWLINE: 
                zWhite = "\n";
            case HTML_TEXT_TOKEN_SPACE: {
                int ii;
                for (ii = 0; ii < nData; ii++) {
                    Tcl_AppendToObj(pRet, zWhite, 1);
                }
                break;
            }
        }
    }

    return pRet;
}


/*
 *---------------------------------------------------------------------------
 *
 * nodeRemoveChild --
 *
 *     If pChild is a child-node of pElem, then remove it from the
 *     HtmlElementNode.apChildren[] array (so that it is no longer a 
 *     child).
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeRemoveChild(pElem, pChild)
    HtmlElementNode *pElem;
    HtmlNode *pChild;
{
    int eSeen = 0;
    int ii;

    for (ii = 0; ii < pElem->nChild; ii++) {
        if (eSeen) {
            pElem->apChildren[ii - 1] = pElem->apChildren[ii];
        }
        if (pElem->apChildren[ii] == pChild) {
            assert(pChild->pParent == (HtmlNode *)pElem);
            pChild->pParent = 0;
            eSeen = 1;
        }
    }
    if (eSeen) {
        pElem->nChild--;
    }
    return eSeen;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlElementNormalize --
 *
 *     This function normalizes the text children of element *pElem.
 *
 * Results:
 *     None
 *
 * Side effects:
 *     May combine two or more text-nodes into a single node.
 *
 *---------------------------------------------------------------------------
 */
void
HtmlElementNormalize(pElem)
    HtmlElementNode *pElem;
{
    int ii;
    for (ii = 0; ii < (pElem->nChild - 1); ii++) {
        if (
            HtmlNodeIsText(pElem->apChildren[ii]) &&
            HtmlNodeIsText(pElem->apChildren[ii + 1])
        ) {
            HtmlNode *pRemove = pElem->apChildren[ii + 1];
            nodeRemoveChild(pElem, pRemove);

            /* TODO: Fold text from pRemove into pElem->apChildren[ii] */

            HtmlTextFree(HtmlNodeAsText(pRemove));
            ii--;
        }
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeHandlerCallbacks --
 *
 *     This is called for every tree node by HtmlWalkTree() immediately
 *     after the document tree is constructed. It calls the node handler
 *     script for the node, if one exists.
 *
 *     If the [$widget reset] method is called within the node-handler,
 *     non-zero is returned. Otherwise 0.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int 
nodeHandlerCallbacks(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    Tcl_HashEntry *pEntry;
    Tcl_Interp *interp = pTree->interp;
    int eTag = HtmlNodeTagType(pNode);
    int isFragment = (pTree->pFragment?1:0);

    /* If this is called as a result of a [parse] (not [fragment])
     * command, this variable will be set to true if there is a node-handler
     * script and the script calls the [reset] method of this widget.
     */

    assert(isFragment || pTree->eWriteState == HTML_WRITE_NONE);
    assert(isFragment || (eTag != Html_TD && eTag != Html_TH) || (
           HtmlNodeParent(pNode) && 
           HtmlNodeTagType(HtmlNodeParent(pNode)) == Html_TR
       )
    );
    
    if (!HtmlNodeIsText(pNode)) {
        /* HtmlElementNormalize(HtmlNodeAsElement(pNode)); */
    }

    if (!isFragment && TAG_TO_TABLELEVEL(eTag) > 0) {
        treeCloseFosterTree(pTree);
    }

    /* Execute the node-handler script for node pNode, if one exists. */
    pEntry = Tcl_FindHashEntry(&pTree->aNodeHandler, (char *)((size_t) eTag));
    if (pEntry) {
        Tcl_Obj *pEval;
        Tcl_Obj *pScript;
        Tcl_Obj *pNodeCmd;
        int rc;

        pScript = (Tcl_Obj *)Tcl_GetHashValue(pEntry);
        pEval = Tcl_DuplicateObj(pScript);
        Tcl_IncrRefCount(pEval);

        if (!isFragment) {
            pTree->eWriteState = HTML_PARSE_NODEHANDLER;
        }

        pNodeCmd = HtmlNodeCommand(pTree, pNode);
        Tcl_ListObjAppendElement(0, pEval, pNodeCmd);
        rc = Tcl_EvalObjEx(interp, pEval, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
        if (rc != TCL_OK) {
            Tcl_BackgroundError(interp);
        }
        Tcl_DecrRefCount(pEval);

        assert(
            isFragment || 
            pTree->eWriteState == HTML_PARSE_NODEHANDLER ||
            pTree->eWriteState == HTML_WRITE_INHANDLERRESET
        );
        if (!isFragment && pTree->eWriteState == HTML_PARSE_NODEHANDLER){
            pTree->eWriteState = HTML_WRITE_NONE;
        }
    }
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlFinishNodeHandlers --
 *
 *     Execute any outstanding node-handler callbacks. This is used when
 *     the end of a document is reached - the EOF implicitly closes all
 *     open nodes. This function executes node-handler scripts for nodes
 *     closed in such a fashion.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
void 
HtmlFinishNodeHandlers(pTree)
    HtmlTree *pTree;
{
    HtmlNode *p;
    for (p = pTree->state.pCurrent ; p; p = HtmlNodeParent(p)) {
        nodeHandlerCallbacks(pTree, p);
    }
    pTree->state.pCurrent = 0;
}   

int HtmlNodeIsOrphan(pNode)
    HtmlNode *pNode;
{
    while (pNode && pNode->iNode != HTML_NODE_ORPHAN) {
        pNode = HtmlNodeParent(pNode);
    }
    return (pNode ? 1 : 0);
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeOrphanize --
 * nodeDeorphanize --
 *
 *     Mark a node as an orphan, or unmark it. All nodes marked as orphans
 *     are stored in the HtmlTree.aOrphan hash table and have HtmlNode.iNode
 *     set to HTML_NODE_ORPHAN.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static void
nodeOrphanize(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    int eNew;
    assert(
        pNode->iNode != HTML_NODE_ORPHAN || 
        pNode == pTree->pFragment->pRoot
    );
    pNode->iNode = HTML_NODE_ORPHAN;
    pNode->pParent = 0;

    Tcl_CreateHashEntry(&pTree->aOrphan, (const char *)pNode, &eNew);
    assert(eNew);
}
static void
nodeDeorphanize(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    Tcl_HashEntry *pEntry;
    assert(pNode->iNode == HTML_NODE_ORPHAN);
    pNode->iNode = 0;
    pEntry = Tcl_FindHashEntry(&pTree->aOrphan, (const char *)pNode);
    assert(pEntry);
    Tcl_DeleteHashEntry(pEntry);
}

int
HtmlNodeIndexOfChild(pParent, pChild)
    HtmlNode *pParent;
    HtmlNode *pChild;
{
    int ii;
    for (ii = 0; ii < HtmlNodeNumChildren(pParent); ii++) {
        if (HtmlNodeChild(pParent, ii) == pChild) return ii;
    }
    return -1;
}

static void
nodeInsertChild(pTree, pElem, pBefore, pAfter, pChild)
    HtmlTree *pTree;
    HtmlElementNode *pElem;
    HtmlNode *pBefore;
    HtmlNode *pAfter;
    HtmlNode *pChild;
{
    int n;                  /* Number of bytes to alloc for pNode->apChildren */
    int ii;
    int iBefore;

    assert(pBefore == 0 || pAfter == 0);
    assert(pChild);

    if (pChild == pBefore || pChild == pAfter) {
        assert(HtmlNodeParent(pChild) == (HtmlNode *)pElem);
        return;
    }

    /* Unlink pChild from it's parent node. */
    if (HtmlNodeParent(pChild)) {
        HtmlNode *pParent = HtmlNodeParent(pChild);

        /* Before removing a child, invalidate the layout of the parent */
        HtmlCallbackLayout(pTree, pChild);

        /* Clear all the style and layout information cached in the
         * sub-tree rooted at the child node. At present anything
         * moved to the orphan tree has all style/layout info cleared.
         */
        HtmlNodeClearRecursive(pTree, pChild);
        nodeRemoveChild(HtmlNodeAsElement(pParent), pChild);
    }

    if (pBefore) {
        iBefore = HtmlNodeIndexOfChild((HtmlNode *)pElem, pBefore);
        assert(iBefore>=0);
    } else if (pAfter) {
        iBefore = HtmlNodeIndexOfChild((HtmlNode *)pElem, pAfter);
        assert(iBefore>=0);
        iBefore++;
    } else {
        iBefore = pElem->nChild;
    }

    /* Extend the size of the HtmlElementNode.apChildren[] array */
    assert(pElem);
    pElem->nChild++;
    n = (pElem->nChild) * sizeof(HtmlNode*);
    pElem->apChildren = (HtmlNode **)HtmlRealloc(
        "HtmlNode.apChildren", (char *)pElem->apChildren, n
    );

    for (ii = (pElem->nChild - 1); ii > iBefore; ii--) {
        pElem->apChildren[ii] = pElem->apChildren[ii - 1];
    }
    pElem->apChildren[iBefore] = pChild;

    /* Link pChild into the new parent node */
    pChild->pParent = (HtmlNode *)pElem;
}


/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeAddChild --
 *
 *     Add a new child node to node pNode. pToken becomes the starting
 *     token for the new node. The value returned is the index of the new
 *     child. So the call:
 *
 *          HtmlNodeChild(pNode, HtmlNodeAddChild(pNode, pToken))
 *
 *     returns the new child node.
 *
 * Results:
 *     Index of the child added to pNode.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
int 
HtmlNodeAddChild(pElem, eTag, zTag, pAttributes)
    HtmlElementNode *pElem;
    int eTag;
    const char *zTag;               /* Atom for tag name */
    HtmlAttributes *pAttributes;
{
    int n;                  /* Number of bytes to alloc for pNode->apChildren */
    int r;                  /* Return value */
    HtmlElementNode *pNew;  /* New child node */

    assert(pElem);
    
    r = pElem->nChild++;
    n = (r+1) * sizeof(HtmlNode*);
    pElem->apChildren = (HtmlNode **)HtmlRealloc(
        "HtmlNode.apChildren", (char *)pElem->apChildren, n
    );

    if (!zTag) {
        zTag = HtmlTypeToName(0, eTag);
    }
    assert(zTag);

    pNew = HtmlNew(HtmlElementNode);
    pNew->pAttributes = pAttributes;
    pNew->node.pParent = (HtmlNode *)pElem;
    pNew->node.eTag = eTag;
    pNew->node.zTag = zTag;
    pElem->apChildren[r] = (HtmlNode *)pNew;

    assert(r < pElem->nChild);
    return r;
}

int 
HtmlNodeAddTextChild(pNode, pTextNode)
    HtmlNode *pNode;
    HtmlTextNode *pTextNode;
{
    int n;             /* Number of bytes to alloc for pNode->apChildren */
    int r;             /* Return value */
    HtmlNode *pNew;    /* New child node */

    HtmlElementNode *pElem = HtmlNodeAsElement(pNode);

    assert(pElem);
    assert(pTextNode);
    
    r = pElem->nChild++;
    n = (r+1) * sizeof(HtmlNode*);
    pElem->apChildren = (HtmlNode **)HtmlRealloc(
        "HtmlNode.apChildren", (char *)pElem->apChildren, n
    );

    pNew = (HtmlNode *)pTextNode;
    memset(pNew, 0, sizeof(HtmlNode));
    pNew->pParent = pNode;
    pNew->eTag = Html_Text;
    pElem->apChildren[r] = pNew;

    assert(r < pElem->nChild);
    return r;
}

/*
 *---------------------------------------------------------------------------
 *
 * setNodeAttribute --
 *
 *     Set the value of an attribute on a node. This function is currently
 *     a bit inefficient, due to the way the HtmlToken structure is 
 *     allocated.
 *
 * Results:
 *     None
 *
 * Side effects:
 *     Modifies the HtmlToken structure associated with the specified node.
 *
 *---------------------------------------------------------------------------
 */
static void
setNodeAttribute(pNode, zAttrName, zAttrVal)
    HtmlNode *pNode;
    const char *zAttrName;
    const char *zAttrVal;
{
    #define MAX_NUM_ATTRIBUTES 100
    char const *azPtr[MAX_NUM_ATTRIBUTES * 2];
    int aLen[MAX_NUM_ATTRIBUTES * 2];

    int i;
    int isDone = 0;
    int nArgs;
    HtmlElementNode *pElem;
    HtmlAttributes *pAttr;

    pElem = HtmlNodeAsElement(pNode);
    if (!pElem) return;
    pAttr = pElem->pAttributes;

    for (i = 0; pAttr && i < pAttr->nAttr && i < MAX_NUM_ATTRIBUTES; i++) {
        azPtr[i*2] = pAttr->a[i].zName;
        if (0 != strcmp(pAttr->a[i].zName, zAttrName)) {
            azPtr[i*2+1] = pAttr->a[i].zValue;
        } else {
            azPtr[i*2+1] = zAttrVal;
            isDone = 1;
        }
    }

    if (!isDone && i < MAX_NUM_ATTRIBUTES) {
        azPtr[i*2] = zAttrName;
        azPtr[i*2+1] = zAttrVal;
        i++;
    }

    nArgs = i * 2;
    for (i = 0; i < nArgs; i++) {
        aLen[i] = strlen(azPtr[i]);
    }

    pElem->pAttributes = HtmlAttributesNew(nArgs, azPtr, aLen, 0);
    HtmlFree(pAttr);

    /* If this was a call to set the "style" attribute, discard the
     * compiled version at version HtmlElementNode.pStyle.
     */
    if (strcmp(HTML_INLINE_STYLE_ATTR, zAttrName) == 0) {
        HtmlCssInlineFree(pElem->pStyle);
        pElem->pStyle = 0;
    }
}

static void
mergeAttributes(pNode, pAttr)
    HtmlNode *pNode;
    HtmlAttributes *pAttr;
{
    int ii;
    for (ii = 0; pAttr && ii < pAttr->nAttr; ii++) {
        setNodeAttribute(pNode, pAttr->a[ii].zName, pAttr->a[ii].zValue);
    }
    HtmlFree(pAttr);
}

static int
doAttributeHandler(pTree, pNode, zAttr, zValue) 
    HtmlTree *pTree;
    HtmlNode *pNode;
    const char *zAttr;
    const char *zValue;
{
    int rc = TCL_OK;
    int eType = pNode->eTag;
    Tcl_HashEntry *pEntry;

    pEntry = Tcl_FindHashEntry(&pTree->aAttributeHandler, (char*)((size_t) eType));
    if (pEntry) {
        Tcl_Obj *pScript;
        pScript = (Tcl_Obj *)Tcl_GetHashValue(pEntry);

        pScript = Tcl_DuplicateObj(pScript);
        Tcl_IncrRefCount(pScript);
        Tcl_ListObjAppendElement(0, pScript, HtmlNodeCommand(pTree, pNode));
        Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zAttr, -1));
        Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zValue, -1));
        rc = Tcl_EvalObjEx(pTree->interp, pScript, TCL_EVAL_GLOBAL);
        Tcl_DecrRefCount(pScript);
    }

    return rc;
}

static int
doParseHandler(pTree, eType, pNode, iOffset)
    HtmlTree *pTree;
    int eType;
    HtmlNode *pNode;
    int iOffset;
{
    int rc = TCL_OK;
    Tcl_HashEntry *pEntry;
    if (iOffset < 0) return TCL_OK;

    if (eType == Html_Space) {
        eType = Html_Text;
    }

    pEntry = Tcl_FindHashEntry(&pTree->aParseHandler, (char *)((size_t) eType));
    if (pEntry) {
        Tcl_Obj *pScript;
        pScript = (Tcl_Obj *)Tcl_GetHashValue(pEntry);

        pScript = Tcl_DuplicateObj(pScript);
        Tcl_IncrRefCount(pScript);
        if (pNode) {
            Tcl_ListObjAppendElement(0, pScript, HtmlNodeCommand(pTree, pNode));
        } else {
            Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj("", -1));
        }
        Tcl_ListObjAppendElement(
            0, pScript, Tcl_NewIntObj(iOffset + pTree->nParsed)
        );

        rc = Tcl_EvalObjEx(pTree->interp, pScript, TCL_EVAL_GLOBAL);
        Tcl_DecrRefCount(pScript);
    }

    return rc;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlInitTree --
 *
 *     Create the parts of the tree that are always present. i.e.:
 *
 *       <html>
 *         <head>
 *         <body>
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     May modify the tree structure at HtmlTree.pRoot and
 *     HtmlTree.pCurrent.
 *
 *---------------------------------------------------------------------------
 */
void
HtmlInitTree(pTree)
    HtmlTree *pTree;
{
    if (!pTree->pRoot) {
        /* If pTree->pRoot is NULL, then the first token of the document
         * has just been parsed. If the document is well-formed, it should
         * be an <html> tag (Html documents may have a DOCTYPE and other such
         * garbage in them, but the tokenizer should ignore all that).
         *
         * But in these uncertain times you really can't trust anyone, so
         * Tkhtml automatically inserts the following structure at the root
         * of every document:
         *
         *    <html>
         *      <head>
         *      </head>
         *      <body>
         */
        HtmlElementNode *pRoot;

        pRoot = HtmlNew(HtmlElementNode);
        pRoot->node.eTag = Html_HTML;
        pRoot->node.zTag = HtmlTypeToName(pTree, Html_HTML);
        pTree->pRoot = (HtmlNode *)pRoot;


        HtmlNodeAddChild(pRoot, Html_HEAD, HtmlTypeToName(pTree, Html_HEAD), 0);
        HtmlNodeAddChild(pRoot, Html_BODY, HtmlTypeToName(pTree, Html_BODY), 0);
        HtmlCallbackRestyle(pTree, (HtmlNode *)pRoot);
    }

    if (!pTree->state.pCurrent) {
        /* If there is no current node, then the <body> node of the 
         * document is the current node. 
         */
        pTree->state.pCurrent = HtmlNodeChild(pTree->pRoot, 1);
    }
}

void
HtmlInitTreeNodeCmd(pTree)
    HtmlTree *pTree;
{
    if (pTree->pRoot
     && !pTree->state.pCurrent) {
        /* If there is no current node, then the <body> node of the
         * document is the current node.
         */
        pTree->state.pCurrent = HtmlNodeChild(pTree->pRoot, 1);
    }
}


static HtmlNode *
findFosterParent(pTree, ppTable)
    HtmlTree *pTree;
    HtmlNode **ppTable;
{
    HtmlNode *pFosterParent;
    HtmlNode *pTable;

    /* Find the parent of the <TABLE> element (the foster-parent) */
    for (
        pTable = pTree->state.pCurrent;
        HtmlNodeTagType(pTable) != Html_TABLE;
        pTable = HtmlNodeParent(pTable)
    );
    pFosterParent = HtmlNodeParent(pTable);
    assert(pFosterParent);
    if (ppTable) {
        *ppTable = pTable;
    }

    return pFosterParent;
}

static void
treeCloseFosterTree(pTree)
    HtmlTree *pTree;
{
    if (pTree->state.pFoster) {
        HtmlNode *pFosterRoot = findFosterParent(pTree, 0);
        HtmlNode *pFoster;

        pFoster = pTree->state.pFoster;
        for ( ;pFoster != pFosterRoot; pFoster = HtmlNodeParent(pFoster)) {
            nodeHandlerCallbacks(pTree, pFoster);
        }

        pTree->state.pFoster = 0;
    }
}

static void
treeAddFosterText(pTree, pTextNode)
    HtmlTree *pTree;
    HtmlTextNode *pTextNode;
{
    if (pTree->state.pFoster) {
        HtmlNodeAddTextChild(pTree->state.pFoster, pTextNode);
    } else {
        HtmlNode *pFosterParent;
        HtmlNode *pBefore = 0;
        pFosterParent = findFosterParent(pTree, &pBefore);
           
        nodeInsertChild(pTree,
            (HtmlElementNode *)pFosterParent, pBefore, 0, (HtmlNode *)pTextNode
        );
    }
}

HtmlNode * 
treeAddFosterElement(pTree, eTag, zTag, pAttr)
    HtmlTree *pTree;
    int eTag;
    const char *zTag;                /* Atom for tag */
    HtmlAttributes *pAttr;
{
    HtmlNode *pFosterParent;

    HtmlNode *pNew;
    HtmlNode *pFoster = pTree->state.pFoster;
    HtmlNode *pBefore = 0;

    /* Find the parent of the <TABLE> element (the foster-parent) */
    pFosterParent = findFosterParent(pTree, &pBefore);

    if (pFoster) {
        int nClose;
        int ii;
        implicitCloseCount(pTree, pTree->state.pFoster, eTag, &nClose);
        for (
            ii = 0; 
            ii < nClose && pFoster != pFosterParent; 
            pFoster = HtmlNodeParent(pFoster)
        ) {
            nodeHandlerCallbacks(pTree, pFoster);
        }
        if (pFoster == pFosterParent) pFoster = 0;
    }

    if (pFoster) {
        int n = HtmlNodeAddChild((HtmlElementNode *)pFoster, eTag, zTag, pAttr);
        pNew = HtmlNodeChild(pFoster, n);
    } else {
        pNew = (HtmlNode *)HtmlNew(HtmlElementNode);
        ((HtmlElementNode *)pNew)->pAttributes = pAttr;
        pNew->eTag = eTag;
        if (!zTag) {
            zTag = HtmlTypeToName(0, eTag);
        }
        pNew->zTag = zTag;
        nodeInsertChild(pTree, (HtmlElementNode *)pFosterParent,pBefore,0,pNew);
    }

    pNew->iNode = pTree->iNextNode++;
    if (HtmlMarkupFlags(eTag) & HTMLTAG_EMPTY) {
        nodeHandlerCallbacks(pTree, pNew);
        pTree->state.pFoster = HtmlNodeParent(pNew);
        if (pTree->state.pFoster == pFosterParent) pTree->state.pFoster = 0;
    } else {
        pTree->state.pFoster = pNew;
    }

    HtmlCallbackRestyle(pTree, pNew);
    return pNew;
}

static void
treeAddFosterClosingTag(pTree, eTag, zTag)
    HtmlTree *pTree;
    int eTag;
    const char *zTag;
{
    HtmlNode *pFosterParent;
    HtmlNode *pFoster;
    int ii;
    int nClose;

    /* Find the parent of the <TABLE> element (the foster-parent) */
    pFosterParent = findFosterParent(pTree, 0);
    assert(pFosterParent);

    explicitCloseCount(pTree->state.pFoster, eTag, zTag, &nClose);
    pFoster = pTree->state.pFoster;
    for (ii = 0; ii < nClose && pFoster != pFosterParent; ii++) {
        nodeHandlerCallbacks(pTree, pFoster);
        pFoster = HtmlNodeParent(pFoster);
    }
    if (pFoster == pFosterParent) {
        pFoster = 0;
    }
    pTree->state.pFoster = pFoster;
}

static HtmlNode *
treeAddTableComponent(pTree, eTag, pAttr)
    HtmlTree *pTree;
    int eTag;
    HtmlAttributes *pAttr;
{
    HtmlNode *pCurrent = pTree->state.pCurrent;
    HtmlNode *pParent;

    int eParentTag;

    /* The newly created document node */
    HtmlNode *pNew;
    int n;

    for (pParent = pCurrent; pParent; pParent = HtmlNodeParent(pParent)) {
        int eCTag = HtmlNodeTagType(pParent);

        if (
            (eCTag == Html_TABLE) || (
                (eCTag==Html_TBODY || eCTag==Html_THEAD || eCTag==Html_TFOOT) &&
                (eTag==Html_TH || eTag==Html_TD || eTag==Html_TR)
            ) ||
            (eCTag == Html_TR && (eTag == Html_TD || eTag == Html_TH))
        ) break;
    }
    if (!pParent) {
        HtmlFree(pAttr);
        return pParent;
    }
    eParentTag = HtmlNodeTagType(pParent);

    /* Invoke node-handler callbacks for implicitly closed nodes */
    for ( ; pCurrent != pParent ; pCurrent = HtmlNodeParent(pCurrent)) {
        nodeHandlerCallbacks(pTree, pCurrent);
    }
    treeCloseFosterTree(pTree);

    assert( 
        eParentTag == Html_TABLE || eParentTag == Html_TBODY || 
        eParentTag == Html_THEAD || eParentTag == Html_TFOOT ||
        eParentTag == Html_TR
    );

    /* See if we need to add an implicit <TBODY> node */
    if (
        eParentTag == Html_TABLE && 
        (eTag == Html_TR || eTag == Html_TD || eTag == Html_TH)
    ) {
        int n2 = HtmlNodeAddChild((HtmlElementNode *)pParent, Html_TBODY, 0, 0);
        pParent = HtmlNodeChild(pParent, n2);
        pParent->iNode = pTree->iNextNode++;
        eParentTag = Html_TBODY;
    }

    /* See if we need to add an implicit <TR> node */
    if (eParentTag != Html_TR && (eTag == Html_TD || eTag == Html_TH)) {
        int n2 = HtmlNodeAddChild((HtmlElementNode *)pParent, Html_TR, 0, 0);
        pParent = HtmlNodeChild(pParent, n2);
        pParent->iNode = pTree->iNextNode++;
        eParentTag = Html_TR;
    }
    
    /* Add the new node to pParent */
    n = HtmlNodeAddChild((HtmlElementNode *)pParent, eTag, 0, pAttr);
    pNew = HtmlNodeChild(pParent, n);
    pNew->iNode = pTree->iNextNode++;
    pTree->state.pCurrent = pNew;

    /* Return a pointer to the node just added */
    return pNew;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlTreeAddElement --
 *
 *     Update the tree structure with an element of type eType, attributes
 *     as specified in *pAttr.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     May modify the tree structure at HtmlTree.pRoot and
 *     HtmlTree.pCurrent.
 *
 *---------------------------------------------------------------------------
 */
void 
HtmlTreeAddElement(pTree, eType, zType, pAttr, iOffset)
    HtmlTree *pTree;
    int eType;
    const char *zType;
    HtmlAttributes *pAttr;
    int iOffset;
{
    HtmlNode *pCurrent;
    HtmlNode *pHeadNode;
    HtmlNode *pBodyNode;
    HtmlElementNode *pHeadElem;

    /* If token pToken causes a node to be added to the tree, or the
     * attributes of an <html>, <body> or <head> element to be updated,
     * this variable is set to point to the node. At the end of this
     * function, it is used as an argument to any registered 
     * [$widget handler parse] callback script.
     */
    HtmlNode *pParsed = 0; 

    /* Initialise the tree and find the <HEAD> and <BODY> elements */
    HtmlInitTree(pTree);
    pHeadNode = HtmlNodeChild(pTree->pRoot, 0);
    pBodyNode = HtmlNodeChild(pTree->pRoot, 1);
    pHeadElem = HtmlNodeAsElement(pHeadNode);

    pCurrent = pTree->state.pCurrent;

    assert(pCurrent);
    assert(pHeadNode);
    assert(eType != Html_Text && eType != Html_Space);

    /* If the HtmlTreeState.isCdataInHead flag is true, then the previous
     * token parsed was <TITLE> (generally: a token that generates an
     * element in the <HEAD> section with #CDATA content). Close the 
     * element before proceeding.
     */
    if (pTree->state.isCdataInHead) {
        int nChild = HtmlNodeNumChildren(pHeadNode) - 1;
        HtmlNode *pTitle = HtmlNodeChild(pHeadNode, nChild);
        nodeHandlerCallbacks(pTree, pTitle);
    }
    pTree->state.isCdataInHead = 0;

    switch (eType) {
        case Html_HTML:
            pParsed = pTree->pRoot;
            mergeAttributes(pParsed, pAttr);
            HtmlCallbackRestyle(pTree, pParsed);
            break;
        case Html_HEAD:
            pParsed = pHeadNode;
            mergeAttributes(pParsed, pAttr);
            HtmlCallbackRestyle(pTree, pParsed);
            break;
        case Html_BODY:
            pParsed = pBodyNode;
            mergeAttributes(pParsed, pAttr);
            HtmlCallbackRestyle(pTree, pParsed);
            break;

        /* Elements with content #CDATA for the document head. 
         *
         * Todo: Technically, we should be worried about <script> and
         * <style> elements in the document head too, but in practice it
         * makes little difference where these wind up. <script> is
         * a bit tricky as this can appear in either the <head> or <body>
         * section.
         */
        case Html_TITLE: {
            int n = HtmlNodeAddChild(pHeadElem, eType, 0, pAttr);
            HtmlNode *p = HtmlNodeChild(pHeadNode, n);
            pTree->state.isCdataInHead = 1;
            p->iNode = pTree->iNextNode++;
            pParsed = p;
            HtmlCallbackRestyle(pTree, pParsed);
            break;
        }

        /* Self-closing elements to add to the document head */
        case Html_META:
        case Html_LINK:
        case Html_BASE: {
            int n = HtmlNodeAddChild(pHeadElem, eType, 0, pAttr);
            HtmlNode *p = HtmlNodeChild(pHeadNode, n);
            p->iNode = pTree->iNextNode++;
            nodeHandlerCallbacks(pTree, p);
            if (pTree->eWriteState != HTML_WRITE_INHANDLERRESET) {
                pParsed = p;
                HtmlCallbackRestyle(pTree, pParsed);
            }
            break;
        }

        /* Elements that form part of <TABLE> structures. Special 
         * rules apply to these so they are handled seperately.
         */
        case Html_TBODY:
        case Html_TFOOT:
        case Html_THEAD:
        case Html_TR:
        case Html_TD:
        case Html_TH: {
            pParsed = treeAddTableComponent(pTree, eType, pAttr);
            break;
        }

        default: {
            int eCurrentType = HtmlNodeTagType(pCurrent);
            int isTableType = ((
                eCurrentType == Html_TABLE || eCurrentType == Html_TBODY || 
                eCurrentType == Html_TFOOT || eCurrentType == Html_THEAD || 
                eCurrentType == Html_TR
            ) ? 1 : 0);
            if (isTableType && eType != Html_FORM) {
                /* Need to add this node to the foster tree. */
                pParsed = treeAddFosterElement(pTree, eType, zType, pAttr);
            } else {
                /* Add this node to pCurrent. */
                int nClose = 0;
                int i;
                HtmlElementNode *pC;
                int N;

                implicitCloseCount(pTree, pCurrent, eType, &nClose);
                for (i = 0; i < nClose && pCurrent != pBodyNode; i++) {
                    nodeHandlerCallbacks(pTree, pCurrent);
                    pCurrent = HtmlNodeParent(pCurrent);
                }
                pTree->state.pCurrent = pCurrent;

                pC = HtmlNodeAsElement(pCurrent);
                assert(!HtmlNodeIsText(pTree->state.pCurrent));
                N = HtmlNodeAddChild(pC, eType, zType, pAttr);
                pCurrent = HtmlNodeChild(pCurrent, N);
                pCurrent->iNode = pTree->iNextNode++;
                pParsed = pCurrent;

                assert(!isTableType || eType == Html_FORM);
                if ((HtmlMarkupFlags(eType) & HTMLTAG_EMPTY) || isTableType) {
                    nodeHandlerCallbacks(pTree, pCurrent);
                    pCurrent = HtmlNodeParent(pCurrent);
                }
                pTree->state.pCurrent = pCurrent;
            }
        }
    }

    if (pParsed) {
        if (HtmlNodeComputedValues(pParsed)) {
            HtmlCallbackRestyle(pTree, pParsed);
        }
        doParseHandler(pTree, eType, pParsed, iOffset);
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlTreeAddText --
 *
 *     Add the text-node pTextNode to the tree.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
void
HtmlTreeAddText(pTree, pTextNode, iOffset)
    HtmlTree *pTree;
    HtmlTextNode *pTextNode;
    int iOffset;
{
    HtmlNode *pCurrent;
    int eCurrentType;

    HtmlInitTree(pTree);
    pCurrent = pTree->state.pCurrent;
    eCurrentType = HtmlNodeTagType(pCurrent);

    if (pTree->state.isCdataInHead) {
        HtmlNode *pHeadNode = HtmlNodeChild(pTree->pRoot, 0);
        int nChild = HtmlNodeNumChildren(pHeadNode) - 1;
        HtmlNode *pTitle = HtmlNodeChild(pHeadNode, nChild);

        HtmlNodeAddTextChild(pTitle, pTextNode);
        pTextNode->node.iNode = pTree->iNextNode++;
        pTree->state.isCdataInHead = 0;
        nodeHandlerCallbacks(pTree, pTitle);
    } else if (
        eCurrentType == Html_TABLE || eCurrentType == Html_TBODY || 
        eCurrentType == Html_TFOOT || eCurrentType == Html_THEAD || 
        eCurrentType == Html_TR
    ) {
        treeAddFosterText(pTree, pTextNode);
        pTextNode->node.iNode = pTree->iNextNode++;
        pTextNode->node.eTag = Html_Text;
    } else {
        HtmlNodeAddTextChild(pCurrent, pTextNode);
        pTextNode->node.iNode = pTree->iNextNode++;
    }

    assert(pTextNode->node.eTag == Html_Text);
    doParseHandler(pTree, Html_Text, (HtmlNode *)pTextNode, iOffset);
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlTreeAddClosingTag --
 *
 *     Process the closing tag eTag. 
 *
 *     This method is prefixed "HtmlTreeAdd" to match HtmlTreeAddText() 
 *     and HtmlTreeAddElement(), the other two functions used by the 
 *     document parser to build the tree.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
void
HtmlTreeAddClosingTag(pTree, eTag, zTag, iOffset)
    HtmlTree *pTree;
    int eTag;
    const char *zTag;
    int iOffset;
{
    int nClose;
    int ii;

    HtmlInitTree(pTree);

    if (pTree->state.pFoster && 0 == TAG_TO_TABLELEVEL(eTag)) {
        assert(TAG_TO_TABLELEVEL(HtmlNodeTagType(pTree->state.pCurrent)) > 0);
        treeAddFosterClosingTag(pTree, eTag, zTag);
    } else {
        HtmlNode *pBody = HtmlNodeChild(pTree->pRoot, 1);
        explicitCloseCount(pTree->state.pCurrent, eTag, zTag, &nClose);
        for (ii = 0; ii < nClose && pTree->state.pCurrent != pBody; ii++) {
            nodeHandlerCallbacks(pTree, pTree->state.pCurrent);
            pTree->state.pCurrent = HtmlNodeParent(pTree->state.pCurrent);
        }
    }

    doParseHandler(pTree, -1 * eTag, 0, iOffset);
}

/*
 *---------------------------------------------------------------------------
 *
 * walkTree --
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int 
walkTree(pTree, xCallback, pNode, clientData)
    HtmlTree *pTree;
    int (*xCallback)(HtmlTree *, HtmlNode *, ClientData clientData);
    HtmlNode *pNode;
    ClientData clientData;
{
    int i;
    if( pNode ){
        int rc = xCallback(pTree, pNode, clientData);
        switch (rc) {
            case HTML_WALK_ABANDON:
                return 1;
            case HTML_WALK_DESCEND:
                break;
            case HTML_WALK_DO_NOT_DESCEND:
                return 0;
            default:
                    assert(!"Bad return value from HtmlWalkTree() callback");
        }

        for (i = 0; i < HtmlNodeNumChildren(pNode); i++) {
            HtmlNode *pChild = HtmlNodeChild(pNode, i);
            int rc = walkTree(pTree, xCallback, pChild, clientData);
            assert(HtmlNodeParent(pChild) == pNode);
            if (rc) return rc;
        }
    }
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlWalkTree --
 *
 *     Traverse the subset of document tree pTree rooted at pNode. If pNode is
 *     NULL the entire tree is traversed. This function does a pre-order or
 *     prefix traversal (each node is visited before it's children).
 *
 *     When a node is visited the supplied callback function is invoked. The
 *     callback function must return one of the following three hash
 *     defined values:
 *
 *         HTML_WALK_DESCEND
 *         HTML_WALK_DO_NOT_DESCEND
 *         HTML_WALK_ABANDON
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
int 
HtmlWalkTree(pTree, pNode, xCallback, clientData)
    HtmlTree *pTree;
    HtmlNode *pNode;
    int (*xCallback)(HtmlTree *, HtmlNode *, ClientData clientData);
    ClientData clientData;
{
    return walkTree(pTree, xCallback, pNode?pNode:pTree->pRoot, clientData);
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeNumChildren --
 *
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
int HtmlNodeNumChildren(pNode)
    HtmlNode *pNode;
{
    if (HtmlNodeIsText(pNode)) return 0;
    return ((HtmlElementNode *)(pNode))->nChild;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeChild --
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
#if 0
HtmlNode * 
HtmlNodeChild(pNode, n)
    HtmlNode *pNode;
    int n;
{
    HtmlElementNode *pElem = (HtmlElementNode *)pNode;
    if (!pNode || HtmlNodeIsText(pNode) || pElem->nChild <= n) return 0;
    return pElem->apChildren[n];
}
#endif

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeBefore --
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
HtmlNode * 
HtmlNodeBefore(pNode)
    HtmlNode *pNode;
{
    if (!HtmlNodeIsText(pNode)) {
        return ((HtmlElementNode *)pNode)->pBefore;
    }
    return 0;
}

#if 0
HtmlComputedValues * 
HtmlNodeComputedValues(pNode)
    HtmlNode *pNode;
{
    if (HtmlNodeIsText(pNode)) {
        pNode = HtmlNodeParent(pNode);
    }
    if (pNode) {
        return ((HtmlElementNode *)pNode)->pPropertyValues;
    }
    return 0;
}
#endif

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeAfter --
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
HtmlNode * 
HtmlNodeAfter(pNode)
    HtmlNode *pNode;
{
    if (!HtmlNodeIsText(pNode)) {
        return ((HtmlElementNode *)pNode)->pAfter;
    }
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeTagType --
 *
 *     Return the tag-type of the node, i.e. Html_P, Html_Text or
 *     Html_Space.
 *
 * Results:
 *     Integer tag type.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
Html_u8 HtmlNodeTagType(pNode)
    HtmlNode *pNode;
{
    assert(pNode);
    return pNode->eTag;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeTagName --
 *
 *     Return the name of the tag-type of the node, i.e. "p", "text" or
 *     "div".
 *
 * Results:
 *     Boolean.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
CONST char * HtmlNodeTagName(pNode)
    HtmlNode *pNode;
{
    assert(pNode->zTag || HtmlNodeIsText(pNode));
    if (!pNode->zTag) return "";
    return pNode->zTag;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeRightSibling --
 * 
 *     Get the right-hand sibling to a node, if it has one.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
HtmlNode *HtmlNodeRightSibling(pNode)
    HtmlNode *pNode;
{
    HtmlElementNode *pParent = (HtmlElementNode *)pNode->pParent;
    if( pParent ){
        int i;
        for (i=0; i < pParent->nChild - 1; i++) {
            if (pNode == pParent->apChildren[i]) {
                return pParent->apChildren[i+1];
            }
        }
        assert(pNode == pParent->apChildren[pParent->nChild - 1]);
    }
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeLeftSibling --
 * 
 *     Get the left-hand sibling to a node, if it has one.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
HtmlNode *HtmlNodeLeftSibling(pNode)
    HtmlNode *pNode;
{
    HtmlElementNode *pParent = (HtmlElementNode *)pNode->pParent;
    if( pParent ){
        int i;
        for (i = 1; i < pParent->nChild; i++) {
            if (pNode == pParent->apChildren[i]) {
                return pParent->apChildren[i-1];
            }
        }
        assert(pNode == pParent->apChildren[0]);
    }
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeAttr --
 *
 *     Return a pointer to the value of node attribute zAttr. Attributes
 *     are always represented as NULL-terminated strings.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
char CONST *HtmlNodeAttr(pNode, zAttr)
    HtmlNode *pNode; 
    char CONST *zAttr;
{
    HtmlElementNode *pElem = HtmlNodeAsElement(pNode);
    if (pElem) {
        return HtmlMarkupArg(pElem->pAttributes, zAttr, 0);
    }
    return 0;
}

static int 
markWindowAsClipped(pTree, pNode, clientData)
    HtmlTree *pTree;
    HtmlNode *pNode;
    ClientData clientData;
{
    if (!HtmlNodeIsText(pNode)) {
        HtmlNodeReplacement *p = ((HtmlElementNode *)pNode)->pReplacement;
        if (p) {
            p->clipped = 1;
        }
    }

    return HTML_WALK_DESCEND;
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeViewCmd --
 *
 *     This function implements the Tcl commands:
 *
 *         [nodeHandle yview] 
 *         [nodeHandle xview]
 *
 *     used to scroll boxes generated by tree elements with "overflow:auto"
 *     or "overflow:scroll". At present, the implementation of this is
 *     not very efficient.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeViewCmd(pNode, isVertical, objv, objc)
    HtmlNode *pNode;
    int isVertical;
    Tcl_Obj *CONST objv[];
    int objc;
{
    HtmlTree *pTree;
    int eType;       /* One of the TK_SCROLL_ symbols */
    double fraction;
    int count;

    int iNew;
    int iMax;
    int iSize;
    int iIncr;

    int x, y, w, h;

    HtmlElementNode *pElem = (HtmlElementNode *)pNode;

    if (HtmlNodeIsText(pNode) || !pElem->pScrollbar) {
        return TCL_ERROR;
    }

    pTree = pNode->pNodeCmd->pTree;
    if (isVertical) {
        iNew = pElem->pScrollbar->iVertical;
        iMax = pElem->pScrollbar->iVerticalMax;
        iSize = pElem->pScrollbar->iHeight;
        iIncr = pTree->options.yscrollincrement;
    } else {
        iNew = pElem->pScrollbar->iHorizontal;
        iMax = pElem->pScrollbar->iHorizontalMax;
        iSize = pElem->pScrollbar->iWidth;
        iIncr = pTree->options.xscrollincrement;
    }

    eType = Tk_GetScrollInfoObj(pTree->interp, objc, objv, &fraction, &count);

    switch (eType) {
        case TK_SCROLL_MOVETO:
            iNew = (int)((double)iMax * fraction);
            break;
        case TK_SCROLL_PAGES: /* TODO */
            iNew += count * (0.9 * iSize);
            break;
        case TK_SCROLL_UNITS: /* TODO */
            iNew += count * iIncr;
            break;
        case TK_SCROLL_ERROR:
            return TCL_ERROR;

        default: assert(!"Not possible");
    }

    iNew = MAX(0, iNew);
    iNew = MIN(iNew, iMax - iSize);
    if (isVertical) {
        pElem->pScrollbar->iVertical = iNew;
    } else {
        pElem->pScrollbar->iHorizontal = iNew;
    }

    /* Invoke the scrollbar callbacks (i.e. [$scrollbar set]) to update
     * the scrollbar widgets with their new positions.
     */
    HtmlNodeScrollbarDoCallback(pNode->pNodeCmd->pTree, pNode);

    HtmlWidgetOverflowBox(pTree, pNode, &x, &y, &w, &h);
    HtmlCallbackDamage(pTree, x - pTree->iScrollX, y - pTree->iScrollY, w, h);
    if (pTree->cb.flags) {
        pTree->cb.flags |= HTML_NODESCROLL;
    }
    HtmlWalkTree(pTree, pNode, markWindowAsClipped, 0);
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeRemoveCmd --
 *
 *         $node remove NODE-LIST...
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeRemoveCmd(pNode, objc, objv)
    HtmlNode *pNode;
    int objc;
    Tcl_Obj *CONST objv[];
{
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    int ii;

    if (objc < 3) {
        Tcl_WrongNumArgs(pTree->interp, 2, objv, "NODE-LIST");
        return TCL_ERROR;
    }

    for (ii = 2; ii < objc; ii++) {
        Tcl_Obj **apNode;
        int nNode;
        int jj;
        int rc;

        rc = Tcl_ListObjGetElements(pTree->interp, objv[ii], &nNode, &apNode);
        if (rc != TCL_OK) {
            return rc;
        }

        for (jj = 0; jj < nNode; jj++) {
            int e;
            Tcl_Obj *pObj = apNode[jj];
            HtmlNode *pChild = HtmlNodeGetPointer(pTree, Tcl_GetString(pObj));
            e = nodeRemoveChild((HtmlElementNode *)pNode, pChild);
            if (e) {
                nodeOrphanize(pTree, pChild);
                HtmlNodeClearRecursive(pTree, pChild);
            }
        }
    }

    HtmlCheckRestylePoint(pTree);
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeDestroyCmd --
 *
 *         $node destroy
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeDestroyCmd(pNode, objc, objv)
    HtmlNode *pNode;
    int objc;
    Tcl_Obj *CONST objv[];
{
    HtmlTree *pTree = pNode->pNodeCmd->pTree;

    if (objc != 2) {
        Tcl_WrongNumArgs(pTree->interp, 2, objv, "");
        return TCL_ERROR;
    }

    assert(
        pNode->iNode == HTML_NODE_ORPHAN || 
        pNode == pTree->pRoot || 
        pNode->pParent
    );

    if (pNode->iNode == HTML_NODE_ORPHAN) {
        nodeDeorphanize(pTree, pNode);
    } else if (pNode->pParent) {
        HtmlCallbackRestyle(pTree, pNode->pParent);
        HtmlCallbackLayout(pTree, pNode->pParent);
        nodeRemoveChild(HtmlNodeAsElement(pNode->pParent), pNode);
    } else {
        assert(!"TODO: Delete the root node?");
    }
    
    freeNode(pTree, pNode);

    HtmlCheckRestylePoint(pTree);
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeInsertCmd --
 *
 *         $node insert ?-before|-after NODE? NODE-LIST...
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeInsertCmd(pNode, objc, objv)
    HtmlNode *pNode;
    int objc;
    Tcl_Obj *CONST objv[];
{
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    Tcl_Interp *interp = pTree->interp;
    int ii;
    HtmlNode *pBefore = 0;
    HtmlNode *pAfter = 0;

    /* Process the "-before" or "-after" option, if one is specified. 
     */
    if (objc > 3 && (
            0 == strcmp(Tcl_GetString(objv[2]), "-before") ||
            0 == strcmp(Tcl_GetString(objv[2]), "-after")
    )) {
        int iBefore;
        pBefore = HtmlNodeGetPointer(pTree, Tcl_GetString(objv[3]));
        iBefore = HtmlNodeIndexOfChild(pNode, pBefore);
        if (iBefore < 0) {
            Tcl_ResetResult(pTree->interp);
            Tcl_AppendResult(pTree->interp, Tcl_GetString(objv[3]), 
                " is not a child node of ", Tcl_GetString(objv[0]), 0
            );
            return TCL_ERROR;
        }
        if (0 == strcmp(Tcl_GetString(objv[2]), "-after")) {
            pAfter = pBefore;
            pBefore = 0;
        }
    }

    /* Complain if there are insufficient arguments to this command */
    if (objc < 3 || (pBefore && objc < 5)) {
        Tcl_WrongNumArgs(interp, 2, objv, "?-before|-after NODE? NODE-LIST");
        return TCL_ERROR;
    }

    for (ii = (pBefore ? 4 : 2); ii < objc; ii++) {
        Tcl_Obj **apNode;
        int nNode;
        int jj;
        int rc;

        rc = Tcl_ListObjGetElements(interp, objv[ii], &nNode, &apNode);
        if (rc != TCL_OK) {
            return rc;
        }

        for (jj = 0; jj < nNode; jj++) {
            Tcl_Obj *pObj = apNode[jj];
            HtmlNode *pChild = HtmlNodeGetPointer(pTree, Tcl_GetString(pObj));
            if (pChild) {
                HtmlElementNode *pElem = HtmlNodeAsElement(pNode);
                if (pChild->iNode == HTML_NODE_ORPHAN) {
                    nodeDeorphanize(pTree, pChild);
                }
                nodeInsertChild(pTree, pElem, pBefore, pAfter, pChild);
            }
        }
    }

    pTree->isSequenceOk = 0;
    HtmlCheckRestylePoint(pTree);

    return TCL_OK;
}

static CssPropertySet *
nodeGetStyle(pTree, p)
    HtmlTree *pTree;
    HtmlNode *p;
{
    HtmlElementNode *pElem = HtmlNodeAsElement(p);
    const char *zStyle;
    if (!pElem->pStyle && (zStyle = HtmlNodeAttr(p, "style"))) { 
        HtmlCssInlineParse(pTree, -1, zStyle, &pElem->pStyle);
    }
    return pElem->pStyle;
}

/*
 */
/*
 *---------------------------------------------------------------------------
 *
 * nodeTextCommand --
 *
 *         $node text ?get?
 *         $node text -tokens 
 *         $node text -pre 
 *         $node text set TEXT
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int
nodeTextCommand(interp, pNode, objc, objv)
    Tcl_Interp *interp;
    HtmlNode *pNode;
    int objc;
    Tcl_Obj *CONST objv[];
{
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    Tcl_Obj *pRet = 0;
    int nByte = 0;

    enum NODE_TEXT_enum {
        NODE_TEXT_GET,
        NODE_TEXT_PRE, 
        NODE_TEXT_SET, 
        NODE_TEXT_TOKENS 
    };
    enum NODE_TEXT_enum eChoice;

    static const struct NodeTextSubCommand {
        const char *zCommand;
        enum NODE_TEXT_enum eSymbol;
        int nArg;
    } aSubCommand[] = {
        {"get",       NODE_TEXT_GET, 0},  
        {"-pre",      NODE_TEXT_PRE, 0},      
        {"set",       NODE_TEXT_SET, 1},
        {"-tokens",   NODE_TEXT_TOKENS, 0},      
        {0, 0, 0}
    };

    HtmlTextNode *pTextNode = HtmlNodeAsText(pNode);

    /* This is a no-op for non text nodes */
    if (!pTextNode) return TCL_OK;

    if (objc==2) {
        eChoice = NODE_TEXT_GET;
    } else {
        int iChoice;
        if (Tcl_GetIndexFromObjStruct(interp, objv[2], aSubCommand, 
            sizeof(struct NodeTextSubCommand), "option", 0, &iChoice) 
        ){
            return TCL_ERROR;
        }
        if (objc != 3+aSubCommand[iChoice].nArg) {
            Tcl_WrongNumArgs(interp, 3, objv, ((objc==3)?"TEXT":""));
            return TCL_ERROR;
        }
        eChoice = aSubCommand[iChoice].eSymbol;
    }

    if (eChoice == NODE_TEXT_SET) {
        /* Because the storage for a text nodes data is allocated as
         * part of the HtmlTextNode allocation, the only way to modify
         * the text of a node is to allocate a new HtmlTextNode 
         * structure and then to change all the pointers that refer to
         * it. There are only three possibilities:
         *
         *     * In the Tcl_CmdInfo struct for this node-handle,
         *     * In the parent node, if this is not an orphan.
         *     * In the orphan node table, if this is an orphan.
         */
        const char *zNew;
        int nNew;
        HtmlTextNode *pOrig;

        pOrig = HtmlNodeAsText(pNode);
        assert(pOrig);

        /* Invalidate the layout of this node. */
        HtmlCallbackLayout(pTree, pNode);

        /* Set the node to contain the new text */
        zNew = Tcl_GetStringFromObj(objv[3], &nNew);
        HtmlTextSet(pOrig, nNew, zNew, 0, 0);

    } else if (eChoice == NODE_TEXT_PRE) {
        pRet = nodeGetPreText(HtmlNodeAsText(pNode));
        Tcl_IncrRefCount(pRet);
    } else {
        HtmlTextIter sIter;

        pRet = Tcl_NewObj();
        Tcl_IncrRefCount(pRet);

        for (
            HtmlTextIterFirst((HtmlTextNode *)pNode, &sIter);
            HtmlTextIterIsValid(&sIter);
            HtmlTextIterNext(&sIter)
        ) {
            int eType = HtmlTextIterType(&sIter);
            int nData = HtmlTextIterLength(&sIter);
            char const * zData = HtmlTextIterData(&sIter);
    
            if (eChoice == NODE_TEXT_TOKENS) {
                char *zType = 0;
                Tcl_Obj *p = Tcl_NewObj();
                Tcl_Obj *pObj = 0;
    
                switch (eType) {
                    case HTML_TEXT_TOKEN_TEXT:
                        zType = "text";
                        pObj = Tcl_NewStringObj(zData, nData);
                        break;
                    case HTML_TEXT_TOKEN_SPACE:
                        zType = "space";
                        pObj = Tcl_NewIntObj(nData);
                        break;
                    case HTML_TEXT_TOKEN_NEWLINE:
                        zType = "newline";
                        pObj = Tcl_NewIntObj(nData);
                        break;
                }
                assert(zType);
                Tcl_ListObjAppendElement(
                    0, p, Tcl_NewStringObj(zType, -1)
                );
                Tcl_ListObjAppendElement(0, p, pObj);
                Tcl_ListObjAppendElement(0, pRet, p);
            } else {
                assert(eChoice == NODE_TEXT_GET);
                if (eType == HTML_TEXT_TOKEN_TEXT) {
                    nByte = (HtmlTextIterData(&sIter) - pTextNode->zText);
                    nByte += HtmlTextIterLength(&sIter);
                }
            }
        }
    }

    if (eChoice == NODE_TEXT_GET) {
        Tcl_SetStringObj(pRet, pTextNode->zText, nByte);
    }

    if( pRet ){
        Tcl_SetObjResult(interp, pRet);
        Tcl_DecrRefCount(pRet);
    }
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * nodeCommand --
 *
 *         attr                    Read/write node attributes 
 *         children                Return a list of the nodes child nodes 
 *         dynamic                 Set/clear dynamic flags (i.e. :hover) 
 *         override                Read/write CSS property overrides 
 *         parent                  Return the parent node 
 *         prop                    Query CSS property values 
 *         property                Query a single CSS property value 
 *         replace                 Set/clear the node replacement object 
 *         tag                     Read/write the node's tag 
 *         text                    Read/write the node's text content 
 *         xview                   Scroll a scrollable node horizontally 
 *         yview                   Scroll a scrollable node vertically 
 *
 *     This function is the implementation of the Tcl node handle command. The
 *     clientData passed to the command is a pointer to the HtmlNode structure
 *     for the document node. 
 *
 *     When this function is called, ((HtmlNode *)clientData)->pNodeCmd is 
 *     guaranteed to point to a valid HtmlNodeCmd structure.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int 
nodeCommand(clientData, interp, objc, objv)
    ClientData clientData;
    Tcl_Interp *interp;
    int objc;
    Tcl_Obj *CONST objv[];
{
    HtmlNode *pNode = (HtmlNode *)clientData;
    HtmlTree *pTree = pNode->pNodeCmd->pTree;
    int iChoice;

    enum NODE_enum {
        NODE_ATTRIBUTE, NODE_CHILDREN, NODE_DESTROY, NODE_DYNAMIC, 
        NODE_HTML,
        NODE_INSERT, NODE_OVERRIDE, NODE_PARENT, NODE_PROPERTY, 
        NODE_REMOVE, NODE_REPLACE, NODE_STACKING, NODE_TAG, NODE_TEXT, 
        NODE_XVIEW, NODE_YVIEW
    };

    static const struct NodeSubCommand {
        const char *zCommand;
        enum NODE_enum eSymbol;
        int TODO;
    } aSubCommand[] = {
        {"attribute", NODE_ATTRIBUTE, 0},  
        {"children",  NODE_CHILDREN,  0},
        {"destroy",   NODE_DESTROY,   0},      
        {"dynamic",   NODE_DYNAMIC,   0},      
        {"html",      NODE_HTML,      0},
        {"insert",    NODE_INSERT,    0},
        {"override",  NODE_OVERRIDE,  0},    
        {"parent",    NODE_PARENT,    0},     
        {"property",  NODE_PROPERTY,  0}, 
        {"remove",    NODE_REMOVE,    0},
        {"replace",   NODE_REPLACE,   0}, 
        {"stacking",  NODE_STACKING,  0},    
        {"tag",       NODE_TAG,       0},    
        {"text",      NODE_TEXT,      0},  
        {"xview",     NODE_XVIEW,     0},
        {"yview",     NODE_YVIEW,     0},
        {0, 0, 0}
    };

    if (objc<2) {
        Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
        return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObjStruct(interp, objv[1], aSubCommand, 
            sizeof(struct NodeSubCommand), "option", 0, &iChoice) 
    ){
        return TCL_ERROR;
    }

    switch (aSubCommand[iChoice].eSymbol) {
        /*
         * nodeHandle attr ??-default DEFAULT-VALUE? ATTR-NAME? ?NEW-VALUE?
         */
        case NODE_ATTRIBUTE: {
            char CONST *zAttr = 0;
            char *zAttrName = 0;
            char *zAttrVal = 0;
            char *zDefault = 0;

            switch (objc) {
                case 2:
                    break;
                case 3:
                    zAttrName = Tcl_GetString(objv[2]);
                    break;
                case 4:
                    zAttrName = Tcl_GetString(objv[2]);
                    zAttrVal = Tcl_GetString(objv[3]);
                    break;
                case 5:
                    if (strcmp(Tcl_GetString(objv[2]), "-default")) {
                        goto node_attr_usage;
                    }
                    zDefault = Tcl_GetString(objv[3]);
                    zAttrName = Tcl_GetString(objv[4]);
                    break;
                default:
                    goto node_attr_usage;
            }

            /* If there are values for both zAttrName and zAttrVal, then
             * set the value of the attribute to the string pointed to by 
             * zAttrVal. After doing this, run the code for an attribute
             * query, so that the new attribute value is returned.
             */
            if (zAttrName && zAttrVal) {
                /* Check if there is an attribute-handler for this type
                 * of node. If so, invoke the script as follows:
                 *
                 *     eval $handler [list $attribute-name] [list $new-value]
                 */
                int rc;
                char *zCopy; 

                assert(!zDefault);

                zCopy = HtmlAlloc("tmp", strlen(zAttrName)+1);
                strcpy(zCopy, zAttrName);
                Tcl_UtfToLower(zCopy);
                rc = doAttributeHandler(pTree, pNode, zCopy, zAttrVal);
                HtmlFree(zCopy);

                if (rc != TCL_OK) {
                    return rc;
                }
                setNodeAttribute(pNode, zAttrName, zAttrVal);
                HtmlCallbackRestyle(pTree, pNode);
            }

            if (zAttrName) {
                zAttr = HtmlNodeAttr(pNode, zAttrName);
                zAttr = (zAttr ? zAttr : zDefault);
                if (zAttr==0) {
                    Tcl_AppendResult(interp, "No such attr: ", zAttrName, 0);
                    return TCL_ERROR;
                }
                Tcl_SetResult(interp, (char *)zAttr, TCL_VOLATILE);
            } else 

            if (!HtmlNodeIsText(pNode)) {
                int i;
                HtmlAttributes *pAttr = ((HtmlElementNode *)pNode)->pAttributes;
                Tcl_Obj *p = Tcl_NewObj();
                for (i = 0; pAttr && i < pAttr->nAttr; i++) {
                    Tcl_Obj *pArg;
                    pArg = Tcl_NewStringObj(pAttr->a[i].zName, -1);
                    Tcl_ListObjAppendElement(interp, p, pArg);
                    pArg = Tcl_NewStringObj(pAttr->a[i].zValue, -1);
                    Tcl_ListObjAppendElement(interp, p, pArg);
                }
                Tcl_SetObjResult(interp, p);
            }
            break;

node_attr_usage:
            Tcl_ResetResult(interp);
            Tcl_AppendResult(interp, "Usage: ",
                Tcl_GetString(objv[0]), " ",
                Tcl_GetString(objv[1]), " ",
                "? ?-default DEFAULT-VALUE? ATTR-NAME ?NEW-VAL??", 0);
            return TCL_ERROR;
        }

        /*
         * nodeHandle children
         *
         *     Return a list of node handles for all children of nodeHandle.
         *     The leftmost child node becomes element 0 of the list, the
         *     second leftmost element 1, and so on.
         */
        case NODE_CHILDREN: {
            if (objc == 2) {
                int i;
                Tcl_Obj *pRes = Tcl_NewObj();
                for (i = 0; i < HtmlNodeNumChildren(pNode); i++) {
                    HtmlNode *pChild = HtmlNodeChild(pNode, i);
                    Tcl_Obj *pCmd = HtmlNodeCommand(pTree, pChild);
                    Tcl_ListObjAppendElement(0, pRes, pCmd);
                }
                Tcl_SetObjResult(interp, pRes);
            } else {
                Tcl_WrongNumArgs(interp, 2, objv, "");
                return TCL_ERROR;
            }
            break;
        }

        /*
         * nodeHandle stacking
         *
         *     Return the node-handle that forms the stacking context
         *     this node is located in. Return "" for the root-element.
         *
         *     Also return "" for any element that is part of an
         *     orphan subtree.
         */
        case NODE_STACKING: {
            HtmlElementNode *pElem = HtmlNodeAsElement(pNode);
            if (!pElem) {
                pElem = HtmlNodeAsElement(HtmlNodeParent(pNode));
            }
            assert(
                pNode==pTree->pRoot || pElem->pStack || HtmlNodeIsOrphan(pNode)
            );
            if ((HtmlNode *)pElem != pTree->pRoot && pElem->pStack) {
                HtmlNode *p = &(pElem->pStack->pElem->node);
                Tcl_SetObjResult(interp, HtmlNodeCommand(pTree, p));
            }
            break;
        }

        case NODE_TAG: {
            char CONST *zTag;
            if (objc!=2) {
                Tcl_WrongNumArgs(interp, 2, objv, "");
                return TCL_ERROR;
            }
            zTag = HtmlNodeTagName(pNode);
            Tcl_SetResult(interp, (char *)zTag, TCL_VOLATILE);
            break;
        }

        case NODE_TEXT: {
            return nodeTextCommand(interp, pNode, objc, objv);
        }

        case NODE_PARENT: {
            HtmlNode *pParent;
            pParent = HtmlNodeParent(pNode);
            if (pParent) {
                Tcl_SetObjResult(interp, HtmlNodeCommand(pTree, pParent));
            } 
            break;
        }

        /*
         * nodeHandle property ?-before|-after|-inline? ?PROPERTY-NAME?
         *
         *     Return the calculated value of a node's CSS property. If the
         *     node is a text node, return the value of the property as
         *     assigned to the parent node.
         */
        case NODE_PROPERTY: {
            int nArg = objc - 2;
            Tcl_Obj * CONST *aArg = &objv[2];

            HtmlComputedValues *pComputed; 
            HtmlNode *p = pNode;

            /* This method is a no-op for text nodes */
            if (HtmlNodeIsText(p)) break;

            if (nArg > 0 && 0 == strcmp(Tcl_GetString(aArg[0]), "-inline")) {
                CssPropertySet *pSet = nodeGetStyle(pTree, p);
                if (nArg == 1) return HtmlCssInlineQuery(interp, pSet, 0);
                if (nArg == 2) return HtmlCssInlineQuery(interp, pSet, aArg[1]);
                /* Otherwise, fall through for the WrongNumArgs() message */
            }

	    /* Orphan nodes may have an inline style specified (required by 
             * DOM implementations to implement HTMLElement.style), but 
             * they do not have a computed style, so the rest of this 
             * function is a no-op for orphan nodes.
             */
            if (HtmlNodeIsOrphan(p)) break;
            HtmlCallbackForce(pTree);

            if (nArg > 0) {
                HtmlElementNode *pElem = HtmlNodeAsElement(pNode);
                char *zArg0 = Tcl_GetString(aArg[0]);
                if (0 == strcmp(zArg0, "-before")) {
                    p = pElem ? pElem->pBefore : 0;
                    aArg = &aArg[1];
                    nArg--;
                }
                else if (0 == strcmp(zArg0, "-after")) {
                    p = pElem ? pElem->pAfter : 0;
                    aArg = &aArg[1];
                    nArg--;
                }
            }

            /* If the -before or -after switch was specified, and the
             * element doesn't have any corresponding generated content,
             * then p is NULL at this point. Return an empty string.
             */
            if (!p) {
                return TCL_OK;
            }

            pComputed = HtmlNodeComputedValues(p);

            switch (nArg) {
                case 0:
                    return HtmlNodeProperties(interp, pComputed);
                case 1:
                    return HtmlNodeGetProperty(interp, objv[2], pComputed);
                default:
                    Tcl_WrongNumArgs(
                        interp, 2, objv,"?-before|-after|-inline? PROPERTY-NAME"
                    );
                    return TCL_ERROR;
            }
            break;
        }

        /*
         * nodeHandle replace ?new-value? ?options?
         *
         *     supported options are:
         *
         *         -configurecmd       <script>
         *         -deletecmd          <script>
         *         -stylecmd           <script>
         */
        case NODE_REPLACE: {

            HtmlElementNode *pElem = HtmlNodeAsElement(pNode);
            if (!pElem) {
                char *zErr = "Text node does not support [replace]";
                Tcl_SetResult(interp, zErr, 0);
                return TCL_ERROR;
            }

            if (objc > 2) {
                Tcl_Obj *aArgs[4];
                HtmlNodeReplacement *pReplace = 0; /* New pNode->pReplacement */
                Tk_Window widget;            /* Replacement widget */
                Tk_Window mainwin = Tk_MainWindow(pTree->interp);

                const char *zWin = 0;        /* Replacement window name */

                SwprocConf aArgConf[] = {
                    {SWPROC_ARG, "new-value", 0, 0},      /* aArgs[0] */
                    {SWPROC_OPT, "configurecmd", 0, 0},   /* aArgs[1] */
                    {SWPROC_OPT, "deletecmd", 0, 0},      /* aArgs[2] */
                    {SWPROC_OPT, "stylecmd", 0, 0},       /* aArgs[3] */
                    {SWPROC_END, 0, 0, 0}
                };
                if (SwprocRt(interp, objc - 2, &objv[2], aArgConf, aArgs)) {
                    return TCL_ERROR;
                }

                zWin = Tcl_GetString(aArgs[0]);

                if (zWin[0]) {
        	    /* If the replacement object is a Tk window,
                     * register Tkhtml as the geometry manager.
                     */
                    widget = Tk_NameToWindow(interp, zWin, mainwin);
                    if (widget) {
                        static Tk_GeomMgr sManage = {
                            "Tkhtml",
                            geomRequestProc,
                            0
                        };
                        Tk_ManageGeometry(widget, &sManage, pNode);
                    }

                    pReplace = HtmlNew(HtmlNodeReplacement);
                    pReplace->pReplace = aArgs[0];
                    pReplace->pConfigureCmd = aArgs[1];
                    pReplace->pDelete = aArgs[2];
                    pReplace->pStyleCmd = aArgs[3];
                    pReplace->win = widget;
                }

        	/* Free any existing replacement object and set
        	 * pNode->pReplacement to point at the new structure. 
                 */
                clearReplacement(pTree, pElem);
                pElem->pReplacement = pReplace;

                /* Run the layout engine. */
                HtmlCallbackLayout(pTree, pNode);
            }

            /* The result of this command is the name of the current
             * replacement object (or an empty string).
             */
            if (pElem->pReplacement) {
                assert(pElem->pReplacement->pReplace);
                Tcl_SetObjResult(interp, pElem->pReplacement->pReplace);
            }
            break;
        }

        /*
         * nodeHandle dynamic set|clear ?flag?
         * nodeHandle dynamic conditions
         *
         *     Note that the [nodeHandle dynamic conditions] command is for
         *     debugging only. It is not documented in the man page.
         */
        case NODE_DYNAMIC: {
            struct DynamicFlag {
                const char *zName;
                Html_u8 flag;
            } flags[] = {
                {"active",  HTML_DYNAMIC_ACTIVE}, 
                {"focus",   HTML_DYNAMIC_FOCUS}, 
                {"hover",   HTML_DYNAMIC_HOVER},
                {"link",    HTML_DYNAMIC_LINK},
                {"visited", HTML_DYNAMIC_VISITED},
                {0, 0}
            };
            const char *zArg1 = (objc>2) ? Tcl_GetString(objv[2]) : 0;
            const char *zArg2 = (objc>3) ? Tcl_GetString(objv[3]) : 0;
            Tcl_Obj *pRet;
            int i;
            Html_u8 mask = 0;

            HtmlElementNode *pElem = (HtmlElementNode *)pNode;
            if (HtmlNodeIsText(pNode)) {
                Tcl_SetResult(interp, 
                    "Cannot call method [dynamic] on a text node", 0
                );
                return TCL_ERROR;
            }

            if (zArg1 && 0 == strcmp(zArg1, "conditions")) {
                HtmlCallbackForce(pTree);
                return HtmlCssTclNodeDynamics(interp, pNode);
            }

            if (zArg2) {
                for (i = 0; flags[i].zName; i++) {
                    if (0 == strcmp(zArg2, flags[i].zName)) {
                        mask = flags[i].flag;
                        break;
                    }
                }
                if (!mask) {
                    Tcl_AppendResult(interp, 
                        "Unsupported dynamic CSS flag: ", zArg2, 0);
                    return TCL_ERROR;
                }
            }

            if ( 
                !zArg1 || 
                (strcmp(zArg1, "set") && strcmp(zArg1, "clear")) ||
                (zArg2 && !mask)
            ) {
                Tcl_WrongNumArgs(interp, 2, objv, "set|clear ?flag?");
                return TCL_ERROR;
            }

            if (*zArg1 == 's') {
                pElem->flags |= mask;
            } else {
                pElem->flags &= ~(mask?mask:0xFF);
            }

            if (zArg2) {
                if (
                    mask == HTML_DYNAMIC_LINK || 
                    mask == HTML_DYNAMIC_VISITED
                ) {
                    HtmlCallbackRestyle(pTree, pNode);
                } else {
                    HtmlCallbackDynamic(pTree, pNode);
                }
            }

            pRet = Tcl_NewObj();
            for (i = 0; flags[i].zName; i++) {
                if (pElem->flags & flags[i].flag) {
                    Tcl_Obj *pNew = Tcl_NewStringObj(flags[i].zName, -1);
                    Tcl_ListObjAppendElement(0, pRet, pNew);
                }
            }
            Tcl_SetObjResult(interp, pRet);
            break;
        }

        /*
         * nodeHandle override ?new-value?
         *
         *     Get/set the override list.
         */
        case NODE_OVERRIDE: {

            HtmlElementNode *pElem = (HtmlElementNode *)pNode;
            if (HtmlNodeIsText(pNode)) {
                Tcl_SetResult(interp, 
                    "Cannot call method [override] on a text node", 0
                );
                return TCL_ERROR;
            }

            if (objc != 2 && objc != 3) {
                Tcl_WrongNumArgs(interp, 2, objv, "?new-value?");
                return TCL_ERROR;
            }

            if (objc == 3) {
                if (pElem->pOverride) {
                    Tcl_DecrRefCount(pElem->pOverride);
                }
                pElem->pOverride = objv[2];
                Tcl_IncrRefCount(pElem->pOverride);
            }

            Tcl_ResetResult(interp);
            if (pElem->pOverride) {
                Tcl_SetObjResult(interp, pElem->pOverride);
            }
            HtmlCallbackRestyle(pTree, pNode);
            return TCL_OK;
        }

        case NODE_XVIEW: {
            return nodeViewCmd(pNode, 0, objv, objc);
        }
        case NODE_YVIEW: {
            return nodeViewCmd(pNode, 1, objv, objc);
        }

        /*
         * nodeHandle html
         */
        case NODE_HTML: {
            if (objc != 2) {
                Tcl_WrongNumArgs(interp, 2, objv, "");
                return TCL_ERROR;
            }
            Tcl_SetResult(interp, 
                (char *)Tcl_GetCommandName(interp, pTree->cmd), TCL_STATIC
            );
            return TCL_OK;
        }

        /*
         * nodeHandle insert ?-before NODE? NODE-LIST
         *
         */
        case NODE_INSERT: {
            HtmlCallbackRestyle(pTree, pNode);
            HtmlCallbackLayout(pTree, pNode);
            return nodeInsertCmd(pNode, objc, objv);
        }

        /*
         * nodeHandle remove NODE-LIST
         */
        case NODE_REMOVE: {
            HtmlCallbackRestyle(pTree, pNode);
            HtmlCallbackLayout(pTree, pNode);
            return nodeRemoveCmd(pNode, objc, objv);
        }

        /*
         * nodeHandle destroy
         */
        case NODE_DESTROY: {
            return nodeDestroyCmd(pNode, objc, objv);
        }

        default:
            assert(!"Impossible!");
    }

    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeCommand --
 *
 *     Return a Tcl object containing the name of the Tcl command used to
 *     access pNode. If the command does not already exist it is created.
 *
 *     The Tcl_Obj * returned is always a pointer to pNode->pCommand.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
Tcl_Obj *
HtmlNodeCommand(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    static int nodeNumber = 0;
    HtmlNodeCmd *pNodeCmd = pNode->pNodeCmd;

    if (pNode->iNode == HTML_NODE_GENERATED) {
        return 0;
    }

    if (!pNodeCmd) {
        char zBuf[100];
        Tcl_Obj *pCmd;
        sprintf(zBuf, "::tkhtml::node%d", nodeNumber++);

        pCmd = Tcl_NewStringObj(zBuf, -1);
        Tcl_IncrRefCount(pCmd);
        Tcl_CreateObjCommand(pTree->interp, zBuf, nodeCommand, pNode, 0);
        pNodeCmd = HtmlNew(HtmlNodeCmd);
        pNodeCmd->pCommand = pCmd;
        pNodeCmd->pTree = pTree;
        pNode->pNodeCmd = pNodeCmd;
    }

    return pNodeCmd->pCommand;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeScrollbarDoCallback --
 *
 *     If node pNode is scrollable, invoke the [$scrollbar set] command
 *     for each of it's scrollbar widgets.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     Invokes 0-2 [$scrollbar set] scripts.
 *
 *---------------------------------------------------------------------------
 */
int HtmlNodeScrollbarDoCallback(pTree, pNode)
    HtmlTree *pTree;
    HtmlNode *pNode;
{
    HtmlElementNode *pElem = (HtmlElementNode *)pNode;

    if (!HtmlNodeIsText(pNode) && pElem->pScrollbar) {
        HtmlNodeScrollbars *p = pElem->pScrollbar;
        char zTmp[256];
        if (p->vertical.win) {
            snprintf(zTmp, 255, "%s set %f %f", 
                Tcl_GetString(p->vertical.pReplace), 
                (double)p->iVertical / (double)p->iVerticalMax,
                (double)(p->iVertical + p->iHeight) / (double)p->iVerticalMax
            );
            zTmp[255] = '\0';
            Tcl_Eval(pTree->interp, zTmp);
        }
        if (p->horizontal.win) {
            snprintf(zTmp, 255, "%s set %f %f", 
                Tcl_GetString(p->horizontal.pReplace), 
                (double)p->iHorizontal / (double)p->iHorizontalMax,
                (double)(p->iHorizontal + p->iWidth) / (double)p->iHorizontalMax
            );
            zTmp[255] = '\0';
            Tcl_Eval(pTree->interp, zTmp);
        }
    }

    return TCL_OK;
}


/*
 *---------------------------------------------------------------------------
 *
 * HtmlTreeClear --
 *
 *     Completely reset the widgets internal structures - for example when
 *     loading a new document.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     Deletes internal document representation.
 *
 *---------------------------------------------------------------------------
 */
int HtmlTreeClear(pTree)
    HtmlTree *pTree;
{
    Tcl_HashEntry *pEntry;
    Tcl_HashSearch search;

    /* Free the canvas representation */
    HtmlDrawCleanup(pTree, &pTree->canvas);
    memset(&pTree->canvas, 0, sizeof(HtmlCanvas));

    /* Free any snapshot */
    HtmlDrawSnapshotFree(pTree, pTree->cb.pSnapshot);
    pTree->cb.pSnapshot = 0;

    /* Free the contents of the search-cache */
    HtmlCssSearchInvalidateCache(pTree);

    /* Free the tree representation - pTree->pRoot */
    freeNode(pTree, pTree->pRoot);
    pTree->pRoot = 0;
    pTree->state.pCurrent = 0;
    pTree->state.pFoster = 0;

    /* Free any orphan nodes associated with this tree: */
    for (
        pEntry = Tcl_FirstHashEntry(&pTree->aOrphan, &search);
        pEntry;
        pEntry = Tcl_NextHashEntry(&search)
    ) {
        HtmlNode *pOrphan = (HtmlNode *)Tcl_GetHashKey(&pTree->aOrphan, pEntry);
        assert(pOrphan->iNode == HTML_NODE_ORPHAN);
        freeNode(pTree, pOrphan);
    }
    Tcl_DeleteHashTable(&pTree->aOrphan);
    Tcl_InitHashTable(&pTree->aOrphan, TCL_ONE_WORD_KEYS);

    /* Free the formatted text, if any (HtmlTree.pText) */
    HtmlTextInvalidate(pTree);

    /* Free the plain text representation */
    if (pTree->pDocument) {
        Tcl_DecrRefCount(pTree->pDocument);
    }
    pTree->nParsed = 0;
    pTree->pDocument = 0;

    /* Free the stylesheets */
    HtmlCssStyleSheetFree(pTree->pStyle);
    pTree->pStyle = 0;

    /* Set the scroll position to top-left and clear the selection */
    pTree->iScrollX = 0;
    pTree->iScrollY = 0;

    /* Deschedule any dynamic, style or layout callback. */
    pTree->cb.pDynamic = 0;
    pTree->cb.pRestyle = 0;
    pTree->cb.flags &= ~(HTML_DYNAMIC|HTML_RESTYLE|HTML_LAYOUT);

    pTree->iNextNode = 0;
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlNodeGetPointer --
 *
 *     String argument zCmd is the name of a node command created for
 *     some node of tree pTree. Find the corresponding HtmlNode pointer
 *     and return it. If zCmd is not the name of a node command, leave
 *     an error in pTree->interp and return NULL.
 *
 * Results:
 *     Pointer to node object associated with Tcl command zCmd, or NULL.
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
HtmlNode *
HtmlNodeGetPointer(pTree, zCmd)
    HtmlTree *pTree;
    char CONST *zCmd;
{
    Tcl_Interp *interp = pTree->interp;
    Tcl_CmdInfo info;
    int rc;

    rc = Tcl_GetCommandInfo(interp, zCmd, &info);
    if (rc == 0 || info.objProc != nodeCommand){ 
        Tcl_AppendResult(interp, "no such node: ", zCmd, 0);
        return 0;
    }
    return (HtmlNode *)info.objClientData;
}

/************************************************************************
 * Start of [fragment] parsing code.
 */

static void
fragmentOrphan(pTree)
    HtmlTree *pTree;
{
    HtmlFragmentContext *pFragment = pTree->pFragment;
    HtmlNode *pOrphan = pFragment->pRoot;

    if (pOrphan) {
        Tcl_Obj *pCmd = HtmlNodeCommand(pTree, pOrphan);
        Tcl_ListObjAppendElement(0, pFragment->pNodeList, pCmd);
        nodeOrphanize(pTree, pOrphan);
        pFragment->pRoot = 0;
        pFragment->pCurrent = 0;
    }

    assert(!pFragment->pRoot && !pFragment->pCurrent);
}

static void 
fragmentAddText(pTree, pTextNode, iOffset)
    HtmlTree *pTree;
    HtmlTextNode *pTextNode; 
    int iOffset;
{
    HtmlFragmentContext *pFragment = pTree->pFragment;

    pTextNode->node.eTag = Html_Text;

    if (pFragment->pRoot) {
        /* If there is a fragment root node, add the new text node
         * as the right-most child of HtmlFragmentContext.pCurrent.
         */
        nodeInsertChild(pTree, pFragment->pCurrent, 0,0, (HtmlNode *)pTextNode);
    } else {
        /* The text node becomes the a sub-tree all on it's own. */
        pFragment->pRoot = (HtmlNode *)pTextNode;
        fragmentOrphan(pTree);
    }
}

static void 
fragmentAddElement(pTree, eType, zType, pAttributes, iOffset)
    HtmlTree *pTree;
    int eType;
    const char *zType;               /* Atom */
    HtmlAttributes *pAttributes; 
    int iOffset;
{
    HtmlElementNode *pElem;
    HtmlFragmentContext *pFragment = pTree->pFragment;
    int nClose;
    int ii;

    switch (eType) {
        /* Ignore <HEAD>, <BODY> and elements that occur as descendants of
         * <HEAD> completely. TODO: This will have to change....
         */
        case Html_HTML:
        case Html_HEAD:
        case Html_BODY:
        case Html_TITLE:
        case Html_META:
        case Html_LINK:
        case Html_BASE:
            return;
    }

    implicitCloseCount(pTree, pFragment->pCurrent, eType, &nClose);
    for (ii = 0; ii < nClose; ii++) {
        HtmlNode *pC = &pFragment->pCurrent->node;
        HtmlNode *pParentC = HtmlNodeParent(pC);
        assert(pC);
        nodeHandlerCallbacks(pTree, pC);
        pFragment->pCurrent = (HtmlElementNode *)pParentC;
    }
    if (!pFragment->pCurrent) {
        fragmentOrphan(pTree);
    }

    pElem = HtmlNew(HtmlElementNode);
    pElem->pAttributes = pAttributes;
    pElem->node.eTag = eType;
    if (!zType) {
        zType = HtmlTypeToName(0, eType);
    }
    pElem->node.zTag = zType;

    if (pFragment->pCurrent) {
        nodeInsertChild(pTree, pFragment->pCurrent, 0, 0, (HtmlNode *)pElem);
    } else {
        assert(!pFragment->pRoot);
        pFragment->pRoot = (HtmlNode *)pElem;
        pElem->node.iNode = HTML_NODE_ORPHAN;
    }
    pFragment->pCurrent = pElem;

    if (HtmlMarkup(eType)->flags & HTMLTAG_EMPTY) {
        nodeHandlerCallbacks(pTree, pFragment->pCurrent);
        pFragment->pCurrent = (HtmlElementNode *)HtmlNodeParent(pElem);
    }
    if (!pFragment->pCurrent) {
        fragmentOrphan(pTree);
    }
}

static void 
fragmentAddClosingTag(pTree, eType, zType, iOffset)
    HtmlTree *pTree;
    int eType;
    const char *zType;
    int iOffset;
{
    int nClose;
    int ii;
    HtmlFragmentContext *p = pTree->pFragment;
    explicitCloseCount(p->pCurrent, eType, zType, &nClose);
    for (ii = 0; ii < nClose; ii++) {
        assert(p->pCurrent);
        nodeHandlerCallbacks(pTree, p->pCurrent);
        p->pCurrent = (HtmlElementNode *)HtmlNodeParent(p->pCurrent);
    }
    if (!p->pCurrent) {
        fragmentOrphan(pTree);
    }
}

void
HtmlParseFragment(pTree, zHtml)
    HtmlTree *pTree;
    const char *zHtml;
{
    HtmlFragmentContext sContext;

    assert(!pTree->pFragment);
    sContext.pRoot = 0;
    sContext.pCurrent = 0;
    sContext.pNodeList = Tcl_NewObj();

    pTree->pFragment = &sContext;
    HtmlTokenize(pTree, zHtml, 1,
        fragmentAddText, fragmentAddElement, fragmentAddClosingTag
    );

    while (sContext.pCurrent) {
        HtmlNode *pParent = HtmlNodeParent(sContext.pCurrent); 
        nodeHandlerCallbacks(pTree, sContext.pCurrent);
        sContext.pCurrent = (HtmlElementNode *)pParent;
    }

    fragmentOrphan(pTree);
    pTree->pFragment = 0;
    Tcl_SetObjResult(pTree->interp, sContext.pNodeList);
}

/*
 *---------------------------------------------------------------------------
 *
 * sequenceCb --
 *
 *     This is an HtmlWalkTree() callback function (the tree iteration
 *     is started from with HtmlSequenceNodes()).
 *
 * Results:
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
static int 
sequenceCb(pTree, pNode, clientData)
    HtmlTree *pTree;
    HtmlNode *pNode;
    ClientData clientData;
{
    pNode->iNode = pTree->iNextNode++;
    return HTML_WALK_DESCEND;
}

/*
 *---------------------------------------------------------------------------
 *
 * HtmlSequenceNodes --
 *
 * Results:
 *
 * Side effects:
 *     None.
 *
 *---------------------------------------------------------------------------
 */
void
HtmlSequenceNodes(pTree)
    HtmlTree *pTree;
{
    if (!pTree->isSequenceOk) {
        pTree->iNextNode = 0;
        HtmlWalkTree(pTree, 0, sequenceCb, 0);
        pTree->isSequenceOk = 1;
    }
}