File: Twig.pm.slow

package info (click to toggle)
libxml-twig-perl 3.02-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 620 kB
  • ctags: 319
  • sloc: perl: 5,334; xml: 79; makefile: 33
file content (7187 lines) | stat: -rw-r--r-- 228,555 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
# XML::Twig 3.02 Twig.pm.slow - 2002-01-16
#
# Copyright (c) 1999-2002 Michel Rodriguez
# All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#

# This is created in the caller's space
BEGIN
  {sub ::PCDATA { '#PCDATA' } 
   sub ::CDATA  { '#CDATA'  } 
  }

######################################################################
package XML::Twig;
######################################################################

require 5.004;

use strict; 
use vars qw($VERSION @ISA);
use Carp;

#start-extract twig_global

# constants: element types
use constant (PCDATA  => '#PCDATA');
use constant (CDATA   => '#CDATA');
use constant (PI      => '#PI');
use constant (COMMENT => '#COMMENT');
use constant (ENT     => '#ENT');

# element classes
use constant (ELT     => '#ELT');
use constant (TEXT    => '#TEXT');

# element properties
use constant (ASIS    => '#ASIS');
use constant (EMPTY   => '#EMPTY');

#end-extract twig_global

# used in parseurl to set the buffer size to the same size as in XML::Parser::Expat
use constant (BUFSIZE => 32768);

# used to store the gi's
my %gi2index;   # gi => index
my @index2gi;   # list of gi's
my $SPECIAL_GI; # first non-special gi;
my %base_ent;   # base entity character => replacement

# flag, set to true if the WeakRef module is available
use vars qw( $weakrefs);

#start-extract twig_global
my $REG_NAME       = q{(?:[#a-zA-Z][#\w:.-]*)};         # xml name
my $REG_NAME_W     = q{(?:[#a-zA-Z][#\w:.-]*|\*)};      # name or wildcard (* or '')
my $REG_REGEXP     = q{(?:/(?:[^\\/]|\\.)*/[eimsox]*)}; # regexp
my $REG_REGEXP_EXP = q{(?:(?:[^\\/]|\\.)*)};            # content of a regexp
my $REG_REGEXP_MOD = q{(?:[eimso]*)};                   # regexp modifiers
my $REG_STRING     = q{(?:"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')};  # string (simple or double quoted)
#end-extract twig_global

my $parser_version;

BEGIN
{ 
  $VERSION = '3.02';

  use XML::Parser;
  my $needVersion = '2.23';
  $parser_version= $XML::Parser::VERSION;
  croak "need at least XML::Parser version $needVersion"
    unless $parser_version >= $needVersion;


  # test whether we can use weak references
  if( eval 'require WeakRef')
    { import WeakRef;
      $weakrefs= 1;
    } 
  # warn "weak references used\n" if( $weakrefs);

  import XML::Twig::Elt;
  import XML::Twig::Entity;
  import XML::Twig::Entity_list;

  # used to store the gi's
  # should be set for each twig really, at least when there are several
  # the init ensures that special gi's are always the same

  # gi => index
  # do NOT use => or the constants become quoted!
  %XML::Twig::gi2index=( PCDATA, 0, CDATA, 1, PI, 2, COMMENT, 3, ENT, 4); 
  # list of gi's
  @XML::Twig::index2gi=( PCDATA, CDATA, PI, COMMENT, ENT);

  # gi's under this value are special 
  $XML::Twig::SPECIAL_GI= @XML::Twig::index2gi;
  
  %XML::Twig::base_ent= ( '>' => '>',
               '<' => '&lt;',
               '&' => '&amp;',
               "'" => '&apos;',
               '"' => '&quot;',
             );

  # now set some aliases
  *find_nodes = *get_xpath;
  *getElementsByTagName= *descendants;
  *descendants_or_self= *descendants;
}

@ISA = qw(XML::Parser);

# fake gi's used in twig_handlers and start_tag_handlers
my $ALL    = '_all_';     # the associated function is always called
my $DEFAULT= '_default_'; # the function is called if no other handler has been

# some defaults
my $COMMENTS_DEFAULT= 'keep';
my $PI_DEFAULT      = 'keep';


# handlers used in regular mode
my %twig_handlers=( Start      => \&twig_start, 
                    End        => \&twig_end, 
                    Char       => \&twig_char, 
                    Entity     => \&twig_entity, 
                    XMLDecl    => \&twig_xmldecl, 
                    Doctype    => \&twig_doctype, 
                    Element    => \&twig_element, 
                    Attlist    => \&twig_attlist, 
                    CdataStart => \&twig_cdatastart, 
                    CdataEnd   => \&twig_cdataend, 
                    Proc       => \&twig_pi,
                    Comment    => \&twig_comment,
                  );

# handlers used when twig_roots is used and we are outside of the roots
my %twig_handlers_roots=
      ( Start      => \&twig_start_check_roots, 
        End        => \&twig_end_check_roots, 
        Doctype    => \&twig_doctype, 
        Char       => undef, Entity     => undef, XMLDecl    => undef, 
        Element    => undef, Attlist    => undef, CdataStart => undef, 
        CdataEnd   => undef, Proc       => undef, Comment    => undef, 
	Default    => undef,
      );

# handlers used when twig_roots and print_outside_roots are used and we are
# outside of the roots
my %twig_handlers_roots_print_2_30=
      ( Start      => \&twig_start_check_roots_print, 
        End        => \&twig_end_check_roots_print, 
        Char       => \&twig_print, 
        # I have no idea why I should not be using this handler!
        #Entity     => \&twig_print_entity, 
        XMLDecl    => \&twig_print,
        # Element    => \&twig_print, Attlist    => \&twig_print, 
        CdataStart => \&twig_print, CdataEnd   => \&twig_print, 
        Proc       => \&twig_print, Comment    => \&twig_print, 
        Default    => \&twig_print, 
      );

# handlers used when twig_rootsi, print_outside_roots and keep_encoding are used
# and we are outside of the roots
my %twig_handlers_roots_print_original_2_30=
      ( Start      => \&twig_start_check_roots_print_original, 
        End        => \&twig_end_check_roots_print_original, 
        Char       => \&twig_print_original, 
        # I have no idea why I should not be using this handler!
        Entity    => \&twig_print_original, 
        XMLDecl    => \&twig_print_original, 
        Element    => \&twig_print_original, Attlist   => \&twig_print_original,
        CdataStart => \&twig_print_original, CdataEnd  => \&twig_print_original,
        Proc       => \&twig_print_original, Comment   => \&twig_print_original,
        Default    => \&twig_print_original, 
      );

# handlers used when twig_roots and print_outside_roots are used and we are
# outside of the roots
my %twig_handlers_roots_print_2_27=
      ( Start      => \&twig_start_check_roots_print, 
        End        => \&twig_end_check_roots_print, 
        Char       => \&twig_print, 
        # I have no idea why I should not be using this handler!
        Entity     => \&twig_print, 
        XMLDecl    => \&twig_print, Doctype    => \&twig_print, 
        CdataStart => \&twig_print, CdataEnd   => \&twig_print, 
        Proc       => \&twig_print, Comment    => \&twig_print, 
        Default    => \&twig_print, 
      );

# handlers used when twig_roots, print_outside_roots and keep_encoding are used
# and we are outside of the roots
my %twig_handlers_roots_print_original_2_27=
      ( Start      => \&twig_start_check_roots_print_original, 
        End        => \&twig_end_check_roots_print_original, 
        Char       => \&twig_print_original, 
        # for some reason original_string is wrong here 
        # this can be a problem if the doctype includes non ascii characters
        XMLDecl    => \&twig_print, Doctype    => \&twig_print,
        # I have no idea why I should not be using this handler!
        # Entity     => \&twig_print, 
        CdataStart => \&twig_print_original, CdataEnd  => \&twig_print_original,
        Proc       => \&twig_print_original, Comment   => \&twig_print_original,
        Default    => \&twig_print_default, #  twig_print_original does not work
      );


my %twig_handlers_roots_print= $parser_version > 2.27 
                               ? %twig_handlers_roots_print_2_30 
                               : %twig_handlers_roots_print_2_27; 
my %twig_handlers_roots_print_original= $parser_version > 2.27 
                                    ? %twig_handlers_roots_print_original_2_30 
                                    : %twig_handlers_roots_print_original_2_27; 


# handlers used when the finish_print method has been called
my %twig_handlers_finish_print=
      ( Start      => \&twig_print, 
        End        => \&twig_print_end, Char       => \&twig_print, 
        Entity     => \&twig_print, XMLDecl    => \&twig_print, 
        Doctype    => \&twig_print, Element    => \&twig_print, 
        Attlist    => \&twig_print, CdataStart => \&twig_print, 
        CdataEnd   => \&twig_print, Proc       => \&twig_print, 
        Comment    => \&twig_print, Default    => \&twig_print, 
      );

# handlers used when the finish_print method has been called and the keep_encoding
# option is used
my %twig_handlers_finish_print_original=
      ( Start      => \&twig_print_original, End      => \&twig_print_end_original, 
        Char       => \&twig_print_original, Entity   => \&twig_print_original, 
        XMLDecl    => \&twig_print_original, Doctype  => \&twig_print_original, 
        Element    => \&twig_print_original, Attlist  => \&twig_print_original, 
        CdataStart => \&twig_print_original, CdataEnd => \&twig_print_original, 
        Proc       => \&twig_print_original, Comment  => \&twig_print_original, 
        Default    => \&twig_print_original, 
      );

# handlers used whithin ignored elements
my %twig_handlers_ignore=
      ( Start      => \&twig_ignore_start, 
        End        => \&twig_ignore_end, 
        Char       => undef, Entity     => undef, XMLDecl    => undef, 
        Doctype    => undef, Element    => undef, Attlist    => undef, 
        CdataStart => undef, CdataEnd   => undef, Proc       => undef, 
        Comment    => undef, Default    => undef,
      );


# those handlers are only used if the entities are NOT to be expanded
my %twig_noexpand_handlers= ( Default => \&twig_default );

my @saved_default_handler;

my $ID= 'id'; # default value, set by the Id argument

# all allowed options
my %valid_option=
    ( # XML::Twig options
      TwigHandlers          => 1, Id                    => 1,
      TwigRoots             => 1, TwigPrintOutsideRoots => 1,
      StartTagHandlers      => 1, EndTagHandlers        => 1,
      IgnoreTags            => 1,
      CharHandler           => 1, KeepEncoding          => 1,
      ParseStartTag         => 1, 
      LoadDTD               => 1, DTDHandler            => 1,
      DoNotOutputDTD        => 1, ExpandExternalEnts    => 1,
      DiscardSpaces         => 1, KeepSpaces            => 1, 
      DiscardSpacesIn       => 1, KeepSpacesIn          => 1, 
      PrettyPrint           => 1, EmptyTags             => 1, 
      Comments              => 1, Pi                    => 1, 
      OutputFilter          => 1, InputFilter           => 1,
      # XML::Parser options
      ErrorContext          => 1, ProtocolEncoding      => 1,
      Namespaces            => 1, NoExpand              => 1,
      Stream_Delimiter      => 1, ParseParamEnt         => 1,
      NoLWP                 => 1, Non_Expat_Options     => 1,
    );

# predefined iinput and output filters
use vars qw( %filter);
%filter= ( html   => \&html_encode,
           safe   => \&safe_encode,
         );

1;


sub new
  { my ($class, %args) = @_;
    my $handlers;

    # cahnge all nice_perlish_names into nicePerlishNames
    %args= normalize_args( %args);

    # check options
    unless( $args{MoreOptions})
      { foreach my $arg (keys %args)
        { carp "illegal option $arg" unless $valid_option{$arg}; }
      }
     
    # a twig is really an XML::Parser
    # my $self= XML::Parser->new(%args);
    my $self;
    $self= XML::Parser->new(%args);   
    
    bless $self, $class;

    if( exists $args{TwigHandlers})
      { $handlers= $args{TwigHandlers};
        $self->setTwigHandlers( $handlers);
        delete $args{TwigHandlers};
      }

    # take care of twig-specific arguments
    if( exists $args{StartTagHandlers})
      { $self->setStartTagHandlers( $args{StartTagHandlers});
        delete $args{StartTagHandlers};
      }

    if(  exists $args{IgnoreTags})
      { $self->setIgnoreTagsHandlers( $args{IgnoreTags});
        delete $args{IgnoreTags};
      }


    $self->{twig_dtd_handler}= $args{DTDHandler};
    delete $args{DTDHandler};
    $self->{twig_char_handler}= $args{CharHandler};
    delete $args{CharHandler};

    if( $args{LoadDTD})
      { $self->{twig_read_external_dtd}= 1;
        delete $args{LoadDTD};
      }
      
    if( $args{ExpandExternalEnts})
      { $self->set_expand_external_entities( 1);
        $self->{twig_read_external_dtd}= 1; # implied by ExpandExternalEnts
        delete $args{LoadDTD};
        delete $args{ExpandExternalEnts};
      }

    # deal with TwigRoots argument, a hash of elements for which
    # subtrees will be built (and associated handlers)
     
    if( $args{TwigRoots})
      { $self->setTwigRoots( $args{TwigRoots});
        delete $args{TwigRoots}; 
      }
    
    if( exists $args{EndTagHandlers})
      { croak "cannot use EndTagHandlers without TwigRoots"
          unless ($self->{twig_roots});
        $self->setEndTagHandlers( $args{EndTagHandlers});
        delete $args{EndTagHandlers};
      }
      
    if( $args{TwigPrintOutsideRoots})
      { croak "cannot use TwigPrintOutsideRoots without TwigRoots"
          unless( $self->{twig_roots});
        $self->{twig_default_print}= $args{TwigPrintOutsideRoots};
      }

    if( $args{PrettyPrint})
      { $self->set_pretty_print( $args{PrettyPrint}); }

    if( $args{EmptyTags})
      { $self->set_empty_tag_style( $args{EmptyTags}); }

    # space policy
    if( $args{KeepSpaces})
      { croak "cannot use both keep_spaces and discard_spaces"
          if( $args{DiscardSpaces});
        croak "cannot use both keep_spaces and keep_spaces_in"
          if( $args{KeepSpacesIn});
        $self->{twig_keep_spaces}=1;
        delete $args{KeepSpaces}; 
      }
    if( $args{DiscardSpaces})
      { croak "cannot use both discard_spaces and keep_spaces_in"
          if( $args{KeepSpacesIn});
        $self->{twig_discard_spaces}=1; 
        delete $args{DiscardSpaces}; 
      }
    if( $args{KeepSpacesIn})
      { croak "cannot use both keep_spaces_in and discard_spaces_in"
          if( $args{DiscardSpacesIn});
        $self->{twig_discard_spaces}=1; 
        $self->{twig_keep_spaces_in}={}; 
        my @tags= @{$args{KeepSpacesIn}}; 
        foreach my $tag (@tags)
          { $self->{twig_keep_spaces_in}->{$tag}=1; } 
        delete $args{KeepSpacesIn}; 
      }
    if( $args{DiscardSpacesIn})
      { $self->{twig_keep_spaces}=1; 
        $self->{twig_discard_spaces_in}={}; 
        my @tags= @{$args{DiscardSpacesIn}};
        foreach my $tag (@tags)
          { $self->{twig_discard_spaces_in}->{$tag}=1; } 
        delete $args{DiscardSpacesIn}; 
      }
    # discard spaces by default 
    $self->{twig_discard_spaces}= 1 unless(  $self->{twig_keep_spaces});

    $args{Comments}||= $COMMENTS_DEFAULT;
    if( $args{Comments} eq 'drop')
      { delete $twig_handlers{Comment}; }
    elsif( $args{Comments} eq 'keep')
      { $self->{twig_keep_comments}= 1; }
    elsif( $args{Comments} ne 'process')
      { croak "wrong value for comments argument: $args{Comments}"; }
    delete $args{Comments};

    $args{Pi}||= $PI_DEFAULT;
    if( $args{Pi} eq 'drop')
      { delete $twig_handlers{Pi}; }
    elsif( $args{Pi} eq 'keep')
      { $self->{twig_keep_pi}= 1; }
    elsif( $args{Pi} ne 'process')
      { croak "wrong value for Pi argument: $args{Pi}"; }
    delete $args{Pi};

    if( $args{KeepEncoding})
      { $self->{twig_keep_encoding}= $args{KeepEncoding};
	# set it in XML::Twig::Elt so print functions know what to do
        $self->set_keep_encoding( 1); 
        $self->{parse_start_tag}= $args{ParseStartTag} || \&parse_start_tag; 
        delete $args{ParseStartTag} if defined( $args{ParseStartTag}) ;
        delete $args{KeepEncoding};
	$self->{NoExpand}= 1;
      }
    else
      { $self->set_keep_encoding( 0); }

    if( $args{OutputFilter})
      { $self->set_output_filter( $args{OutputFilter}); 
        delete $args{OutputFilter};
      }
    else
      { $self->set_output_filter( 0); }

    if( $args{InputFilter})
      { $self->set_input_filter(  $args{InputFilter}); delete  $args{InputFilter}; }

    if( exists $args{Id}) { $ID= $args{Id}; delete $args{ID}; }

    if( $args{NoExpand})
      { $self->setHandlers( %twig_noexpand_handlers);
        $self->{twig_no_expand}=1;
      }

    if( $args{DoNotOutputDTD})
      { $self->{no_dtd_output}= 1; 
        delete $args{DoNotOutputDTD}; 
      }
     
    # set handlers
    if( $self->{twig_roots})
      { if( $self->{twig_default_print})
          { if( $self->{twig_keep_encoding})
              { $self->setHandlers( %twig_handlers_roots_print_original); }
            else
              { $self->setHandlers( %twig_handlers_roots_print);  }
          }
        else
          { $self->setHandlers( %twig_handlers_roots); }
      }
    else
      { $self->setHandlers( %twig_handlers); }

    # XML::Parser::Expat does not like these handler to be set. So in order to 
    # use the various sets of handlers on XML::Parser or XML::Parser::Expat
    # objects when needed, these ones have to be set only once, here, at 
    # XML::Parser level
    $self->setHandlers( Init => \&twig_init, Final => \&twig_final);

    $self->{twig_entity_list}= XML::Twig::Entity_list->new; 

    $self->{twig_id}= $ID; 
    $self->{twig_stored_spaces}='';

    $self->{twig}= $self;
    weaken( $self->{twig}) if( $weakrefs);

    return $self;
  }


# I should really add extra options to allow better configuration of the 
# LWP::UserAgent object
# this method forks: 
#   - the child gets the data and copies it to the pipe,
#   - the parent reads the stream and sends it to XML::Parser
# the data is cut it chunks the size of the XML::Parser::Expat buffer
sub parseurl
  { my( $t, $url, $agent)= @_;
    pipe( README, WRITEME) or croak  "cannot create connected pipes: $!";
    if( my $pid= fork)
      { # parent code: parse the incoming file
        close WRITEME; # no need to write
        $t->parse( \*README);
        close README;
      }
    else
     { # child
	close README; # no need to read
	require LWP;  # so we can get LWP::UserAgent and HTTP::Request
	$|=1;
        $agent    ||= LWP::UserAgent->new;
	my $request  = HTTP::Request->new( GET => $url);
        # pass_url_content is called with chunks of data the same size as
        # the XML::Parser buffer
        my $response = $agent->request( $request, 
	                 sub { pass_url_content( \*WRITEME, @_); }, BUFSIZE);
        $response->is_success or croak "$url ", $response->message, "\n";
	close WRITEME;
      }
  }

# get the (hopefully!) XML data from the URL and 
sub pass_url_content
  { my( $fh, $data, $response, $protocol)= @_;
    print $fh $data;
  }

sub add_options
  { my %args= map { $_, 1 } @_;
    %args= normalize_args( %args);
    $valid_option{$_}++ foreach (keys %args);
  }

sub twig_store_internal_dtd
  { my( $p, $string)= @_;
    my $t= $p->{twig};
    $string= $p->original_string() if( $t->{twig_keep_encoding});
    # print STDERR "internal: $string\n";
    $t->{twig_doctype}->{internal} .= $string;
  }

sub twig_stop_storing_internal_dtd
  { my $p= shift;
    # print STDERR "\ntwig_stop_storing_internal_dtd called\n";
     if( @saved_default_handler && defined $saved_default_handler[1])
       { # print STDERR "restoring saved handlers for";
         while( @saved_default_handler) 
	   { # print STDERR shift( @saved_default_handler) . " "; 
	     shift @saved_default_handler;
	   }
         $p->setHandlers( @saved_default_handler); }
     else
       {  # print STDERR "resetting Default handler\n";
         my $t= $p->{twig};
	 $t->setHandlers( Default => undef);
	 $p->setHandlers( Default => undef);
       }
  }


sub normalize_args
  { my %normalized_args;
    while( my $key= shift )
      { $key= join '', map { ucfirst } split /_/, $key;
        #$key= "Twig".$key unless( substr( $key, 0, 4) eq 'Twig');
        $normalized_args{$key}= shift ;
      }
    return %normalized_args;
  }    


sub set_handler
  { my( $handlers, $path, $handler)= @_;

    $handlers ||= {}; # create the handlers struct if necessary

    my $prev_handler= $handlers->{handlers}->{$path} || undef;

       set_gi_handler              ( $handlers, $path, $handler, $prev_handler)
    || set_path_handler            ( $handlers, $path, $handler, $prev_handler)
    || set_subpath_handler         ( $handlers, $path, $handler, $prev_handler)
    || set_special_handler         ( $handlers, $path, $handler, $prev_handler)
    || set_attribute_handler       ( $handlers, $path, $handler, $prev_handler)
    || set_star_att_handler        ( $handlers, $path, $handler, $prev_handler)
    || set_string_handler          ( $handlers, $path, $handler, $prev_handler)
    || set_attribute_regexp_handler( $handlers, $path, $handler, $prev_handler)
    || set_string_regexp_handler   ( $handlers, $path, $handler, $prev_handler)
    || set_pi_handler              ( $handlers, $path, $handler, $prev_handler)
    || croak "unrecognized expression in handler: $path";


    # this both takes care of the simple (gi) handlers and store
    # the handler code reference for other handlers
    $handlers->{handlers}->{$path}= $handler;

    return $prev_handler;
  }


sub set_gi_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    if( $path =~ m{^\s*($REG_NAME)\s*$}o )
      { my $gi= $1;
        # print STDERR "gi handler found: $gi\n";
        $handlers->{handlers}->{gi}->{$gi}= $handler; 
        return 1;
      }
    else 
      { return 0; 
      }
  }

sub set_special_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    if( $path =~ m{^\s*($ALL|$DEFAULT)\s*$}o )
      { $handlers->{handlers}->{$1}= $handler; 
        return 1;
      }
    else 
      { return 0; 
      }
  }
	
sub set_path_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    if( $path=~ m{^\s*(?:/$REG_NAME)*/($REG_NAME)\s*$}o)
      { # a full path has been defined
        # update the path_handlers count, knowing that
        # either the previous or the new handler can be undef
        $handlers->{path_handlers}->{$1}-- if( $prev_handler);
        $handlers->{path_handlers}->{$1}++ if( $handler);
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub set_subpath_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    if( $path=~ m{^\s*(?:$REG_NAME/)+($REG_NAME)\s*$}o)
      { # a partial path has been defined
        $handlers->{subpath_handlers}->{$1}-- if( $prev_handler);
        $handlers->{subpath_handlers}->{$1}++ if( $handler);
        return 1;
      }
    else 
      { return 0; 
      }
  }

sub set_attribute_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # check for attribute conditions
    if( $path=~ m{^\s*($REG_NAME)          # elt
                 \s*\[\s*\@                #    [@
                 ($REG_NAME)\s*            #      att
                 (?:=\s*($REG_STRING)\s*)? #           = value (optional)         
                 \]\s*$}xo)                #                             ]  
      { my( $gi, $att, $val)= ($1, $2, $3);
        $val= substr( $val, 1, -1) if( defined $val); # remove the quotes
        if( $prev_handler)
          { # replace or remove the previous handler
            my $i=0; # so we can splice the array if need be
            foreach my $exp ( @{$handlers->{attcond_handlers_exp}->{$gi}})
             { if( ($exp->{att} eq $att) && ($exp->{val} eq $val) )
                 { if( $handler) # just replace the handler
                     { $exp->{handler}= $handler; }
                   else          # remove the handler
                     { $handlers->{attcond_handlers}->{$gi}--;
                       splice( @{$handlers->{attcond_handlers_exp}->{$gi}}, $i, 1);
                       last;
                     }
                 }
               $i++;
             }
          }
        elsif( $handler)
          { # new handler only
	    $handlers->{attcond_handlers}->{$gi}++;
            my $exp={att => $att, val => $val, handler => $handler};
            $handlers->{attcond_handlers_exp}->{$gi} ||= [];
            push @{$handlers->{attcond_handlers_exp}->{$gi}}, $exp;
	  }
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub set_attribute_regexp_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # check for attribute regexp conditions
    if( $path=~ m{^\s*($REG_NAME)     # elt
                 \s*\[\s*\@           #    [@
                 ($REG_NAME)          #      att
                 \s*=~\s*             #          =~
		 /($REG_REGEXP_EXP)/  #             /regexp/
		 ($REG_REGEXP_MOD)    #                     mods
                 \s*]\s*$}gxo)        #                         ] 
      { my( $gi, $att, $regexp, $mods)= ($1, $2, $3, $4);
        $regexp= qr/(?$mods:$regexp)/;
        # print STDERR "\ngi: $gi - att: $att - regexp: $regexp\n";
        if( $prev_handler)
          { # replace or remove the previous handler
            my $i=0; # so we can splice the array if need be
            foreach my $exp ( @{$handlers->{attregexp_handlers_exp}->{$gi}})
             { if( ($exp->{att} eq $att) && ($exp->{regexp} eq $regexp) )
                 { if( $handler) # just replace the handler
                     { $exp->{handler}= $handler; }
                   else          # remove the handler
                     { $handlers->{attregexp_handlers}->{$gi}--;
                       splice( @{$handlers->{attregexp_handlers_exp}->{$gi}}, $i, 1);
                       last;
                     }
                 }
               $i++;
             }
          }
        elsif( $handler)
          { # new handler only
	    $handlers->{attregexp_handlers}->{$gi}++;
            my $exp={att => $att, regexp => $regexp, handler => $handler};
            $handlers->{attregexp_handlers_exp}->{$gi} ||= [];
            push @{$handlers->{attregexp_handlers_exp}->{$gi}}, $exp;
          }
        return 1;
      }
    else 
      { return 0; 
      }
  }

sub set_string_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # check for string conditions
    if( $path=~/^\s*($REG_NAME)           # elt
                 \s*\[\s*string           #    [string
		 \s*\(\s*($REG_NAME)?\s*\)#           (sub_elt)
                 \s*=\s*                  #                     =
                 ($REG_STRING)            #                       "text" (or 'text')
                 \s*\]\s*$/ox)           #                              ] 
      { my( $gi, $sub_elt, $text)= ($1, $2, $3);
        $text= substr( $text, 1, -1) if( defined $text); # remove the quotes
        if( $prev_handler)
          { # replace or remove the previous handler
            my $i=0; # so we can splice the array if need be
            foreach my $exp ( @{$handlers->{text_handlers_exp}->{$gi}})
             { if( ($exp->{text} eq $text) &&
                   ( !$exp->{sub_elt} || ($exp->{sub_elt} eq $sub_elt) )
                 )
                 { if( $handler) # just replace the handler
                     { $exp->{handler}= $handler; }
                   else          # remove the handler
                     { $handlers->{text_handlers}->{$gi}--;
                       splice( @{$handlers->{text_handlers_exp}->{$gi}}, $i, 1);
                       last;
                     }
                 }
               $i++;
             }
          }
        elsif( $handler)
          { # new handler only
	    $handlers->{text_handlers}->{$gi}++;
            my $exp={sub_elt => $sub_elt, text => $text, handler => $handler};
            $handlers->{text_handlers_exp}->{$gi} ||= [];
            push @{$handlers->{text_handlers_exp}->{$gi}}, $exp;
          }
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub set_string_regexp_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # check for string regexp conditions
    if( $path=~m{^\s*($REG_NAME)        # elt
                 \s*\[\s*string         #    [string
		 \s*\(\s*($REG_NAME?)\) #           (sub_elt)
                 \s*=~\s*               #              =~ 
                 /$REG_REGEXP_EXP/      #                 /regexp/
                 \s*($REG_REGEXP_MOD)?  #                         mods
                 \s*\]\s*$}ox)         #                             ]   (or ')
      { my( $gi, $sub_elt, $regexp, $mods)= ($1, $2, $3, $4);
        $mods||="";
        $regexp= qr/(?$mods:$regexp)/;
        if( $prev_handler)
          { # replace or remove the previous handler
            my $i=0; # so we can splice the array if need be
            foreach my $exp ( @{$handlers->{regexp_handlers_exp}->{$gi}})
             { if( ($exp->{regexp} eq $regexp) &&
                   ( !$exp->{sub_elt} || ($exp->{sub_elt} eq $sub_elt) )
                 )
                 { if( $handler) # just replace the handler
                     { $exp->{handler}= $handler;  
                     }
                   else          # remove the handler
                     { $handlers->{regexp_handlers}->{$gi}--;
                       splice( @{$handlers->{regexp_handlers_exp}->{$gi}}, $i, 1);
                       last;
                     }
                 }
               $i++;
             }
          }
        elsif( $handler)
          { # new handler only
	    $handlers->{regexp_handlers}->{$gi}++;
            my $exp= {sub_elt => $sub_elt, regexp => $regexp, handler => $handler};
            $handlers->{regexp_handlers_exp}->{$gi} ||= [];
            push @{$handlers->{regexp_handlers_exp}->{$gi}}, $exp;
          }
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub set_star_att_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # check for *[@att="val"] or *[@att] conditions
    if( $path=~/^(?:\s*\*)?         # * (optionnal)
                 \s*\[\s*\@         #    [@
                 ($REG_NAME)        #      att
                 (?:\s*=\s*         #         = 
                 ($REG_STRING))?      #           string
                     \s*\]\s*$/ox)  #                 ]  
      { my( $att, $val)= ($1, $2);
        $val= substr( $val, 1, -1) if( defined $val); # remove the quotes from the string
        # print STDERR "star att handler: $path -> $att - ",$val || '', "\n";
        if( $prev_handler)
          { # replace or remove the previous handler
            my $i=0; # so we can splice the array if need be
            foreach my $exp ( @{$handlers->{att_handlers_exp}->{$att}})
             { if( ($exp->{att} eq $att) && ( !defined( $val) || ($exp->{val} eq $val) ) )
                 { if( $handler) # just replace the handler
                     { $exp->{handler}= $handler; }
                   else          # remove the handler
                     { splice( @{$handlers->{att_handlers_exp}->{$att}}, $i, 1);
                       last;
                     }
                 }
               $i++;
             }
          }
        elsif( $handler)
          { # new handler only
	    $handlers->{att_handlers}->{$att}++;
            my $exp={att => $att, val => $val, handler => $handler};
            $handlers->{att_handlers_exp}->{$att} ||= [];
            push @{$handlers->{att_handlers_exp}->{$att}}, $exp;
          }
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub set_pi_handler
  { my( $handlers, $path, $handler, $prev_handler)= @_;
    # PI conditions ( '?target' => \&handler or '?' => \&handler
    if( $path=~ /^\s*\?\s*([^\s]*\s*)$/)
      { my $target= $1 || '';
        # update the path_handlers count, knowing that
        # either the previous or the new handler can be undef
        $handlers->{pi_handlers}->{$1}= $handler;
        return 1;
      }
    else 
      { return 0; 
      }
  }


sub reset_handlers
  { my $handlers= shift;
    delete $handlers->{handlers};
    delete $handlers->{path_handlers};
    delete $handlers->{subpath_handlers};
    $handlers->{attcond_handlers_exp}=[] if( $handlers->{attcond_handlers});
    delete $handlers->{attcond_handlers};
  }
  
sub set_handlers
  { my $handlers= shift || return;
    my $set_handlers= {};
    foreach my $path (keys %{$handlers})
      { set_handler( $set_handlers, $path, $handlers->{$path}); }
    return $set_handlers;
  }
    

sub setTwigHandler
  { my( $t, $path, $handler)= @_;
    return set_handler( $t->{twig_handlers}, $path, $handler);
  }

sub setTwigHandlers
  { my( $t, $handlers)= @_;
    my $previous_handlers= $t->{twig_handlers} || undef;
    reset_handlers( $t->{twig_handlers});
    $t->{twig_handlers}= set_handlers( $handlers);
    return $previous_handlers;
  }

sub setStartTagHandler
  { my( $t, $path, $handler)= @_;
    return set_handler( $t->{twig_starttag_handlers}, $path,$handler);
  }

sub setStartTagHandlers
  { my( $t, $handlers)= @_;
    my $previous_handlers= $t->{twig_starttag_handlers} || undef;
    reset_handlers( $t->{twig_starttag_handlers});
    $t->{twig_starttag_handlers}= set_handlers( $handlers);
    return $previous_handlers;
   }

sub setIgnoreTagsHandler
  { my( $t, $path)= @_;
    return set_handler( $t->{twig_ignore_tags_handlers}, $path, sub { $_->ignore} );
  }

sub setIgnoreTagsHandlers
  { my( $t, $handlers)= @_;
    my %handlers= map { $_, sub { $_->ignore(); } } @$handlers;
    my $previous_handlers= $t->{twig_ignore_tags_handlers} || undef;
    reset_handlers( $t->{twig_ignore_tags_handlers});
    $t->{twig_ignore_tags_handlers}= set_handlers( \%handlers);
    return $previous_handlers;
   }

sub setEndTagHandler
  { my( $t, $path, $handler)= @_;
    return set_handler( $t->{twig_endtag_handlers}, $path,$handler);
  }

sub setEndTagHandlers
  { my( $t, $handlers)= @_;
    my $previous_handlers= $t->{twig_endtag_handlers} || undef;
    reset_handlers( $t->{twig_endtag_handlers});
    $t->{twig_endtag_handlers}= set_handlers( $handlers);
    return $previous_handlers;
   }

# a little more complex: set the twig_handlers only if a code ref is given
sub setTwigRoots
  { my( $t, $handlers)= @_;
    my $previous_roots= $t->{twig_roots} || undef;
    reset_handlers($t->{twig_roots});
    $t->{twig_roots}= set_handlers( $handlers);
    foreach my $path (keys %{$handlers})
      { $t->{twig_handlers}||= {};
        set_handler( $t->{twig_handlers}, $path, $handlers->{$path})
          if( UNIVERSAL::isa( $handlers->{$path}, 'CODE')); 
      }
    return $previous_roots;
  }

# just store the reference to the expat object in the twig
sub twig_init
  { my $p= shift;
    my $t=$p->{twig};
    $t->{twig_parser}= $p; 
    weaken( $t->{twig_parser}) if( $weakrefs);
    $t->{twig_parsing}=1;
  }

# uses eval to catch the parser's death
sub safe_parse
  { my( $t, $str)= @_;
    eval { $t->parse( $str); } ;
    return $@ ? 0 : $t;
  }

sub safe_parsefile
  { my( $t, $file)= @_;
    eval { $t->parsefile( $file); } ;
    return $@ ? 0 : $t;
  }

sub safe_parseurl
  { my( $t, $url)= @_;
    eval { $t->parseurl( $url); } ;
    return $@ ? 0 : $t;
  }

# the default twig handlers, which build the tree
sub twig_start($$%)
  { my ($p, $gi, %att)  = @_;
    my $t=$p->{twig};
    # print STDERR "[start tag " . $p->original_string() ."]";
    # empty the stored pcdata (space stored in case they are really part of 
    # a pcdata element) or stored it if the space policy dictades so
    # create a pcdata element with the spaces if need be

    if( $t->{twig_stored_spaces})
      { if( $t->{twig_current}->is_pcdata)
          { $t->{twig_current}->append_pcdata($t->{twig_stored_spaces}); }
        else
	  { my $current_gi= $t->{twig_current}->gi;
            $t->{twig_space_policy}->{$current_gi}= space_policy( $t, $current_gi)
              unless defined( $t->{twig_space_policy}->{$current_gi});
            if( $t->{twig_space_policy}->{$current_gi})
              {     insert_pcdata( $t, $t->{twig_stored_spaces} ); }
            $t->{twig_stored_spaces}='';
	  }
      }

    my $parent= $t->{twig_current};

    # if we were parsing PCDATA then we exit the pcdata
    if( $t->{twig_in_pcdata})
      { $t->{twig_in_pcdata}= 0;
        $parent->del_twig_current;
        $parent= $parent->_parent;
      }

    # if we choose to keep the encoding then we need to parse the tag
    if( $t->{twig_keep_encoding})
      { my $func = $t->{parse_start_tag};
        ($gi, %att)= &$func($p->original_string);
      }
    
    # filter the input data if need be  
    if( my $filter= $t->{twig_input_filter})
      { $gi= $filter->( $gi);
        %att= map { $filter->($_), $filter->($att{$_})} keys %att; 
      }

    my $elt= XML::Twig::Elt->new( $gi);
    $elt->set_atts( \%att);
 
    $parent->del_twig_current if( $parent);
    $t->{twig_current}= $elt;
    $elt->set_twig_current;


    if( $parent)
      { my $prev_sibling= $parent->_last_child;
        if( $prev_sibling) 
          { $prev_sibling->set_next_sibling( $elt); 
            $elt->set_prev_sibling( $prev_sibling);
          }

        $elt->set_parent( $parent);
        $parent->set_first_child( $elt) unless( $parent->_first_child); 
        $parent->set_last_child( $elt);
      }
    else 
      { # processing root
        $t->{twig_root}= $elt;
        $elt->{twig}= $t;
        weaken(  $elt->{twig}) if( $weakrefs);
        # call dtd handlerif need be
        $t->{twig_dtd_handler}->($t, $t->{twig_dtd})
          if( defined $t->{twig_dtd_handler});
	  
	# set this so we can catch external entities
        $twig_handlers{Default} = \&twig_default; 
        $t->setHandlers( Default => \&twig_default);
        $p->setHandlers( Default => \&twig_default);
        #$t->setHandlers( %twig_handlers);
          
      }
    
    if( $p->recognized_string=~ m{/>$}s) { $elt->{empty}=1; }

    $elt->{extra_data}= $t->{extra_data} if( $t->{extra_data});
    $t->{extra_data}='';

    # if the element is ID-ed then store that info
    my $id= $elt->id;
    if( $id) { $t->{twig_id_list}->{$id}= $elt; }


    # call user handler if need be
    if( $t->{twig_starttag_handlers})
      { # call all appropriate handlers
        my @handlers= handler( $t, $t->{twig_starttag_handlers}, $gi, $elt);
	
	local $_= $elt;
	
        foreach my $handler ( @handlers)
          { $handler->($t, $elt) || last; }
	# call _all_ handler if needed
        if( my $all= $t->{twig_starttag_handlers}->{handlers}->{$ALL})
          { $all->($t, $elt); }
      }
  }

# the default function to parse a start tag (in keep_encoding mode)
# can be overridden with the parse_start_tag (or parse_start_tag) method
# only works for 1-byte character sets
sub parse_start_tag
  { my $string= shift;
    my( $gi, %atts);

    # get the gi (between < and the first space, / or > character)
    if( $string=~ s{^<\s*([^\s>/]*)[\s>/]*}{}s)
      { $gi= $1; }
    else
      { croak "internal error when parsing start tag $string"; }
    while( $string=~ s{^([^\s=]*)\s*=\s*(["'])(.*?)\2\s*}{}s)
      { $atts{$1}= $3; }
    return $gi, %atts;
  }


sub twig_end($$;@)
  { my ($p, $gi)  = @_;
    my $t=$p->{twig};
   
    if( $t->{twig_stored_spaces})
      { $t->{twig_space_policy}->{$gi}= space_policy( $t, $gi)
          unless defined( $t->{twig_space_policy}->{$gi});
        if( $t->{twig_space_policy}->{$gi})
          { insert_pcdata( $t, $t->{twig_stored_spaces}) };
        $t->{twig_stored_spaces}='';
      }

    # the new twig_current is the parent
    my $elt= $t->{twig_current};
    $elt->del_twig_current;

    # if we were parsing PCDATA then we exit the pcdata too
    if( $t->{twig_in_pcdata})
      { $t->{twig_in_pcdata}= 0;
        $elt= $elt->_parent if($elt->_parent);
        $elt->del_twig_current;
      }

    # parent is the new current element
    my $parent= $elt->_parent;
    $parent->set_twig_current if( $parent);
    $t->{twig_current}= $parent;

    $elt->{extra_data_before_end_tag}= $t->{extra_data} if( $t->{extra_data}); 
    $t->{extra_data}='';

    if( $t->{twig_handlers})
      { # look for handlers
        my @handlers= handler( $t, $t->{twig_handlers}, $gi, $elt);

        local $_= $elt; # so we can use $_ in the handlers
	
        foreach my $handler ( @handlers)
          { $handler->($t, $elt) || last; }
	# call _all_ handler if needed
        if( my $all= $t->{twig_handlers}->{handlers}->{$ALL})
          { $all->($t, $elt); }
      }

    # if twig_roots is set for the element then set appropriate handler
    if( handler( $t, $t->{twig_roots}, $gi, $elt))
      { if( $t->{twig_default_print})
          { if( $t->{twig_keep_encoding})
              { $p->setHandlers( %twig_handlers_roots_print_original); }
            else
              { $p->setHandlers( %twig_handlers_roots_print); }
          }
        else
          { $p->setHandlers( %twig_handlers_roots); }
      }

  }

# return of handler that can be activated for an element 
# (either of CODE ref's or 1's for twig_roots)

sub handler
  { my( $t, $handlers, $gi, $elt)= @_;

    my @found_handlers=();

    # warning: $elt can be either a regular element or a ref to the
    #          attribute hash (when called for an element for which
    #          the XML::Twig::Elt has not been built, outside of
    #          the twig_roots)

    # check for an attribute expression with no gi
    if( $handlers->{att_handlers})
      { my %att_handlers= %{$handlers->{att_handlers_exp}};
        foreach my $att ( keys %att_handlers)
          { my $att_val;
            # get the attribute value
	    if( ref $elt eq 'HASH')
	      { $att_val= $elt->{$att}; }     # $elt is the atts hash
	    else
	      { $att_val= $elt->att($att); }  # $elt is an element
            if( defined $att_val)
              { my @cond= @{$handlers->{att_handlers_exp}->{$att}};
                foreach my $cond (@cond)
                  {  # 2 cases: either there is a val and the att value should be equal to it
                     #          or there is no val (condition was gi[@att]), just for the att to be defined 
	            if( !defined $cond->{val} || ($att_val eq $cond->{val}) )  
                      { push @found_handlers, $cond->{handler};}
                  }
              }
          }
      }

    # check for a text expression
    if( $handlers->{text_handlers}->{$gi})
      { my @text_handlers= @{$handlers->{text_handlers_exp}->{$gi}};
        foreach my $exp ( @text_handlers)
          { if( (!$exp->{sub_elt} && $elt->text eq $exp->{text})
                || ($elt->field( $exp->{sub_elt}) eq $exp->{text})
              )
              { push @found_handlers, $exp->{handler}; }
          }
      }

    # check for a text regexp expression
    if( $handlers->{regexp_handlers}->{$gi})
      { my @regexp_handlers= @{$handlers->{regexp_handlers_exp}->{$gi}};
        foreach my $exp ( @regexp_handlers)
          { if( (!$exp->{sub_elt} && $elt->text=~ $exp->{regexp})
                || ($elt->field( $exp->{sub_elt})=~ $exp->{regexp})
              )
              { push @found_handlers, $exp->{handler}; }
          }
      }

    # check for an attribute expression
    if( $handlers->{attcond_handlers}->{$gi})
      { my @attcond_handlers= @{$handlers->{attcond_handlers_exp}->{$gi}};
        foreach my $exp ( @attcond_handlers)
          { my $att_val;
	    # get the attribute value
	    if( ref $elt eq 'HASH')
	      { $att_val= $elt->{$exp->{att}}; }    # $elt is the atts hash
	    else
	      { $att_val= $elt->att( $exp->{att}); }# $elt is an element

	    # 2 cases: either there is a val and the att value should be equal to it
            #          or there is no val (condition was gi[@att]), just for the att to be defined 
	    if( defined $att_val && ( !defined $exp->{val} || ($att_val eq $exp->{val}) ) ) 
              { push @found_handlers, $exp->{handler}; }
          }
      }

    # check for an attribute regexp
    if( $handlers->{attregexp_handlers}->{$gi})
      { my @attregexp_handlers= @{$handlers->{attregexp_handlers_exp}->{$gi}};
        foreach my $exp ( @attregexp_handlers)
          { my $att_val;
	    # get the attribute value
	    if( ref $elt eq 'HASH')
	      { $att_val= $elt->{$exp->{att}}; }    # $elt is the atts hash
	    else
	      { $att_val= $elt->att( $exp->{att}); }# $elt is an element

	    if( defined $att_val && ( ($att_val=~  $exp->{regexp}) ) ) 
              { push @found_handlers, $exp->{handler}; }
          }
      }

    # check for a full path
    if( defined $handlers->{path_handlers}->{$gi})
      { my $path= $t->path( $gi); 
        if( defined $handlers->{handlers}->{$path})
          { push @found_handlers, $handlers->{handlers}->{$path}; }
      }

    # check for a partial path
    if( $handlers->{subpath_handlers}->{$gi})
      { my $path= $t->path( $gi);
        while( $path)
          { # test each sub path
            if( defined $handlers->{handlers}->{$path})
              { push @found_handlers, $handlers->{handlers}->{$path}; }
             $path=~ s{^[^/]*/?}{}; # remove initial gi and /
          }
      }

    # check for a gi (simple gi's are stored directly in the handlers field)
    if( defined $handlers->{handlers}->{gi}->{$gi})
      { push @found_handlers, $handlers->{handlers}->{gi}->{$gi}; }

    # if no handler found call default handler if defined
    if( !@found_handlers && defined $handlers->{handlers}->{$DEFAULT})
      { push @found_handlers, $handlers->{handlers}->{$DEFAULT}; }

    return @found_handlers; # empty if no handler found

  }

sub twig_char
  { my ($p, $string)= @_;
    # print STDERR "[char: $string (" . $p->original_string(). ")]";
    my $t=$p->{twig}; 

    # if keep_encoding was set then use the original string instead of
    # the parsed (UTF-8 converted) one
    if( $t->{twig_keep_encoding})
      { $string= $p->original_string(); }

    if( $t->{twig_input_filter})
      { $string= $t->{twig_input_filter}->( $string); }

    if( $t->{twig_char_handler})
      { $string= $t->{twig_char_handler}->( $string); }

    my $elt= $t->{twig_current};

    if(    $t->{twig_in_cdata})
      { # text is the continuation of a previously created pcdata
        $elt->append_cdata( $t->{twig_stored_spaces}.$string); } 
    elsif( $t->{twig_in_pcdata})
      { # text is the continuation of a previously created cdata
        $elt->append_pcdata( $string); 
      } 
    else
      { # text is just space, which might be discarded later
        if( $string=~/\A\s*\Z/s)
          { if( $t->{extra_data})
	      { # we got extra data (comment, pi), lets add the spaces to it
	        $t->{extra_data} .= $string; 
	      }
	    else
	      { # no extra data, just store the spaces
	        $t->{twig_stored_spaces}.= $string;
	      }
          } 
        else
          { my $new_elt= insert_pcdata( $t, $t->{twig_stored_spaces}.$string);
	    $elt->del_twig_current;
	    $new_elt->set_twig_current;
	    $t->{twig_current}= $new_elt;
	    $t->{twig_in_pcdata}=1;
            $new_elt->{extra_data}= $t->{extra_data} if( $t->{extra_data});
            $t->{extra_data}='';
	  }
      }
  }

sub twig_cdatastart
  { my $p= shift;
    my $t=$p->{twig};

    $t->{twig_in_cdata}=1;
    my $twig_current= $t->{twig_current};
    my $cdata=  XML::Twig::Elt->new( '#CDATA');
    if( $t->{twig_in_pcdata})
      { # create the node as a sibling of the #PCDATA
        $cdata->set_prev_sibling( $twig_current);
        $twig_current->set_next_sibling( $cdata);
	my $parent= $twig_current->_parent;
        $cdata->set_parent( $parent);
        $parent->set_last_child( $cdata);
        $t->{twig_in_pcdata}=0;
      }
    else
      { # create the node as a child of the current element
        $cdata->set_parent( $twig_current);
        $twig_current->set_last_child( $cdata);
        if( my $prev_sibling= $twig_current->_first_child)
          { $cdata->set_prev_sibling( $prev_sibling);
            $prev_sibling->set_next_sibling( $cdata);
          }
        else
          { $twig_current->set_first_child( $cdata); }
      }

    $twig_current->del_twig_current;
    $t->{twig_current}= $cdata;
    $cdata->set_twig_current;
  }

sub twig_cdataend
  { my $p= shift;
    my $t=$p->{twig};

    $t->{twig_in_cdata}=0;

    my $elt= $t->{twig_current};
    $elt->del_twig_current;
    my $cdata= $elt->cdata;
    $elt->set_cdata( $cdata);

    $elt= $elt->_parent;
    $t->{twig_current}= $elt;
    $elt->set_twig_current;
  }

sub twig_pi
  { my( $p, $target, $data)= @_;
    my $t=$p->{twig};

    if( $t->{twig_input_filter})
      { $target = $t->{twig_input_filter}->( $target) ;
        $data   = $t->{twig_input_filter}->( $data)   ;
      }

    my $twig_current= $t->{twig_current};    # always defined

    # if pi's are to be kept then we piggiback them to the current element
    if( $t->{twig_keep_pi})
      {  
        if( my $handler= $t->{twig_handlers}->{pi_handlers}->{$target})
          { $t->{extra_data}.= $handler->( $t, $target, $data); }
        elsif( $handler= $t->{twig_handlers}->{pi_handlers}->{''})
          { $t->{extra_data}.= $handler->( $t, $target, $data); }
        else
          { if( $t->{twig_stored_spaces})
	      { $t->{extra_data}.= $t->{twig_stored_spaces};
	        $t->{twig_stored_spaces}= '';
              }
	    $t->{extra_data}.= $p->recognized_string();
	  }

      }
    else
      {
        my $pi=  XML::Twig::Elt->new( PI);
        $pi->set_pi( $target, $data);

        return add_prolog_data( $t, $pi) unless( $t->root);
    
        if( $t->{twig_in_pcdata})
          { # create the node as a sibling of the #PCDATA
	    $pi->paste_after( $twig_current);
            $t->{twig_in_pcdata}=0;
          }
        else
          { # create the node as a child of the current element
            $pi->paste_last_child( $twig_current);
          }
    
        $twig_current->del_twig_current;
        my $parent= $pi->_parent;
        $t->{twig_current}= $parent;
        $parent->set_twig_current;

        if( my $handler= $t->{twig_handlers}->{pi_handlers}->{$target})
          { $handler->( $t, $pi); }
        elsif( $handler= $t->{twig_handlers}->{pi_handlers}->{''})
          { $handler->( $t, $pi); }
      }

  }


sub twig_comment
  { my( $p, $data)= @_;
    my $t=$p->{twig};
    $data= $t->{twig_input_filter}->( $data) if( $t->{twig_input_filter});

    my $twig_current= $t->{twig_current};    # always defined

    # if comments are to be kept then we piggiback them to the current element
    if( $t->{twig_keep_comments})
      { $t->{extra_data}.= $XML::Twig::Elt::keep_encoding ?
                             $p->recognized_string()
                           : $p->original_string();
        return;
      }

    my $comment=  XML::Twig::Elt->new( COMMENT);
    $comment->set_comment( $data);

    return add_prolog_data( $t, $comment) unless( $t->root);

    if( $t->{twig_in_pcdata})
      { # create the node as a sibling of the #PCDATA
        $comment->paste_after( $twig_current);
        $t->{twig_in_pcdata}=0;
      }
    else
      { # create the node as a child of the current element
	$comment->paste_last_child( $twig_current);
      }

    $twig_current->del_twig_current;

    my $parent= $comment->_parent;
    $t->{twig_current}= $parent;
    $parent->set_twig_current;

  }

sub add_prolog_data
  { my($t, $prolog_data)= @_;
    # comment before the first element
    $t->{prolog_data} ||= XML::Twig::Elt->new( '#PROLOG_DATA');
    # create the node as a child of the current element
    $prolog_data->paste_last_child( $t->{prolog_data});
  }
  
sub twig_final
  { my $p= shift;
    my $t=$p->{twig};

    # tries to clean-up (probably not very well at the moment)
    undef $p->{twig};
    undef $t->{twig_parser};

    undef $t->{twig_parsing};

    return $t;
  }

sub insert_pcdata
  { my( $t, $string)= @_;
    # create a new #PCDATA element
    my $parent= $t->{twig_current};    # always defined
    my $elt=  XML::Twig::Elt->new( PCDATA);
    $elt->set_pcdata( $string);
    my $prev_sibling= $parent->_last_child;
    if( $prev_sibling) 
      { $prev_sibling->set_next_sibling( $elt); 
        $elt->set_prev_sibling( $prev_sibling);
      }
    else
      { $parent->set_first_child( $elt); }

    $elt->set_parent( $parent);
    $parent->set_last_child( $elt);
    $t->{twig_stored_spaces}='';
    return $elt;
  }


sub space_policy
  { my( $t, $gi)= @_;
    my $policy;
    $policy=0 if( $t->{twig_discard_spaces});
    $policy=1 if( $t->{twig_keep_spaces});
    $policy=1 if( $t->{twig_keep_spaces_in}
               && $t->{twig_keep_spaces_in}->{$gi});
    $policy=0 if( $t->{twig_discard_spaces_in} 
               && $t->{twig_discard_spaces_in}->{$gi});
    return $policy;
  }


sub twig_entity($$$$$$)
  { my( $p, $name, $val, $sysid, $pubid, $ndata)= @_;
    my $t=$p->{twig};
    my $ent=XML::Twig::Entity->new( $name, $val, $sysid, $pubid, $ndata);
    $t->{twig_entity_list}->add( $ent);
  }

sub twig_xmldecl
  { my $p= shift;
    my $t=$p->{twig};
    $t->{twig_xmldecl}={};
    $t->{twig_xmldecl}->{version}= shift;
    $t->{twig_xmldecl}->{encoding}= shift; 
    $t->{twig_xmldecl}->{standalone}= shift;
  }

sub twig_doctype
  { my( $p, $name, $sysid, $pub, $internal)= @_;
    my $t=$p->{twig};
    $t->{twig_doctype}||= {};                   # create 
    $t->{twig_doctype}->{name}= $name;          # always there
    $t->{twig_doctype}->{sysid}= $sysid;        #  
    $t->{twig_doctype}->{pub}= $pub;            #  


    # now let's try to cope with XML::Parser 2.28 and above
    if( $parser_version > 2.27)
      { @saved_default_handler= $p->setHandlers( 
                           Default     => \&twig_store_internal_dtd,
                                           );
      $p->setHandlers( DoctypeFin  => \&twig_stop_storing_internal_dtd);
      $t->{twig_doctype}->{internal}='';
      }
    else			
      # for XML::Parser before 2.28
      { $t->{twig_doctype}->{internal}=$internal; }

    # now check if we want to get the DTD info
    if( $t->{twig_read_external_dtd} && $sysid)
      { # let's build a fake document with an internal DTD
        # is this portable?
	# print STDERR "loading external DTD\n";
        my $tmpfile= "twig_tmp$$";
        open( TMP, ">$tmpfile") 
          or croak "cannot create temp file $tmpfile: $!";
        print TMP "<!DOCTYPE $name [\n";   # print the doctype
        # slurp the DTD
          { open( DTD, "<$sysid") 
              or croak "cannot open dtd file $sysid: $!";
            local undef $/;
            my $dtd= <DTD>;
            close DTD;
            print TMP $dtd;                 # add the dtd
          }
        print TMP "]>";                     # close the dtd
        print TMP "<dummy></dummy>\n";      # XML::Parser needs an element

        close TMP;
        
        my $t_dtd= XML::Twig->new;           # create a temp twig
        $t_dtd->parsefile( $tmpfile);       # parse it
        $t->{twig_dtd}= $t_dtd->{twig_dtd}; # grab the dtd info
        $t->{twig_entity_list}= $t_dtd->{twig_entity_list}; # grab the entity info

        unlink $tmpfile;
      }

  }

sub twig_element
  { my( $p, $name, $model)= @_;
    my $t=$p->{twig};
    $t->{twig_dtd}||= {};                     # may create the dtd 
    $t->{twig_dtd}->{model}||= {};            # may create the model hash 
    $t->{twig_dtd}->{elt_list}||= [];         # ordered list of elements 
    push @{$t->{twig_dtd}->{elt_list}}, $name; # store the elt
    $t->{twig_dtd}->{model}->{$name}= $model; # store the model
    if( $parser_version > 2.27) 
      { $t->{twig_doctype}->{internal} .= 
          $XML::Twig::Elt::keep_encoding ? $p->original_string 
                                         : $p->recognized_string; 
      }
  }

sub twig_attlist
  { my( $p, $el, $att, $type, $default, $fixed)= @_;
    my $t=$p->{twig};
    $t->{twig_dtd}||= {};                      # create dtd if need be 
    $t->{twig_dtd}->{$el}||= {};               # create elt if need be 
    $t->{twig_dtd}->{$el}->{att}||= {};        # create att if need be 
    $t->{twig_dtd}->{att}->{$el}->{$att}= {} ;
    $t->{twig_dtd}->{att}->{$el}->{$att}->{type}= $type; 
    $t->{twig_dtd}->{att}->{$el}->{$att}->{default}= $default; 
    $t->{twig_dtd}->{att}->{$el}->{$att}->{fixed}= $fixed; 
    if( $parser_version > 2.27) 
      { $t->{twig_doctype}->{internal} .= 
          $XML::Twig::Elt::keep_encoding ? $p->original_string 
                                         : $p->recognized_string; 
      }
  }

# called only when the NoExpand option is set
sub twig_default
  { my( $p, $string)= @_;
    
    my $t= $p->{twig};
    
    # print STDERR "[default: $string (". $p->original_string(). ")]";
    # process only if we have an entity
    return unless( $string=~ m{^&[^;]*;$});
    # print STDERR "entity $string found\n";
    # the entity has to be pure pcdata, or we have a problem
    if( $t->{twig_keep_encoding}) { twig_char( $p, $string);        }
    else                          { twig_insert_ent( $t, $string);  }
  }
    
sub twig_insert_ent
  { my( $t, $string)=@_;

    # print STDERR "[set_ent $string]";

    my $twig_current= $t->{twig_current};

    my $ent=  XML::Twig::Elt->new( '#ENT');
    $ent->set_ent( $string);
    
    if( $t->{twig_in_pcdata})
      { # create the node as a sibling of the #PCDATA
        $ent->set_prev_sibling( $twig_current);
        $twig_current->set_next_sibling( $ent);
	my $parent= $twig_current->_parent;
        $ent->set_parent( $parent);
        $parent->set_last_child( $ent);
	# the twig_current is now the parent
        $twig_current->del_twig_current;
        $t->{twig_current}= $parent;
	# we left pcdata
	$t->{twig_in_pcdata}=0;
      }
    else
      { # create the node as a child of the current element
        $ent->set_parent( $twig_current);
        if( my $prev_sibling= $twig_current->_last_child)
          { $ent->set_prev_sibling( $prev_sibling);
            $prev_sibling->set_next_sibling( $ent);
          }
	else
	  { $twig_current->set_first_child( $ent); }
        $twig_current->set_last_child( $ent);
      }

  }

sub parser
  { return $_[0]->{twig_parser}; }

# returns the declaration text (or a default one)
sub xmldecl
  { my $t= shift;
    my $decl= $t->{'twig_xmldecl'} or return '';
    my $string= "<?xml";
    $string .= " version=\"$decl->{version}\""       if( $decl->{version});
    $string .= " encoding=\"$decl->{encoding}\""     if( $decl->{encoding});
    if( defined( $decl->{standalone}))
      { $string .= " standalone=\"";  
        $string .= $decl->{standalone} ? "yes" : "no";  
        $string .= "\""; 
      } 
    $string .= "?>\n";
    return $string;
  }

# returns the doctype text (or none)
# that's the doctype just has it was in the original document
sub doctype
  { my $t= shift;
    my $doctype= $t->{'twig_doctype'} or return '';
    my $string= "<!DOCTYPE " . $doctype->{name};
    $string  .= qq{ SYSTEM "$doctype->{sysid}"} if( $doctype->{sysid});
    $string  .= qq{ PUBLIC  "$doctype->{pub}" } if( $doctype->{pub});
    $string  .= "\n" . $doctype->{internal} . "\n";
    return $string;
  }

# return the dtd object
sub dtd
  { my $t= shift;
    return $t->{twig_dtd};
  }

# return an element model, or the list of element models
sub model
  { my $t= shift;
    my $elt= shift;
    return $t->dtd->{'model'}->{$elt} if( $elt);
    return sort keys %{$t->{'dtd'}->{'model'}};
  }

        
# return the entity_list object 
sub entity_list($)
  { my $t= shift;
    return $t->{twig_entity_list};
  }

# return the list of entity names 
sub entity_names($)
  { my $t= shift;
    return sort keys %{$t->{twig_entity_list}} ;
  }

# return the entity object 
sub entity($$)
  { my $t= shift;
    my $entity_name= shift;
    return $t->{twig_entity_list}->{$entity_name};
  }


sub print_prolog
  { my $t= shift;
    my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB' ) );
    if( $fh) { print $fh $t->prolog( @_); }
    else     { print $t->prolog( @_);     }
  }

sub prolog
  { my $t= shift;
    my %args= @_;
    my $prolog='';

    my $update_dtd = $args{Update_DTD} || '';

    $prolog .= $t->xmldecl;
    return $prolog unless( defined $t->{'twig_doctype'} || defined $t->{no_dtd_output});
    my $doctype= $t->{'twig_doctype'};
    if( $update_dtd)
      { 
        if( defined $doctype->{sysid}  )  
          { $prolog .= "<!DOCTYPE ".$doctype->{name};
            $prolog .= " SYSTEM \"$doctype->{sysid}\"";
            $prolog .= " PUBLIC  \"$doctype->{pub}\""  if( $doctype->{pub});
            $prolog .= "[\n";
            $prolog .= $t->{twig_entity_list}->text;
            $prolog .= "]>\n";
          }
        else
          { my $dtd= $t->{'twig_dtd'};
            $prolog .= $t->dtd_text;
          }            
      }
    else
      { $prolog .= "<!DOCTYPE ". $doctype->{name}  if( $doctype->{name});
        $prolog .= " PUBLIC  \"$doctype->{pub}\""  if( $doctype->{pub});
        $prolog .= " SYSTEM" if( $doctype->{sysid} && !$doctype->{pub});
        $prolog .= ' "' . $doctype->{sysid} . '"'  if( $doctype->{sysid}); 
        if( $doctype->{internal})
          { $prolog .= "\n" if( $doctype->{internal}=~ /^\s*[[<]/s);
            $prolog .=  $doctype->{internal}; 
          }
        unless( $parser_version > 2.27)
          { $prolog .= ">\n" unless( $t->{twig_no_expand}); } 
      }

    # terrible hack, as I can't figure out in which case the darn prolog
    # should get an extra >
    $prolog=~ s/>*$/>/;

    return $prolog;
  }

sub print_prolog_data
  { my $t= shift;
    my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB' ) );
    if( $fh) { print $fh $t->prolog_data( @_); }
    else     { print $t->prolog_data( @_);     }
  }

sub prolog_data
  { my $t= shift;
    return''  unless( $t->{prolog_data});
    my $prolog_data_text='';
    foreach ( $t->{prolog_data}->children)
      { $prolog_data_text .= $_->sprint . "\n"; }
    return$ prolog_data_text;
  }


sub print
  { my $t= shift;
    my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') );
    my %args= @_;

    my $old_pretty;
    if( defined $args{PrettyPrint})
      { $old_pretty= $t->set_pretty_print( $args{PrettyPrint}); 
        delete $args{PrettyPrint};
      }

     my $old_empty_tag_style;
     if( defined $args{EmptyTags})
      { $old_empty_tag_style= $t->set_empty_tag_style( $args{EmptyTags}); 
        delete $args{EmptyTags};
      }

    if( $fh) 
      { $t->print_prolog( $fh, %args); 
        $t->print_prolog_data( $fh, %args);
      }
    else 
      { $t->print_prolog( %args);
        $t->print_prolog_data( %args);
      }

    $t->{twig_root}->print( $fh) if( $t->{twig_root});
    $t->set_pretty_print( $old_pretty) if( defined $old_pretty); 
    $t->set_empty_tag_style( $old_empty_tag_style) if( defined $old_empty_tag_style); 
  }


sub flush
  { my $t= shift;
    my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') );
    my $old_select= select $fh if( defined $fh);
    my $up_to= shift if( ref $_[0]);
    my %args= @_;

    my $old_pretty;
    if( defined $args{PrettyPrint})
      { $old_pretty= $t->set_pretty_print( $args{PrettyPrint}); 
        delete $args{PrettyPrint};
      }

     my $old_empty_tag_style;
     if( $args{EmptyTags})
      { $old_empty_tag_style= $t->set_empty_tag_style( $args{EmptyTags}); 
        delete $args{EmptyTags};
      }


    # the "real" last element processed, as twig_end has closed it
    my $last_elt;
    if( $up_to)
      { $last_elt= $up_to; }
    elsif( $t->{twig_current})
      { $last_elt= $t->{twig_current}->_last_child; }
    else
      { $last_elt= $t->{twig_root}; }

    # flush the DTD unless it has ready flushed (id root has been flushed)
    my $elt= $t->{twig_root};
    $t->print_prolog( %args) unless( $elt->flushed);

    while( $elt)
      { my $next_elt; 
        if( $last_elt && $last_elt->in( $elt))
          { 
            unless( $elt->flushed) 
              { # just output the front tag
                print $elt->start_tag();
                $elt->set_flushed;
              }
            $next_elt= $elt->_first_child;
          }
        else
          { # an element before the last one or the last one,
            $next_elt= $elt->_next_sibling;  
            $elt->_flush();
            $elt->delete; 
            last if( $last_elt && ($elt == $last_elt));
          }
        $elt= $next_elt;
      }
    select $old_select if( defined $old_select);
    $t->set_pretty_print( $old_pretty) if( defined $old_pretty); 
    $t->set_empty_tag_style( $old_empty_tag_style) if( defined $old_empty_tag_style); 
  }

# flushes up to an element
# this method just reorders the arguments and calls flush
sub flush_up_to
  { my $t= shift;
    my $up_to= shift;
    if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') )
      { my $fh=  shift;
        $t->flush( $fh, $up_to, @_);
      }
    else
      { $t->flush( $up_to, @_); }
  }

    
# same as print except the entire document text is returned as a string
sub sprint
  { my $t= shift;
    my %args= @_;

    my $old_pretty;
    if( $args{PrettyPrint})
      { $old_pretty= $t->set_pretty_print( $args{PrettyPrint}); 
        delete $args{PrettyPrint};
      }

     my $old_empty_tag_style;
     if( $args{EmptyTags})
      { $old_empty_tag_style= $t->set_empty_tag_style( $args{EmptyTags}); 
        delete $args{EmptyTags};
      }
      
    my $prolog= $t->prolog( %args) || '';
    my $prolog_data= $t->prolog_data( %args) || '';
    
    my $string=  $prolog . $prolog_data . $t->{twig_root}->sprint;

    $t->set_pretty_print( $old_pretty) if( $old_pretty); 
    $t->set_empty_tag_style( $old_empty_tag_style) if( $old_empty_tag_style); 

    return $string;
  }
    

# this method discards useless elements in a tree
# it does the same thing as a purge except it does not print it
# the second argument is an element, the last purged element
# (this argument is usually set through the purge_up_to method)
sub purge
  { my $t= shift;
    my $up_to= shift;

    # the "real" last element processed, as twig_end has closed it
    my $last_elt;
    if( $up_to)
      { $last_elt= $up_to; }
    elsif( $t->{twig_current})
      { $last_elt= $t->{twig_current}->_last_child; }
    else
      { $last_elt= $t->{twig_root}; }
    
    my $elt= $t->{twig_root};

    while( $elt)
      { my $next_elt; 
        if( $last_elt && $last_elt->in( $elt))
          { $elt->set_flushed;
            $next_elt= $elt->_first_child;
          }
        else
          { # an element before the last one or the last one,
            $next_elt= $elt->_next_sibling;  
            $elt->delete; 
            last if( $elt == $last_elt);
          }
        $elt= $next_elt;
      }
  }
    
# flushes up to an element. This method just calls purge
sub purge_up_to
  { my $t= shift;
    my $up_to= shift;
    $t->purge( $up_to);
  }

sub root
  { return $_[0]->{twig_root}; }

#start-extract twig_document (used to generate XML::(DOM|GDOME)::Twig)
sub first_elt
  { my( $t, $cond)= @_;
    my $root= $t->root;
    return $root if( $root->passes( $cond));
    return $root->next_elt( $cond); 
  }

sub get_xpath
  { my $twig= shift;
    $twig->root->get_xpath( @_);
  }

# return a list with just the root
# if a condition is given then return an empty list unless the root matches
sub children
  { my( $t, $cond)= @_;
    my $root= $t->root;
    unless( $cond && !($root->passes( $cond)) )
      { return ($root); }
    else
      { return (); }
  }

sub descendants
  { my( $t, $cond)= @_;
    my $root= $t->root;
    if( $root->passes( $cond) )
      { return ($root, $root->descendants( $cond)); }
    else
      { return ( $root->descendants( $cond)); }
  }

#end-extract twig_document

sub set_keep_encoding
  { return XML::Twig::Elt::set_keep_encoding( @_); }

sub set_expand_external_entities
  { return XML::Twig::Elt::set_expand_external_entities( @_); }

# WARNING: at the moment the id list is not updated reliably
sub elt_id
  { return $_[0]->{twig_id_list}->{$_[1]}; }

# change it in ALL twigs at the moment
sub change_gi 
  { my( $twig, $old_gi, $new_gi)= @_;
    my $index;
    return unless($index= $gi2index{$old_gi});
    $index2gi[$index]= $new_gi;
    delete $gi2index{$old_gi};
    $gi2index{$new_gi}= $index;
  }


# builds the DTD from the stored (possibly updated) data
sub dtd_text
  { my $t= shift;
    my $dtd= $t->{twig_dtd};
    my $doctype= $t->{'twig_doctype'} or return '';
    my $string= "<!DOCTYPE ".$doctype->{name};

    unless( $parser_version > 2.27) { $string .= "[\n"; }

    foreach my $gi (@{$dtd->{elt_list}})
      { $string.= "<!ELEMENT $gi ".$dtd->{'model'}->{$gi}.">\n" ;
        if( $dtd->{att}->{$gi})
          { my $attlist= $dtd->{att}->{$gi};
            $string.= "<!ATTLIST $gi\n";
            foreach my $att ( sort keys %{$attlist})
              { $string.= "   $att $attlist->{$att}->{type} ".
                            "$attlist->{$att}->{default}"; 
                if( $attlist->{$att}->{fixed})
                  { $string .= " #FIXED"};
                $string.= "\n";
              }
            $string.= ">\n";
          }
      }
    $string.= $t->entity_list->text if( $t->entity_list);
    $string.= "\n]>\n";
    return $string;
  }
        
# prints the DTD from the stored (possibly updated) data
sub dtd_print
  { my $t= shift;
    my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') );
    if( $fh) { print $fh $t->dtd_text; }
    else     { print $t->dtd_text; }
  }

# build the subs that call directly expat
BEGIN
  { my @expat_methods= qw( depth in_element within_element context
                           current_line current_column current_byte
			   namespace eq_name generate_ns_name new_ns_prefixes
                           expand_ns_prefix current_ns_prefixes
			   recognized_string original_string 
			   xpcroak xpcarp 
			   base current_element element_index 
                           position_in_context);
    foreach my $method (@expat_methods)
      { no strict 'refs';
        *{$method}= sub { my $t= shift;
                          warn "calling $method after parsing is finished" 
                                 unless( $t->{twig_parsing}); 
                          return $t->{twig_parser}->$method(\@_); 
                        };
      }
  }

sub path
  { my( $t, $gi)= @_;
    return "/" . join( "/", ($t->{twig_parser}->context, $gi));
  }

sub finish
  { my $t= shift;
    return $t->{twig_parser}->finish;
  }

# just finish the parse by printing the rest of the document
sub finish_print
  { my( $t, $fh)= @_;
    select $fh if( defined $fh);
    $t->flush;
    my $p=$t->{twig_parser};
    if( $t->{twig_keep_encoding})
      { $p->setHandlers( %twig_handlers_finish_print); }
    else
      { $p->setHandlers( %twig_handlers_finish_print_original); }

  }

sub set_output_filter
  { return XML::Twig::Elt::set_output_filter( @_); }

sub set_input_filter
  { my( $t, $input_filter)= @_;
    my $old_filter= $t->{twig_input_filter};
      if( !$input_filter || UNIVERSAL::isa( $input_filter, 'CODE') )
        { $t->{twig_input_filter}= $input_filter; }
      elsif( $input_filter eq 'latin1')
        {  $t->{twig_input_filter}= latin1(); }
      elsif( $filter{$input_filter})
        {  $t->{twig_input_filter}= $filter{$input_filter}; }
      else
        { croak "invalid input filter: $input_filter"; }
      
      return $old_filter;
    }

sub set_empty_tag_style
  { return XML::Twig::Elt::set_empty_tag_style( @_); }

sub set_pretty_print
  { return XML::Twig::Elt::set_pretty_print( @_); }

sub set_quote
  { return XML::Twig::Elt::set_quote( @_); }

sub set_indent
  { return XML::Twig::Elt::set_indent( @_); }


sub dispose
  { my $t= shift;
    $t->DESTROY;
  }
  
sub DESTROY
  { my $t= shift;
    if( $t->{twig_root} &&UNIVERSAL::isa(  $t->{twig_root}, 'XML::Twig')) 
      { $t->{twig_root}->delete } 

# added to break circular references
    undef $t->{twig};
    undef $t->{twig_root}->{twig} if( $t->{twig_root});
    undef $t->{twig_parser};
    
    $t={}; # prevents memory leaks (especially when using mod_perl)
    undef $t;
  }        


#
#  non standard handlers
#

sub twig_print
  { my $p= shift;
    print $p->recognized_string();
    #print STDERR "twig_print: /",  $p->recognized_string(), "/\n";
  }

sub twig_print_default
  { my( $p, $string)= @_;
    print $string;
    # print STDERR "twig_print_default: /",  $string, "/\n";
  }

# recognized_string does not seem to work for entities, go figure!
# so this handler is not used 
sub twig_print_entity
  { my $p= shift;
    print STDERR "\n entity: \n  recognized /",
                 $p->recognized_string(), "/\n  original /",
                 $p->original_string(), "/\n";
  }

# account for the case where the element is empty
sub twig_print_end
  { my $p= shift; 
    print $p->recognized_string(); 
    # print $p->recognized_string() unless( $p->recognized_string()=~ /\/>\Z/); 
  }


sub twig_print_original
  { my $p= shift;
    print $p->original_string();
  }

sub twig_print_original_default
  { my $p= shift;
    print $p->original_string();
    # print STDERR "DEFAULT[", $p->original_string(), "]";
  }

# account for the case where the element is empty
sub twig_print_end_original
  { my $p= shift;
    print $p->original_string(); 
    # print $p->original_string() unless( $p->original_string()=~ /\/>\Z/); 
  }

sub twig_start_check_roots
  { my( $p, $gi, %att)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { twig_start( $p, $gi, %att); }
    elsif( handler( $t, $t->{twig_roots}, $gi, \%att))
      { $p->setHandlers( %twig_handlers); # restore regular handlers
        twig_start( $p, $gi, %att);
      }
    elsif( $t->{twig_starttag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_starttag_handlers}, $gi, \%att);
        foreach my $handler ( @handlers)
          { $handler->($t, $gi, %att) || last; }
      }
  }

sub twig_start_check_roots_print
  { my( $p, $gi, %att)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { print $p->recognized_string();
        twig_start( $p, $gi, %att);
      }
    elsif( handler( $t, $t->{twig_roots}, $gi, \%att))
      { $p->setHandlers( %twig_handlers); # restore regular handlers
        twig_start( $p, $gi, %att);
      }
    elsif( $t->{twig_starttag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_starttag_handlers}, $gi, \%att);
        my $last_handler_res;
        foreach my $handler ( @handlers)
          { $last_handler_res= $handler->($t, $gi, %att);
            last unless $last_handler_res;
          }
        print $p->recognized_string() if( $last_handler_res);   
      }
    else
      { print $p->recognized_string(); }  
  }

sub twig_start_check_roots_print_original
  { my( $p, $gi, %att)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { print $p->original_string();     
        twig_start( $p, $gi, %att);
      }
    elsif( handler( $t, $t->{twig_roots}, $gi, \%att))
      { $p->setHandlers( %twig_handlers); # restore regular handlers
        twig_start( $p, $gi, %att);
      }
    elsif( $t->{twig_starttag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_starttag_handlers}, $gi, \%att);
        my $last_handler_res;
        foreach my $handler ( @handlers)
          { $last_handler_res= $handler->($t, $gi, %att);
            last unless( $last_handler_res);
          }
        print $p->original_string() if( $last_handler_res);   
      }
    else
      { print $p->original_string(); }
  }

sub twig_end_check_roots
  { my( $p, $gi)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { twig_end( $p, $gi); }
    elsif( $t->{twig_endtag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_endtag_handlers}, $gi, {});
        my $last_handler_res=1;
        foreach my $handler ( @handlers)
          { $last_handler_res= $handler->($t, $gi) || last; }
        return unless $last_handler_res;
      }
  }

sub twig_end_check_roots_print
  { my( $p, $gi, %att)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { twig_end( $p, $gi); }
    elsif( $t->{twig_endtag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_endtag_handlers}, $gi, {});
        my $last_handler_res=1;
        foreach my $handler ( @handlers)
          { $last_handler_res= $handler->($t, $gi) || last; }
        return unless $last_handler_res;
      }
    print $p->recognized_string();  
  }

sub twig_end_check_roots_print_original
  { my( $p, $gi, %att)= @_;
    my $t= $p->{twig};
    if( $p->depth == 0)
      { twig_end( $p, $gi); }
    elsif( $t->{twig_endtag_handlers})
      { # look for start tag handlers
        my @handlers= handler( $t, $t->{twig_endtag_handlers}, $gi, {});
        my $last_handler_res=1;
        foreach my $handler ( @handlers)
          { $last_handler_res= $handler->($t, $gi) || last; }
        return unless $last_handler_res;
      }
    print $p->original_string();
  }

sub twig_ignore_start
  { my( $p, $gi)= @_;
    my $t= $p->{twig};
    return unless( $gi eq $t->{twig_ignore_gi});
    $t->{twig_ignore_level}++;
  }

sub twig_ignore_end
  { my( $p, $gi)= @_;
    my $t= $p->{twig};
    return unless( $gi eq $t->{twig_ignore_gi});
    $t->{twig_ignore_level}--;
    unless( $t->{twig_ignore_level})
      { $t->{twig_ignore_elt}->delete; 
        $p->setHandlers( @{$t->{twig_saved_handlers}})
      };
  }
    
sub ignore
  { my( $t, $elt)= @_;
    $elt ||= $t->{twig_current};     # get the element (default: current elt)
    $t->{twig_ignore_elt}= $elt;     # save it
    $t->{twig_ignore_gi }= $elt->gi; # save its gi
    $t->{twig_ignore_level}++;
    my $p= $t->{twig_parser};
    my @saved_handlers= $p->setHandlers( %twig_handlers_ignore); # set handlers
    $t->{twig_saved_handlers}= \@saved_handlers;        # save current handlers
  }
      

# input/output filters

sub latin1 
  { if( eval 'require Text::Iconv;')
      { #warn "using iconv";
        return iconv_convert( 'latin1');
      }
    elsif( eval 'require Unicode::Map8 && require Unicode::String;')
      { #warn "using unicode convert";
        return unicode_convert( 'latin1'); 
      }
    else
      { return \&regexp2latin1; }
  }

# shamelessly lifted from XML::TyePYX
sub regexp2latin1
  { my $text=shift;
    $text=~s{([\xc0-\xc3])(.)}{ my $hi = ord($1);
                                my $lo = ord($2);
                                chr((($hi & 0x03) <<6) | ($lo & 0x3F))
                              }ge;
    return $text;
  }


sub html_encode
  { require HTML::Entities;
    return HTML::Entities::encode(latin1($_[0]));
  }

sub safe_encode
  {   my $str= shift;
       $str =~ s{([\xC0-\xDF].|[\xE0-\xEF]..|[\xF0-\xFF]...)}
	        {XmlUtf8Decode ($1)}egs; 
      return $str;
  }

# this one shamelessly lifted from XML::DOM
sub XmlUtf8Decode
  { my ($str, $hex) = @_;
    my $len = length ($str);
    my $n;

    if ($len == 2)
      { my @n = unpack "C2", $str;
	$n = (($n[0] & 0x3f) << 6) + ($n[1] & 0x3f);
      }
    elsif ($len == 3)
    { my @n = unpack "C3", $str;
      $n = (($n[0] & 0x1f) << 12) + (($n[1] & 0x3f) << 6) + ($n[2] & 0x3f);
    }
    elsif ($len == 4)
    { my @n = unpack "C4", $str;
      $n = (($n[0] & 0x0f) << 18) + (($n[1] & 0x3f) << 12) 
         + (($n[2] & 0x3f) << 6) + ($n[3] & 0x3f);
    }
    elsif ($len == 1)	# just to be complete...
    { $n = ord ($str); }
    else
    { croak "bad value [$str] for XmlUtf8Decode"; }

    $hex ? sprintf ("&#x%x;", $n) : "&#$n;";
}



sub unicode_convert
  { my $enc= $_[1] ? $_[1] : $_[0]; # so the method can be called on the twig or directly
    require Unicode::Map8;
    require Unicode::String;
    import Unicode::String qw(utf8);
    my $sub= eval q{
            { my $cnv;
	      sub { $cnv ||= Unicode::Map8->new($enc) 
	              or croak "Can't create converter to $enc";
		    return  $cnv->to8 (utf8($_[0])->ucs2); 
	          } 
	    } };
    return $sub;
  }

sub iconv_convert
  { my $enc= $_[1] ? $_[1] : $_[0]; # so the method can be called on the twig or directly
    require Text::Iconv;
    my $sub= eval q{
            { my $cnv;
	      sub { $cnv ||= Text::Iconv->new( 'utf8', $enc) 
	              or croak "Can't create converter to $enc";
		    return  $cnv->convert( $_[0]); 
	          } 
	    } };
    return $sub;
  }

######################################################################
package XML::Twig::Entity_list;
######################################################################
sub new
  { my $class = shift;
    my $self={};

    bless $self, $class;
    return $self;

  }

sub add
  { my( $list, $ent)= @_;
    $list->{$ent->{name}}= $ent;
  }

# can be called with an entity or with an entity name
sub delete
  { my $list= shift;
    if( ref $_[0] eq 'XML::Twig::Entity_list')
      { # the second arg was an entity
        my $ent= shift;
        delete $list->{$ent->{name}};
      }
    else
      { # the second arg was not entity, must be a string then
        my $name= shift;
        delete $list->{$name};
      }
  }

sub print
  { my ($ent_list, $fh)= @_;
    my $old_select= select $fh if( defined $fh);

    foreach my $ent_name ( sort keys %{$ent_list})
      { my $ent= $ent_list->{$ent_name};
        # we have to test what the entity is or un-defined entities can creep in
        $ent->print() if( UNIVERSAL::isa( $ent, 'XML::Twig::Entity'));
      }
    select $old_select if( defined $old_select);
  }

sub text
  { my ($ent_list)= @_;
    return join "\n", map { $ent_list->{$_}->text} sort keys %{$ent_list};
  }

sub list
  { my ($ent_list)= @_;
    return @{[$ent_list]};
  }

######################################################################
package XML::Twig::Entity;
######################################################################

sub new
  { my( $ent, $name, $val, $sysid, $pubid, $ndata)= @_;

    my $self={};

    $self->{name}= $name;
    if( $val)
      { $self->{val}= $val; }
    else
      { $self->{sysid}= $sysid;
        $self->{pubid}= $pubid;
        $self->{ndata}= $ndata;
      }
    bless $self;
    return $self;
  }

sub name  { return $_[0]->{name}; }
sub val   { return $_[0]->{val}; }
sub sysid { return $_[0]->{sysid}; }
sub pubid { return $_[0]->{pubid}; }
sub ndata { return $_[0]->{ndata}; }

sub print
  { my ($ent, $fh)= @_;
    if( $fh) { print $fh $ent->text . "\n"; }
    else     { print $ent->text . "\n"; }
  }

sub text
  { my ($ent)= @_;
    if( $ent->{'val'})
      { if( $ent->{'val'}=~ /"/)
          { return "<!ENTITY $ent->{'name'} '$ent->{'val'}'>"; }
        return "<!ENTITY $ent->{'name'} \"$ent->{'val'}\">";
      }
    elsif( $ent->{'sysid'})
      { my $text= "<!ENTITY $ent->{'name'} ";
        $text .= "SYSTEM \"$ent->{'sysid'}\" " if( $ent->{'sysid'});
        $text .= "PUBLIC \"$ent->{'pubid'}\" " if( $ent->{'pubid'});
        $text .= "NDATA $ent->{'ndata'}"        if( $ent->{'ndata'});
        $text .= ">";
        return $text;
      }
  }

                

######################################################################
package XML::Twig::Elt;
######################################################################
use Carp;


use constant  PCDATA  => '#PCDATA'; 
use constant  CDATA   => '#CDATA'; 
use constant  PI      => '#PI'; 
use constant  COMMENT => '#COMMENT'; 
use constant  ENT     => '#ENT'; 

use constant  ASIS    => '#ASIS';    # pcdata elements not to be XML-escaped

use constant  ELT     => '#ELT'; 
use constant  TEXT    => '#TEXT'; 
use constant  EMPTY   => '#EMPTY'; 

use constant CDATA_START    => "<![CDATA[";
use constant CDATA_END      => "]]>";
use constant PI_START       => "<?";
use constant PI_END         => "?>";
use constant COMMENT_START  => "<!--";
use constant COMMENT_END    => "-->";


BEGIN
  { # set some aliases for methods
    *tag        = *gi; 
    *set_tag    = *set_gi; 
    *find_nodes = *get_xpath;
    *field      = *first_child_text;
    *is_field   = *contains_only_text;
    *is         = *passes;
    *matches    = *passes;
    *has_child  = *first_child;
    *all_children_pass = *all_children_are;
    *all_children_match= *all_children_are;
    *getElementsByTagName= *descendants;
  
    *first_child_is  = *first_child_matches;
    *last_child_is   = *last_child_matches;
    *next_sibling_is = *next_sibling_matches;
    *prev_sibling_is = *prev_sibling_matches;
    *next_elt_is     = *next_elt_matches;
    *prev_elt_is     = *prev_elt_matches;
    *parent_is       = *parent_matches;
    *child_is        = *child_matches;

  # try using weak references
  import WeakRef if( eval 'require WeakRef');
  }

 
# can be called as XML::Twig::Elt->new( [[$gi, $atts, [@content]])
# - gi is an optional gi given to the element
# - $atts is a hashref to attributes for the element
# - @content is an optional list of text and elements that will
#   be inserted under the element 
sub new 
  { my $class= shift;
    my $self  = {};
    bless ($self, $class);

    return $self unless @_;

    # if a gi is passed then use it
    my $gi= shift;
    $self->set_gi( $gi);

    if( ref $_[0] eq 'HASH')
      { my $atts= shift;
        # the attribute hash can be used to pass the asis status 
        if( defined $atts->{ASIS})
	  { $self->set_asis;
	    delete $atts->{ASIS};
	  }
        $self->set_atts( $atts);
      }

    if( $gi eq PCDATA)
      { $self->set_pcdata( shift); }
    elsif( $gi eq ENT)
      { $self->set_ent( shift); }
    elsif( $gi eq CDATA)
      { $self->set_cdata( shift); }
    elsif( $gi eq COMMENT)
      { $self->set_comment( shift); }
    elsif( $gi eq PI)
      { $self->set_pi( shift, shift); }
    else
      { # the rest of the arguments are the content of the element
        $self->set_content( @_) if @_; 
      }

    return $self;
  }

# this function creates an XM:::Twig::Elt from a string
# it is quite clumsy at the moment, as it just creates a
# new twig then returns its root
# there might also be memory leaks there
# additional arguments are passed to new XML::Twig
sub parse
  { my $class= shift;
    my $string= shift;
    my %args= @_;
    my $t= XML::Twig->new(%args);
    $t->parse( $string);
    my $self= $t->root;
    # clean-up the node 
    delete $self->{twig};         # get rid of the twig data
    delete $self->{twig_current}; # better get rid of this too
    return $self;
  }
    

sub set_gi 
  { my ($elt, $gi)= @_;
    unless( defined $XML::Twig::gi2index{$gi})
      { # new gi, create entries in %gi2index and @index2gi
        push  @XML::Twig::index2gi, $gi;
        $XML::Twig::gi2index{$gi}= $#XML::Twig::index2gi;
      }
    $elt->{gi}= $XML::Twig::gi2index{$gi}; 
  }

sub gi  { return $XML::Twig::index2gi[$_[0]->{gi}]; }

# return #ELT for an element and #PCDATA... for others
sub get_type
  { my $gi_nb= $_[0]->{gi}; # the number, not the string
    return ELT if( $gi_nb > $XML::Twig::SPECIAL_GI);
    return $_[0]->gi;
  }

# return the gi if it's a "real" element, 0 otherwise
sub is_elt
  { return $_[0]->gi if(  $_[0]->{gi} >  $XML::Twig::SPECIAL_GI);
    return 0;
  }


sub is_pcdata
  { my $elt= shift;
    return (exists $elt->{'pcdata'});
  }

sub is_cdata
  { my $elt= shift;
    return (exists $elt->{'cdata'});
  }

sub is_pi
  { my $elt= shift;
    return (exists $elt->{'target'});
  }

sub is_comment
  { my $elt= shift;
    return (exists $elt->{'comment'});
  }

sub is_ent
  { my $elt= shift;
    return (exists $elt->{'ent_name'});
  }


sub is_text
  { my $elt= shift;
    return (exists( $elt->{'pcdata'}) || (exists $elt->{'cdata'}));
  }

sub is_empty
  { return $_[0]->{empty} || 0; }

sub set_empty
  { $_[0]->{empty}= 1 unless( $_[0]->is_empty); }

sub set_not_empty
  { delete $_[0]->{empty} if( $_[0]->is_empty); }


sub set_asis
  { my $elt=shift;
    $elt->{asis}= 1 if( $elt->is_pcdata);
    foreach my $pcdata ($elt->descendants( PCDATA))
      { $pcdata->{asis}= 1;}
  }

sub set_not_asis
  { my $elt=shift;
    $elt->{asis}= 0 if $elt->{asis};
    foreach my $pcdata ($elt->descendants())
      { delete $pcdata->{asis} if $elt->{asis};}
  }

sub is_asis
  { return $_[0]->{asis}; }

sub closed 
  { my $elt= shift;
    my $t= $elt->twig || return;
    my $curr_elt= $t->{twig_current};
    return unless( $curr_elt);
    return $curr_elt->in( $elt);
  }

sub set_pcdata 
  { $_[0]->set_not_empty;
    return( $_[0]->{'pcdata'}= $_[1]); 
  }
sub append_pcdata
  { return( $_[0]->{'pcdata'}.= $_[1]); 
  }
sub pcdata        { return $_[0]->{pcdata}; }

sub set_data 

  { return( $_[0]->{'data'}= $_[1]); 
  }

sub data { return $_[0]->{data}; }


sub append_extra_data 
  {  return( $_[0]->{extra_data}.= $_[1]); 
  }
sub set_extra_data 
  { return( $_[0]->{extra_data}= $_[1]); 
  }
sub extra_data { return $_[0]->{extra_data}; }

sub set_target 
  { return( $_[0]->{'target'}= $_[1]); 
  }
sub target { return $_[0]->{target}; }

sub set_pi
  { $_[0]->set_target( $_[1]);
    $_[0]->set_data( $_[2]);
  }
sub pi_string { return PI_START . $_[0]->target . " " . $_[0]->data . PI_END; }

sub set_comment { return( $_[0]->{'data'}= $_[1]); }
sub comment { return $_[0]->{data}; }
sub comment_string { return COMMENT_START . $_[0]->comment . COMMENT_END; }


sub set_ent { return( $_[0]->{ent}= $_[1]); }
sub ent { return $_[0]->{ent}; }
sub ent_name { return substr( $_[0]->ent, 1, -1);}

sub set_cdata 
  { $_[0]->set_not_empty;
   return( $_[0]->{'cdata'}= $_[1]); 
  }
sub append_cdata
  { return( $_[0]->{'cdata'}.= $_[1]); 
  }
sub cdata { return $_[0]->{'cdata'}; }
sub cdata_string { return CDATA_START . $_[0]->cdata . CDATA_END; }


#start-extract twig_node
sub contains_only_text
  { my $elt= shift;
    return 0 unless $elt->is_elt;
    foreach my $child ($elt->children)
      { return 0 if $child->is_elt; }
    return 1;
  } 

sub root 
  { my $elt= shift;
    while( $elt->_parent) { $elt= $elt->_parent; }
    return $elt;
  }
#end-extract twig_node

sub twig 
  { my $elt= shift;
    my $root= $elt->root;
    return $root->{twig};
  }


#start-extract twig_node

# returns undef or the element, depending on whether $elt passes $cond
# $cond can be
# - empty: the element passes the condition
# - ELT ('#ELT'): the element passes the condition if it is a "real" element
# - TEXT ('#TEXT'): the element passes if it is a CDATA or PCDATA element
# - a string: the element passes if its gi is equal to the string
# - a regexp: the element passes if its gi matches the regexp
# - a code ref: the element passes if the code, applied on the element,
#   returns true

  my %cond_cache; # expression => coderef
{ # my %cond_cache; # expression => coderef
 
  sub install_cond
    { my $cond= shift;
      my $sub;


      if( ref $cond eq 'CODE') { return $cond; }
    
      if( ref $cond eq 'Regexp')
        { $sub = qq{return \$_[0] if \$_[0]->gi=~ /$cond/;}; }
      else
      { # the condition is a string
        if( $cond eq ELT)     
          { $sub = qq{return \$_[0] if \$_[0]->is_elt;}; }
        elsif( $cond eq TEXT) 
          { $sub = qq{return \$_[0] if \$_[0]->is_text;}; }
	elsif( $cond=~ m{^\s*($REG_NAME_W)\s*$}o)                  
          { # gi
	    if( $1 ne '*')
	      { # 2 options, depending on whether the gi exists in gi2index
	        # start optimization
	        my $gi= $XML::Twig::gi2index{$1};
	        if( $gi)
	          { # the gi exists, use its index as a faster shortcut
		    $sub = qq{return \$_[0] if \$_[0]->{gi} eq "$XML::Twig::gi2index{$1}";};
		  }
		else
	        # end optimization
                  { # it does not exist (but might be created later), compare the strings
		    $sub = qq{return \$_[0] if \$_[0]->gi eq "$1";}; 
                  }
              }
	    else
	      { $sub = qq{ return \$_[0]; } }
	  }
	elsif( $cond=~ m{^\s*($REG_REGEXP)\s*$}o)
	  { # /regexp/
	    $sub = qq{return \$_[0] if \$_[0]->gi=~ $1;}; 
	  }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*\[\s*\@($REG_NAME)\s*\]\s*$}o)
          { # gi[@att]
	    if( $1 && ($1 ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$1") && (defined \$_[0]->att( "$2")));}; }
	    else
	      { $sub = qq{return \$_[0] if(defined \$_[0]->att( "$2"));}; }
	   }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*  # $1
	                 \[\@($REG_NAME)        #   [@$2
			 \s*=\s*                #        =
			 ($REG_STRING)          #          "$3" or '$3'
			 \s*\]\s*$}xo)          #                       ]
          { # gi[@att="val"]
	    if( $1 && ($1 ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$1") && (defined \$_[0]->att( "$2")) && ( \$_[0]->att( "$2") eq $3) );}; }
	    else
	      { $sub = qq{return \$_[0] if((defined \$_[0]->att( "$2")) && ( \$_[0]->att( "$2") eq $3) );}; }
	   }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*  # $1
	                 \[\@($REG_NAME)        #   [@$2
			 \s*=~\s*               #        =~
			 ($REG_REGEXP)          #           /$3/
			 \s*\]\s*$}xo)          #                ]
          { # gi[@att=~ /regexp/]
	    if( $1 && ($1 ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$1") && (defined \$_[0]->att( "$2")) && ( \$_[0]->att( "$2")=~ $3) );}; }
	    else
	      { $sub = qq{return \$_[0] if((defined \$_[0]->att( "$2")) && ( \$_[0]->att( "$2") =~ $3) );}; }
	   }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*      # $1
	                 \[\s*text(?:\(\s*\))?      #   [text()
			 \s*=\s*                    #          =
			 ($REG_STRING)              #           "$2" or '$2'
			 \s*\]\s*$}xo)              #                       ]
          { # gi[text()= "val"]
	    my ($gi, $text)= ($1, $2);
	    if( $gi && ($gi ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$gi") && ( \$_[0]->text eq $text) );}; }
	    else
	      { $sub = qq{return \$_[0] if( \$_[0]->text eq $text) );} ; }
	  }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*       # $1
	                 \[\s*text(?:\(\s*\))?       #   [text()
			 \s*=~\s*                    #          =~
			 ($REG_REGEXP)               #           /$2/
			 \s*\]\s*$}xo)               #                ]
          { # gi[text()=~ /regexp/]
	    if( $1 && ($1 ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$1") && ( \$_[0]->text=~ $2) );}; }
	    else
	      { $sub = qq{return \$_[0] if( \$_[0]->text=~ $2) );}; }
          }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*  # $1
	                 \[\s*text\s*\(\s*      # [text(
			 ($REG_NAME)\s*\)       #       $2)
			 \s*=\s*                #          =
			 ($REG_STRING)          #           "$3" or '$3'
			 \s*\]\s*$}xo)          #                       ]
          { # gi[text(gi2)= "text"]
	    my ($gi, $gi2, $text)= ($1, $2, $3);
	    $text=~ s/([{}])/\\$1/g;
	    #warn "gi: $gi - gi2: $gi2 - text: $text";
	    if( $gi && ($gi ne '*'))
	      { $sub = qq{ return \$_[0] if(    (\$_[0]->gi eq "$gi") 
	                                    && ( \$_[0]->first_child( qq{$gi2\[text()= $text]}))
					   );}; }
	    else
	      { $sub = qq{return \$_[0] if( \$_[0]->first_child(qq{$gi2\[text()= $text]})) ;} ; }
	    #warn "$cond: $sub\n";
	  }
	elsif( $cond=~ m{^\s*($REG_NAME_W)?\s*  # $1
	                 \[\s*text\(\s*         #   [text(
			 ($REG_NAME)\s*\)       #         $2)
			 \s*=~\s*               #            =~
			 ($REG_REGEXP)          #              /$3/
			 \s*\]\s*$}xo)          #                   ]
          { # gi[text(gi2)=~ /regexp/]
	    if( $1 && ($1 ne '*'))
	      { $sub = qq{return \$_[0] if((\$_[0]->gi eq "$1") && ( \$_[0]->field( "$2") =~ $3) );}; }
	    else
	      { $sub = qq{return \$_[0] if( \$_[0]->field( "$2") =~ $3);}; }
          }
	else
	  { croak "wrong condition $cond"; }
      }

      # warn "\n$cond: $sub";
      my $s= eval "sub { $sub }";
      if( $@) { warn "sub: $sub"; croak "wrong navigation condition $cond ($@);" }
      return $s;
    }
 
  sub passes
  
    { my( $elt, $cond)= @_;
      return $elt unless $cond;
      my $sub= ($cond_cache{$cond} ||= install_cond( $cond));
      return $sub->( $elt);
    }
}
# end-extract twig_nodes

sub my_passes
  { my( $elt, $cond)= @_;
    return $elt unless $cond;
    unless( ref $cond)
      { # the condition is a string
        if( $cond eq ELT)     { return $elt if $elt->is_elt;      }
        elsif( $cond eq TEXT) { return $elt if $elt->is_text;     }
	else                  { return $elt if $elt->gi eq $cond; }
      }
    elsif( ref $cond eq 'Regexp')
      { return $elt if $elt->gi=~ $cond; }
    elsif( ref $cond eq 'CODE')
      { return $elt if $cond->($elt); }
    return undef;
  }

sub set_parent 
  { $_[0]->{parent}= $_[1];
    weaken( $_[0]->{parent}) if( $XML::Twig::weakrefs);
    # warn "weakening parent\n" if( $XML::Twig::weakrefs);
  }

#start-extract twig_node
sub parent
  { my $elt= shift;
    my $cond= shift || return $elt->_parent;
    do { $elt= $elt->_parent || return; } until (!$elt || $elt->passes( $cond));
    return $elt;
  }
#end-extract twig_node

sub set_first_child 
  { $_[0]->set_not_empty;
    $_[0]->{'first_child'}= $_[1]; 
  }

#start-extract twig_node
sub first_child
  { my $elt= shift;
    my $cond= shift || return $elt->_first_child;
    my $child= $elt->_first_child;
    my $test_cond= ($cond_cache{$cond} ||= install_cond( $cond));
    while( $child && !$test_cond->( $child)) 
       { $child= $child->_next_sibling; }
    return $child;
  }
#end-extract twig_node
  
sub _first_child  { return $_[0]->{first_child};  }
sub _last_child   { return $_[0]->{last_child};   }
sub _next_sibling { return $_[0]->{next_sibling}; }
sub _prev_sibling { return $_[0]->{prev_sibling}; }
sub _parent       { return $_[0]->{parent};       }

# sets a field
# arguments $record, $cond, @content
sub set_field
  { my $record = shift;
    my $cond = shift;
    my $child= $record->first_child( $cond);
    my $new_field= XML::Twig::Elt->new( @_);
    if( $child)
      { $new_field->replace( $child); }
    else
      { $new_field->paste( last_elt => $record); } 
    return $new_field;
  }

sub set_last_child 
  { $_[0]->set_not_empty;
    $_[0]->{'last_child'}= $_[1];
    weaken( $_[0]->{'last_child'}) if( $XML::Twig::weakrefs);
  }

#start-extract twig_node
sub last_child
  { my $elt= shift;
    my $cond= shift || return $elt->_last_child;
    my $test_cond= ($cond_cache{$cond} ||= install_cond( $cond));
    my $child= $elt->_last_child;
    while( $child && !$test_cond->( $child) )
      { $child= $child->_prev_sibling; }
    return $child
  }
#end-extract twig_node


sub set_prev_sibling 
  { $_[0]->{'prev_sibling'}= $_[1]; 
    weaken( $_[0]->{'prev_sibling'}) if( $XML::Twig::weakrefs); 
  }

#start-extract twig_node
sub prev_sibling
  { my $elt= shift;
    my $cond= shift || return $elt->_prev_sibling;
    my $test_cond= ($cond_cache{$cond} ||= install_cond( $cond));
    my $sibling= $elt->_prev_sibling;
    while( $sibling && !$test_cond->( $sibling) )
          { $sibling= $sibling->_prev_sibling; }
    return $sibling;
  }
#end-extract twig_node

sub set_next_sibling { $_[0]->{'next_sibling'}= $_[1]; }

#start-extract twig_node
sub next_sibling
  { my $elt= shift;
    my $cond= shift || return $elt->_next_sibling;
    my $test_cond= ($cond_cache{$cond} ||= install_cond( $cond));
    my $sibling= $elt->_next_sibling;
    while( $sibling && !$test_cond->( $sibling) )
          { $sibling= $sibling->_next_sibling; }
    return $sibling;
  }
#end-extract twig_node

# get or set all attributes
sub set_atts { $_[0]->{'att'}= $_[1]; }
sub atts { return $_[0]->{att}; }
sub att_names { return keys %{$_[0]->{att}}; }
sub del_atts { $_[0]->{att}={}; }

# get or set a single attributes
sub set_att 
  { my $elt= shift;
    while(@_) { my( $att, $val)= (shift, shift);
                $elt->{att}->{$att}= $val;
	      }
  }
sub att { return $_[0]->{att}->{$_[1]}; }
sub del_att 
  { my $elt= shift;
    while( @_) { delete $elt->{'att'}->{shift()}; }
  }

sub set_twig_current { $_[0]->{twig_current}=1; }
sub del_twig_current { delete $_[0]->{twig_current}; }


# get or set the id attribute
sub set_id 
  { my( $elt, $id)= @_;
    $elt->set_att($ID, $_[1]); 
    my $t= $elt->twig || return;
    $elt->twig->{twig_id_list}->{$id}= $elt;
    weaken(  $elt->twig->{twig_id_list}->{$id}) if( $XML::Twig::weakrefs);
  }

sub id { return $_[0]->{'att'}->{$ID}; }

# delete the id attribute and remove the element from the id list
sub del_id 
  { my $elt= shift;
    my $id= $elt->{'att'}->{$ID} or return;
    my $t= $elt->twig && delete $elt->twig->{twig_id_list}->{$id};
    delete $elt->{'att'}->{$ID}; 
  }

# return the list of children
#start-extract twig_node
sub children
  { my $elt= shift;
    my @children;
    my $child= $elt->first_child( @_);
    while( $child) 
      { push @children, $child;
        $child= $child->next_sibling( @_);
      } 
    return @children;
  }

sub children_count
  { my $elt= shift;
    my $cond= shift;
    my $count=0;
    my $child= $elt->_first_child;
    while( $child)
      { $count++ if( $child->passes( $cond)); 
        $child= $child->_next_sibling;
      }
    return $count;
  }


sub all_children_are
  { my( $parent, $cond)= @_;
    foreach my $child ($parent->children)
      { return 0 unless( $child->passes( $cond)); }
    return 1;
  }


sub ancestors
  { my( $elt, $cond)= @_;
    my @ancestors;
    while( $elt->_parent)
      { $elt= $elt->_parent;
        push @ancestors, $elt
          if( $elt->passes( $cond));
      }
    return @ancestors;
  }


sub inherit_att
  { my $elt= shift;
    my $att= shift;
    my %tags= map { ($_, 1) } @_;

    do 
      { if(   (defined $elt->att( $att))
           && ( !%tags || $tags{$elt->gi})
          )
          { return $elt->att( $att); }
      } while( $elt= $elt->_parent);
    return undef;
  }


# kinda counter-intuitive actually:
# the next element is found by looking for the next open tag after from the
# current one, which is the first child, if it exists, or the next sibling
# or the first next sibling of an ancestor
# optional arguments are: 
#   - $subtree_root: a reference to an element, when the next element is not 
#                    within $subtree_root anymore then next_elt returns undef
#   - $gi: a gi, next_elt returns the next element of this gi
                 
sub next_elt
  { my $elt= shift;
    my $subtree_root= 0;
    $subtree_root= shift if( UNIVERSAL::isa( $_[0], 'XML::Twig::Elt'));
    my $cond= shift;
    my $next_elt;

    my $ind;                                                             # optimization
    my $test_cond;
    if( $cond)                                                           # optimization
      { unless( defined( $ind= $XML::Twig::gi2index{$cond}) )            # optimization
          { $test_cond= ($cond_cache{$cond} ||= install_cond( $cond)); } # optimization
      }                                                                  # optimization
    
    do
      { if( $next_elt= $elt->_first_child)
          { # simplest case: the elt has a child
          }
         elsif( $next_elt= $elt->_next_sibling) 
          { # no child but a next sibling (just check we stay within the subtree)
          
            # case where elt is subtree_root, is empty and has a sibling
            return undef if( $subtree_root && ($elt == $subtree_root));
            
          }
        else
          { # case where the element has no child and no next sibling:
            # get the first next sibling of an ancestor, checking subtree_root 
          
            # case where elt is subtree_root, is empty and has no sibling
            return undef if( $subtree_root && ($elt == $subtree_root));
             
            # backtrack until we find a parent with a next sibling
            $next_elt= $elt->_parent || return undef;
            until( $next_elt->_next_sibling)
              { return undef if( $subtree_root && ($subtree_root == $next_elt));
                $next_elt= $next_elt->_parent || return undef;
              }
            return undef if( $subtree_root && ($subtree_root == $next_elt)); 
            $next_elt= $next_elt->_next_sibling;   
          }  
	  $elt= $next_elt;                   # just in case we need to loop
	} until(    ! defined $elt 
	         || ! defined $cond 
		 || (defined $ind       && ($elt->{gi} eq $ind))   # optimization
		 || (defined $test_cond && ($test_cond->( $elt)))
               );
	
      return $elt;
      }

# counter-intuitive too:
# the previous element is found by looking
# for the first open tag backwards from the current one
# it's the last descendant of the previous sibling 
# if it exists, otherwise it's simply the parent
sub prev_elt
  { my $elt= shift;
    my $cond= shift;
    # get prev elt
    my $prev_elt;
    do
      { if( $prev_elt= $elt->_prev_sibling)
          { while( $prev_elt->_last_child)
              { $prev_elt= $prev_elt->_last_child; }
          }
        else
          { $prev_elt= $elt->_parent || return; }
        $elt= $prev_elt;     # in case we need to loop 
      } until( $elt->passes( $cond));

    return $prev_elt;
  }


# checks whether $elt is included in $ancestor, returns 1 in that case
sub in($$)
  { my ($elt, $ancestor)= @_;
    while( $elt= $elt->_parent) { return 1 if( $elt ==  $ancestor); }
    return 0;           
  }

# generated methods
sub first_child_text  
  { my $elt= shift;
    my $dest=$elt->first_child(@_) or return '';
    return $dest->text;
  }
  
sub first_child_matches
  { my $elt= shift;
    my $dest= $elt->_first_child or return undef;
    return $dest->passes( @_);
  }
  
sub last_child_text  
  { my $elt= shift;
    my $dest=$elt->last_child(@_) or return '';
    return $dest->text;
  }
  
sub last_child_matches
  { my $elt= shift;
    my $dest= $elt->_last_child or return undef;
    return $dest->passes( @_);
  }
  
sub child_text
  { my $elt= shift;
    my $dest=$elt->child(@_) or return '';
    return $dest->text;
  }
  
sub child_matches
  { my $elt= shift;
    my $nb= shift;
    my $dest= $elt->child( $nb) or return undef;
    return $dest->passes( @_);
  }

sub prev_sibling_text  
  { my $elt= shift;
    my $dest=$elt->prev_sibling(@_) or return '';
    return $dest->text;
  }
  
sub prev_sibling_matches
  { my $elt= shift;
    my $dest= $elt->_prev_sibling or return undef;
    return $dest->passes( @_);
  }
  
sub next_sibling_text  
  { my $elt= shift;
    my $dest=$elt->next_sibling(@_) or return '';
    return $dest->text;
  }
  
sub next_sibling_matches
  { my $elt= shift;
    my $dest= $elt->_next_sibling or return undef;
    return $dest->passes( @_);
  }
  
sub prev_elt_text  
  { my $elt= shift;
    my $dest=$elt->prev_elt(@_) or return '';
    return $dest->text;
  }
  
sub prev_elt_matches
  { my $elt= shift;
    my $dest= $elt->_prev_elt or return undef;
    return $dest->passes( @_);
  }
  
sub next_elt_text  
  { my $elt= shift;
    my $dest=$elt->next_elt(@_) or return '';
    return $dest->text;
  }
  
sub next_elt_matches
  { my $elt= shift;
    my $dest= $elt->_next_elt or return undef;
    return $dest->passes( @_);
  }
  
sub parent_text  
  { my $elt= shift;
    my $dest=$elt->parent(@_) or return '';
    return $dest->text;
  }
  
sub parent_matches
  { my $elt= shift;
    my $dest= $elt->_parent or return undef;
    return $dest->passes( @_);
  }
  

# returns the depth level of the element
# if 2 parameter are used then counts the 2cd element name in the
# ancestors list
sub level
  { my $elt= shift;
    my $level=0;
    my $name=shift || '';
    while( $elt= $elt->_parent) { $level++ if( !$name || ($name eq $elt->gi)); }
    return $level;           
  }

# checks whether $elt has an ancestor type $gi, returns the ancestor
sub in_context
  { my ($elt, $gi, $level)= @_;
    $level= -1 unless( $level) ;  # $level-- will never hit 0

    while( $level && $elt->_parent)
      { if( $elt->gi eq $gi) { return $elt; }
        $elt= $elt->_parent;
        $level--;
      }
    return ;           
  }

sub descendants
  { my( $subtree_root, $cond)= @_;
    my @descendants=(); 
    my $elt= $subtree_root;
    
    # this branch is pure optimisation for speed: if $cond is a gi replace it
    # by the index of the gi and loop here 
    # start optimization
    my $ind;
    if( !$cond || ( defined ( $ind= $XML::Twig::gi2index{$cond})) )
      {
        my $next_elt;

        while( 1)  
          { if( $next_elt= $elt->_first_child)
                { # simplest case: the elt has a child
                }
             elsif( $next_elt= $elt->_next_sibling) 
              { # no child but a next sibling (just check we stay within the subtree)
           
                # case where elt is subtree_root, is empty and has a sibling
                last if( $subtree_root && ($elt == $subtree_root));
              }
            else
              { # case where the element has no child and no next sibling:
                # get the first next sibling of an ancestor, checking subtree_root 
                
                # case where elt is subtree_root, is empty and has no sibling
                last if( $subtree_root && ($elt == $subtree_root));
               
                # backtrack until we find a parent with a next sibling
                $next_elt= $elt->_parent || last undef;
                until( $next_elt->_next_sibling)
                  { last if( $subtree_root && ($subtree_root == $next_elt));
                    $next_elt= $next_elt->_parent || last;
                  }
                last if( $subtree_root && ($subtree_root == $next_elt)); 
                $next_elt= $next_elt->_next_sibling;   
              }  
	    $elt= $next_elt || last;
            push @descendants, $elt if( !$cond || ($elt->{gi} eq $ind));
	  }
      }
    else
    # end optimization
      { # branch for a complex condition: use the regular (slow but simple) way
        while( $elt= $elt->next_elt( $subtree_root, $cond))
          { push @descendants, $elt; }
      }
    return @descendants;
  }
  
sub descendants_or_self
  { my( $elt, $cond)= @_;
    my @descendants= $elt->passes( $cond) ? ($elt) : (); 
    push @descendants, $elt->descendants( $cond);
    return @descendants;
  }
  
sub sibling
  { my $elt= shift;
    my $nb= shift;
    if( $nb > 0)
      { foreach( 1..$nb)
          { $elt= $elt->next_sibling( @_) or return undef; }
      }
    elsif( $nb < 0)
      { foreach( 1..(-$nb))
          { $elt= $elt->prev_sibling( @_) or return undef; }
      }
    else # $nb == 0
      { return $elt->passes( $_[0]); }
    return $elt;
  }

sub sibling_text
  { my $elt= sibling( @_);
    return $elt ? $elt->text : undef;
  }


sub child
  { my $elt= shift;
    my $nb= shift;
    if( $nb >= 0)
      { $elt= $elt->first_child( @_) or return undef;
        foreach( 1..$nb)
          { $elt= $elt->next_sibling( @_) or return undef; }
      }
    else
      { $elt= $elt->last_child( @_) or return undef;
        foreach( 2..(-$nb))
          { $elt= $elt->prev_sibling( @_) or return undef; }
      }
    return $elt;
  }

sub prev_siblings
  { my $elt= shift;
    my @siblings=();
    while( $elt= $elt->prev_sibling( @_))
      { unshift @siblings, $elt; }
    return @siblings;
  }

sub next_siblings
  { my $elt= shift;
    my @siblings=();
    while( $elt= $elt->next_sibling( @_))
      { push @siblings, $elt; }
    return @siblings;
  }

# used by get_xpath: parses the xpath expression and generates a sub that performs the
# search
# used by get_xpath: parses the xpath expression and generates a sub that performs the
# search
sub install_xpath
  { my( $xpath_exp, $type)= @_;
    my $original_exp= $xpath_exp;
    my $sub= 'my $elt= shift; my @results=();';
    
    # grab the root if expression starts with a /
    if( $xpath_exp=~ s{^/}{})
      { $sub .= '@results= ($elt->twig);'; }
    elsif( $xpath_exp=~ s{^\./}{})
      { $sub .= '@results= ($elt);'; }
    else
      { $sub .= '@results= ($elt);'; }

    while( $xpath_exp &&
           $xpath_exp=~s{^\s*(/?)                            
                          # the xxx=~/regexp/ is a pain as it includes /  
                          (\s*([\w:-_]+\s*)?\[\s*(string\(\s*\)|@[\w:_-]+)\s*=~  
                            \s*/([^\\/]|\\.)*/\s*\]\s* 
                          # or a regular condition, with no / excepts \/
                          |([^\\/]|\\.)*
                          )
                          (/|$)}{}x)

      { my $wildcard= $1;
        my $sub_exp= $2;
        
        # grab a parent
        if( $sub_exp eq '..')
          { croak "error in xpath expression $original_exp" if( $wildcard);
            $sub .= '@results= map { $_->parent} @results;';
          }
        # grab children
        elsif( $sub_exp=~ m{([^\[]+)\s*               # * or a gi    ($1)
                       (?:\[([^\]]*))?\s*}xs)         # optional condition ($2)
          { my $gi= $1 unless( $1 eq '*');
            my $cond= $2; 
            if( $cond) { $cond=~ s{^\s*}{}; $cond=~ s{\s*$}{}; }
            my $function;
            

            # "special" conditions, that return just one element
            if( $cond && ($cond =~ m{^((-\s*)?\d+)$}) )
              { my $offset= $1;
	        $offset-- if( $offset > 0);
                $function=  $wildcard ? "next_n_elt( $offset, '$gi')" 
                                      : "child( $offset, '$gi')";
                $sub .= "\@results= map { \$_->$function } \@results;"
              }
            elsif( $cond && ($cond =~ m{^last\s*\(\s*\)$}) )
              { croak "error in xpath expression $original_exp, cant use // and last()"
                  if( $wildcard);
                 $sub .= "\@results= map { \$_->last_sibling( '$gi') } \@results;";
              }
            else
              { # go down and get the children or descendants
                unless ( defined $gi)
                  { if( $wildcard)
                      { $sub .= '@results= map { $_->descendants  } @results;' }
                    else
                      { $sub .= '@results= map { $_->children } @results;'; }
                  }
                else
                  { if( $wildcard)
                      { $sub .= "\@results= map { \$_->descendants( '$gi')  } \@results;";  }            
                    else
                      { $sub .= "\@results= map { \$_->children( '$gi')  } \@results;"; }
                  } 
                # now filter using the condition
                if( $cond)
                  { my $op='';
                    my $test="";
                    do
                      { if( $op)
                          { $cond=~ s{^\s*$op\s*}{};
                            $op= lc( $op);
                            $test .= $op;
                          }
                      
                       if( $cond =~ s{^string\(\s*\)\s*=\s*($REG_STRING)\s*}{}o)  # string()="string" cond
                          { $test .= "\$_->text eq $1"; 
                          }
                       elsif( $cond =~ s{^string\(\s*\)\s*=~\s*/(([^/\\]|\\.)*)/\s*}{})  # string()=~/regex/ cond
                          { $test .= "\$_->text=~/$1/"; 
                          }
                       elsif( $cond=~ s{^@([^=\s]+)\s*=\s*($REG_STRING)}{}o)  # @att="val" cond
                          { $test .= qq{((defined \$_->att("$1"))  && (\$_->att( "$1" ) eq $2))};
                          }
                       elsif( $cond =~ s{^@([^=\s]+)\s*=~\s*/(([^/\\]|\\.)*)/\s*}{})  # @att=~/regex/ cond
                          { $test .= qq{((defined \$_->att("$1"))  && (\$_->att( "$1" )=~ /$3/))};; 
                          }
                       elsif( $cond=~ s{^@([\w:-]+)\s*}{})                      # @att cond
                          { $test .= qq{(defined \$_->att("$1"))};
                          }
                       } while( ($op)=($cond=~ m{^\s*(and|or)\s*}i));
                     croak "error in xpath expression $original_exp at $cond" if( $cond);
                     $sub .= "\@results= grep { $test } \@results;";
                   }
              }
          }
        else
          { croak "error in xpath expression $original_exp around $sub_exp"; }
      }

    if( $xpath_exp)
      { croak "error in xpath expression $original_exp around $xpath_exp"; }
      
    $sub .= "return \@results; ";
    # warn "installing $_[0] => $sub\n\n";
    my $s= eval "sub { $sub }";
    if( $@) { croak "error in xpath expression $original_exp ($@);" }
    return( $s); 
   }
        
{ # extremely elaborate caching mechanism
  my %xpath; # xpath_expression => subroutine_code;  
  sub get_xpath
    { my( $elt, $xpath_exp, $offset)= @_;
      my $sub= ($xpath{$xpath_exp} ||= install_xpath( $xpath_exp));
      return $sub->( $elt) unless( defined $offset); 
      my @res= $sub->( $elt);
      return $res[$offset];
    }
    1; # so the module returns 1 as this is the last BEGIN block in the file
}


#end-extract twig_node

sub flushed { return $_[0]->{'flushed'}; }
sub set_flushed { $_[0]->{'flushed'}=1; }
sub del_flushed { delete $_[0]->{'flushed'}; }


sub cut
  { my $elt= shift;
    my( $parent, $prev_sibling, $next_sibling, $last_elt);

    # you can't cut the root, sorry
    unless( $parent= $elt->_parent) 
      { return; }
    # it we cut the current element then its parent becomes the current elt
    if( $elt->{twig_current})
      { my $twig_current= $elt->_parent;
        my $t= $elt->twig;
        $t->{twig_current}= $twig_current;
        $twig_current->set_twig_current;
        $elt->del_twig_current;
      }

    $parent->set_first_child( $elt->_next_sibling) 
      if( $parent->_first_child == $elt);
    $parent->set_last_child( $elt->_prev_sibling) 
      if( $parent->_last_child == $elt);

    if( $prev_sibling= $elt->_prev_sibling)
      { $prev_sibling->set_next_sibling( $elt->_next_sibling); }
    if( $next_sibling= $elt->_next_sibling)
      { $next_sibling->set_prev_sibling( $elt->_prev_sibling); }


    $elt->set_parent( undef);
    $elt->set_prev_sibling( undef);
    $elt->set_next_sibling( undef);

    return $elt;
  }


sub erase
  { my $elt= shift;
    #you cannot erase the current element
    if( $elt->{twig_current})
      { croak "trying to erase an element before it has been completely parsed"; }
    unless( $elt->_parent)
      { croak "cannot erase an element with no parent"; }

    my @children= $elt->children;
    if( @children)
      { # elt has children, move them up
        if( $elt->_prev_sibling)
          { # connect first child to previous sibling
            $elt->_first_child->set_prev_sibling( $elt->_prev_sibling);      
            $elt->_prev_sibling->set_next_sibling( $elt->_first_child); 
          }
        else
          { # elt was the first child
            $elt->_parent->set_first_child( $elt->_first_child);
          }
        if( $elt->_next_sibling)
          { # connect last child to next sibling
            $elt->_last_child->set_next_sibling( $elt->_next_sibling);      
            $elt->_next_sibling->set_prev_sibling( $elt->_last_child); 
          }
        else
          { # elt was the last child
            $elt->_parent->set_last_child( $elt->_last_child);
          }
        # update parent for all siblings
        foreach my $child (@children)
          { $child->set_parent( $elt->_parent); }
      }
    else
      { # elt had no child
        if( $elt->_prev_sibling)
          { # connect previous sibling to next sibling (can be undef)
            $elt->_prev_sibling->set_next_sibling( $elt->_next_sibling);      
          }
        else
          { # elt was the first child
            $elt->_parent->set_first_child( $elt->_next_sibling);
          }
        if( $elt->_next_sibling)
          { # connect next sibling to previous sibling (can be undef)
            $elt->_next_sibling->set_prev_sibling( $elt->_prev_sibling); 
          }
        else
          { # elt was the last child
            $elt->_parent->set_last_child( $elt->_next_sibling);
          }
      }

    # elt is not referenced any more, so it will be DESTROYed
    # so we'd better break the links to its children
    undef $elt->{'first_child'};
    undef $elt->{'last_child'};
    undef $elt->{'parent'};
    undef $elt->{'prev_sibling'};
    undef $elt->{'next_sibling'};

  }
        

BEGIN
  { my %method= ( before      => \&paste_before,
                  after       => \&paste_after,
		  first_child => \&paste_first_child,
		  last_child  => \&paste_last_child,
		  within      => \&paste_within,
		);
	
    # paste elt somewhere around ref
    # pos can be first_child (default), last_child, before, after or within
    sub paste
      { my $elt= shift;
        if( $elt->_parent) 
          { croak "cannot paste an element that belongs to a tree"; }
        my $pos;
        my $ref;
        if( ref $_[0]) 
          { $pos= 'first_child'; 
            croak "wrong argument order in paste, should be $_[1] first" 
	      if($_[1]); 
          }
        else
          { $pos= shift; }

    if( my $method= $method{$pos})
      { $elt->$method( @_); }
    else
      { croak "tried to paste in wrong position ($pos), allowed positions " . 
              " are 'first_child', 'last_child', 'before', 'after' and "    .
	      "'within'";
      }
  }
  

    sub paste_before
      { my( $elt, $ref)= @_;
        my( $parent, $prev_sibling, $next_sibling );
        unless( $ref->_parent) { croak "cannot paste before root"; }
        $parent= $ref->_parent;
        $prev_sibling= $ref->_prev_sibling;
        $next_sibling= $ref;

        $elt->set_parent( $parent);
        $parent->set_first_child( $elt) if( $parent->_first_child == $ref);

        $prev_sibling->set_next_sibling( $elt) if( $prev_sibling);
        $elt->set_prev_sibling( $prev_sibling);

        $next_sibling->set_prev_sibling( $elt);
        $elt->set_next_sibling( $ref);
      }
     
     sub paste_after
      { my( $elt, $ref)= @_;
        my( $parent, $prev_sibling, $next_sibling );
        unless( $ref->_parent) { croak "cannot paste after root"; }
        $parent= $ref->_parent;
        $prev_sibling= $ref;
        $next_sibling= $ref->_next_sibling;

        $elt->set_parent( $parent);
        $parent->set_last_child( $elt) if( $parent->_last_child== $ref);

        $prev_sibling->set_next_sibling( $elt);
        $elt->set_prev_sibling( $prev_sibling);

        $next_sibling->set_prev_sibling( $elt) if( $next_sibling);
        $elt->set_next_sibling( $next_sibling);

      }

    sub paste_first_child
      { my( $elt, $ref)= @_;
        my( $parent, $prev_sibling, $next_sibling );
        $parent= $ref;
        $next_sibling= $ref->_first_child;
        $ref->set_not_empty;

        $elt->set_parent( $parent);
        $parent->set_first_child( $elt);
        $parent->set_last_child( $elt) unless( $parent->_last_child);

        $elt->set_prev_sibling( undef);

        $next_sibling->set_prev_sibling( $elt) if( $next_sibling);
        $elt->set_next_sibling( $next_sibling);

      }
      
    sub paste_last_child
      { my( $elt, $ref)= @_;
        my( $parent, $prev_sibling, $next_sibling );
        $parent= $ref;
        $prev_sibling= $ref->_last_child;
        $ref->set_not_empty;

        $elt->set_parent( $parent);
        $parent->set_last_child( $elt);
        $parent->set_first_child( $elt) unless( $parent->_first_child);

        $elt->set_prev_sibling( $prev_sibling);
        $prev_sibling->set_next_sibling( $elt) if( $prev_sibling);

        $elt->set_next_sibling( undef);

      }

    sub paste_within
      { my( $elt, $ref, $offset)= @_;
        my( $parent, $prev_sibling, $next_sibling );
        my $new= $ref->split( $offset);
	$elt->paste_before( $new);
      }
  }

# split a text element at a given offset
sub split_at
  { my( $elt, $offset)= @_;
    unless( $elt->is_text)
      { $elt= $elt->first_child( TEXT) || return ''; }
    my $string= $elt->text; 
    my $left_string= substr( $string, 0, $offset);
    my $right_string= substr( $string, $offset);
    $elt->set_pcdata( $left_string);
    my $new_elt= XML::Twig::Elt->new( $elt->gi, $right_string);
    $new_elt->paste( 'after', $elt);
    return $new_elt;
  }

    
# split an element or its text descendants into several, in place
# all elements (new and untouched) are returned
sub split    
  { my $elt= shift;
    my @text_chunks;
    my @result;
    if( $elt->is_text) { @text_chunks= ($elt); }
    else               { @text_chunks= $elt->descendants( '#TEXT'); }
    foreach my $text_chunk (@text_chunks)
      { push @result, $text_chunk->_split( 1, @_); }
    return @result;
  }

# split an element or its text descendants into several, in place
# created elements (those which match the regexp) are returned
sub mark
  { my $elt= shift;
    my @text_chunks;
    my @result;
    if( $elt->is_text) { @text_chunks= ($elt); }
    else               { @text_chunks= $elt->descendants( '#TEXT'); }
    foreach my $text_chunk (@text_chunks)
      { push @result, $text_chunk->_split( 0, @_); }
    return @result;
  }

# split a single text element
# return_all defines what is returned: if it is true 
# only returns the elements created by matches in the split regexp
# otherwise all elements (new and untouched) are returned
sub _split
  { my $elt= shift;
    my $return_all= shift;
    my( $regexp, $tag, $atts)= @_;
    my @result;                                 # the returned list of elements
    my $text= $elt->text;
    my $gi= $elt->gi;
    $tag||= $gi;                                # default: same tag as $elt
    $atts ||= {};                               # default: no attributes

    # 2 uses: if split matches then the first substring reuses $elt
    #         once a split has occured then the last match needs to be put in
    #         a new element      
    my $replaced= 0;

    # emulate the split built-in: break on \s+ (probably useless!)
    $regexp ||= " ";
    if( $regexp eq " ") { $regexp= '\s+'; }

    while( $text=~/(.*?)(?:($regexp)|$)/sg)
      { # $1 is the pre-regexp match
        # $2 is the string that matches the regexp (if true then the regexp 
        #    matched, otherwise $ matched)
        # $3...$n are captured by the regexp (and should be wrapped in tag)
        if( defined $2 || $replaced)
          { # the regexp matched this time ($2) or previously ($replaced)
            unless( $replaced)
              { # first match in $elt, re-use $elt for the first sub-string
                $elt->set_text( $1);
                $replaced++;                     # note that there was a match
                push @result, $elt if( $return_all);
              }
            else
              { # match, not the first one, create a new text ($gi) element
                my $new_text= XML::Twig::Elt->new( $gi, $1);
                $new_text->paste( 'after', $elt); # paste it after $elt
                $elt= $new_text;                  # $elt: element to paste after
                push @result, $elt if( $return_all);
              }
            # now deal with matches captured in the regexp
            no strict( 'refs');                   # needed to access $3...$n
            for( my $match=3; defined $$match; $match++)
              { # create new element, text is the match
                my %atts= %$atts; # or the same atts is used for all matches!
                my $new_text= XML::Twig::Elt->new( $tag, \%atts, $$match);
                $new_text->paste( 'after', $elt); # paste it after the current
                $elt= $new_text;                  # it becomes the current elt
                push @result, $elt;
              }
          }
        else
          { # the regep did not match at all, $elt is not changed
            push @result, $elt if( $return_all);
          }
      } 
    return @result; # return all elements
 }


# recursively copy an element and returns the copy (can be huge and long)
sub copy
  { my $elt= shift;
    my $copy= XML::Twig::Elt->new( $elt->gi);

    if( $elt->extra_data)
      { $copy->set_extra_data( $elt->extra_data) }

    if( $elt->is_pcdata)
      { $copy->set_pcdata( $elt->pcdata); }
    elsif( $elt->is_cdata)
      { $copy->set_cdata( $elt->cdata); }
    elsif( $elt->is_pi)
      { $copy->set_pi( $elt->target, $elt->data); }
    elsif( $elt->is_comment)
      { $copy->set_comment( $elt->comment); }
    elsif( $elt->is_ent)
      { $copy->set_ent( $elt->ent); }
    else
      { my @children= $elt->children;
        if( my $atts= $elt->atts)
          { my %atts= %{$atts}; # we want to do a real copy of the attributes
            $copy->set_atts( \%atts);
          }
        foreach my $child (@children)
          { my $child_copy= $child->copy;
            $child_copy->paste( 'last_child', $copy);
          }
      }
    return $copy;
  }

sub delete
  { my $elt= shift;
    $elt->cut;
    $elt->DESTROY;
  }

sub DESTROY
  { my $elt= shift;

    return if( $XML::Twig::weakrefs);

    foreach( @{[$elt->children]}) { XML::Twig::Elt::DESTROY($_); }
    # destroy all references in the tree
    delete $elt->{'parent'};
    delete $elt->{'first_child'};
    delete $elt->{'last_child'};
    delete $elt->{'prev_sibling'};
    delete $elt->{'next_sibling'};
    # the id reference also needs to be destroyed
    $elt->del_id if( $ID && exists $elt->{att}->{$ID});
    delete $elt->{'att'};         # $elt->set_atts( undef);
    $elt= undef;
  }


# to be called only from a start_tag_handler: ignores the current element
sub ignore
  { my $elt= shift;
    my $t= $elt->twig;
    $t->ignore( $elt);
  }

BEGIN {
  my $pretty=0;
  my $quote='"';
  my $INDENT= '  ';
  my $empty_tag_style= 0;
  my $keep_encoding= 0;
  my $expand_external_entities= 0;

  my ($NSGMLS, $NICE, $INDENTED, $RECORD1, $RECORD2)= (1..5);

  my %pretty_print_style=
    ( none     => 0,         # no added \n
      nsgmls   => $NSGMLS,   # nsgmls-style, \n in tags
      # below this line styles are UNSAFE (the generated XML can be invalid)
      nice     => $NICE,     # \n after open/close tags except when the element
                            # starts with text
      indented => $INDENTED, # nice plus idented
      record_c => $RECORD1,  # for record-like data (compact)
      record   => $RECORD2,  # for record-like data  (not so compact)
    );

  my ($HTML, $EXPAND)= (1..2);
  my %empty_tag_style=
    ( normal => 0,        # <tag/>
      html   => $HTML,    # <tag />
      xhtml  => $HTML,    # <tag />
      expand => $EXPAND,  # <tag></tag>
    );

  my %quote_style=
    ( double  => '"',    
      single  => "'", 
      # smart  => "smart", 
    );

  my $output_filter;

  # set the pretty_print style (in $pretty) and returns the old one
  # can be called from outside the package with 2 arguments (elt, style)
  # or from inside with only one argument (style)
  # the style can be either a string (one of the keys of %pretty_print_style
  # or a number (presumably an old value saved)
  sub set_pretty_print
    { my $style= lc( $_[1] || $_[0]); # so we cover both cases 
      my $old_pretty= $pretty;
      if( $style=~ /^\d+$/)
        { croak "illegal pretty print style $style"
	    unless( $style < keys %pretty_print_style);
	    $pretty= $style;
	}
      else
        { croak "illegal pretty print style $style"
            unless( exists $pretty_print_style{$style});
          $pretty= $pretty_print_style{$style};
	}
      return $old_pretty;
    }
  
  
  # set the empty tag style (in $empty_tag_style) and returns the old one
  # can be called from outside the package with 2 arguments (elt, style)
  # or from inside with only one argument (style)
  # the style can be either a string (one of the keys of %empty_tag_style
  # or a number (presumably an old value saved)
  sub set_empty_tag_style
    { my $style= lc( $_[1] || $_[0]);  # works whether called on an elt or
                                       # just as a regular function call
      my $old_style= $empty_tag_style;
      if( $style=~ /^\d+$/)
        { croak "illegal empty tag style $style"
	    unless( $style < keys %empty_tag_style);
	    $empty_tag_style= $style;
	}
      else
        { croak "illegal empty_tag stype style $style"
            unless( exists $empty_tag_style{$style});
          $empty_tag_style= $empty_tag_style{$style};
	}
      return $old_style;
    }
      
  sub set_quote
    { my $style= $_[1] || $_[0];
      my $old_quote= $quote;
      croak "illegal quote style $_[1]"
        unless( exists $quote_style{$style});
      $quote= $quote_style{$style};
      return $old_quote;
    }
      
  sub set_indent
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $INDENT;
      $keep_encoding= $new_value;
      return $old_value;
    }
       
  sub set_keep_encoding
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $keep_encoding;
      $keep_encoding= $new_value;
      return $old_value;
    
   }

  sub set_output_filter
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $output_filter;
      if( !$new_value || UNIVERSAL::isa( $new_value, 'CODE') )
        { $output_filter= $new_value; }
      elsif( $new_value eq 'latin1')
        { $output_filter= XML::Twig::latin1(); }
      elsif( $XML::Twig::filter{$new_value})
        {  $output_filter= $XML::Twig::filter{$new_value}; }
      else
        { croak "invalid output filter: $new_value"; }
      
      return $old_value;
    }
       
  sub set_expand_external_entities
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $expand_external_entities;
      $expand_external_entities= $new_value;
      return $old_value;
    }
       
  # $elt is an element to print
  # $pretty is an optionnal value, if true a \n is printed after the <
  sub start_tag
    { my $elt= shift;
  
      return if( $elt->{gi}<$XML::Twig::SPECIAL_GI);
  
      my $tag="<" . $elt->gi;
  
      # get the attribute and their values
      my $att= $elt->atts;
      if( $att)
        { foreach my $att_name (sort keys %{$att}) 
           { # skip private attributes (they start with #)
             next if( substr( $att_name, 0,1) eq '#');

             if( $pretty==$NSGMLS) { $tag .= "\n"; } 
             else                  { $tag .= ' ';  }
             $tag .=   $att_name . '=' . $quote  
	             . $elt->att_xml_string( $att_name, $quote) . 
		       $quote; 
           }
        } 
  
      $tag .= "\n" if($pretty==$NSGMLS);

      if( $elt->{empty})
        { if( !$empty_tag_style)
            { $tag .= "/>";     }
          elsif( $empty_tag_style eq $HTML)
            { $tag .= " />";  }
	  else #  $empty_tag_style eq $EXPAND
            { $tag .= "></" . $elt->gi .">";  }
        }
      else
        { $tag .= ">"; }

      return $tag unless $pretty;

      my $prefix='';
      my $return=0;    # 1 if a \n is to be printed before the tag
      my $indent=0;    # number of indents before the tag

      if( $pretty==$RECORD1)
        { my $level= $elt->level;
          $return= 1 if( $level < 2);
          $indent= 1 if( $level == 1);
        }

     elsif( $pretty==$RECORD2)
        { $return= 1;
          $indent= $elt->level;
        }

      elsif( $pretty==$NICE)
        { my $parent= $elt->_parent;
          unless( !$parent || $parent->{contains_text}) 
            { $return= 1; }
          $elt->{contains_text}= 1 if( ($parent && $parent->{contains_text})
                                     || $elt->contains_text);
        }

      elsif( $pretty==$INDENTED)
        { my $parent= $elt->_parent;
          unless( !$parent || $parent->{contains_text}) 
            { $return= 1; 
              $indent= $elt->level; 
            }
          $elt->{contains_text}= 1 if( ($parent && $parent->{contains_text})
                                     || $elt->contains_text);
        }

      if( $return || $indent)
        { # check for elements in which spaces should be kept
	  my $t= $elt->twig;
	  if( $t && $t->{twig_keep_spaces_in})
	    { foreach my $ancestor ($elt->ancestors)
	        { return $tag if( $t->{twig_keep_spaces_in}->{$ancestor->gi}) }
            }
	    
	  $prefix= "\n" if( $return and !$elt->{extra_data});
          $prefix.= $INDENT x $indent;
	}
              
      return $prefix . $tag;

    }
  
  sub end_tag
    { my $elt= shift;
      return  '' if( ($elt->{gi}<$XML::Twig::SPECIAL_GI) || $elt->is_empty);
      my $tag= "<";
      $tag.= "\n" if($pretty==$NSGMLS);
      $tag .=  "/$elt->gi>";

      $tag = ($elt->{extra_data_before_end_tag} || '') . $tag;

      return $tag unless $pretty;

      my $prefix='';
      my $return=0;    # 1 if a \n is to be printed before the tag
      my $indent=0;    # number of indents before the tag

      if( $pretty==$RECORD1)
        { $return= 1 if( $elt->level == 0);
        }

     elsif( $pretty==$RECORD2)
        { unless( $elt->contains_text)
            { $return= 1 ;
              $indent= $elt->level;
            }
        }

      elsif( $pretty==$NICE)
        { my $parent= $elt->_parent;
          unless( ($parent || $parent->{contains_text}) || $elt->{contains_text}
                  || !$elt->_first_child() ) 
            { $return= 1; }
        }

      elsif( $pretty==$INDENTED)
        { my $parent= $elt->_parent;
          unless( ($parent || $parent->{contains_text}) || $elt->{contains_text}
                  || !$elt->_first_child() ) 
            { $return= 1; 
              $indent= $elt->level; 
            }
        }

      if( $return || $indent)
        { # check for elements in which spaces should be kept
	  my $t= $elt->twig;
	  if( $t && $t->{twig_keep_spaces_in})
	    { foreach my $ancestor ($elt, $elt->ancestors)
	        { return $tag if( $t->{twig_keep_spaces_in}->{$ancestor->gi}) }
            }
      
          $prefix= "\n" if( $return);
          $prefix.= $INDENT x $indent;
	}
              
      return $prefix . $tag;
    }

  sub pretty_print
    { print( @_); }

  # $elt is an element to print
  # $fh is an optionnal filehandle to print to
  # $pretty is an optionnal value, if true a \n is printed after the < of the
  # opening tag
  sub print
    { my $elt= shift;
  
      my $pretty;
      my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') );
      my $old_select= select $fh if( defined $fh);
      my $old_pretty= set_pretty_print( $pretty) if( defined ($pretty= shift));
  
      $elt->_print;
    
      select $old_select if( defined $old_select);
      set_pretty_print( $old_pretty) if( defined $old_pretty);
    }
      
 sub _print
   { my $elt= shift;
      # in case there's some comments or PI's piggybacking
      if( $elt->{extra_data})
        { print $output_filter ? $output_filter->($elt->{extra_data}) 
                               : $elt->{extra_data};
        }

      if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
        { print $output_filter ? $output_filter->($elt->start_tag()) 
                               : $elt->start_tag();
  
          # print the children
          my $child= $elt->_first_child;
          while( $child)
            { $child->_print();
              $child= $child->_next_sibling;
            }
          print $output_filter ? $output_filter->($elt->end_tag()) 
                               : $elt->end_tag;
        }
      else # text or special element
        { my $text='';
          if( $elt->is_pcdata)     { $text= $elt->pcdata_xml_string;  }
          elsif( $elt->is_cdata)   { $text= $elt->cdata_string;       }
          elsif( $elt->is_pi)      { $text= $elt->pi_string;          }
          elsif( $elt->is_comment) { $text= $elt->comment_string;     }
          elsif( $elt->is_ent)     { $text= $elt->ent_string;         }

          print $output_filter ? $output_filter->( $text) : $text;
        }
    }
  
  
  # same as output but does not output the start tag if the element
  # is marked as flushed
  sub flush
    { my $elt= shift;
  
      my $pretty;
      my $fh=  shift if( defined( $_[0]) && UNIVERSAL::isa($_[0], 'GLOB') );
      my $old_select= select $fh if( defined $fh);
      my $old_pretty= set_pretty_print( shift) if( defined $_[0]);

      $elt->_flush();

      select $old_select if( defined $old_select);
      set_pretty_print( $old_pretty) if( defined $old_pretty);
    }

sub _flush
  { my $elt= shift;
  
      # in case there's some comments or PI's piggybacking
      if( $elt->{extra_data})
        { print $output_filter ? $output_filter->($elt->{extra_data}) 
                               : $elt->{extra_data};
        }

      if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
        {
          unless( $elt->flushed)
            { print $output_filter ? $output_filter->($elt->start_tag()) 
                                   : $elt->start_tag();
            }
      
          # flush the children
          my @children= $elt->children;
          foreach my $child (@children)
            { $child->_flush( $pretty); }
          print $output_filter ? $output_filter->($elt->end_tag()) 
                               : $elt->end_tag;
        }
      else # text or special element
        { my $text;
          if( $elt->is_pcdata)     { $text= $elt->pcdata_xml_string;  }
          elsif( $elt->is_cdata)   { $text= $elt->cdata_string;       }
          elsif( $elt->is_pi)      { $text= $elt->pi_string;          }
          elsif( $elt->is_comment) { $text= $elt->comment_string;     }
          elsif( $elt->is_ent)     { $text= $elt->ent_string;         }

          print $output_filter ? $output_filter->( $text) : $text;
        }
    }
  
  # just a shortcut to $elt->sprint( 1)
  sub xml_string
    { $_[0]->sprint( 1); }

  # same as print but except... it does not print but rather returns the string
  # if the second parameter is set then only the content is returned, not the
  # start and end tags of the element (but the tags of the included elements are
  # returned)
  sub sprint
    { my $elt= shift;
      my $no_tag= shift || 0;
  
      # in case there's some comments or PI's piggybacking
      my $string='';
      if( $elt->{extra_data})
        { $string= $output_filter ? $output_filter->($elt->{extra_data}) 
                                  : $elt->{extra_data};
        }

      if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
        {
          unless( $no_tag)
            { $string.=$output_filter ? $output_filter->($elt->start_tag) 
                                      :  $elt->start_tag;
            }
      
          # sprint the children
          my $child= $elt->_first_child||'';
          while( $child)
            { $string.= $child->sprint;
              $child= $child->_next_sibling;
            }
          unless( $no_tag)
            { $string.=$output_filter ? $output_filter->($elt->end_tag) 
                                      :  $elt->end_tag;
            }
        }
      elsif( $elt->is_pcdata)  { $string .= $elt->pcdata_xml_string; }
      elsif( $elt->is_cdata)   { $string .= $elt->cdata_string;      }
      elsif( $elt->is_pi)      { $string .= $elt->pi_string;         }
      elsif( $elt->is_comment) { $string .= $elt->comment_string;    }
      elsif( $elt->is_ent)     { $string .= $elt->ent_string;        }

      if( $output_filter) { $string= $output_filter->( $string); }
      return $string;
    }

sub pcdata_xml_string 
  { my $string='';
    if( defined( $string= $_[0]->{pcdata}) )
      { $string=~ s/([&<])/$XML::Twig::base_ent{$1}/g
          unless( $keep_encoding || $_[0]->{asis}); 
      }
    return $string;
  }

sub att_xml_string 
  { my $elt= shift;
    my $att= shift;
    my $quote= shift || '"';
    my $string='';
    if( defined ($string= $elt->{att}->{$att}))
      { $string=~ s/([$quote<&])/$XML::Twig::base_ent{$1}/g
          unless( $keep_encoding); 
      }
    return $string;
  }

sub ent_string 
  { my $ent= shift;
    my $ent_text= $ent->{ent};
    my( $t, $el, $ent_string);
    if(    $expand_external_entities
        && ($t= $ent->twig) 
        && ($el= $t->entity_list)
        && ($ent_string= $el->{$ent->ent_name}->{val})
      )
     { return $ent_string; }

     return $ent_text; 
  }

# returns just the text, no tags, for an element
sub text
  { my $elt= shift;
    my $string;

    if( $elt->is_pcdata)     { return  $elt->pcdata;   }
    elsif( $elt->is_cdata)   { return  $elt->cdata;    }
    elsif( $elt->is_pi)      { return  $elt->pi;       }
    elsif( $elt->is_comment) { return  $elt->comment;  }
    elsif( $elt->is_ent)     { return  $elt->ent ;     }

    my $child= $elt->_first_child ||'';
    while( $child)
      { $string.= defined($child->text) ? $child->text : '';
        $child= $child->_next_sibling;
      }
    unless( defined $string) { $string=''; }

    return $string;
  }

# un-escape XML base entities if $keep_encoding is set
sub unescape
  { return $_[0] unless $keep_encoding;
    my $string= shift;
    $string=~ s{&lt;}   {<}g;
    $string=~ s{&gt;}   {>}g;
    $string=~ s{&apos;} {'}g;
    $string=~ s{&quot;} {"}g;
    $string=~ s{&amp;}  {&}g;
    return $string;
   }

} # end of block containing package globals ($pretty_print, $quotes, keep_encoding...)


#start-extract twig_node
  sub contains_text
  { my $elt= shift;
    my $child= $elt->_first_child;
    while ($child)
      { return 1 if( $child->is_text); 
        $child= $child->_next_sibling;
      }
    return 0;
  }

#end-extract twig_node

# creates a single pcdata element containing the text as child of the element
sub set_text
  { my $elt= shift;
    my $string= shift;

    if( $elt->gi eq PCDATA) 
      { return $elt->set_pcdata( $string); }
    elsif( $elt->gi eq CDATA)  
      { $elt->set_gi( PCDATA);
        $elt->set_cdata('');
        return $elt->set_pcdata( $string);
      }

    foreach my $child (@{[$elt->children]})
      { $child->cut; }

    my $pcdata= XML::Twig::Elt->new( PCDATA, $string);
    $pcdata->paste( $elt);

    $elt->set_not_empty;

    return;
  }

# set the content of an element from a list of strings and elements
sub set_content
  { my $elt= shift;

    return unless defined $_[0];

    # attributes can be given as a hash (passed by ref)
    if( ref $_[0] eq 'HASH')
      { my $atts= shift;
        $elt->del_atts; # usually useless but better safe than sorry
        $elt->set_atts( $atts);
        return unless defined $_[0];
      }

    # check next argument for #EMPTY
    if( !(ref $_[0]) && ($_[0] eq EMPTY) ) 
      { $elt->set_empty; return; }

    # case where we really want to do a set_text, the element is '#PCDATA'
    # and we only want to add text in it
    if( ($elt->gi eq PCDATA) && ($#_ == 0) && !( ref $_[0]))
      { $elt->set_pcdata( $_[0]);
        return;
      }
    elsif( ($elt->gi eq CDATA) && ($#_ == 0) && !( ref $_[0]))
      { $elt->set_cdata( $_[0]);
        return;
      }

    # delete the children
    # WARNING: potential problem here if the children are used
    # somewhere else (where?). Will be solved when I use weak refs
    foreach my $child (@{[$elt->children]})
      { $child->delete; }

    foreach my $child (@_)
      { if( UNIVERSAL::isa( $child, 'XML::Twig::Elt'))
          { $child->paste( 'last_child', $elt); }
        else
          { my $pcdata= XML::Twig::Elt->new( PCDATA, $child);
            $pcdata->paste( 'last_child', $elt);  
          }
      }

    $elt->set_not_empty;

    return;
  }

# inserts an element (whose gi is given) as child of the element
# all children of the element are now children of the new element
# returns the new element
sub insert
  { my ($elt, @args)= @_;
    # first cut the childrena
    my @children= $elt->children;
    foreach my $child (@children)
      { $child->cut; }
    # insert elements
    while( my $gi= shift @args)
      { my $new_elt= XML::Twig::Elt->new( $gi);
        # add attributes if needed
        if( UNIVERSAL::isa( $args[0], 'HASH'))
	  { $new_elt->set_atts( shift @args); }
	# paste the element
        $new_elt->paste( $elt);
        $elt->set_not_empty;
        $elt= $new_elt;
      }
    # paste back the children
    foreach my $child (@children)
      { $child->paste( 'last_child', $elt); }
    return $elt;
  }

# insert a new element 
# $elt->insert_new_element( $opt_position, $gi, $opt_atts_hash, @opt_content); 
# the element is created with the same syntax as new
# position is the same as in paste, first_child by default
sub insert_new_elt
  { my $elt= shift;
    my $position= $_[0];
    if(     ($position eq 'before') || ($position eq 'after')
         || ($position eq 'first_child') || ($position eq 'last_child'))
      { shift; }
    else
      { $position= 'first_child'; }

    my $new_elt= XML::Twig::Elt->new( @_);
    $new_elt->paste( $position, $elt);
    return $new_elt;
  }

# wraps an element in elements which gi's are given as arguments
# $elt->wrap_in( 'td', 'tr', 'table') wraps the element as a single
# cell in a table for example
# returns the new element
sub wrap_in
  { my $elt= shift;
    while( my $gi = shift @_)
      { my $new_elt = XML::Twig::Elt->new( $gi);
        if( $elt->{twig_current})
          { my $t= $elt->twig;
            $t->{twig_current}= $new_elt;
            $elt->del_twig_current;
            $new_elt->set_twig_current;
          }

        if( my $parent= $elt->_parent)
          { $new_elt->set_parent( $parent); 
            $parent->set_first_child( $new_elt) if( $parent->_first_child == $elt);
            $parent->set_last_child( $new_elt)  if( $parent->_last_child == $elt);
          }
        else
          { # wrapping the root
            my $twig= $elt->twig;
            if( twig->root && (twig->root eq $elt) )
              { $twig->{twig_root}= $new_elt; }
          }

        if( my $prev_sibling= $elt->_prev_sibling)
          { $new_elt->set_prev_sibling( $prev_sibling);
            $prev_sibling->set_next_sibling( $new_elt);
          }

        if( my $next_sibling= $elt->next_sibling)
          { $new_elt->set_next_sibling( $next_sibling);
            $next_sibling->set_prev_sibling( $new_elt);
          }
        $new_elt->set_first_child( $elt);
        $new_elt->set_last_child( $elt);

        $elt->set_parent( $new_elt);
        $elt->set_prev_sibling( undef);
        $elt->set_next_sibling( undef);

        # add the attributes if the next argument is a hash ref
	if( UNIVERSAL::isa( $_[0], 'HASH'))
	  { $new_elt->set_atts( shift @_); }

        $elt= $new_elt;
      }
      
    return $elt;
  }

sub replace
  { my( $elt, $ref)= @_;
    if( my $parent= $ref->_parent)
      { $elt->set_parent( $parent);
        $parent->set_first_child( $elt) if( $parent->_first_child == $ref);
        $parent->set_last_child( $elt)  if( $parent->_last_child == $ref);
      }
    if( my $prev_sibling= $ref->_prev_sibling)
      { $elt->set_prev_sibling( $prev_sibling);
        $prev_sibling->set_next_sibling( $elt);
      }
    if( my $next_sibling= $ref->_next_sibling)
      { $elt->set_next_sibling( $next_sibling);
        $next_sibling->set_prev_sibling( $elt);
      }
   
    $ref->set_parent( undef);
    $ref->set_prev_sibling( undef);
    $ref->set_next_sibling( undef);
    return $ref;
  }


#start-extract twig_node
# move an element, same syntax as paste, except the element is first cut
sub move
  { my $elt= shift;
    $elt->cut;
    $elt->paste( @_);
  }
#end-extract twig_node


# adds a prefix to an element, creating a pcdata child if needed
sub prefix
  { my ($elt, $prefix, $option)= @_;
    my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
    if( $elt->is_pcdata 
        && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
      )
      { $elt->set_pcdata( $prefix . $elt->pcdata); }
    elsif( $elt->_first_child && $elt->_first_child->is_pcdata
        && (   ($asis && $elt->_first_child->{asis}) 
            || (!$asis && ! $elt->_first_child->{asis}))
         )
      { $elt->_first_child->set_pcdata( $prefix . $elt->_first_child->pcdata); }
    else
      { my $new_elt= XML::Twig::Elt->new( PCDATA, $prefix);
        $new_elt->paste( $elt);
        $new_elt->set_asis if( $asis);
      }
  }

# adds a suffix to an element, creating a pcdata child if needed
sub suffix
  { my ($elt, $suffix, $option)= @_;
    my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
    if( $elt->is_pcdata
        && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
      )
      { $elt->set_pcdata( $elt->pcdata . $suffix); }
    elsif( $elt->_last_child && $elt->_last_child->is_pcdata
        && (   ($asis && $elt->_last_child->{asis}) 
            || (!$asis && ! $elt->_last_child->{asis}))
         )
      { $elt->last_child->set_pcdata( $elt->_first_child->pcdata . $suffix); }
    else
      { my $new_elt= XML::Twig::Elt->new( PCDATA, $suffix);
        $new_elt->paste( 'last_child', $elt);
        $new_elt->set_asis if( $asis);
      }
  }

#start-extract twig_node
# create a path to an element ('/root/.../gi)
sub path
  { my $elt= shift;
    my @context= ( $elt, $elt->ancestors);
    return "/" . join( "/", reverse map {$_->gi} @context);
  }

sub before
  { my( $a, $b)=@_;
    if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
  }

sub after
  { my( $a, $b)=@_;
    if( $a->cmp( $b) == 1) { return 1; } else { return 0; }
  }

sub lt
  { my( $a, $b)=@_;
    return 1 if( $a->cmp( $b) == -1);
    return 0;
  }

sub le
  { my( $a, $b)=@_;
    return 1 if( $a->cmp( $b) == 1);
    return 0;
  }

sub gt
  { my( $a, $b)=@_;
    return 1 unless( $a->cmp( $b) == 1);
    return 0;
  }

sub ge
  { my( $a, $b)=@_;
    return 1 unless( $a->cmp( $b) == -1);
    return 0;
  }


sub cmp
  { my( $a, $b)=@_;

    # easy cases
    return  0 if( $a == $b);    
    return  1 if( $a->in($b)); # a starts after b 
    return -1 if( $b->in($a)); # a starts before b

    # ancestors does not include the element itself
    my @a_pile= ($a, $a->ancestors); 
    my @b_pile= ($b, $b->ancestors);

    # the 2 elements are not in the same twig
    return undef unless( $a_pile[-1] == $b_pile[-1]);

    # find the first non common ancestors (they are siblings)
    my $a_anc= pop @a_pile;
    my $b_anc= pop @b_pile;

    while( $a_anc == $b_anc) 
      { $a_anc= pop @a_pile;
        $b_anc= pop @b_pile;
      }

    # from there move left and right and figure out the order
    my( $a_prev, $a_next, $b_prev, $b_next)= ($a_anc, $a_anc, $b_anc, $b_anc);
    while()
      { $a_prev= $a_prev->_prev_sibling || return( -1);
        return 1 if( $a_prev == $b_next);
        $a_next= $a_next->_next_sibling || return( 1);
        return -1 if( $a_next == $b_prev);
        $b_prev= $b_prev->_prev_sibling || return( 1);
        return -1 if( $b_prev == $a_next);
        $b_next= $b_next->_next_sibling || return( -1);
        return 1 if( $b_next == $a_prev);
      }
  }
    
#end-extract twig_node

__END__

=head1 NAME

XML::Twig - A perl module for processing huge XML documents in tree mode.

=head1 SYNOPSIS

Small documents

  my $twig=XML::Twig->new(); # create the twig
  $twig->parse( 'doc.xml'); # build it
  my_process( $twig);       # use twig methods to process it 
  $twig->print;             # output the twig

Huge documents

  my $twig=XML::Twig->new(   
    twig_handlers => 
      { title   => sub { $_->set_gi( 'h2' }, # change title tags to h2
        para    => sub { $_->set_gi( 'p') }, # change para to p
	hidden  => sub { $_->delete;      }, # remove hidden elements
	list    => \&my_list_process,        # process list elements
	div     => sub { $_[0]->flush;    }, # output and free memory
      },
    PrettyPrint => 'indented',               # output will be nicely formatted
    EmptyTags   => 'html',                   # outputs <empty_tag />
	                );
    $t->flush;                               # flush the end of the document

See L<XML::Twig 101|XML::Twig 101> for other ways to use the module, as a 
filter for example

=head1 DESCRIPTION

This module provides a way to process XML documents. It is build on top
of XML::Parser.

The module offers a tree interface to the document, while allowing you
to output the parts of it that have been completely processed.

It allows minimal resource (CPU and memory) usage by building the tree
only for the parts of the documents that need actual processing, through the 
use of the C<L<twig_roots|twig_roots>> and 
C<L<twig_print_outside_roots|twig_print_outside_roots>> options. The 
C<L<finish|finish>> and C<L<finish_print|finish_print>> methods also help 
to increase performances.

XML::Twig tries to make simple things easy so it tries its best to takes care 
of a lot of the (usually) annoying (but sometimes necessary) features that 
come with XML and XML::Parser.

=head1 XML::Twig 101

XML::Twig can be used either on "small" XML documents (that fit in memory)
or on huge ones, by processing parts of the document and outputting or
discarding them once they are processed.


=head2 Loading an XML document and processing it

        my $t= XML::Twig->new();
        $t->parse( '<d><tit>title</tit><para>para1</para><para>p2</para></d>');
        my $root= $t->root;
	$root->set_gi( 'html');               # change doc to html
	$title= $root->first_child( 'tit');   # get the title
	$title->set_gi( 'h1');                # turn it into h1
	my @para= $root->children( 'para');   # get the para children
	foreach my $para (@para)
	  { $para->set_gi( 'p'); }            # turn them into p
	$t->print;                            # output the document

Other useful methods include:

L<att|att>: C<< $elt->att( 'type') >> returns the C<type> attribute for an 
element,

L<set_att|set_att>: C<< $elt->set_att( type => "important") >> sets the C<type> 
attribute to the C<important> value,

L<next_sibling|next_sibling>: C<< $elt->next_sibling >> returns the next sibling
in the document (in the example C<< $title->next_sibling >> is the first C<para>
while C<< $elt->next_sibling( 'table') >> is the next C<table> sibling 

The document can also be transformed through the use of the L<cut|cut>, 
L<copy|copy>, L<paste|paste> and L<move|move> methods: 
C<< $title->cut; $title->paste( 'after', $p); >> for example

And much, much more, see L<Elt|"Elt">.

=head2 Processing an XML document chunk by chunk

One of the strength of XML::Twig is that it let you work with files that do 
not fit in memory (BTW storing an XML document in memory as a tree is quite
memory-expensive, the expansion factor being often around 10).

To do this you can define handlers, that will be called once a specific 
element has been completely parsed. In this handlers you can access the
element and process it as you see fit, using the navigation and the
cut-n-paste methods, plus lots of convenient ones like C<L<prefix|prefix>>.
Once the element is completely processed you can then C<L<flush|flush>> it, 
which will output it and free the memory. You can also C<L<purge|purge>> it 
if you don't need to output it (if you are just extracting some data from 
the document for example). The handler will be called again once the next 
relevant element has been parsed.

        my $t= XML::Twig->new( twig_handlers => 
                                { section => \&section,
	                          para   => sub { $_->set_gi( 'p');
			        },
		            );
        $t->parsefile( 'doc.xml');
        $t->flush; # don't forget to flush one last time in the end or anything
	           # after the last </section> tag will not be output 
	
	# the handler is called once a section is completely parsed, ie when 
	# the end tag for section is found, it receives the twig itself and
	# the element (including all its sub-elements) as arguments
        sub section 
	  { my( $t, $section)= @_;      # arguments for all twig_handlers
	    $section->set_gi( 'div');   # change the gi, my favourite method...
	    # let's use the attribute nb as a prefix to the title
	    my $title= $section->first_child( 'title'); # find the title
	    my $nb= $title->att( 'nb'); # get the attribute
	    $title->prefix( "$nb - ");  # easy isn't it?
	    $section->flush;            # outputs the section and frees memory
	  }

        my $t= XML::Twig->new( twig_handlers => 
	                        { 'section/title' => \&print_elt_text} );
        $t->parsefile( 'doc.xml');
        sub print_elt_text 
          { my( $t, $elt)= @_;
            print $elt->text; 
          }

        my $t= XML::Twig->new( twig_handlers => 
	                        { 'section[@level="1"]' => \&print_elt_text }
			    );
        $t->parsefile( 'doc.xml');

There is of course more to it: you can trigger handlers on more elaborate 
conditions than just the name of the element, C<section/title> for example.
You can also use C<L<TwigStartHandlers|TwigStartHandlers>> to process an 
element as soon as the start tag is found. Besides C<L<prefix|prefix>> you
can also use C<L<suffix|suffix>>, 

=head2 Processing just parts of an XML document

The twig_roots mode builds only the required sub-trees from the document
Anything outside of the twig roots will just be ignored:

        my $t= XML::Twig->new( 
	         # the twig will include just the root and selected titles 
                 twig_roots   => { 'section/title' => \&print_elt_text,
                                   'annex/title'   => \&print_elt_text
				 }
                            );
        $t->parsefile( 'doc.xml');
	
        sub print_elt_text 
          { my( $t, $elt)= @_;
            print $elt->text;    # print the text (including sub-element texts)
	    $t->purge;           # frees the memory
          }

You can use that mode when you want to process parts of a documents but are
not interested in the rest and you don't want to pay the price, either in
time or memory, to build the tree for the it.


=head2 Building an XML filter

You can combine the twig_roots and the twig_print_outside_roots options to build
filters, which let you modify selected elements and will output the rest of 
the document as is.

This would convert prices in $ to prices in Euro in a document:

        my $t= XML::Twig->new( 
                 twig_roots   => { 'price' => \&convert, },    # process prices 
		 twig_print_outside_roots => 1,                # print the rest
                            );
        $t->parsefile( 'doc.xml');
	
        sub convert 
          { my( $t, $price)= @_;
	    my $currency=  $price->att( 'currency');        # get the currency
	    if( $currency eq 'USD')
	      { $usd_price= $price->text;                   # get the price
	        # %rate is just a conversion table 
	        my $euro_price= $usd_price * $rate{usd2euro};
		$price->set_text( $euro_price);             # set the new price
		$price->set_att( currency => 'EUR');        # don't forget this!
	      }
            $price->print;                                  # output the price
	  }


=head2 Simplifying XML processing

=over 4

=item Whitespaces

Whitespaces that look non-significant are discarded, this behaviour can be 
controlled using the C<L<keep_spaces|keep_spaces>>, 
C<L<keep_spaces_in|keep_spaces_in>> and 
C<L<discard_spaces_in options|discard_spaces_in options>>.

=item Encoding

You can specify that you want the output in the same encoding as the input
(provided you have valid XML, which means you have to specify the encoding
either in the document or when you create the Twig object) using the 
C<L<keep_encoding|keep_encoding>> option

=item Comments and Processing Instructions (PI)

Comments and PI's can be hidden from the processing, but still appear in the
output (they are carried by the "real" element closer to them)

=item Pretty Printing

XML::Twig can output the document pretty printed so it is easier to read for
us humans.

=item Surviving an untimely death

XML parsers are supposed to react violently when fed improper XML. 
XML::Parser just dies.

XML::Twig provides the C<L<safe_parse|safe_parse>> and the 
C<L<safe_parsefile|safe_parsefile>> methods which wrap the parse in an eval
and return either the parsed twig or 0 in case of failure.

=item Private attributes

Attributes with a name starting with # (illegal in XML) will not be
output, so you can safely use them to store temporary values during
processing.

=back

=head1 METHODS

=head2 Twig 

A twig is a subclass of XML::Parser, so all XML::Parser methods can be
called on a twig object, including parse and parsefile.
setHandlers on the other hand cannot be used, see C<L<BUGS|BUGS>>


=over 4

=item new 

This is a class method, the constructor for XML::Twig. Options are passed
as keyword value pairs. Recognized options are the same as XML::Parser,
plus some XML::Twig specifics:

=over 4

=item twig_handlers

This argument replaces the corresponding XML::Parser argument. It consists
of a hash { expression => \&handler} where expression is a 
I<generic_attribute_condition>, I<string_condition>,
an I<attribute_condition>,I<full_path>, a I<partial_path>, a I<gi>,
I<_default_> or <_all_>.

The idea is to support a usefull but efficient (thus limited) subset of
XPATH. A fuller expression set will be supported in the future, as users
ask for more and as I manage to implement it efficiently. This will never
encompass all of XPATH due to the streaming nature of parsing (no lookahead
after the element end tag).

A B<generic_attribute_condition> is a condition on an attribute, in the form
I<*[@att="val"]> or I<*[@att]>, simple quotes can be used instead of double 
quotes and the leading '*' is actually optional. No matter what the gi of the
element is, the handler will be triggered either if the attribute has the 
specified value or if it just exists. 

A B<string_condition> is a condition on the content of an element, in the form
I<gi[string()="foo"]>, simple quotes can be used instead of double quotes, at 
the moment you cannot escape the quotes (this will be added as soon as I
dig out my copy of Mastering Regular Expressions from its storage box).
The text returned is, as per what I (and Matt Sergeant!) understood from
the XPATH spec the concatenation of all the text in the element, excluding
all markup. Thus to call a handler on the element <p>text <b>bold</b></p>
the appropriate condition is p[string()="text bold"]. Note that this is not
exactly conformant to the XPATH spec, it just tries to mimic it while being
still quite concise. 

A extension of that notation is I<gi[string(B<child_gi>)="foo"]> where the
handler will be called if a child of a C<gi> element has a text value of 
C<foo>.  At the moment only direct children of the C<gi> element are checked.
If you need to test on descendants of the element let me know. The fix is
trivial but would slow down the checks, so I'd like to keep it the way it is.

A B<regexp_condition> is a condition on the content of an element, in the form
I<gi[string()=~ /foo/"]>. This is the same as a string condition except that
the text of the element is matched to the regexp. The C<i>, C<m>, <s> and C<o>
modifiers can be used on the regexp.

The I<gi[string(B<child_gi>)=~ /foo/"]> extension is also supported.

An B<attribute_condition> is a simple condition of an attribute of the
current element in the form I<gi[@att="val"]> (simple quotes can be used
instead of double quotes, you can escape quotes either). 
If several attribute_condition are true the same element all the handlers
can be called in turn (in the order in which they were first defined).
If the ="val" part is ommited ( the condition is then gi[@att]) then
the handler is triggered if the attribute actually exists for the element,
no matter what it's value is.

A B<full_path> looks like I<'/doc/section/chapter/title'>, it starts with
a / then gives all the gi's to the element. The handler will be called if
the path to the current element (in the input document) is exactly as
defined by the full_path.

A B<partial_path> is like a full_path except it does not start with a /:
I<'chapter/title'> for example. The handler will be called if the path to
the element (in the input document) ends as defined in the partial_path.

B<WARNING>: (hopefully temporary) at the moment I<string_condition>, 
I<regexp_condition> and I<attribute_condition> are only supported on a 
simple gi, not on a path.

A B<gi> (generic identifier) is just a tag name.

A special gi B<_all_> is used to call a function for each element.
The special gi B<_default_> is used to call a handler for each element
that does NOT have a specific handler.

The order of precedence to trigger a handler is: I<generic_attribute_condition>,
I<string_condition>, I<regexp_condition>, I<attribute_condition>, I<full_path>,
longer I<partial_path>, shorter I<partial_path>, I<gi>, I<_default_> . 

B<Important>: once a handler has been triggered if it returns 0 then no other
handler is called, exept a _all_ handler which will be called anyway.

If a handler returns a true value and other handlers apply, then the next
applicable handler will be called. Repeat, rince, lather..;

When an element is CLOSED the corresponding handler is called, with 2
arguments: the twig and the C<L</Element|/Element>>. The twig includes the 
document tree that has been built so far, the element is the complete sub-tree
for the element. $_ is also set to the element. 

Text is stored in elements where gi is #PCDATA (due to mixed content, text
and sub-element in an element there is no way to store the text as just an
attribute of the enclosing element).

B<Warning>: if you have used purge or flush on the twig the element might not
be complete, some of its children might have been entirely flushed or purged,
and the start tag might even have been printed (by flush) already, so changing
its gi might not give the expected result.

More generally, the I<full_path>, I<partial_path> and I<gi> expressions are
evaluated against the input document. Which means that even if you have changed
the gi of an element (changing the gi of a parent element from a handler for
example) the change will not impact the expression evaluation. Attributes in
I<attribute_condition> are different though. As the initial value of attribute
is not stored the handler will be triggered if the B<current> attribute/value
pair is found when the element end tag is found. Although this can be quite
confusing it should not impact most of users, and allow others to play clever
tricks with temporary attributes. Let me know if this is a problem for you.


=item twig_roots

This argument let's you build the tree only for those elements you are
interested in. 

  Example: my $t= XML::Twig->new( twig_roots => { title => 1, subtitle => 1});
           $t->parsefile( file);
           my $t= XML::Twig->new( twig_roots => { 'section/title' => 1});
           $t->parsefile( file);


returns a twig containing a document including only title and subtitle 
elements, as children of the root element.

You can use I<generic_attribute_condition>, I<attribute_condition>,
I<full_path>, I<partial_path>, I<gi>, I<_default_> and I<_all_> to 
trigger the building of the twig. 
I<string_condition> and I<regexp_condition> cannot be used as the content 
of the element, and the string, have not yet been parsed when the condition
is checked.

B<WARNING>: path are checked for the document. Even if the twig_roots option
is used they will be checked against the full document tree, not the virtual
tree created by XML::Twig


B<WARNING>: twig_roots elements should NOT be nested, that would hopelessly
confuse XML::Twig ;--(

Note: you can set handlers (twig_handlers) using twig_roots
  Example: my $t= XML::Twig->new( twig_roots => 
                                   { title    => sub { $_{1]->print;}, 
                                     subtitle => \&process_subtitle 
                                   }
                               );
           $t->parsefile( file);
 

=item twig_print_outside_roots

To be used in conjunction with the twig_roots argument. When set to a true 
value this will print the document outside of the twig_roots elements.

 Example: my $t= XML::Twig->new( twig_roots => { title => \&number_title },
                                twig_print_outside_roots => 1,
                               );
           $t->parsefile( file);
           { my $nb;
           sub number_title
             { my( $twig, $title);
               $nb++;
               $title->prefix( "$nb "; }
               $title->print;
             }
           }
               

This example prints the document outside of the title element, calls 
number_title for each title element, prints it, and then resumes printing
the document. The twig is built only for the title elements. 


=item start_tag_handlers

A hash { expression => \&handler}. Sets element handlers that are called when
the element is open (at the end of the XML::Parser Start handler). The handlers
are called with 2 params: the twig and the element. The element is empty at 
that point, its attributes are created though. 

You can use I<generic_attribute_condition>, I<attribute_condition>,
I<full_path>, I<partial_path>, I<gi>, I<_default_>  and I<_all_> to trigger 
the handler. 

I<string_condition> and I<regexp_condition> cannot be used as the content of 
the element, and the string, have not yet been parsed when the condition is 
checked.

The main uses for those handlers are to change the tag name (you might have to 
do it as soon as you find the open tag if you plan to C<flush> the twig at some
point in the element, and to create temporary attributes that will be used
when processing sub-element with TwigHanlders. 

You should also use it to change tags if you use flush. If you change the tag 
in a regular TwigHandler then the start tag might already have been flushed. 

B<Note>: StartTag handlers can be called outside ot I<twig_roots> if this 
argument is used, in this case handlers are called with the following arguments:
$t (the twig), $gi (the gi of the element) and %att (a hash of the attributes
of the element). 

If the I<twig_print_outside_roots> argument is also used then the start tag
will be printed if the last handler called returns a C<true> value, if it
does not then the start tag will B<not> be printed (so you can print a
modified string yourself for example);

Note that you can use the L<ignore|ignore> method in start_tag_handlers 
(and only there). 

=item end_tag_handlers

A hash { expression => \&handler}. Sets element handlers that are called when
the element is closed (at the end of the XML::Parser End handler). The handlers
are called with 2 params: the twig and the gi of the element. 

I<twig_handlers> are called when an element is completely parsed, so why have 
this redundant option? There is only one use for end_tag_handlers: when using
the twig_roots option, to trigger a handler for an element B<outside> the roots.
It is for example very useful to number titles in a document using nested 
sections: 

  my @no= (0);
  my $no;
  my $t= XML::Twig->new( 
          start_tag_handlers => 
           { section => sub { $no[$#no]++; $no= join '.', @no; push @no, 0; } },
          twig_roots         => 
           { title   => sub { $_[1]->prefix( $no); $_[1]->print; } },
          end_tag_handlers   => { section => sub { pop @no;  } },
          twig_print_outside_roots => 1
                      );
   $t->parsefile( $file);

Using the end_tag_handlers argument without twig_roots will result in an error.

=item CharHandler

A reference to a subroutine that will be called every time PCDATA is found.

=item keep_encoding

This is a (slightly?) evil option: if the XML document is not UTF-8 encoded and
you want to keep it that way, then setting keep_encoding will use the Expat
original_string method for character, thus keeping the original encoding, as 
well as the original entities in the strings.

See the t/test6.t test file to see what results you can expect from the various
encoding options.

B<WARNING>: if the original encoding is multi-byte then attribute parsing will
be EXTREMELY unsafe under any Perl before 5.6, as it uses regular expressions
which do not deal properly with multi-byte characters. You can specify an 
alternate function to parse the start tags with the parse_start_tag option 
(see below)

B<WARNING>: this option is NOT used when parsing with the non-blocking parser 
(parse_start, parse_more, parse_done methods) which you probably should not use
with XML::Twig anyway as they are totally untested!

=item output_filter

This option is used to convert the character encoding of the output document.
It is passed either a string corresponding to a predefined filter or
a subroutine reference. The filter will be called every time a document or 
element is processed by the "print" functions (C<print>, C<sprint>, C<flush>). 

Pre-defined filters are: 

=over 4 

=item latin1 

uses either Text::Iconv or Unicode::Map8 and Unicode::String or a regexp
(which works only with XML::Parser 2.27), in this order, to convert all 
characters to ISO-8859-1 (aka latin1)

=item html

does the same conversion as latin1, plus encodes entities using HTML::Entities
(you need to have HTML::Entities intalled for it to be available). This should
only be used if the tags and attribute names themselves are in US-ASCII, or they
will be converted and the output will not be valid XML any more

=item safe

converts the output to ASCII (US) only  plus character entities (&#nnn;) this
should be used only if the tags and attribute names themselves are in US-ASCII,
or they will be converted and the output will not be valid XML any more

=item iconv_convert ($encoding)

this function is used to create a filter subroutine that will be used to 
convert the characters to the target encoding using Text::Iconv (which need
to be installed, look at the documentation for the module and for the
C<iconv> library to find out which encodings are available on your system)

   my $conv = XML::Twig::iconv_convert( 'latin1');
   my $t = XML::Twig->new(output_filter => $conv);

=item :unicode_convert ($encoding)

this function is used to create a filter subroutine that will be used to 
convert the characters to the target encoding using  Unicode::Strings 
and Unicode::Map8 (which need to be installed, look at the documentation 
for the modules to find out which encodings are available on your system)

   my $conv = XML::Twig::unicode_convert( 'latin1');
   my $t = XML::Twig->new(output_filter => $conv);

=back

Note that the C<text> and C<att> methods do not use the filter, so their 
result are always in unicode.

=item input_filter

This option is similar to output_filter except the filter is applied to 
the characters before they are stored in the twig, at parsing time.


=item parse_start_tag

If you use the keep_encoding option then this option can be used to replace the
default parsing function. You should provide a coderef (a reference to a 
subroutine) as the argument, this subroutine takes the original tag (given
by XML::Parser::Expat original_string() method) and returns a gi and the
attributes in a hash (or in a list attribute_name/attribute value).

=item expand_external_ents

When this option is used external entities (that are defined) are expanded
when the document is output using "print" functions such as C<Lprint>>,
C<L<sprint|sprint>>, C<L<flush|flush>> and C<L<xml_string|xml_string>>. 
Note that in the twig the entity will be stored as an element whith a 
gi '#ENT', the entity will not be expanded there, so you might want to 
process the entities before outputting it. 

=item load_DTD

If this argument is set to a true value, parse or parsefile on the twig will 
load  the DTD information. This information can then be accessed through the 
twig, in a DTD_handler for example. This will load even an external DTD.

Note that to do this the module will generate a temporary file in the current
directory. If this is a problem let me know and I will add an option to
specify an alternate directory.

See L<DTD Handling|DTD Handling> for more information

=item DTD_handler

Sets a handler that will be called once the doctype (and the DTD) have been 
loaded, with 2 arguments, the twig and the DTD.

=item id

This optional argument gives the name of an attribute that can be used as
an ID in the document. Elements whose ID is known can be accessed through
the elt_id method. id defaults to 'id'.
See C<L<BUGS|BUGS>>

=item discard_spaces

If this optional argument is set to a true value then spaces are discarded
when they look non-significant: strings containing only spaces are discarded.
This argument is set to true by default.

=item keep_spaces

If this optional argument is set to a true value then all spaces in the
document are kept, and stored as PCDATA.
keep_spaces and discard_spaces cannot be both set.

=item discard_spaces_in

This argument sets keep_spaces to true but will cause the twig builder to
discard spaces in the elements listed.
The syntax for using this argument is: 
  XML::Twig->new( discard_spaces_in => [ 'elt1', 'elt2']);

=item keep_spaces_in

This argument sets discard_spaces to true but will cause the twig builder to
keep spaces in the elements listed.
The syntax for using this argument is: 
  XML::Twig->new( keep_spaces_in => [ 'elt1', 'elt2']);

=item PrettyPrint

Sets the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 
'indented', 'record' and 'record_c'

=over 4

=item none

The document is output as one ling string, with no linebreaks except those 
found within text elements

=item nsgmls

Line breaks are inserted in safe places: that is within tags, between a tag 
and an attribute, between attributes and before the > at the end of a tag.

This is quite ugly but better than C<none>, and it is very safe, the document 
will still be valid (conforming to its DTD).

This is how the SGML parser C<sgmls> splits documents, hence the name.

=item nice

This option inserts line breaks before any tag that does not contain text (so
element with textual content are not broken as the \n is the significant).

B<WARNING>: this option leaves the document well-formed but might make it
invalid (not conformant to its DTD). If you have elements declared as

  <!ELEMENT foo (#PCDATA|bar)>

then a C<foo> element including a C<bar> one will be printed as

  <foo>
  <bar>bar is just pcdata</bar>
  </foo>

This is invalid, as the parser will take the line break after the foo tag as a
sign that the element contains PCDATA, it will then die when it finds the 
C<bar> tag. This may or may not be important for you, but be aware of it!

=item indented

Same as C<nice> (and with the same warning) but indents elements according to 
their level 

=item record

This is a record_oriented pretty print, that display data in records, one field 
per line (which looks a LOT like C<indented>)

=item record_c

Stands for record compact, one record per line

=back


=item EmptyTags

Sets the empty tag display style (normal, html or expand).

=item comments

Sets the way comments are processed: drop (default), keep or process

=over 4

=item drop

drops the comments, they are not read, nor printed to the output

=item keep

comments are loaded and will appear on the output, they are not 
accessible within the twig and will not interfere with processing
though

B<Bug>: comments in the middle of a text element such as 

  <p>text <!-- comment --> more text --></p>

are output at the end of the text:

  <p>text  more text <!-- comment --></p>

=item process

comments are loaded in the twig and will be treated as regular elements 
(their C<gi> is C<#COMMENT>) this can interfere with processing if you
expect C<< $elt->first_child >> to be an element but find a comment there.
Validation will not protect you from this as comments can happen anywhere.
You can use C<< $elt->first_child( 'gi') >> (which is a good habit anyway)
to get where you want. Consider using 

=back

=item pi

Sets the way processing instructions are processed: C<drop>, C<keep> 
(default) or C<process>

Note that you can also set PI handlers in the twig_handlers option: 

  '?'       => \&handler
  '?target' => \&handler 2

The handlers will be called with 2 parameters, the twig and the PI element if
pi is set to C<process>, and with 3, the twig, the target and the data if pi
is set to C<keep>. Of course they will not be called if PI is set to C<drop>.

If pi is set to C<keep> the handler should return a string that will be used
as-is as the PI text (it should look like "C< <?target data?> >" or '' if you
want to remove the PI), 

Only one handler will be called, C<?target> or C<?> if no specific handler for
that target is available.


=back

B<Note>: I _HATE_ the Java-like name of arguments used by most XML modules. 
As XML::Twig is based on XML::Parser I kept the style, but you can also use
a more perlish naming convention, using C<twig_print_outside_roots> instead
of C<twig_print_outside_roots> or C<pretty_print> instead of C<PrettyPrint>,
XML::Twig then normalizes all the argument names. 

=item parse(SOURCE [, OPT => OPT_VALUE [...]])

This method is inherited from XML::Parser.
The SOURCE parameter should either be a string containing the whole XML
document, or it should be an open IO::Handle. Constructor options to
XML::Parser::Expat given as keyword-value pairs may follow the SOURCE
parameter. These override, for this call, any options or attributes passed
through from the XML::Parser instance.

A die call is thrown if a parse error occurs. Otherwise it will return 
the twig built by the parse. Use I<safe_parse> if you want the parsing
to return even when an error occurs.

=item parsestring

This is just an alias for parse for backwards compatibility.

=item parsefile(FILE [, OPT => OPT_VALUE [...]])

This method is inherited from XML::Parser.

Open FILE for reading, then call parse with the open handle. The file
is closed no matter how parse returns. 

A die call is thrown if a parse error occurs. Otherwise it will return 
the twig built by the parse. Use I<safe_parsefile> if you want the parsing
to return even when an error occurs.

=item parseurl $url $optionnal_user_agent

Gets the data from the url and parse it. Note that the data is piped to the
parser in chunks the size of the XML::Parser::Expat buffer, so memory 
consumption and hopefully speed are optimal.

If the $optionnal_user_agent argument is used then it is used, otherwise a
new one is created.

=item safe_parse( SOURCE [, OPT => OPT_VALUE [...]])

This method is similar to I<parse> except that it wraps the parsing in an
eval block. It returns the twig on success and 0 on failure (the twig object
also contains the parsed twig). $@ contains the error message on failure.

Note that the parsing still stops as soon as an error is detected, there is
no way to keep going after an error.

=item safe_parsefile(FILE [, OPT => OPT_VALUE [...]])

This method is similar to I<parsefile> except that it wraps the parsing in an
eval block. It returns the twig on success and 0 on failure (the twig object
also contains the parsed twig) . $@ contains the error message on failure

Note that the parsing still stops as soon as an error is detected, there is
no way to keep going after an error.

=item safe_parseurl $url $optional_user_agent

Same as I<parseurl> except that it wraps the parsing in an eval block. It 
returns the twig on success and 0 on failure (the twig object also contains
the parsed twig) . $@ contains the error message on failure

=item parser

This method returns the expat object (actually the XML::Parser::Expat object) 
used during parsing. It is useful for example to call XML::Parser::Expat methods
on it. To get the line of a tag for example use $t->parser->current_line.

=item setTwigHandlers ($handlers)

Set the Twig handlers. $handlers is a reference to a hash similar to the
one in the TwigHandlers option of new. All previous handlers are unset.
The method returns the reference to the previous handlers.

=item setTwigHandler ($gi $handler)

Set a single Twig handlers for the $gi element. $handler is a reference to 
a subroutine. If the handler was previously set then the reference to the
previous handler is returned.

=item setStartTagHandlers ($handlers)

Set the StartTag handlers. $handlers is a reference to a hash similar to the
one in the start_tag_handlers option of new. All previous handlers are unset.
The method returns the reference to the previous handlers.

=item setStartTagHandler ($gi $handler)

Set a single StartTag handlers for the $gi element. $handler is a reference to 
a subroutine. If the handler was previously set then the reference to the
previous handler is returned.

=item setEndTagHandlers ($handlers)

Set the EndTag handlers. $handlers is a reference to a hash similar to the
one in the end_tag_handlers option of new. All previous handlers are unset.
The method returns the reference to the previous handlers.

=item setEndTagHandler ($gi $handler)

Set a single EndTag handlers for the $gi element. $handler is a reference to 
a subroutine. If the handler was previously set then the reference to the
previous handler is returned.


=item setTwigHandlers ($handlers)

Set the Twig handlers. $handlers is a reference to a hash similar to the
one in the twig_handlers option of new.


=item dtd

Returns the dtd (an XML::Twig::DTD object) of a twig

=item root

Returns the root element of a twig

=item first_elt ($optionnal_gi)

Returns the first element whose gi is $optionnal_gi of a twig, if
no $optionnal_gi is given then the root is returned

=item elt_id        ($id)

Returns the element whose id attribute is $id

=item entity_list

Returns the entity list of a twig

=item change_gi      ($old_gi, $new_gi)

Performs a (very fast) global change. All elements old_gi are now new_gi.
See C<L<BUGS|BUGS>>

=item flush            ($optional_filehandle, $options)

Flushes a twig up to (and including) the current element, then deletes
all unnecessary elements from the tree that's kept in memory.
flush keeps track of which elements need to be open/closed, so if you
flush from handlers you don't have to worry about anything. Just keep 
flushing the twig every time you're done with a sub-tree and it will
come out well-formed. After the whole parsing don't forget to flush
one more time to print the end of the document.
The doctype and entity declarations are also printed.

flush take an optional filehandle as an argument.

options: use the Update_DTD option if you have updated the (internal) DTD 
and/or the entity list and you want the updated DTD to be output 

The PrettyPrint option sets the pretty printing of the document.

   Example: $t->flush( Update_DTD => 1);
            $t->flush( \*FILE, Update_DTD => 1);
            $t->flush( \*FILE);


=item flush_up_to ($elt, $optionnal_filehandle, %options)

Flushes up to the $elt element. This allows you to keep part of the
tree in memory when you flush.

options: see flush.

=item purge

Does the same as a flush except it does not print the twig. It just deletes
all elements that have been completely parsed so far.

=item purge_up_to ($elt)

Purges up to the $elt element. This allows you to keep part of the tree in 
memory when you flush.

=item print            ($optional_filehandle, %options)

Prints the whole document associated with the twig. To be used only AFTER the
parse.
 
options: see flush.

=item sprint

Returns the text of the whole document associated with the twig. To be used only
AFTER the parse.

options: see flush.

=item ignore

This method can B<only> be called in start_tag_handlers. It causes the element
to be skipped during the parsing: the twig is not built for this element, it 
will not be accessible during parsing or after it. The element will not take
up any memory and parsing will be faster.

Note that this method can also be called on an element. If the element is a 
parent of the current element then this element will be ignored (the twig will
not be built any more for it and what has already been built will be deleted)


=item set_pretty_print  ($style)

Sets the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 
'indented', 'record' and rec'record'ord_c

B<WARNING:> the pretty print style is a B<GLOBAL> variable, so once set it's
applied to B<ALL> print's (and sprint's). Same goes if you use XML::Twig
with mod_perl . This should not be a problem as the XML that's generated 
is valid anyway, and XML processors (as well as HTML processors, including
browsers) should not care. Let me know if this is a big problem, but at the
moment the performance/cleanliness trade-off clearly favors the global 
approach.

=item set_empty_tag_style  ($style)

Sets the empty tag display style (normal, html or expand). As with 
set_pretty_print this sets a global flag.  

normal outputs an empty tag '<tag/>', html adds a space '<tag /> and
expand outputs '<tag></tag>'

=item print_prolog     ($optional_filehandle, %options)

Prints the prolog (XML declaration + DTD + entity declarations) of a document.

options: see flush.

=item prolog     ($optional_filehandle, %options)

Returns the prolog (XML declaration + DTD + entity declarations) of a document.

options: see flush.

=item finish

Call Expat finish method.
Unsets all handlers (including internal ones that set context), but expat
continues parsing to the end of the document or until it finds an error.
It should finish up a lot faster than with the handlers set.

=item finish_print

Stop twig processing, flush the twig and proceed to finish printing the 
document as fast as possible. Use this method when modifying a document and 
the modification is done. 

=item Methods inherited from XML::Parser::Expat

A twig inherits all the relevant methods from XML::Parser::Expat. These 
methods can only be used during the parsing phase (they will generate
a fatal error otherwise).

Inherited methods are:

  depth in_element within_element context
  current_line current_column current_byte position_in_context
  base current_element element_index 
  namespace eq_name generate_ns_name new_ns_prefixes expand_ns_prefix current_ns_prefixes
  recognized_string original_string 
  xpcroak xpcarp 
                           

=item path($gi)

Returns the element context in a form similar to XPath's short
form: '/root/gi1/../gi'

=item get_xpath  ($xpath, $optional_offset)

Performs a get_xpath on the document root (see <Elt|"Elt">)

=item find_nodes

same as get_xpath

=item dispose

Useful only if you don't have WeakRef installed.

Reclaims properly the memory used by an XML::Twig object. As the object has
circular references it never goes out of scope, so if you want to parse lots 
of XML documents then the memory leak becomes a problem. Use $twig->dispose
to clear this problem.

=back 


=head2 Elt

=over 4

=item print         ($optional_filehandle, $optional_pretty_print_style)

Prints an entire element, including the tags, optionally to a 
$optional_filehandle, optionally with a $pretty_print_style.

The print outputs XML data so base entities are escaped.

=item sprint       ($elt, $optional_no_enclosing_tag)

Returns the xml string for an entire element, including the tags. 
If the optional second argument is true then only the string inside the 
element is returned (the start and end tag for $elt are not).
The text is XML-escaped: base entities (& and < in text, & < and " in
attribute values) are turned into entities.

=item gi                       

Returns the gi of the element (the gi is the C<generic identifier> the tag
name in SGML parlance).

=item tag

Same as L<gi|gi>

=item set_gi         ($gi)

Sets the gi (tag) of an element

=item set_tag        ($gi)

Sets the tag (=L<gi|gi>) of an element

=item root 

Returns the root of the twig in which the element is contained.

=item twig 

Returns the twig containing the element. 

=item parent        ($optional_cond)

Returns the parent of the element, or the first ancestor matching the 
L<cond|cond>

=item first_child   ($optional_cond)

Returns the first child of the element, or the first child matching the 
L<cond|cond>

=item first_child_text   ($optional_cond)

Returns the text of the first child of the element, or the first child
If there is no first_child then returns ''. This avoids getting the
child, checking for its existence then getting the text for trivial cases.

Similar methods are available for the other navigation methods: 
C<last_child_text>, C<prev_sibling_text>, C<next_sibling_text>,
C<prev_elt_text>, C<next_elt_text>, C<child_text>, C<parent_text>

=item field         ($optional_cond)

Same method as first_child_text with a different name

=item first_child_matches   ($optional_cond)

Returns the element if the first child of the element (if it exists) passes
the $cond, C<undef> otherwise

  if( $elt->first_child_matches( 'title')) ... 

is equivalent to

  if( $elt->first_child && $elt->first_child->passes( 'title')) 

C<first_child_is> is an other name for this method

Similar methods are available for the other navigation methods: 
C<last_child_matches>, C<prev_sibling_matches>, C<next_sibling_matches>,
C<prev_elt_matches>, C<next_elt_matches>, C<child_matches>, 
C<parent_matches>

=item prev_sibling  ($optional_cond)

Returns the previous sibling of the element, or the previous sibling matching
L<cond|cond>

=item next_sibling  ($optional_cond)

Returns the next sibling of the element, or the first one matching L<cond|cond>. 

=item next_elt     ($optional_elt, $optional_cond)

Returns the next elt (optionally matching L<cond|cond>) of the element. This is 
defined as the next element which opens after the current element opens.
Which usually means the first child of the element.
Counter-intuitive as it might look this allows you to loop through the
whole document by starting from the root.

The $optional_elt is the root of a subtree. When the next_elt is out of the
subtree then the method returns undef. You can then walk a sub tree with:

  my $elt= $subtree_root;
  while( $elt= $elt->next_elt( $subtree_root)
    { # insert processing code here
    }

=item prev_elt     ($optional_cond)

Returns the previous elt (optionally matching L<cond|cond>) of the
element. This is the first element which opens before the current one.
It is usually either the last descendant of the previous sibling or
simply the parent


=item children     ($optional_cond)

Returns the list of children (optionally which matches L<cond|cond>) of the
element. The list is in document order.

=item descendants     ($optional_cond)

Returns the list of all descendants (optionally which matches L<cond|cond>)
of the element. This is the equivalent of the getElementsByTagName of the DOM
(by the way, if you are really a DOM addict, you can use C<getElementsByTagName>
instead)

=item descendants_or_self ($optional_cond)

Same as descendants except that the element itself is included in the list
if it matches the $optional_cond

=item ancestors    ($optional_cond)

Returns the list of ancestors (optionally matching L<cond|cond>) of the element.
The list is ordered from the innermost ancestor to the outtermost one

NOTE: the element itself is not part of the list, in order to include it 
you will have to write:

  my @array= ($elt, $elt->ancestors)

=item att          ($att)

Returns the attribute value or C<undef>

=item set_att      ($att, $att_value)

Sets the attribute of the element to the given value

You can actually set several attributes this way:

  $elt->set_att( att1 => "val1", att2 => "val2");

=item del_att      ($att)

Delete the attribute for the element

You can actually delete several attributes at once:

  $elt->del_att( 'att1', 'att2', 'att3');


=item cut

Cuts the element from the tree. The element still exists, it can be copied
or pasted somewhere else, it is just not attached to the tree anymore.

=item copy        ($elt)

Returns a copy of the element. The copy is a "deep" copy: all sub elements of 
the element are duplicated.

=item paste       ($optional_position, $ref)

Pastes a (previously cut or newly generated) element. Dies if the element
already belongs to a tree.

The optional position element can be:

=over 4

=item first_child (default)

The element is pasted as the first child of the element object this
method is called on.

=item last_child

The element is pasted as the last child of the element object this
method is called on.

=item before

The element is pasted before the element object, as its previous
sibling.

=item after

The element is pasted after the element object, as its next sibling.

=item within

In this case an extra argument, $offset, should be supplied. The element
will be pasted in the reference element (or in its first text child) at the
given offset. To achieve this the reference element will be split at the 
offset.

=back

=item move       ($optional_position, $ref)

Move an element in the tree.
This is just a cut then a paste.  The syntax is the same as paste.

=item replace       ($ref)

Replaces an element in the tree. Sometimes it is just not possible to cut
an element then paste another in its place, so replace comes in handy.

=item delete

Cut the element and frees the memory.

=item prefix       ($text, $optional_option)

Add a prefix to an element. If the element is a PCDATA element the text
is added to the pcdata, if the elements first_child is a PCDATA then the
text is added to it's pcdata, otherwise a new PCDATA element is created 
and pasted as the first child of the element.

If the option is C<asis> then the prefix is added asis: it is created in
a separate PCDATA element with an asis property. You can then write:

  $elt1->prefix( '<b>', 'asis');

to create a C< <b> > in the output of C<print>.

=item suffix       ($text, $optional_option)

Add a suffix to an element. If the element is a PCDATA element the text
is added to the pcdata, if the elements last_child is a PCDATA then the
text is added to it's pcdata, otherwise a new PCDATA element is created 
and pasted as the last child of the element.

If the option is C<asis> then the suffix is added asis: it is created in
a separate PCDATA element with an asis property. You can then write:

  $elt2->suffix( '<b>', 'asis');

=item split_at        ($offset)

Split a text (C<PCDATA> or C<CDATA>) element in 2 at $offset, the original
element now holds the first part of the string and a new element holds the
right part. The new element is returned

If the element is not a text element then the first text child of the element
is split

=item split        ( $optional_regexp, $optional_tag, $optional_attribute_ref)

Split the text descendants of an element in place, the text is split using 
the regexp, if the regexp includes () then the matched separators will be 
wrapped in $optional_tag, with $optional_attribute_ref attributes

if $elt is C<< <p>tati tata <b>tutu tati titi</b> tata tati tata</p> >>

  $elt->split( qr/(ta)ti/, 'foo', {type => 'toto'} )

will change $elt to

  <p><foo type="toto">ta</foo> tata <b>tutu <foo type="toto">ta</foo>
      titi</b> tata <foo type="toto">ta</foo> tata</p> 

The regexp can be passed either as a string or as qr// (perl 5.005 and later),
it defaults to \s+ just as the C<split> built-in (but this would be quite a
useless behaviour without the $optional_tag parameter)

$optional_tag defaults to PCDATA or CDATA, depending on the initial element
type

The list of descendants is returned (including un-touched original elements 
and newly created ones)

=item mark        ( $regexp, $optional_tag, $optional_attribute_ref)

This method behaves exactly as L<split|split>, except only the newly created 
elements are returned

=item new          ($optional_gi, $optional_atts, @optional_content)

The gi is optional (but then you can't have a content ), the optional atts
is the ref of a hash of attributes, the content can be just a string or a 
list of strings and element. A content of '#EMPTY' creates an empty element;

 Examples: my $elt= XML::Twig::Elt->new();
           my $elt= XML::Twig::Elt->new( 'para', { align => 'center' });  
           my $elt= XML::Twig::Elt->new( 'para', { align => 'center' }, 'foo');  
	   my $elt= XML::Twig::Elt->new( 'br', '#EMPTY');
	   my $elt= XML::Twig::Elt->new( 'para');
           my $elt= XML::Twig::Elt->new( 'para', 'this is a para');  
           my $elt= XML::Twig::Elt->new( 'para', $elt3, 'another para'); 

The strings are not parsed, the element is not attached to any twig.

B<WARNING>: if you rely on ID's then you will have to set the id yourself. At
this point the element does not belong to a twig yet, so the ID attribute
is not known so it won't be strored in the ID list.

=item parse         ($string, %args)

Creates an element from an XML string. The string is actually
parsed as a new twig, then the root of that twig is returned.
The arguments in %args are passed to the twig.
As always if the parse fails the parser will die, so use an
eval if you want to trap syntax errors.

As obviously the element does not exist beforehand this method has to be 
called on the class: 

  my $elt= parse XML::Twig::Elt( "<a> string to parse, with <sub/>
                                  <elements>, actually tons of </elements>
				  h</a>");

=item get_xpath  ($xpath, $optional_offset)

Returns a list of elements satisfying the $xpath. $xpath is an XPATH-like 
expression.

A subset of the XPATH abbreviated syntax is covered:

  gi
  gi[1] (or any other positive number)
  gi[last()]
  gi[@att] (the attribute exists for the element)
  gi[@att="val"]
  gi[@att=~ /regexp/]
  gi[att1="val1" and att2="val2"]
  gi[att1="val1" or att2="val2"]
  gi[string()="toto"] (returns gi elements which text (as per the text method) 
                       is toto)
  gi[string()=~/regexp/] (returns gi elements which text (as per the text 
                          method) matches regexp)
  expressions can start with / (search starts at the document root)
  expressions can start with . (search starts at the current element)
  // can be used to get all descendants instead of just direct children
  * matches any gi
  
So the following examples from the XPATH recommendation 
(http://www.w3.org/TR/xpath.html#path-abbrev) work:

  para selects the para element children of the context node
  * selects all element children of the context node
  para[1] selects the first para child of the context node
  para[last()] selects the last para child of the context node
  */para selects all para grandchildren of the context node
  /doc/chapter[5]/section[2] selects the second section of the fifth chapter 
     of the doc 
  chapter//para selects the para element descendants of the chapter element 
     children of the context node
  //para selects all the para descendants of the document root and thus selects
     all para elements in the same document as the context node
  //olist/item selects all the item elements in the same document as the 
     context node that have an olist parent
  .//para selects the para element descendants of the context node
  .. selects the parent of the context node
  para[@type="warning"] selects all para children of the context node that have
     a type attribute with value warning 
  employee[@secretary and @assistant] selects all the employee children of the
     context node that have both a secretary attribute and an assistant 
     attribute


The elements will be returned in the document order.

If $optional_offset is used then only one element will be returned, the one 
with the appropriate offset in the list, starting at 0

Quoting and interpolating variables can be a pain when the Perl syntax and the 
XPATH syntax collide, so here are some more examples to get you started:

  my $p1= "p1";
  my $p2= "p2";
  my @res= $t->get_xpath( "p[string( '$p1') or string( '$p2')]");

  my $a= "a1";
  my @res= $t->get_xpath( "//*[@att=\"$a\"]);

  my $val= "a1";
  my $exp= "//p[ \@att='$val']"; # you need to use \@ or you will get a warning
  my @res= $t->get_xpath( $exp);

XML::Twig does not provide full XPATH support. If that's what you want then 
look no further than the XML::XPath module on CPAN.

Note that the only supported regexps delimiters are / and that you must 
backslash all / in regexps AND in regular strings.

=item find_nodes

same as get_xpath

=item text

Returns a string consisting of all the PCDATA and CDATA in an element, 
without any tags. The text is not XML-escaped: base entities such as &
and < are not escaped.

=item set_text        ($string)

Sets the text for the element: if the element is a PCDATA, just set its
text, otherwise cut all the children of the element and create a single
PCDATA child for it, which holds the text.

=item insert         ($gi1, [$optional_atts1], $gi2, [$optional_atts2],...)

For each gi in the list inserts an element $gi as the only child of the 
element.  The element gets the optional attributes in $optional_attsn.
All children of the element are set as children of the new element.
The upper level element is returned.

  $p->insert( table => { border=> 1}, 'tr', 'td') 

puts $p in a table with a visible border, a single tr and a single td and
returns the table element:

  <p><table border="1"><tr><td>original content of p</td></tr></table></p>

=item wrap_in        (@gi)

Wraps elements $gi as the successive ancestors of the element, returns the 
new element.
$elt->wrap_in( 'td', 'tr', 'table') wraps the element as a single cell in a 
table for example.

=item insert_new_elt $opt_position, $gi, $opt_atts_hashref, @opt_content

Combines a C<L<new|new>> and a C<L<paste|paste>>: creates a new element using 
$gi, $opt_atts_hashref and @opt_content which are arguments similar to those for
C<new>, then paste it, using $opt_position or C<'first_child'>, relative to 
$elt.

Returns the newly created element

=item erase

Erases the element: the element is deleted and all of its children are
pasted in its place.

=item set_content    ( $optional_atts, @list_of_elt_and_strings)
                     ( $optional_atts, '#EMPTY')

Sets the content for the element, from a list of strings and
elements.  Cuts all the element children, then pastes the list
elements as the children.  This method will create a PCDATA element
for any strings in the list.

The optional_atts argument is the ref of a hash of attributes. If this
argument is used then the previous attributes are deleted, otherwise they
are left untouched. 

B<WARNING>: if you rely on ID's then you will have to set the id yourself. At
this point the element does not belong to a twig yet, so the ID attribute
is not known so it won't be strored in the ID list.

A content of '#EMPTY' creates an empty element;

=item inherit_att  ($att, @optional_gi_list)

Returns the value of an attribute inherited from parent tags. The value
returned is found by looking for the attribute in the element then in turn
in each of its ancestors. If the @optional_gi_list is supplied only those
ancestors whose gi is in the list will be checked. 

=item all_children_are ($cond)

returns 1 if all children of the element pass the condition, 0 otherwise

=item level       ($optional_gi)

Returns the depth of the element in the twig (root is 0).
If the optional gi is given then only ancestors of the given type are counted.
 
B<WARNING>: in a tree created using the twig_roots option this will not return
the level in the document tree, level 0 will be the document root, level 1 
will be the twig_roots elements. During the parsing (in a TwigHandler)
you can use the depth method on the twig object to get the real parsing depth.

=item in           ($potential_parent)

Returns true if the element is in the potential_parent ($potential_parent is an element)

=item in_context   ($gi, $optional_level)

Returns true if the element is included in an element whose gi is $gi,
optionally within $optional_level levels. The returned value is the including
element.

=item pcdata

Returns the text of a PCDATA element or undef if the element is not PCDATA.

=item pcdata_xml_string

Returns the text of a PCDATA element or undef if the element is not PCDATA. 
The text is "XML-escaped" ('&' and '<' are replaced by '&amp;' and '&lt;')

=item set_pcdata     ($text)

Sets the text of a PCDATA element. 

=item append_pcdata  ($text)

Add the text at the end of a #PCDATA element.

=item is_cdata

Returns 1 if the element is a #CDATA element, returns 0 otherwise.

=item is_text

Returns 1 if the element is a #CDATA or #PCDATA element, returns 0 otherwise.

=item cdata

Returns the text of a CDATA element or undef if the element is not CDATA.

=item set_cdata     ($text)

Sets the text of a CDATA element. 

=item append_cdata  ($text)

Add the text at the end of a #CDATA element.

=item extra_data 

Returns the extra_data (comments and PI's) attached to an element

=item set_extra_data

Sets the extra_data (comments and PI's) attached to an element

=item append_extra_data

Append extra_data to teh existing extra_data before the element (if no
previous extra_data exists then it is created)

=item set_asis

Sets a property of the element that causes it to be output without being XML
escaped by the print functions: if it contains C<a < b> it will be output as
such and not as C<< a > b >>. This can be useful to create text elements that 
will be output as markup. Note that all PCDATA descendants of the element
are also marked as having the property (they are the ones impacted by the
change).

=item set_not_asis

Unsets the asis property for the element and its text descendants.

=item is_asis

Returns the asis property status of the element ( 1 or C<undef>)

=item closed                   

Returns true if the element has been closed. Might be usefull if you are
somewhere in the tree, during the parse, and have no idea whether a parent
element is completely loaded or not.

=item get_type

Returns the type of the element: '#ELT' for "real" elements, or '#PCDATA',
'#CDATA', '#COMMENT', '#ENT', '#PI'

=item is_elt

Returns the gi if the element is a "real" element, or 0 if it is PCDATA, 
CDATA...

=item contains_only_text

Returns 1 if the element does not contain any other "real" element

=item is_field

same as contains_only_text

=item is_pcdata

Returns 1 if the element is a #PCDATA element, returns 0 otherwise.

=item is_empty

Returns 1 if the element is empty, 0 otherwise

=item set_empty

Flags the element as empty. No further check is made, so if the element
is actually not empty the output will be messed. The only effect of this 
method is that the output will be <gi att="value""/>.

=item set_not_empty

Flags the element as not empty. if it is actually empty then the element will
be output as <gi att="value""></gi>

=item child ($offset, $optional_gi)

Returns the $offset-th child of the element, optionally the $offset-th child 
with a gi of $optional_gi. The children are treated as a list, so 
$elt->child( 0) is the first child, while $elt->child( -1) is the last child.

=item child_text ($offset, $optional_gi)

Returns the text of a child or undef if the sibling does not exist. Arguments
are the same as child.

=item last_child    ($optional_gi)

Returns the last child of the element, or the last child whose gi is 
$optional_gi (ie the last of the element children whose gi matches).

=item last_child_text   ($optional_gi)

Same as first_child_text but for the last child.

=item sibling  ($offset, $optional_gi)

Returns the next or previous $offset-th sibling of the element, or the 
$offset-th one whose gi is $optional_gi. If $offset is negative then a 
previous sibling is returned, if $offset is positive then  a next sibling is 
returned. $offset=0 returns the element if there is no $optional_gi or if the 
element gi matches $optional_gi, undef otherwise.

=item sibling_text ($offset, $optional_gi)

Returns the text of a sibling or undef if the sibling does not exist. 
Arguments are the same as sibling.

=item prev_siblings ($optional_gi)

Returns the list of previous siblings (optionaly whose gi is $optional_gi)
for the element. The elements are ordered in document order.

=item next_siblings ($optional_gi)

Returns the list of siblings (optionaly whose gi is $optional_gi)
following the element. The elements are ordered in document order.


=item atts

Returns a hash ref containing the element attributes

=item set_atts      ({att1=>$att1_val, att2=> $att2_val... })

Sets the element attributes with the hash ref supplied as the argument

=item del_atts

Deletes all the element attributes.

=item att_names

returns a list of the attribute names for the element

=item att_xml_string ($att, $optional_quote)

Returns the attribute value, where '&', '<' and $quote (" by default)
are XML-escaped

=item set_id       ($id)

Sets the id attribute of the element to the value.
See C<L<elt_id|elt_id>> to change the id attribute name

=item id

Gets the id attribute value

=item del_id       ($id)

Deletes the id attribute of the element and remove it from the id list
for the document

=item DESTROY

Frees the element from memory.

=item start_tag

Returns the string for the start tag for the element, including 
the /> at the end of an empty element tag

=item end_tag

Returns the string for the end tag of an element.  For an empty
element, this returns the empty string ('').

=item xml_string ($elt)

Equivalent to $elt->sprint( 1), returns the string for the entire element, 
excluding the element's tags (but nested element tags are present)

=item set_pretty_print ($style)

Sets the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 
'indented', 'record' and 'record_c'

=over 4

=item none

the default, no \n is used

=item nsgmls

nsgmls style, with \n added within tags

=item nice

adds \n wherever possible (NOT SAFE, can lead to invalid XML)

=item indented

same as nice plus indents elements (NOT SAFE, can lead to invalid XML) 

=item record

table-oriented pretty print, one field per line 

=item record_c

table-oriented pretty print, more compact than record, one record per line 

=back

=item set_empty_tag_style ($style)

Sets the method to output empty tags, amongst 'normal' (default), 'html',
and 'expand', 

=item set_indent ($string)

Sets the indentation for the indented pretty print style (default is 2 spaces)

=item set_quote ($quote)

Sets the quotes used for attributes. can be 'double' (default) or 'single'

=item cmp       ($elt)
  Compare the order of the 2 elements in a twig.

  $a is the <A>..</A> element, $b is the <B>...</B> element
  
  document                        $a->cmp( $b)
  <A> ... </A> ... <B>  ... </B>     -1
  <A> ... <B>  ... </B> ... </A>     -1
  <B> ... </B> ... <A>  ... </A>      1
  <B> ... <A>  ... </A> ... </B>      1
   $a == $b                           0
   $a and $b not in the same tree   undef

=item before       ($elt)

Returns 1 if $elt starts before the element, 0 otherwise. If the 2 elements 
are not in the same twig then return undef.

    if( $a->cmp( $b) == -1) { return 1; } else { return 0; }

=item after       ($elt)

Returns 1 if $elt starts after the element, 0 otherwise. If the 2 elements 
are not in the same twig then return undef.

    if( $a->cmp( $b) == -1) { return 1; } else { return 0; }

=item path

Returns the element context in a form similar to XPath's short
form: '/root/gi1/../gi'

=item private methods

=over 4

=item set_parent        ($parent)

=item set_first_child   ($first_child)

=item set_last_child    ($last_child)

=item set_prev_sibling  ($prev_sibling)

=item set_next_sibling  ($next_sibling)

=item set_twig_current

=item del_twig_current

=item twig_current

=item flushed

This method should NOT be used, always flush the twig, not an element.

=item set_flushed

=item del_flushed

=item flush

=item contains_text

=back

Those methods should not be used, unless of course you find some creative 
and interesting, not to mention useful, ways to do it.

=back

=head2 cond

Most of the navigation functions accept a condition as an optional argument
The first element (or all elements for C<L<children|children>> or 
C<L<ancestors|ancestors>>) that passes the condition is returned.

The condition can be 

=over 4

=item #ELT

return a "real" element (not a PCDATA, CDATA, comment or pi element) 

=item #TEXT

return a PCDATA or CDATA element

=item XPath expression

actually a subset of XPath that makes sense in this context

  gi
  /regexp/
  gi[@att]
  gi[@att="val"]
  gi[@att=~/regexp/]
  gi[text()="blah"]
  gi[text(subelt)="blah"]
  gi[text()=~ /blah/]
  gi[text(subelt)=~ /blah/]
  *[@att]            (the * is actually optional)
  *[@att="val"]
  *[@att=~/regexp/]

=item regular expression

return an element whose gi matches the regexp. The regexp has to be created 
with C<qr//> (hence this is available only on perl 5.005 and above)

=item code reference

applies the code, passing the current element as argument, if the code returns
true then the element is returned, if it returns false then the code is applied
to the next candidate.

=back

=head2 Entity_list

=over 4

=item new

Creates an entity list.

=item add         ($ent)

Adds an entity to an entity list.

=item delete     ($ent or $gi).

Deletes an entity (defined by its name or by the Entity object)
from the list.

=item print      ($optional_filehandle)

Prints the entity list.

=back


=head2 Entity

=over 4

=item new        ($name, $val, $sysid, $pubid, $ndata)

Same arguments as the Entity handler for XML::Parser.

=item print       ($optional_filehandle)

Prints an entity declaration.

=item text

Returns the entity declaration text.

=back


=head1 EXAMPLES

See the test file in t/test[1-n].t 
Additional examples (and a complete tutorial) can be found at 
http://www.xmltwig.com/

To figure out what flush does call the following script with an
 xml file and an element name as arguments

  use XML::Twig;

  my ($file, $elt)= @ARGV;
  my $t= XML::Twig->new( twig_handlers => 
      { $elt => sub {$_[0]->flush; print "\n[flushed here]\n";} });
  $t->parsefile( $file, ErrorContext => 2);
  $t->flush;
  print "\n";



=head1 NOTES


=head2 DTD Handling

There are 3 possibilities here.  They are:

=over 4

=item No DTD

No doctype, no DTD information, no entity information, the world is simple...

=item Internal DTD

The XML document includes an internal DTD, and maybe entity declarations.

If you use the load_DTD option when creating the twig the DTD information and
the entity declarations can be accessed.

The DTD and the entity declarations will be flush'ed (or print'ed) either as is
(if they have not been modified) or as reconstructed (poorly, comments are lost, 
order is not kept, due to it's content this DTD should not be viewed by anyone) 
if they have been modified. You can also modify them directly by changing the 
$twig->{twig_doctype}->{internal} field (straight from XML::Parser, see the 
Doctype handler doc)

=item External DTD

The XML document includes a reference to an external DTD, and maybe entity 
declarations.

If you use the load_DTD when creating the twig the DTD information and the 
entity declarations can be accessed. The entity declarations will be flush'ed 
(or print'ed) either as is (if they have not been modified) or as reconstructed 
(badly, comments are lost, order is not kept).

You can change the doctype through the $twig->set_doctype method and print the
dtd through the $twig->dtd_text or $twig->dtd_print methods.

If you need to modify the entity list this is probably the easiest way to do it.

=back


=head2 Flush

If you set handlers and use flush, do not forget to flush the twig one
last time AFTER the parsing, or you might be missing the end of the document.

Remember that element handlers are called when the element is CLOSED, so
if you have handlers for nested elements the inner handlers will be called
first. It makes it for example trickier than it would seem to number nested
clauses.



=head1 BUGS

=over 4

=item entity handling

Due to XML::Parser behaviour, non-base entities in attribute values disappear:
C<att="val&ent;"> will be turned into att => val, unless you use the 
C<keep_encoding> argument to C<< XML::Twig->new >> 

=item DTD handling

Basically the DTD handling methods are competely bugged. No one uses them and it
seems very difficult to get them to work in all cases, including with 2 
slightly incompatible versions of XML::Parser.

So use XML::Twig with standalone documents, or with documents refereing to an
external DTD, but don't expect it to properly parse and even output back the
DTD.

=item memory leak

If you use a lot of twigs you might find that you leak quite a lot of memory
(about 2Ks per twig). You can use the C<L<dispose|dispose>> method to free that
memory after you are done.

If you create elements the same thing might happen, use the C<L<delete|delete>>
method to get rid of them.

Alternatively installing the WeakRef module on a version of Perl that supports
it will get rid of the memory leaks automagically.

=item ID list

The ID list is NOT updated when ID's are modified or elements cut or
deleted.

=item change_gi

This method will not function properly if you do:

     $twig->change_gi( $old1, $new);
     $twig->change_gi( $old2, $new);
     $twig->change_gi( $new, $even_newer);

=item sanity check on XML::Parser method calls

XML::Twig should really prevent calls to some XML::Parser methods, especially 
the setHandlers method.

=back

=head1 Globals

These are the things that can mess up calling code, especially if threaded.
They might also cause problem under mod_perl. 

=over 4

=item Exported constants

Whether you want them or not you get them! These are subroutines to use
as constant when creating or testing elements

=over 4

=item PCDATA

returns '#PCDATA'

=item CDATA

returns '#CDATA'

=item PI

returns '#PI', I had the choice between PROC and PI :--(

=back

=item Module scoped values: constants

these should cause no trouble:

  %base_ent= ( '>' => '&gt;',
               '<' => '&lt;',
               '&' => '&amp;',
               "'" => '&apos;',
               '"' => '&quot;',
             );
  CDATA_START   = "<![CDATA[";
  CDATA_END     = "]]>";
  PI_START      = "<?";
  PI_END        = "?>";
  COMMENT_START = "<!--";
  COMMENT_END   = "-->";

pretty print styles

  ( $NSGMLS, $NICE, $INDENTED, $RECORD1, $RECORD2)= (1..5);

empty tag output style

  ( $HTML, $EXPAND)= (1..2);

=item Module scoped values: might be changed

Most of these deal with pretty printing, so the worst that can
happen is probably that XML output does not look right, but is
still valid and processed identically by XML processors.

$empty_tag_style can mess up HTML bowsers though and changing $ID 
would most likely create problems.

  $pretty=0;           # pretty print style
  $quote='"';          # quote for attributes
  $INDENT= '  ';       # indent for indented pretty print
  $empty_tag_style= 0; # how to display empty tags
  $ID                  # attribute used as a gi ('id' by default)

=item Module scoped values: definitely changed

These 2 variables are used to replace gi's by an index, thus 
saving some space when creating a twig. If they really cause
you too much trouble, let me know, it is probably possible to
create either a switch or at least a version of XML::Twig that 
does not perform this optimisation.

  %gi2index;     # gi => index
  @index2gi;     # list of gi's

=back

=head1 TODO 

=over 4

=item SAX handlers

Allowing XML::Twig to work on top of any SAX parser, and to emit SAX
events to a handler is a priority for version 3.01

=item multiple twigs are not well supported

A number of twig features are just global at the moment. These include
the ID list and the "gi pool" (if you use change_gi then you change the gi 
for ALL twigs).

A future version will try to support this while trying not to be to
hard on performance (at least when a single twig is used!).


=back


=head1 BENCHMARKS

You can use the C<benchmark_twig> file to do additional benchmarks.
Please send me benchmark information for additional systems.

=head1 AUTHOR

Michel Rodriguez <m.v.rodriguez@ieee.org>

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

Bug reports and comments to m.v.rodriguez@ieee.org

The XML::Twig page is at http://www.xmltwig.com/xmltwig/
It includes examples and a tutorial at 
  http://www.xmltwig.com/xmltwig/tutorial/index.html

=head1 SEE ALSO

XML::Parser


=cut