File: TextToHTML.pm

package info (click to toggle)
txt2html 2.23-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 552 kB
  • ctags: 135
  • sloc: perl: 2,993; makefile: 2
file content (4484 lines) | stat: -rwxr-xr-x 126,705 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
#! /usr/bin/perl
#------------------------------------------------------------------------

=head1 NAME

HTML::TextToHTML - convert plain text file to HTML

=head1 SYNOPSIS

  From the command line:

    perl -MHTML::TextToHTML -e run_txt2html -- I<arguments>;
    (calls the txt2html method with the given arguments)

  From Scripts:

    use HTML::TextToHTML;
 
    # create a new object
    my $conv = new HTML::TextToHTML();

    # convert a file
    $conv->txt2html(infile=>[$text_file],
                     outfile=>$html_file,
		     title=>"Wonderful Things",
		     mail=>1,
      ]);

    # reset arguments
    $conv->args(infile=>[], mail=>0);

    # convert a string
    $newstring = $conv->process_chunk($mystring)

=head1 DESCRIPTION

HTML::TextToHTML converts plain text files to HTML.

It supports headings, tables, lists, simple character markup, and
hyperlinking, and is highly customizable. It recognizes some of the
apparent structure of the source document (mostly whitespace and
typographic layout), and attempts to mark that structure explicitly
using HTML. The purpose for this tool is to provide an easier way of
converting existing text documents to HTML format.

There are two ways to use this module:
    (1) called from a perl script
    (2) call run_txt2html from the command line

The first usage requires one to create a HTML::TextToHTML object, and
then call the txt2html or process_para method with suitable arguments.
One can also pass arguments in when creating the object, or call the
args method to pass arguments in.

The second usage allows one to pass arguments in from the command line, by
calling perl and executing the module, and calling run_txt2html which
creates an object for you and parses the command line.

Either way, the arguments are the same.  See L<OPTIONS> for the
arguments; see L<METHODS> for the methods of the HTML::TextToHTML object.

The following are the exported functions of this module:

=over 4

=item run_txt2html

    run_txt2html()

This is what is used to run this module from the command-line.  It creates
a HTML::TextToHTML object and parses the command-line arguments, and passes
them to the object, and runs the txt2html method.  It takes no arguments.

=back 4

=head1 OPTIONS

All arguments can be set when the object is created, and further options
can be set when calling the actual txt2html method. Arguments
to methods can take either a hash of arguments, or a reference to an
array (which will then be processed as if it were a command-line, which
makes this easy to use from scripts even if you don't wish to use
the commonly used Getopt::Long module in your script).

Note that all option-names must match exactly -- no abbreviations are
allowed.

The arguments get treated differently depending on whether they are
given in a hash or a reference to an array.  When the arguments are
in a hash, the argument-keys are expected to have values matching
those required for that argument -- whether that be a boolean, a string,
a reference to an array or a reference to a hash.  These will replace
any value for that argument that might have been there before.

When the arguments are in a reference to an array, it is treated
somewhat as if it were a command-line: option names are expected to
start with '--' or '-', boolean options are set to true as soon as the
option is given (no value is expected to follow),  boolean options with
the word "no" prepended set the option to false, string options are
expected to have a string value following, and those options which are
internally arrays or hashes are treated as cumulative; that is, the
value following the --option is added to the current set for that
option,  to add more, one just repeats the --option with the next value,
and in order to reset that option to empty, the special value of "CLEAR"
must be added to the list.

=over 8

=item append_file

    append_file=>I<filename>

If you want something appended by default, put the filename here.
The appended text will not be processed at all, so make sure it's
plain text or decent HTML.  i.e. do not have things like:
    Mary Andersen E<lt>kitty@example.comE<gt>
but instead, have:
    Mary Andersen &lt;kitty@example.com&gt;

(default: nothing)

=item append_head

    append_head=>I<filename>

If you want something appended to the head by default, put the filename here.
The appended text will not be processed at all, so make sure it's
plain text or decent HTML.  i.e. do not have things like:
    Mary Andersen E<lt>kitty@example.comE<gt>
but instead, have:
    Mary Andersen &lt;kitty@example.com&gt;

(default: nothing)

=item body_deco

    body_deco=>I<string>

Body decoration string: a string to be added to the BODY tag so that
one can set attributes to the BODY (such as class, style, bgcolor etc)
For example, "class='withimage'".

=item bullets

    bullets=>I<string>

This defines what single characters are taken to be "bullet" characters
for unordered lists.  Note that because this is used as a character
class, if you use '-' it must come first.
(default:-=o*\267)

=item bullets_ordered

    bullets_ordered=>I<string>

This defines what single characters are taken to be "bullet" placeholder
characters for ordered lists.  Ordered lists are normally marked by
a number or letter followed by '.' or ')' or ']' or ':'.  If an ordered
bullet is used, then it simply indicates that this is an ordered list,
without giving explicit numbers.

Note that because this is used as a character class, if you use '-' it
must come first.
(default:nothing)

=item caps_tag

    caps_tag=>I<tag>

Tag to put around all-caps lines
(default: STRONG)
If an empty tag is given, then no tag will be put around all-caps lines.

=item custom_heading_regexp

    custom_heading_regexp=>I<regexp>

Add a regexp for headings.  Header levels are assigned by regexp
in order seen When a line matches a custom header regexp, it is tagged as
a header.  If it's the first time that particular regexp has matched,
the next available header level is associated with it and applied to
the line.  Any later matches of that regexp will use the same header level.
Therefore, if you want to match numbered header lines, you could use
something like this:
    -H '^ *\d+\. \w+' -H '^ *\d+\.\d+\. \w+' -H '^ *\d+\.\d+\.\d+\. \w+'

Then lines like

                " 1. Examples "
                " 1.1. Things"
            and " 4.2.5. Cold Fusion"

Would be marked as H1, H2, and H3 (assuming they were found in that
order, and that no other header styles were encountered).
If you prefer that the first one specified always be H1, the second
always be H2, the third H3, etc, then use the -EH/--explicit-headings
option.

This is a multi-valued option.

(default: none)

=item debug
    
    debug=>1

Enable copious script debugging output (don't bother, this is for the
developer) (default: false)

=item default_link_dict

    default_link_dict=>I<filename>

The name of the default "user" link dictionary.
(default: "$ENV{'HOME'}/.txt2html.dict" -- this is the same as for
the txt2html script)

=item dict_debug

    dict_debug=>I<n>

Debug mode for link dictionaries Bitwise-Or what you want to see:
          1: The parsing of the dictionary
          2: The code that will make the links
          4: When each rule matches something
          8: When each tag is created

(default: 0)

=item doctype

    doctype=>I<doctype>

This gets put in the DOCTYPE field at the top of the document, unless it's
empty.  (default : "-//W3C//DTD HTML 3.2 Final//EN")
If --xhtml is true, the contents of this is ignored, unless it's
empty, in which case no DOCTYPE declaration is output.

=item eight_bit_clean

    eight_bit_clean=>1

disable Latin-1 character entity naming
(default: false)

=item escape_HTML_chars

    escape_HTML_chars=>1

turn & E<lt> E<gt> into &amp; &gt; &lt;
(default: true)

=item explicit_headings

    explicit_headings=>1

Don't try to find any headings except the ones specified in the
--custom_heading_regexp option.
Also, the custom headings will not be assigned levels in the order they
are encountered in the document, but in the order they are specified on
the command line.
(default: false)

=item extract

    extract=>1

Extract Mode; don't put HTML headers or footers on the result, just
the plain HTML (thus making the result suitable for inserting into
another document (or as part of the output of a CGI script).
(default: false)

=item hrule_min

    hrule_min=>I<n>

Min number of ---s for an HRule.
(default: 4)

=item indent_width

    indent_width=>I<n>

Indents this many spaces for each level of a list.
(default: 2)

=item indent_par_break

    indent_par_break=>1

Treat paragraphs marked solely by indents as breaks with indents.
That is, instead of taking a three-space indent as a new paragraph,
put in a <BR> and three non-breaking spaces instead.
(see also --preserve_indent)
(default: false)

=item infile

    infile=>\@my_files
    infile=>['chapter1.txt', 'chapter2.txt']
    "--infile", "chapter1.txt", "--infile", "chapter2.txt"

The name of the input file(s).  When the arguments are given as a hash,
this expects a reference to an array of filenames.  When the arguments
are given as a reference to an array, then the "--infile" option must
be repeated for each new file added to the list.  If you want to reset
the list to be empty, give the special value of "CLEAR".

(default:-)

=item links_dictionaries

    links_dictionaries=>\@my_link_dicts
    links_dictionaries=>['url_links.dict', 'format_links.dict']
    "--links_dictionaries", "url_links.dict", "--links_dictionaries", "format_links.dict"

File(s) to use as a link-dictionary.  There can be more than one of
these.  These are in addition to the System Link Dictionary and the User
Link Dictionary.  When the arguments are given as a hash, this expects a
reference to an array of filenames.  When the arguments are given as a
reference to an array, then the "--links_dictionaries" option must be
repeated for each new file added to the list.  If you want to reset the
list to be empty, give the special value of "CLEAR".

=item link_only

    link_only=>1

Do no escaping or marking up at all, except for processing the links
dictionary file and applying it.  This is useful if you want to use
the linking feature on an HTML document.  If the HTML is a
complete document (includes HTML,HEAD,BODY tags, etc) then you'll
probably want to use the --extract option also.
(default: false)

=item mailmode

    mailmode=>1

Deal with mail headers & quoted text
(default: false)

=item make_anchors

    make_anchors=>0

Should we try to make anchors in headings?
(default: true)

=item make_links

    make_links=>0

Should we try to build links?  If this is false, then the links
dictionaries are not consulted and only structural text-to-HTML
conversion is done.  (default: true)

=item make_tables

    make_tables=>1

Should we try to build tables?  If true, spots tables and marks them up
appropriately.  See L<Input File Format> for information on how tables
should be formatted.

This overrides the detection of lists; if something looks like a table,
it is taken as a table, and list-checking is not done for that
paragraph.

(default: false)

=item min_caps_length

    min_caps_length=>I<n>

min sequential CAPS for an all-caps line
(default: 3)

=item outfile

    outfile=>I<filename>

The name of the output file.  If it is "-" then the output goes
to Standard Output.
(default: - )

=item par_indent

    par_indent=>I<n>

Minumum number of spaces indented in first lines of paragraphs.
  Only used when there's no blank line
preceding the new paragraph.
(default: 2)

=item preformat_trigger_lines

    preformat_trigger_lines=>I<n>

How many lines of preformatted-looking text are needed to switch to <PRE>
          <= 0 : Preformat entire document
             1 : one line triggers
          >= 2 : two lines trigger

(default: 2)

=item endpreformat_trigger_lines

    endpreformat_trigger_lines=>I<n>

How many lines of unpreformatted-looking text are needed to switch from <PRE>
           <= 0 : Never preformat within document
              1 : one line triggers
           >= 2 : two lines trigger
(default: 2)

NOTE for preformat_trigger_lines and endpreformat_trigger_lines:
A zero takes precedence.  If one is zero, the other is ignored.
If both are zero, entire document is preformatted.

=item preformat_start_marker

    preformat_start_marker=>I<regexp>

What flags the start of a preformatted section if --use_preformat_marker
is true.

(default: "^(:?(:?&lt;)|<)PRE(:?(:?&gt;)|>)\$")

=item preformat_end_marker

    preformat_end_marker=>I<regexp>

What flags the end of a preformatted section if --use_preformat_marker
is true.

(default: "^(:?(:?&lt;)|<)/PRE(:?(:?&gt;)|>)\$")

=item preformat_whitespace_min

    preformat_whitespace_min=>I<n>

Minimum number of consecutive whitespace characters to trigger
normal preformatting. 
NOTE: Tabs are expanded to spaces before this check is made.
That means if B<tab_width> is 8 and this is 5, then one tab may be
expanded to 8 spaces, which is enough to trigger preformatting.
(default: 5)

=item prepend_file

    prepend_file=>I<filename>

If you want something prepended to the processed body text, put the
filename here.  The prepended text will not be processed at all, so make
sure it's plain text or decent HTML.

(default: nothing)

=item preserve_indent

    preserve_indent=>1

Preserve the first-line indentation of paragraphs marked with indents
by replacing the spaces of the first line with non-breaking spaces.
(default: false)

=item short_line_length

    short_line_length=>I<n>

Lines this short (or shorter) must be intentionally broken and are kept
that short.
(default: 40)

=item style_url

    style_url=>I<url>

This gives the URL of a stylesheet; a LINK tag will be added to the
output.

=item system_link_dict

    system_link_dict=>I<filename>

The name of the default "system" link dictionary.
(default: "/usr/share/txt2html/txt2html.dict")

=item tab_width

    tab_width=>I<n>

How many spaces equal a tab?
(default: 8)

=item table_type
    
    table_type=>{ ALIGN=>0, PGSQL=>0, BORDER=>1, DELIM=>0 }

This determines which types of tables will be recognised when "make_tables"
is true.  The possible types are ALIGN, PGSQL, BORDER and DELIM.
(default: all types are true)

=item title

    title=>I<title>

You can specify a title.  Otherwise it will use a blank one.
(default: nothing)

=item titlefirst

    titlefirst=>1

Use the first non-blank line as the title.

=item underline_length_tolerance

    underline_length_tolerance=>I<n>

How much longer or shorter can underlines be and still be underlines?
(default: 1)

=item underline_offset_tolerance

    underline_offset_tolerance=>I<n>

How far offset can underlines be and still be underlines?
(default: 1)

=item unhyphenation

    unhyphenation=>0

Enables unhyphenation of text.
(default: true)

=item use_mosaic_header

    use_mosaic_header=>1

Use this option if you want to force the heading styles to match what Mosaic
outputs.  (Underlined with "***"s is H1,
with "==="s is H2, with "+++" is H3, with "---" is H4, with "~~~" is H5
and with "..." is H6)
This was the behavior of txt2html up to version 1.10.
(default: false)

=item use_preformat_marker

    use_preformat_marker=>1

Turn on preformatting when encountering
"<PRE>" on a line by itself, and turn it
off when there's a line containing only "</PRE>".
(default: off)

=item xhtml

    xhtml=>1

Try to make the output conform to the XHTML standard, including
closing all open tags and marking empty tags correctly.  This
turns on --lower_case_tags and overrides the --doctype option.
Note that if you add a header or a footer file, it is up to you
to make it conform; the header/footer isn't touched by this.
Likewise, if you make link-dictionary entries that break XHTML,
then this won't fix them, except to the degree of putting all tags
into lower-case.

=back 8

=head1 METHODS

=cut

#------------------------------------------------------------------------
package HTML::TextToHTML;

use 5.005_03;
use strict;

require Exporter;
use vars qw($VERSION $PROG @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

BEGIN {
    @ISA = qw(Exporter);
    require Exporter;
    use Data::Dumper;
}

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration	use HTML::TextToHTML ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
%EXPORT_TAGS = (
    'all' => [
        qw(

        )
    ]
);

@EXPORT_OK = (@{$EXPORT_TAGS{'all'}});

@EXPORT = qw(
  run_txt2html
);
$PROG = 'HTML::TextToHTML';
$VERSION = '2.23';

#------------------------------------------------------------------------
use constant TEXT_TO_HTML => "TEXT_TO_HTML";

########################################
# Definitions  (Don't change these)
#

# These are just constants I use for making bit vectors to keep track
# of what modes I'm in and what actions I've taken on the current and
# previous lines.  
use vars qw($NONE $LIST $HRULE $PAR $PRE $END $BREAK $HEADER
  $MAILHEADER $MAILQUOTE $CAPS $LINK $PRE_EXPLICIT $TABLE
  $IND_BREAK $LIST_START $LIST_ITEM);

$NONE         = 0;
$LIST         = 1;
$HRULE        = 2;
$PAR          = 4;
$PRE          = 8;
$END          = 16;
$BREAK        = 32;
$HEADER       = 64;
$MAILHEADER   = 128;
$MAILQUOTE    = 256;
$CAPS         = 512;
$LINK         = 1024;
$PRE_EXPLICIT = 2048;
$TABLE        = 4096;
$IND_BREAK    = 8192;
$LIST_START   = 16384;
$LIST_ITEM    = 32768;

# Constants for Link-processing
# bit-vectors for what to do with a particular link-dictionary entry
use vars qw($LINK_NOCASE $LINK_EVAL $LINK_HTML $LINK_ONCE $LINK_SECT_ONCE);
$LINK_NOCASE    = 1;
$LINK_EVAL      = 2;
$LINK_HTML      = 4;
$LINK_ONCE      = 8;
$LINK_SECT_ONCE = 16;

# Constants for Ordered Lists and Unordered Lists.  
# And Definition Lists.
# I use this in the list stack to keep track of what's what.

use vars qw($OL $UL $DL);
$OL = 1;
$UL = 2;
$DL = 3;

# Constants for table types
use vars qw($TAB_ALIGN $TAB_PGSQL $TAB_BORDER $TAB_DELIM);
$TAB_ALIGN = 1;
$TAB_PGSQL = 2;
$TAB_BORDER = 3;
$TAB_DELIM = 4;

# Character entity names
use vars qw(%char_entities %char_entities2);

# characters to replace *before* processing a line
%char_entities = (
    "\241", "&iexcl;",  "\242", "&cent;",   "\243", "&pound;",
    "\244", "&curren;", "\245", "&yen;",    "\246", "&brvbar;",
    "\247", "&sect;",   "\250", "&uml;",    "\251", "&copy;",
    "\252", "&ordf;",   "\253", "&laquo;",  "\254", "&not;",
    "\255", "&shy;",    "\256", "&reg;",    "\257", "&hibar;",
    "\260", "&deg;",    "\261", "&plusmn;", "\262", "&sup2;",
    "\263", "&sup3;",   "\264", "&acute;",  "\265", "&micro;",
    "\266", "&para;",   "\270", "&cedil;",  "\271", "&sup1;",
    "\272", "&ordm;",   "\273", "&raquo;",  "\274", "&frac14;",
    "\275", "&frac12;", "\276", "&frac34;", "\277", "&iquest;",
    "\300", "&Agrave;", "\301", "&Aacute;", "\302", "&Acirc;",
    "\303", "&Atilde;", "\304", "&Auml;",   "\305", "&Aring;",
    "\306", "&AElig;",  "\307", "&Ccedil;", "\310", "&Egrave;",
    "\311", "&Eacute;", "\312", "&Ecirc;",  "\313", "&Euml;",
    "\314", "&Igrave;", "\315", "&Iacute;", "\316", "&Icirc;",
    "\317", "&Iuml;",   "\320", "&ETH;",    "\321", "&Ntilde;",
    "\322", "&Ograve;", "\323", "&Oacute;", "\324", "&Ocirc;",
    "\325", "&Otilde;", "\326", "&Ouml;",   "\327", "&times;",
    "\330", "&Oslash;", "\331", "&Ugrave;", "\332", "&Uacute;",
    "\333", "&Ucirc;",  "\334", "&Uuml;",   "\335", "&Yacute;",
    "\336", "&THORN;",  "\337", "&szlig;",  "\340", "&agrave;",
    "\341", "&aacute;", "\342", "&acirc;",  "\343", "&atilde;",
    "\344", "&auml;",   "\345", "&aring;",  "\346", "&aelig;",
    "\347", "&ccedil;", "\350", "&egrave;", "\351", "&eacute;",
    "\352", "&ecirc;",  "\353", "&euml;",   "\354", "&igrave;",
    "\355", "&iacute;", "\356", "&icirc;",  "\357", "&iuml;",
    "\360", "&eth;",    "\361", "&ntilde;", "\362", "&ograve;",
    "\363", "&oacute;", "\364", "&ocirc;",  "\365", "&otilde;",
    "\366", "&ouml;",   "\367", "&divide;", "\370", "&oslash;",
    "\371", "&ugrave;", "\372", "&uacute;", "\373", "&ucirc;",
    "\374", "&uuml;",   "\375", "&yacute;", "\376", "&thorn;",
    "\377", "&yuml;",
);

# characters to replace *after* processing a line
%char_entities2 = ("\267", "&middot;",);

# alignments for tables
use vars qw(@alignments @lc_alignments @xhtml_alignments);
@alignments = ('', '', ' ALIGN="RIGHT"', ' ALIGN="CENTER"');
@lc_alignments = ('', '', ' align="right"', ' align="center"');
@xhtml_alignments = ('', '', ' style="text-align: right;"', ' style="text-align: center;"');

#---------------------------------------------------------------#
# Object interface
#---------------------------------------------------------------#

=head2 new

    $conv = new HTML::TextToHTML()

    $conv = new HTML::TextToHTML(\@args)

    $conv = new HTML::TextToHTML(titlefirst=>1,
	...
    );

Create a new object with new.  If one argument is given, it is assumed
to be a reference to an array of arguments.  If more than one argument
is given, it is assumed to be a hash of arguments.  These arguments will
be used in invocations of other methods.

See L<OPTIONS> for the possible values of the arguments.

=cut

sub new {
    my $invocant = shift;
    my $self = {};

    my $class = ref($invocant) || $invocant;    # Object or class name
    init_our_data($self);

    # bless self
    bless($self, $class);

    $self->args(@_);

    return $self;
}    # new

=head2 args

    $conv->args(\@args)

    $conv->args(short_line_length=>60,
	titlefirst=>1,
	....
    );

Updates the current arguments/options of the HTML::TextToHTML object.
Takes either a hash, or a reference to an array of arguments, which will
be used in invocations of other methods.
See L<OPTIONS> for the possible values of the arguments.

=cut

sub args {
    my $self     = shift;
    my %args = ();
    my @arg_array = ();
    if (@_ && @_ == 1)
    {
	# assume this is a reference to an array -- use the old style args
	my $aref = shift;
	@arg_array = @{$aref};
    }
    elsif (@_)
    {
	%args = @_;
    }

    if (%args) {
	if ($self->{debug}) {
	    print STDERR "========args(hash)========\n";
	    print STDERR Dumper(%args);
	}
	foreach my $arg (keys %args) {
	    if (defined $args{$arg}) {
		if ($arg =~ /^-/) {
		    $arg =~ s/^-//; # get rid of first dash
		    $arg =~ s/^-//; # get rid of possible second dash
		}
		if ($self->{debug}) {
		    print STDERR "--", $arg;
		}
		$self->{$arg} = $args{$arg};
		if ($self->{debug}) {
		    print STDERR " ", $args{$arg}, "\n";
		}
	    }
	}
    } elsif (@arg_array) {
	if ($self->{debug}) {
	    print STDERR "========args(array)========\n";
	    print STDERR Dumper(@arg_array);
	}
	# the arg array may have filenames at the end of it,
	# so don't consume them
	my $look_at_args = 1;
	while (@arg_array && $look_at_args) {
	    my $arg = shift @arg_array;
	    # check for arguments which are bools,
	    # and thus have no companion value
	    if ($arg =~ /^-/) {
		$arg =~ s/^-//; # get rid of first dash
		$arg =~ s/^-//; # get rid of possible second dash
		if ($self->{debug}) {
		    print STDERR "--", $arg;
		}
		if ($arg eq 'debug'
		    || $arg eq 'eight_bit_clean'
		    || $arg eq 'escape_HTML_chars'
		    || $arg eq 'explicit_headings'
		    || $arg eq 'extract'
		    || $arg eq 'link_only'
		    || $arg eq 'lower_case_tags'
		    || $arg eq 'mailmode'
		    || $arg eq 'make_anchors'
		    || $arg eq 'make_links'
		    || $arg eq 'make_tables'
		    || $arg eq 'preserve_indent'
		    || $arg eq 'titlefirst'
		    || $arg eq 'unhyphenation'
		    || $arg eq 'use_mosaic_header'
		    || $arg eq 'use_preformat_marker'
		    || $arg eq 'verbose'
		    || $arg eq 'xhtml'
		) {
		    $self->{$arg} = 1;
		    if ($self->{debug}) {
			print STDERR "=true\n";
		    }
		} elsif ($arg eq 'nodebug'
		    || $arg eq 'noeight_bit_clean'
		    || $arg eq 'noescape_HTML_chars'
		    || $arg eq 'noexplicit_headings'
		    || $arg eq 'noextract'
		    || $arg eq 'nolink_only'
		    || $arg eq 'nolower_case_tags'
		    || $arg eq 'nomailmode'
		    || $arg eq 'nomake_anchors'
		    || $arg eq 'nomake_links'
		    || $arg eq 'nomake_tables'
		    || $arg eq 'nopreserve_indent'
		    || $arg eq 'notitlefirst'
		    || $arg eq 'nounhyphenation'
		    || $arg eq 'nouse_mosaic_header'
		    || $arg eq 'nouse_preformat_marker'
		    || $arg eq 'noverbose'
		    || $arg eq 'noxhtml'
		) {
		    $arg =~ s/^no//;
		    $self->{$arg} = 0;
		    if ($self->{debug}) {
			print STDERR " $arg=false\n";
		    }
		} else {
		    my $val = shift @arg_array;
		    if ($self->{debug}) {
			print STDERR "=", $val, "\n";
		    }
		    # check the types
		    if (defined $arg && defined $val) {
			if ($arg eq 'infile' 
			    || $arg eq 'custom_heading_regexp'
			    || $arg eq 'links_dictionaries'
			) {	# arrays
			    if ($val eq 'CLEAR') {
				$self->{$arg} = [];
			    } else {
				push @{$self->{$arg}}, $val;
			    }
			} elsif ($arg eq 'file') {	# alternate for 'infile'
			    if ($val eq 'CLEAR') {
				$self->{infile} = [];
			    } else {
				push @{$self->{infile}}, $val;
			    }
			} elsif ($arg eq 'table_type') {
			    # hash
			    if ($val eq 'CLEAR') {
				$self->{$arg} = {};
			    } else {
				my ($f1, $v1) = split(/=/, $val, 2);
				$self->{$arg}->{$f1} = $v1;
			    }
			} else {
			    $self->{$arg} = $val;
			}
		    }
		}
	    } else {
		# if an option don't start with - then we've
		# come to the end of the options
		$look_at_args = 0;
	    }
	}
    }
    if ($self->{debug})
    {
    	print STDERR Dumper($self);
    }

    return 1;
}    # args

=head2 process_chunk

$newstring = $conv->process_chunk($mystring);

Convert a string to a HTML fragment.  This assumes that this string is
at the least, a single paragraph, but it can contain more than that.
This returns the processed string.  If you want to pass arguments to
alter the behaviour of this conversion, you need to do that earlier,
either when you create the object, or with the L<args> method.

    $newstring = $conv->process_chunk($mystring,
			    close_tags=>0);

If there are open tags (such as lists) in the input string,
process_chunk will now automatically close them, unless you specify not
to, with the close_tags option.

    $newstring = $conv->process_chunk($mystring,
			    is_fragment=>1);

If you want this string to be treated as a fragment, and not assumed to
be a paragraph, set is_fragment to true.  If there is more than one
paragraph in the string (ie it contains blank lines) then this option
will be ignored.

=cut
sub process_chunk ($$;%) {
    my $self = shift;
    my $chunk = shift;
    my %args = (
	close_tags=>1,
	is_fragment=>0,
	@_
    );

    my $ret_str = '';
    my @paras = split(/\n\n/, $chunk);
    my $ind = 0;
    if (@paras == 1) # just one paragraph
    {
	$ret_str .= $self->process_para($chunk,
				close_tags=>$args{close_tags},
				is_fragment=>$args{is_fragment});
    }
    else
    {
	for ($ind = 0; $ind < @paras; $ind++)
	{
	    my $para = $paras[$ind];
	    # if the paragraph doesn't end with a newline, add one
	    if ($para !~ /\n$/)
	    {
		$para .= "\n";
	    }
	    if ($ind == @paras - 1) # last one
	    {
		$ret_str .= $self->process_para($para,
			close_tags=>$args{close_tags},
			is_fragment=>0);
	    }
	    else
	    {
		$ret_str .= $self->process_para($para,
			close_tags=>0,
			is_fragment=>0);
	    }
	}
    }
    $ret_str;
} # process_chunk

=head2 process_para

$newstring = $conv->process_para($mystring);

Convert a string to a HTML fragment.  This assumes that this string is
at the most a single paragraph, with no blank lines in it.  If you don't
know whether your string will contain blank lines or not, use the
L<process_chunk> method instead.

This returns the processed string.  If you want to pass arguments to
alter the behaviour of this conversion, you need to do that earlier,
either when you create the object, or with the L<args> method.

    $newstring = $conv->process_para($mystring,
			    close_tags=>0);

If there are open tags (such as lists) in the input string, process_para
will now automatically close them, unless you specify not to, with the
close_tags option.

    $newstring = $conv->process_para($mystring,
			    is_fragment=>1);

If you want this string to be treated as a fragment, and not assumed to be
a paragraph, set is_fragment to true.

=cut
sub process_para ($$;%) {
    my $self = shift;
    my $para = shift;
    my %args = (
	close_tags=>1,
	is_fragment=>0,
	@_
    );

    # if this is an external call, do certain initializations
    $self->do_init_call();

    my $para_action = $NONE;

    # tables and mailheaders don't carry over from one para to the next
    if ($self->{__mode} & $TABLE) {
        $self->{__mode} ^= $TABLE;
    }
    if ($self->{__mode} & $MAILHEADER) {
        $self->{__mode} ^= $MAILHEADER;
    }

    # if we are not just linking, we are discerning structure
    if (!$self->{link_only}) {

	# Chop trailing whitespace and DOS CRs
	$para =~ s/[ \011]*\015$//g;

	my @done_lines = (); # lines which have been processed

	# The PRE_EXPLICIT structure can carry over from one
	# paragraph to the next, but it is ended with the
	# explicit end-tag designated for it.
	# Therefore we can shortcut for this by checking
	# for the end of the PRE_EXPLICIT and chomping off
	# the preformatted string part of this para before
	# we have to split it into lines.
	# Note that after this check, we could *still* be
	# in PRE_EXPLICIT mode.
	if ($self->{__mode} & $PRE_EXPLICIT) {
	    my $pre_str = $self->split_end_explicit_preformat(
				    para_ref=>\$para);
	    if ($pre_str) {
		push @done_lines, $pre_str;
	    }
	}

	if ($para) {
	    #
	    # Now we split the paragraph into lines
	    #
	    my $para_len         = length($para);
	    my @para_lines       = split (/^/, $para);
	    my @para_line_len    = ();
	    my @para_line_indent = ();
	    my @para_line_action = ();
	    my $line;
	    for (my $i = 0 ; $i < @para_lines ; $i++) {
		$line = $para_lines[$i];
		my $ind;

		$line = $self->untabify($line);    # Change all tabs to spaces
		    push @para_line_len, length($line);
		if ($i > 0) {
		    $ind = count_indent($line, $para_line_indent[$i - 1]);
		    push @para_line_indent, $ind;
		}
		else {
		    $ind = count_indent($line, 0);
		    push @para_line_indent, $ind;
		}
		push @para_line_action, $NONE;
		$para_lines[$i] = $line;
	    }

	    # There are two more structures which carry over from one
	    # paragraph to the next: LIST, PRE
	    # There are also certain things which will immediately end
	    # multi-paragraph LIST and PRE, if found at the start
	    # of a paragraph:
	    # A list will be ended by
	    # TABLE, MAILHEADER, HEADER, custom-header
	    # A PRE will be ended by
	    # TABLE, MAILHEADER and non-pre text

	    my $is_table = 0;
	    my $is_mailheader = 0;
	    my $is_header = 0;
	    my $is_custom_header = 0;
	    if (@{$self->{custom_heading_regexp}}) {
		$is_custom_header =
		    $self->is_custom_heading(line=>$para_lines[0]);
	    }
	    if ($self->{make_tables}
		&& @para_lines > 1) {
		$is_table = $self->is_table(
			rows_ref=>\@para_lines,
			para_len=>$para_len);
	    }
	    if (!$self->{explicit_headings}
		&& @para_lines > 1
		&& !$is_table)
	    {
		$is_header = $self->is_heading(line_ref=>\$para_lines[0],
			next_ref=>\$para_lines[1]);
	    }
	    # Note that it is concievable that someone has
	    # partially disabled mailmode by making a custom header
	    # which matches the start of mail.
	    # This is stupid, but allowable, so we check.
	    if ($self->{mailmode}
		&& !$is_table
		&& !$is_custom_header) {
		$is_mailheader = $self->is_mailheader(
			rows_ref=>\@para_lines);
	    }

	    # end the list if we can end it
	    if (($self->{__mode} & $LIST)
		&& ($is_table || $is_mailheader
		    || $is_header || $is_custom_header))
	    {
		my $list_end = '';
		my $action = 0;
		$self->endlist(num_lists=>$self->{__listnum},
			prev_ref=>\$list_end,
			line_action_ref=>\$action);
		push @done_lines, $list_end;
		$self->{__prev_para_action} |= $END;
	    }

	    # end the PRE if we can end it
	    if (($self->{__mode} & $PRE)
		&& !($self->{__mode} & $PRE_EXPLICIT)
		&& ($is_table || $is_mailheader 
		    || !$self->is_preformatted($para_lines[0]))
		&& ($self->{preformat_trigger_lines} != 0))
	    {
		my $pre_end = '';
		my $tag = $self->get_tag('PRE', tag_type=>'end');
		$pre_end = "${tag}\n";
		$self->{__mode} ^= ($PRE & $self->{__mode});
		push @done_lines, $pre_end;
		$self->{__prev_para_action} |= $END;
	    }

	    # Now, we do certain things which are only found at the
	    # start of a paragraph:
	    # HEADER, custom-header, TABLE and MAILHEADER
	    # These could concievably eat the rest of the paragraph.

	    if ($is_custom_header) {
		# custom header eats the first line
		my $header = shift @para_lines;
		shift @para_line_len;
		shift @para_line_indent;
		shift @para_line_action;
		$self->custom_heading(line_ref=>\$header);
		push @done_lines, $header;
		$self->{__prev_para_action} |= $HEADER;
	    }
	    elsif ($is_header) {
		# normal header eats the first two lines
		my $header = shift @para_lines;
		shift @para_line_len;
		shift @para_line_indent;
		shift @para_line_action;
		my $underline = shift @para_lines;
		shift @para_line_len;
		shift @para_line_indent;
		shift @para_line_action;
		$self->heading(line_ref=>\$header,
			next_ref=>\$underline);
		push @done_lines, $header;
		$self->{__prev_para_action} |= $HEADER;
	    }

	    # do the table stuff on the array of lines
	    if ($self->{make_tables}) {
		if ($self->tablestuff(
			rows_ref=>\@para_lines,
			para_len=>$para_len))
		{
		    # this has used up all the lines
		    push @done_lines, @para_lines;
		    @para_lines = ();
		}
	    }

	    # check of this para is a mail-header
	    if ($is_mailheader
		    && !($self->{__mode} & $TABLE)
		    && @para_lines) {
		$self->mailheader(
			rows_ref=>\@para_lines);
		# this has used up all the lines
		push @done_lines, @para_lines;
		@para_lines = ();
	    }

	    #
	    # Now go through the paragraph lines one at a time
	    # Note that we won't have TABLE, MAILHEADER, HEADER modes
	    # because they would have eaten the lines
	    #
	    my $prev        = '';
	    my $next        = '';
	    my $prev_action = $self->{__prev_para_action};
	    for (my $i = 0 ; $i < @para_lines ; $i++) {
		my $prev_ref;
		my $prev_action_ref;
		my $prev_line_indent;
		my $prev_line_len;
		if ($i == 0) {
		    $prev_ref         = \$prev;
		    $prev_action_ref  = \$prev_action;
		    $prev_line_indent = 0;
		    $prev_line_len    = 0;
		}
		else {
		    $prev_ref         = \$para_lines[$i - 1];
		    $prev_action_ref  = \$para_line_action[$i - 1];
		    $prev_line_indent = $para_line_indent[$i - 1];
		    $prev_line_len    = $para_line_len[$i - 1];
		}
		my $next_ref;
		if ($i == @para_lines - 1) {
		    $next_ref = \$next;
		}
		else {
		    $next_ref = \$para_lines[$i + 1];
		}

		if ($self->{escape_HTML_chars}) {
		    $para_lines[$i] = escape($para_lines[$i]);
		}

		if ($self->{mailmode}
			&& !($self->{__mode} & ($PRE_EXPLICIT)))
		{
		    $self->mailquote(
			    line_ref=>\$para_lines[$i],
			    line_action_ref=>\$para_line_action[$i],
			    prev_ref=>$prev_ref,
			    prev_action_ref=>$prev_action_ref,
			    next_ref=>$next_ref
			    );
		}

		if (($self->{__mode} & $PRE)
			&& ($self->{preformat_trigger_lines} != 0))
		{
		    $self->endpreformat(
			    para_lines_ref=>\@para_lines,
			    para_action_ref=>\@para_line_action,
			    ind=>$i,
			    prev_ref=>$prev_ref);
		}

		if (!($self->{__mode} & $PRE)) {
		    $self->hrule(para_lines_ref=>\@para_lines,
			    para_action_ref=>\@para_line_action,
			    ind=>$i);
		}
		if (!($self->{__mode} & ($PRE))
			&& !is_blank($para_lines[$i]))
		{
		    $self->liststuff(
			    para_lines_ref=>\@para_lines,
			    para_action_ref=>\@para_line_action,
			    para_line_indent_ref=>\@para_line_indent,
			    ind=>$i,
			    prev_ref=>$prev_ref);
		}
		if (
			!($para_line_action[$i] &
			    ($HEADER | $LIST ))
			&& !($self->{__mode} & ($LIST | $PRE))
			&& $self->{__preformat_enabled})
		{
		    $self->preformat(
			    mode_ref=>\$self->{__mode},
			    line_ref=>\$para_lines[$i],
			    line_action_ref=>\$para_line_action[$i],
			    prev_ref=>$prev_ref,
			    next_ref=>$next_ref,
			    prev_action_ref=>$prev_action_ref
			    );
		}
		if (!($self->{__mode} & ($PRE)))
		{
		    $self->paragraph(
			    line_ref=>\$para_lines[$i],
			    line_action_ref=>\$para_line_action[$i],
			    prev_ref=>$prev_ref,
			    prev_action_ref=>$prev_action_ref,
			    line_indent=>$para_line_indent[$i],
			    prev_indent=>$prev_line_indent,
			    is_fragment=>$args{is_fragment},
			    ind=>$i,
			    );
		}
		if (!($self->{__mode} & ($PRE | $LIST)))
		{
		    $self->shortline(
			    line_ref=>\$para_lines[$i],
			    line_action_ref=>\$para_line_action[$i],
			    prev_ref=>$prev_ref,
			    prev_action_ref=>$prev_action_ref,
			    prev_line_len=>$prev_line_len
			    );
		}
		if (!($self->{__mode} & ($PRE))) {
		    $self->caps(line_ref=>\$para_lines[$i],
			    line_action_ref=>\$para_line_action[$i]);
		}

		# put the "prev" line in front of the first line
		if ($i == 0 && !is_blank($prev))
		{
		    $line = $para_lines[$i];
		    $para_lines[$i] = $prev . $line;
		}
		# put the "next" at the end of the last line
		if ($i == @para_lines - 1 && !is_blank($next))
		{
		    $para_lines[$i] .= $next;
		}
	    }

	    # para action is the action of the last line of the para
	    $para_action = $para_line_action[$#para_line_action];
	    if (!defined $para_action) {
		$para_action = $NONE;
	    }

	    # push them on the done lines
	    push @done_lines, @para_lines;
	    @para_lines = ();

	}
	# now put the para back together as one string
	$para = join ("", @done_lines);

	# if this is a paragraph, and we are in XHTML mode,
	# close an open paragraph.
	if ($self->{xhtml})
	{
	    my $open_tag = @{$self->{__tags}}[$#{$self->{__tags}}];
	    if (defined $open_tag && $open_tag eq 'P')
	    {
		$para .= $self->close_tag('P');
	    }
	}

        if ($self->{unhyphenation}

            # ends in hyphen & next line starts w/letters
            && ($para =~ /[^\W\d_]\-\n\s*[^\W\d_]/s)
            && !($self->{__mode} &
                ($PRE | $HEADER | $MAILHEADER | $TABLE | $BREAK))
          )
        {
            $self->unhyphenate_para(\$para);
        }

    }

    if ($self->{make_links}
        && !is_blank($para)
        && @{$self->{__links_table_order}})
    {
        $self->make_dictionary_links(line_ref=>\$para,
	    line_action_ref=>\$para_action);
    }

    # close any open lists if required to
    if ($args{close_tags}
	&& $self->{__mode} & $LIST)    # End all lists
    {
	$self->endlist(num_lists=>$self->{__listnum},
			prev_ref=>\$para,
			line_action_ref=>\$para_action);
    }
    # close any open tags
    if ($args{close_tags} && $self->{xhtml})
    {
	while (@{$self->{__tags}})
	{
	    $para .= $self->close_tag('');
	}
    }

    # All the matching and formatting is done.  Now we can 
    # replace non-ASCII characters with character entities.
    if (!$self->{eight_bit_clean}) {
        my @chars = split (//, $para);
        foreach $_ (@chars) {
            $_ = $char_entities{$_} if defined($char_entities{$_});
        }
        $para = join ("", @chars);
    }


    $self->{__prev_para_action} = $para_action;

    return $para;
}

=head2 txt2html

    $conv->txt2html(\@args);

    $conv->txt2html(%args);

Convert a text file to HTML.  Takes a hash of arguments, or a reference
to an array of arguments to customize the conversion; (this includes
saying what file to convert!) See L<OPTIONS> for the possible values of
the arguments.  Arguments which have already been set with B<new> or
B<args> will remain as they are, unless they are overridden.

=cut
sub txt2html ($;$) {
    my $self     = shift;

    if (@_) {
	$self->args(@_);
    }

    $self->do_init_call();

    my $outhandle;
    my $not_to_stdout;

    # open the output
    if ($self->{outfile} eq "-") {
        $outhandle     = *STDOUT;
        $not_to_stdout = 0;
    }
    else {
        open(HOUT, "> " . $self->{outfile}) || die "Error: unable to open ",
          $self->{outfile}, ": $!\n";
        $outhandle     = *HOUT;
        $not_to_stdout = 1;
    }

    # slurp up a paragraph at a time, a file at a time
    local $/ = "";
    my $para  = '';
    my $count = 0;
    my $print_count = 0;
    my $inhandle;
    foreach my $file (@{$self->{infile}}) {
        if ((-f $file && open(IN, $file))
	    || $file eq '-' ) {
	    if ($file eq '-') { # stdin
		$inhandle = *STDIN;
	    }
	    else {
		$inhandle = *IN;
	    }
            while (<$inhandle>) {
                $para = $_;
                $para =~ s/\n$//;    # trim the endline
                if ($count == 0) {
                    $self->do_file_start($outhandle, $para);
                }
		$self->clear_section_links();
                $para = $self->process_para($para, 
		    close_tags=>0);
                print $outhandle $para, "\n";
                $print_count++;
                $count++;
            }
	    if ($file ne '-') { # not stdin
		close(IN);
	    }
        }
    }

    $self->{__prev} = "";
    if ($self->{__mode} & $LIST)    # End all lists
    {
	$self->endlist(num_lists=>$self->{__listnum},
			prev_ref=>\$self->{__prev},
			line_action_ref=>\$self->{__line_action})
    }
    print $outhandle $self->{__prev};

    # close all open tags
    if ($self->{xhtml}
	&& !$self->{extract}
	&& @{$self->{__tags}})
    {
	if ($self->{dict_debug} & 8)
	{
	    print STDERR "closing all tags at end\n";
	}
	# close any open tags (until we get to the body)
	my $open_tag = @{$self->{__tags}}[$#{$self->{__tags}}];
	while (@{$self->{__tags}}
	    && $open_tag ne 'BODY'
	    && $open_tag ne 'HTML')
	{
	    print $outhandle $self->close_tag('');
	    $open_tag = @{$self->{__tags}}[$#{$self->{__tags}}];
	}
	print $outhandle "\n";
    }

    if ($self->{append_file}) {
        if (-r $self->{append_file}) {
            open(APPEND, $self->{append_file});
            while (<APPEND>) {
                print $outhandle $_;
		$print_count++;
            }
            close(APPEND);
        }
        else {
            print STDERR "Can't find or read file ", $self->{append_file},
              " to append.\n";
        }
    }

    # print the closing tags (if we have printed stuff at all)
    if ($print_count && !$self->{extract}) {
        print $outhandle $self->get_tag('BODY', tag_type=>'end'), "\n";
        print $outhandle $self->get_tag('HTML', tag_type=>'end'), "\n";
    }
    if ($not_to_stdout) {
        close($outhandle);
    }
    return 1;
}

#---------------------------------------------------------------#
# Init-related subroutines

#--------------------------------#
# Name: init_our_data
# Args:
#   $self
sub init_our_data ($) {
    my $self = shift;

    $self->{debug} = 0;

    #
    # All the options, in alphabetical order
    #
    $self->{append_file} = '';
    $self->{append_head} = '';
    $self->{body_deco} = '';
    $self->{bullets} = '-=o*\267';
    $self->{bullets_ordered} = '';
    $self->{caps_tag} = 'STRONG';
    $self->{custom_heading_regexp} = [];
    $self->{default_link_dict} = "$ENV{HOME}/.txt2html.dict";
    $self->{dict_debug} = 0;
    $self->{doctype} = "-//W3C//DTD HTML 3.2 Final//EN";
    $self->{eight_bit_clean} = 0;
    $self->{escape_HTML_chars} = 1;
    $self->{explicit_headings} = 0;
    $self->{extract} = 0;
    $self->{hrule_min} = 4;
    $self->{indent_width} = 2;
    $self->{indent_par_break} = 0;
    $self->{infile} = [];
    $self->{links_dictionaries} = [];
    $self->{link_only} = 0;
    $self->{lower_case_tags} = 0;
    $self->{mailmode} = 0;
    $self->{make_anchors} = 1;
    $self->{make_links} = 1;
    $self->{make_tables} = 0;
    $self->{min_caps_length} = 3;
    $self->{outfile} = '-';
    $self->{par_indent} = 2;
    $self->{preformat_trigger_lines} = 2;
    $self->{endpreformat_trigger_lines} = 2;
    $self->{preformat_start_marker} = "^(:?(:?&lt;)|<)PRE(:?(:?&gt;)|>)\$";
    $self->{preformat_end_marker} = "^(:?(:?&lt;)|<)/PRE(:?(:?&gt;)|>)\$";
    $self->{preformat_whitespace_min} = 5;
    $self->{prepend_file} = '';
    $self->{preserve_indent} = 0;
    $self->{short_line_length} = 40;
    $self->{style_url} = '';
    $self->{system_link_dict} = '/usr/share/txt2html/txt2html.dict';
    $self->{tab_width} = 8;
    $self->{table_type} = {
	ALIGN => 1,
	PGSQL => 1,
	BORDER => 1,
	DELIM => 1,
    };
    $self->{title} = '';
    $self->{titlefirst} = 0;
    $self->{underline_length_tolerance} = 1;
    $self->{underline_offset_tolerance} = 1;
    $self->{unhyphenation} = 1;
    $self->{use_mosaic_header} = 0;
    $self->{use_preformat_marker} = 0;
    $self->{xhtml} = 0;

    # accumulation variables
    $self->{__file} = "";    # Current file being processed
    my %heading_styles = ();
    $self->{__heading_styles}     = \%heading_styles;
    $self->{__num_heading_styles} = 0;
    my %links_table = ();
    $self->{__links_table} = \%links_table;
    my @links_table_order = ();
    $self->{__links_table_order} = \@links_table_order;
    my @search_patterns = ();
    $self->{__search_patterns} = \@search_patterns;
    my @repl_code = ();
    $self->{__repl_code}        = \@repl_code;
    $self->{__prev_para_action} = 0;
    $self->{__non_header_anchor} = 0;
    $self->{__mode}              = 0;
    $self->{__listnum}           = 0;
    $self->{__list_nice_indent}       = "";
    $self->{__list_indent}	= [];

    $self->{__call_init_done}    = 0;

}    # init_our_data

#---------------------------------------------------------------#
# txt2html-related subroutines

#--------------------------------#
# Name: init_our_data
#   do extra processing related to particular options
# Args:
#   $self
sub deal_with_options ($) {
    my $self = shift;

    if ($self->{links_dictionaries}) {
	# only put into the links dictionaries files which are readable
	my @dict_files = @{$self->{links_dictionaries}};
	$self->args(links_dictionaries=>[]);

        foreach my $ld (@dict_files) {
            if (-r $ld) {
                $self->{'make_links'} = 1;
		$self->args(['--links_dictionaries', $ld]);
            }
            else {
                print STDERR "Can't find or read link-file $ld\n";
            }
        }
    }
    if (!$self->{make_links}) {
        $self->{'links_dictionaries'} = 0;
        $self->{'system_link_dict'}  = "";
    }
    if ($self->{append_file}) {
        if (!-r $self->{append_file}) {
            print STDERR "Can't find or read ", $self->{append_file}, "\n";
	    $self->{append_file} = '';
        }
    }
    if ($self->{prepend_file}) {
        if (!-r $self->{prepend_file}) {
            print STDERR "Can't find or read ", $self->{prepend_file}, "\n";
	    $self->{'prepend_file'} = '';
        }
    }
    if ($self->{append_head}) {
        if (!-r $self->{append_head}) {
            print STDERR "Can't find or read ", $self->{append_head}, "\n";
	    $self->{'append_head'} = '';
        }
    }

    if (!$self->{outfile}) {
        $self->{'outfile'} = "-";
    }

    $self->{'preformat_trigger_lines'} = 0
      if ($self->{preformat_trigger_lines} < 0);
    $self->{'preformat_trigger_lines'} = 2
      if ($self->{preformat_trigger_lines} > 2);

    $self->{'endpreformat_trigger_lines'} = 1
      if ($self->{preformat_trigger_lines} == 0);
    $self->{'endpreformat_trigger_lines'} = 0
      if ($self->{endpreformat_trigger_lines} < 0);
    $self->{'endpreformat_trigger_lines'} = 2
      if ($self->{endpreformat_trigger_lines} > 2);

    $self->{__preformat_enabled} =
      (($self->{endpreformat_trigger_lines} != 0)
      || $self->{use_preformat_marker});

    if ($self->{use_mosaic_header}) {
        my $num_heading_styles = 0;
        my %heading_styles     = ();
        $heading_styles{"*"} = ++$num_heading_styles;
        $heading_styles{"="} = ++$num_heading_styles;
        $heading_styles{"+"} = ++$num_heading_styles;
        $heading_styles{"-"} = ++$num_heading_styles;
        $heading_styles{"~"} = ++$num_heading_styles;
        $heading_styles{"."} = ++$num_heading_styles;
        $self->{__heading_styles}     = \%heading_styles;
        $self->{__num_heading_styles} = $num_heading_styles;
    }
    if ($self->{xhtml}) # XHTML implies lower case
    {
	$self->{'lower_case_tags'} = 1;
    }
}

sub is_blank ($) {

    return $_[0] =~ /^\s*$/;
}

sub escape ($) {
    my ($text) = @_;
    $text =~ s/&/&amp;/g;
    $text =~ s/>/&gt;/g;
    $text =~ s/</&lt;/g;
    return $text;
}

# output the tag wanted (add the <> and the / if necessary)
# - output in lower or upper case
# - do tag-related processing
# options:
#   tag_type=>'start' | tag_type=>'end' | tag_type=>'empty'
#   (default start)
#   inside_tag=>string (default empty)
sub get_tag ($$;%) {
    my $self	    = shift;
    my $in_tag	    = shift;
    my %args = (
	tag_type=>'start',
	inside_tag=>'',
	@_
    );
    my $inside_tag  = $args{inside_tag};

    my $open_tag = @{$self->{__tags}}[$#{$self->{__tags}}];
    if (!defined $open_tag)
    {
	$open_tag = '';
    }
    # close any open tags that need closing
    # Note that we only have to check for the structural tags we make,
    # not every possible HTML tag
    my $tag_prefix = '';
    if ($self->{xhtml})
    {
	if ($open_tag eq 'P' and $in_tag eq 'P'
	    and $args{tag_type} ne 'end')
	{
	    $tag_prefix = $self->close_tag('P');
	}
	elsif ($open_tag eq 'P' and $in_tag =~ /(HR|UL|OL|DL|PRE|TABLE|^H)/)
	{
	    $tag_prefix = $self->close_tag('P');
	}
	elsif ($open_tag eq 'LI' and $in_tag eq 'LI'
	    and $args{tag_type} ne 'end')
	{
	    # close a LI before the next LI
	    $tag_prefix = $self->close_tag('LI');
	}
	elsif ($open_tag eq 'LI' and $in_tag =~ /(UL|OL)/
	    and $args{tag_type} eq 'end')
	{
	    # close the LI before the list closes
	    $tag_prefix = $self->close_tag('LI');
	}
	elsif ($open_tag eq 'DT' and $in_tag eq 'DD'
	    and $args{tag_type} ne 'end')
	{
	    # close a DT before the next DD
	    $tag_prefix = $self->close_tag('DT');
	}
	elsif ($open_tag eq 'DD' and $in_tag eq 'DT'
	    and $args{tag_type} ne 'end')
	{
	    # close a DD before the next DT
	    $tag_prefix = $self->close_tag('DD');
	}
	elsif ($open_tag eq 'DD' and $in_tag =~ /DL/
	    and $args{tag_type} eq 'end')
	{
	    # close the DD before the list closes
	    $tag_prefix = $self->close_tag('DD');
	}
    }

    my $out_tag = $in_tag;
    if ($args{tag_type} eq 'end')
    {
	$out_tag = $self->close_tag($in_tag);
    }
    else
    {
	if ($self->{lower_case_tags})
	{
	    $out_tag =~ s/($in_tag)/\L$1/;
	}
	else # upper case
	{
	    $out_tag =~ s/($in_tag)/\U$1/;
	}
	if ($args{tag_type} eq 'empty')
	{
	    if ($self->{xhtml})
	    {
		$out_tag = "<${out_tag}${inside_tag}/>";
	    }
	    else
	    {
		$out_tag = "<${out_tag}${inside_tag}>";
	    }
	}
	else
	{
	    push @{$self->{__tags}}, $in_tag;
	    $out_tag = "<${out_tag}${inside_tag}>";
	}
    }
    $out_tag = $tag_prefix . $out_tag;
    if ($self->{dict_debug} & 8)
    {
	print STDERR "open_tag = '${open_tag}', in_tag = '${in_tag}', tag_type = ", $args{tag_type}, ", inside_tag = '${inside_tag}', out_tag = '$out_tag'\n";
    }

    return $out_tag;
} # get_tag

# close the open tag
sub close_tag ($$) {
    my $self	    = shift;
    my $in_tag	    = shift;

    my $open_tag = @{$self->{__tags}}[$#{$self->{__tags}}];
    if (!$in_tag)
    {
	$in_tag = $open_tag;
    }
    my $out_tag = $in_tag;
    if ($self->{lower_case_tags})
    {
	$out_tag =~ s/($in_tag)/\L$1/;
    }
    else # upper case
    {
	$out_tag =~ s/($in_tag)/\U$1/;
    }
    $out_tag = "<\/${out_tag}>";
    if (defined $open_tag
	&& $open_tag eq $in_tag)
    {
	pop @{$self->{__tags}};
    }
    if ($self->{dict_debug} & 8)
    {
	print STDERR "close_tag: open_tag = '${open_tag}', in_tag = '${in_tag}', out_tag = '$out_tag'\n";
    }

    return $out_tag;
}

sub hrule ($%) {
    my $self            = shift;
    my %args = (
	para_lines_ref=>undef,
	para_action_ref=>undef,
	ind=>0,
	@_
	);
    my $para_lines_ref  = $args{para_lines_ref};
    my $para_action_ref = $args{para_action_ref};
    my $ind		= $args{ind};

    my $hrmin = $self->{hrule_min};
    if ($para_lines_ref->[$ind] =~ /^\s*([-_~=\*]\s*){$hrmin,}$/) {
	my $tag = $self->get_tag("HR", tag_type=>'empty');
        $para_lines_ref->[$ind] = "$tag\n";
	$para_action_ref->[$ind] |= $HRULE;
    }
    elsif ($para_lines_ref->[$ind] =~ /\014/) {
	# Linefeeds become horizontal rules
	$para_action_ref->[$ind] |= $HRULE;
	my $tag = $self->get_tag("HR", tag_type=>'empty');
        $para_lines_ref->[$ind] =~ s/\014/\n${tag}\n/g;
    }
}

sub shortline ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	prev_ref=>undef,
	prev_action_ref=>undef,
	prev_line_len=>0,
	@_
	);
    my $mode_ref        = $args{mode_ref};
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};
    my $prev_ref        = $args{prev_ref};
    my $prev_action_ref = $args{prev_action_ref};
    my $prev_line_len   = $args{prev_line_len};

    # Short lines should be broken even on list item lines iff the
    # following line is more text.  I haven't figured out how to do
    # that yet.  For now, I'll just not break on short lines in lists.
    # (sorry)

    my $tag = $self->get_tag('BR', tag_type=>'empty');
    if (!is_blank(${$line_ref})
        && !is_blank(${$prev_ref})
        && ($prev_line_len < $self->{short_line_length})
        && !(${$line_action_ref} & ($END | $HEADER | $HRULE | $LIST | $IND_BREAK| $PAR))
        && !(${$prev_action_ref} & ($HEADER | $HRULE | $BREAK | $IND_BREAK)))
    {
        ${$prev_ref} .= $tag . chop(${$prev_ref});
        ${$prev_action_ref} |= $BREAK;
    }
}

sub is_mailheader ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	@_
    );
    my $rows_ref = $args{rows_ref};

    # a mail header is assumed to be the whole
    # paragraph which starts with a From , From: or Newsgroups: line

    if ($rows_ref->[0] =~ /^(From:?)|(Newsgroups:) /)
    {
	return 1;
    }
    return 0;

} # is_mailheader

sub mailheader ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	@_
    );
    my $rows_ref = $args{rows_ref};

    # a mail header is assumed to be the whole
    # paragraph which starts with a From: or Newsgroups: line
    my $tag = '';
    my @rows = @{$rows_ref};

    if ($self->is_mailheader(%args))
    {
	$self->{__mode} |= $MAILHEADER;
	if ($self->{escape_HTML_chars}) {
	    $rows[0] = escape($rows[0]);
	}
	$self->anchor_mail(\$rows[0]);
	chomp ${rows}[0];
	$tag = $self->get_tag('P');
	my $tag2 = $self->get_tag('BR', tag_type=>'empty');
	$rows[0] = "<!-- New Message -->\n$tag" . $rows[0] . "${tag2}\n";
	# now put breaks on the rest of the paragraph
	# apart from the last line
	for (my $rn=1; $rn < @rows; $rn++)
	{
	    if ($self->{escape_HTML_chars}) {
		$rows[$rn] = escape($rows[$rn]);
	    }
	    if ($rn != (@rows - 1))
	    {
		$tag = $self->get_tag('BR', tag_type=>'empty');
		chomp $rows[$rn];
		$rows[$rn] =~ s/$/${tag}\n/;
	    }
	}
    }
    @{$rows_ref} = @rows;

} # mailheader

sub mailquote ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	prev_ref=>undef,
	prev_action_ref=>undef,
	next_ref=>undef,
	@_
    );
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};
    my $prev_ref        = $args{prev_ref};
    my $prev_action_ref = $args{prev_action_ref};
    my $next_ref        = $args{next_ref};

    my $tag = '';
    if (((${$line_ref} =~ /^\w*&gt/)    # Handle "FF> Werewolves."
        || (${$line_ref} =~ /^[\|:]/))    # Handle "[|:] There wolves."
        && !is_blank(${$next_ref})
      )
    {
	$tag = $self->get_tag('BR', tag_type=>'empty');
        ${$line_ref} =~ s/$/${tag}/;
        ${$line_action_ref} |= ($BREAK | $MAILQUOTE);
        if (!(${$prev_action_ref} & ($BREAK | $MAILQUOTE))) {
	    $tag = $self->get_tag('P', inside_tag=>" class='quote_mail'");
            ${$prev_ref} .= $tag;
            ${$line_action_ref} |= $PAR;
        }
    }
}

# Subtracts modes listed in $mask from $vector.
sub subtract_modes ($$) {
    my ($vector, $mask) = @_;
    return ($vector | $mask) - $mask;
}

sub paragraph ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	prev_ref=>undef,
	prev_action_ref=>undef,
	line_indent=>0,
	prev_indent=>0,
	is_fragment=>0,
	ind=>0,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};
    my $prev_ref        = $args{prev_ref};
    my $prev_action_ref = $args{prev_action_ref};
    my $line_indent     = $args{line_indent};
    my $prev_indent     = $args{prev_indent};
    my $is_fragment	= $args{is_fragment};
    my $line_no		= $args{ind};

    my $tag = '';
    if (!is_blank(${$line_ref})
        && !subtract_modes(${$line_action_ref},
            $END | $MAILQUOTE | $CAPS | $BREAK)
        && (is_blank(${$prev_ref})
            || (${$line_action_ref} & $END)
            || ($line_indent > $prev_indent + $self->{par_indent}))
	&& !($is_fragment && $line_no == 0)
	)
    {
	if ($self->{indent_par_break}
	    && !is_blank(${$prev_ref})
	    && !(${$line_action_ref} & $END)
	    && ($line_indent > $prev_indent + $self->{par_indent}))
	{
	    $tag = $self->get_tag('BR', tag_type=>'empty');
	    ${$prev_ref} .= $tag;
	    ${$prev_ref} .= "&nbsp;" x $line_indent;
	    ${$line_ref} =~ s/^ {$line_indent}//;
	    ${$prev_action_ref} |= $BREAK;
	    ${$line_action_ref} |= $IND_BREAK;
	}
	elsif ($self->{preserve_indent})
	{
	    $tag = $self->get_tag('P');
	    ${$prev_ref} .= $tag;
	    ${$prev_ref} .= "&nbsp;" x $line_indent;
	    ${$line_ref} =~ s/^ {$line_indent}//;
	    ${$line_action_ref} |= $PAR;
	}
	else
	{
	    $tag = $self->get_tag('P');
	    ${$prev_ref} .= $tag;
	    ${$line_action_ref} |= $PAR;
	}
    }
    # detect also a continuing indentation at the same level
    elsif ($self->{indent_par_break}
        && !($self->{__mode} & ($PRE | $TABLE | $LIST))
	&& !is_blank(${$prev_ref})
	&& !(${$line_action_ref} & $END)
	&& (${$prev_action_ref} & ($IND_BREAK | $PAR))
        && !subtract_modes(${$line_action_ref},
            $END | $MAILQUOTE | $CAPS)
        && ($line_indent > $self->{par_indent})
	&& ($line_indent == $prev_indent)
	)
    {
	$tag = $self->get_tag('BR', tag_type=>'empty');
	${$prev_ref} .= $tag;
	${$prev_ref} .= "&nbsp;" x $line_indent;
	${$line_ref} =~ s/^ {$line_indent}//;
	${$prev_action_ref} |= $BREAK;
	${$line_action_ref} |= $IND_BREAK;
    }
}

# If the line is blank, return the second argument.  Otherwise,
# return the number of spaces before any nonspaces on the line.
sub count_indent ($$) {
    my ($line, $prev_length) = @_;

    if (is_blank($line)) {
        return $prev_length;
    }
    my ($ws) = $line =~ /^( *)[^ ]/;
    return length($ws);
}

sub listprefix ($$) {
    my $self = shift;
    my $line = shift;

    my ($prefix, $number, $rawprefix, $term);

    my $bullets = $self->{bullets};
    my $bullets_ordered = $self->{bullets_ordered};
    my $number_match = '(\d+|[^\W\d])';
    if ($bullets_ordered) {
	$number_match = '(\d+|[a-zA-Z]|[' . "${bullets_ordered}])";
    }
    $self->{__number_match} = $number_match;
    my $term_match = '(\w\w+)';
    $self->{__term_match} = $term_match;
    return (0, 0, 0, 0)
	if (!($line =~ /^\s*[${bullets}]\s+\S/)
		&& !($line =~ /^\s*${number_match}[\.\)\]:]\s+\S/)
		&& !($line =~ /^\s*${term_match}:$/));

    ($term) = $line =~ /^\s*${term_match}:$/;
    ($number) = $line =~ /^\s*${number_match}\S\s+\S/;
    $number = 0 unless defined($number);
    if ($bullets_ordered
	&& $number =~ /[${bullets_ordered}]/) {
	$number = 1;
    }

    # That slippery exception of "o" as a bullet
    # (This ought to be determined using the context of what lists
    #  we have in progress, but this will probably work well enough.)
    if ($bullets =~ /o/ && $line =~ /^\s*o\s/) {
        $number = 0;
    }

    if ($term) {
        ($rawprefix) = $line =~ /^(\s*${term_match}.)$/;
        $prefix = $rawprefix;
        $prefix =~ s/${term_match}//;    # Take the term out
    }
    elsif ($number) {
        ($rawprefix) = $line =~ /^(\s*${number_match}.)/;
        $prefix = $rawprefix;
        $prefix =~ s/${number_match}//;    # Take the number out
    }
    else {
        ($rawprefix) = $line =~ /^(\s*[${bullets}].)/;
        $prefix = $rawprefix;
    }
    ($prefix, $number, $rawprefix, $term);
} # listprefix

sub startlist ($%) {
    my $self		= shift;
    my %args = (
	prefix=>'',
	number=>0,
	rawprefix=>'',
	term=>'',
	para_lines_ref=>undef,
	para_action_ref=>undef,
	ind=>0,
	prev_ref=>undef,
	total_prefix=>'',
	@_
	);
    my $prefix		= $args{prefix};
    my $number		= $args{number};
    my $rawprefix	= $args{rawprefix};
    my $term		= $args{term};
    my $para_lines_ref	= $args{para_lines_ref};
    my $para_action_ref	= $args{para_action_ref};
    my $ind		= $args{ind};
    my $prev_ref	= $args{prev_ref};

    my $tag = '';
    $self->{__listprefix}->[$self->{__listnum}] = $prefix;
    if ($number) {

        # It doesn't start with 1,a,A.  Let's not screw with it.
        if (($number ne "1") && ($number ne "a") && ($number ne "A")) {
            return 0;
        }
	$tag = $self->get_tag('OL');
        ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
        $self->{__list}->[$self->{__listnum}] = $OL;
    }
    elsif ($term) {
	$tag = $self->get_tag('DL');
        ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
        $self->{__list}->[$self->{__listnum}] = $DL;
    }
    else {
	$tag = $self->get_tag('UL');
        ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
        $self->{__list}->[$self->{__listnum}] = $UL;
    }

    $self->{__list_indent}->[$self->{__listnum}] = length($args{total_prefix});
    $self->{__listnum}++;
    $self->{__list_nice_indent} = " " x $self->{__listnum} x $self->{indent_width};
    $para_action_ref->[$ind] |= $LIST;
    $para_action_ref->[$ind] |= $LIST_START;
    $self->{__mode} |= $LIST;
    1;
} # startlist

# End N lists
sub endlist ($%) {
    my $self            = shift;
    my %args = (
	num_lists=>0,
	prev_ref=>undef,
	line_action_ref=>undef,
	@_
	);
    my $n               = $args{num_lists};
    my $prev_ref        = $args{prev_ref};
    my $line_action_ref = $args{line_action_ref};

    my $tag = '';
    for (; $n > 0 ; $n--, $self->{__listnum}--) {
        $self->{__list_nice_indent} =
          " " x ($self->{__listnum} - 1) x $self->{indent_width};
        if ($self->{__list}->[$self->{__listnum} - 1] == $UL) {
	    $tag = $self->get_tag('UL', tag_type=>'end');
            ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
	    pop @{$self->{__list_indent}};
        }
        elsif ($self->{__list}->[$self->{__listnum} - 1] == $OL) {
	    $tag = $self->get_tag('OL', tag_type=>'end');
            ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
	    pop @{$self->{__list_indent}};
        }
        elsif ($self->{__list}->[$self->{__listnum} - 1] == $DL) {
	    $tag = $self->get_tag('DL', tag_type=>'end');
            ${$prev_ref} .= $self->{__list_nice_indent} . "${tag}\n";
	    pop @{$self->{__list_indent}};
        }
        else {
            print STDERR "Encountered list of unknown type\n";
        }
    }
    ${$line_action_ref} |= $END;
    $self->{__mode} ^= $LIST if (!$self->{__listnum});
} # endlist

sub continuelist ($%) {
    my $self            = shift;
    my %args = (
	para_lines_ref=>undef,
	para_action_ref=>undef,
	ind=>0,
	term=>'',
	@_
	);
    my $para_lines_ref	= $args{para_lines_ref};
    my $para_action_ref	= $args{para_action_ref};
    my $ind		= $args{ind};
    my $term		= $args{term};

    my $list_indent = $self->{__list_nice_indent};
    my $bullets = $self->{bullets};
    my $num_match = $self->{__number_match};
    my $term_match = $self->{__term_match};
    my $tag = '';
    if ($self->{__list}->[$self->{__listnum} - 1] == $UL
	&& $para_lines_ref->[$ind] =~ /^\s*[${bullets}]\s*/)
    {
	$tag = $self->get_tag('LI');
	$para_lines_ref->[$ind] =~ s/^\s*[${bullets}]\s*/${list_indent}${tag}/;
	$para_action_ref->[$ind] |= $LIST_ITEM;
    }
    if ($self->{__list}->[$self->{__listnum} - 1] == $OL)
    {
	$tag = $self->get_tag('LI');
	$para_lines_ref->[$ind] =~ s/^\s*${num_match}.\s*/${list_indent}${tag}/;
	$para_action_ref->[$ind] |= $LIST_ITEM;
    }
    if ($self->{__list}->[$self->{__listnum} - 1] == $DL
	&& $term)
    {
	$tag = $self->get_tag('DT');
	my $tag2 = $self->get_tag('DT', tag_type=>'end');
	$term =~ s/_/ /g; # underscores are now spaces in the term
	$para_lines_ref->[$ind]
	    =~ s/^\s*${term_match}.$/${list_indent}${tag}${term}${tag2}/;
	$tag = $self->get_tag('DD');
	$para_lines_ref->[$ind] .= ${tag};
	$para_action_ref->[$ind] |= $LIST_ITEM;
    }
    $para_action_ref->[$ind] |= $LIST;
} # continuelist


sub liststuff ($%) {
    my $self            = shift;
    my %args = (
	para_lines_ref=>undef,
	para_action_ref=>undef,
	para_line_indent_ref=>undef,
	ind=>0,
	prev_ref=>undef,
	@_
	);
    my $para_lines_ref	= $args{para_lines_ref};
    my $para_action_ref	= $args{para_action_ref};
    my $para_line_indent_ref = $args{para_line_indent_ref};
    my $ind		= $args{ind};
    my $prev_ref	= $args{prev_ref};

    my $i;

    my ($prefix, $number, $rawprefix, $term) =
	$self->listprefix($para_lines_ref->[$ind]);

    if (!$prefix) {
	# if the previous line is not blank
	if ($ind > 0 && !is_blank($para_lines_ref->[$ind - 1]))
	{
	    # inside a list item
	    return;
	}
	# This might be a new paragraph within an existing list item;
	# It will be the first line, and have the same indentation
	# as the list's indentation.
	if ($ind == 0
	    && $self->{__listnum}
	    && $para_line_indent_ref->[$ind]
		== $self->{__list_indent}->[$self->{__listnum} - 1])
	{
	    # start a paragraph
	    my $tag = $self->get_tag('P');
	    ${$prev_ref} .= $tag;
	    $para_action_ref->[$ind] |= $PAR;
	    return;
	}
        # This ain't no list.  We'll want to end all of them.
        if ($self->{__listnum}) {
            $self->endlist(num_lists=>$self->{__listnum},
		prev_ref=>$prev_ref,
		line_action_ref=>\$para_action_ref->[$ind]);
        }
        return;
    }

    # If numbers with more than one digit grow to the left instead of
    # to the right, the prefix will shrink and we'll fail to match the
    # right list.  We need to account for this.
    my $prefix_alternate;
    if (length("" . $number) > 1) {
        $prefix_alternate = (" " x (length("" . $number) - 1)) . $prefix;
    }

    # Maybe we're going back up to a previous list
    for ($i = $self->{__listnum} - 1 ;
        ($i >= 0) && ($prefix ne $self->{__listprefix}->[$i]) ; $i--
      )
    {
        if (length("" . $number) > 1) {
            last if $prefix_alternate eq $self->{__listprefix}->[$i];
        }
    }

    my $islist;

    # Measure the indent from where the text starts, not where the
    # prefix starts.  This won't screw anything up, and if we don't do
    # it, the next line might appear to be indented relative to this
    # line, and get tagged as a new paragraph.
    my $bullets = $self->{bullets};
    my $bullets_ordered = $self->{bullets_ordered};
    my $term_match = $self->{__term_match};
    my ($total_prefix) =
	$para_lines_ref->[$ind] =~ /^(\s*[${bullets}${bullets_ordered}\w]+.\s*)/;
    # a DL indent starts from the edge of the term, plus indent_width
    if ($term) {
	($total_prefix) =
	    $para_lines_ref->[$ind] =~ /^(\s*)${term_match}.$/;
	$total_prefix .= " " x $self->{indent_width};
    }

    # Of course, we only use it if it really turns out to be a list.

    $islist = 1;
    $i++;
    if (($i > 0) && ($i != $self->{__listnum})) {
        $self->endlist(num_lists=>$self->{__listnum} - $i,
		prev_ref=>$prev_ref,
		line_action_ref=>\$para_action_ref->[$ind]);
        $islist = 0;
    }
    elsif (!$self->{__listnum} || ($i != $self->{__listnum})) {
        if (($para_line_indent_ref->[$ind] > 0)
	    || $ind == 0
            || ($ind > 0 && is_blank($para_lines_ref->[$ind - 1]))
            || ($ind > 0
		&& $para_action_ref->[$ind - 1] & ($BREAK | $HEADER | $CAPS))
	    )
        {
            $islist = $self->startlist(prefix=>$prefix,
		number=>$number,
		rawprefix=>$rawprefix,
		term=>$term,
		para_lines_ref=>$para_lines_ref,
		para_action_ref=>$para_action_ref,
		ind=>$ind,
		prev_ref=>$prev_ref,
		total_prefix=>$total_prefix);
        }
        else {

            # We have something like this: "- foo" which usually
            # turns out not to be a list.
            return;
        }
    }

    $self->continuelist(para_lines_ref=>$para_lines_ref,
	    para_action_ref=>$para_action_ref,
	    ind=>$ind,
	    term=>$term)
      if ($self->{__mode} & $LIST);
    $para_line_indent_ref->[$ind] = length($total_prefix) if $islist;
} # liststuff

# check if the given paragraph-array is a table
sub is_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $table_type = $self->get_table_type(%args);

    return ($table_type != 0);
}

# figure out the table type of this table, if any
sub get_table_type ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $table_type = 0;
    if ($self->{table_type}->{DELIM}
	&& $self->is_delim_table(%args))
    {
	$table_type = $TAB_DELIM;
    }
    elsif ($self->{table_type}->{ALIGN}
	&& $self->is_aligned_table(%args))
    {
	$table_type = $TAB_ALIGN;
    }
    elsif ($self->{table_type}->{PGSQL}
	&& $self->is_pgsql_table(%args))
    {
	$table_type = $TAB_PGSQL;
    }
    elsif ($self->{table_type}->{BORDER}
	&& $self->is_border_table(%args))
    {
	$table_type = $TAB_BORDER;
    }

    return $table_type;
}

# check if the given paragraph-array is an aligned table
sub is_aligned_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # TABLES: spot and mark up tables.  We combine the lines of the
    # paragraph using the string bitwise or (|) operator, the result
    # being in $spaces.  A character in $spaces is a space only if
    # there was a space at that position in every line of the
    # paragraph.  $space can be used to search for contiguous spaces
    # that occur on all lines of the paragraph.  If this results in at
    # least two columns, the paragraph is identified as a table.

    # Note that this sub must be called before checking for preformatted
    # lines because a table may well have whitespace to the left, in
    # which case it must not be incorrectly recognised as a preformat.
    my @rows = @{$rows_ref};
    my @starts;
    my $spaces = '';
    my $max = 0;
    my $min = $para_len;
    foreach my $row (@rows) {
        ($spaces |= $row) =~ tr/ /\xff/c;
        $min = length $row if length $row < $min;
        $max = length $row if $max < length $row;
    }
    $spaces = substr $spaces, 0, $min;
    push (@starts, 0) unless $spaces =~ /^ /;
    while ($spaces =~ /((?:^| ) +)(?=[^ ])/g) {
        push @starts, pos($spaces);
    }

    if (2 <= @rows and 2 <= @starts) {
	return 1;
    }
    else {
	return 0;
    }
}

sub is_pgsql_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a PGSQL table can start with an optional table-caption,
    # then it has a row of column headings separated by |
    # then it has a row of ------+-----
    # then it has one or more rows of column values separated by |
    # then it has a row-count (N rows)
    # Thus it must have at least 4 rows.
    if (@{$rows_ref} < 4) {
	return 0;
    }

    my @rows = @{$rows_ref};
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	shift @rows;
    }
    if (@rows < 4) {
	return 0;
    }
    if ($rows[0] !~ /^\s*\w+\s+\|\s+/) # Colname |
    {
	return 0;
    }
    if ($rows[1] !~ /^\s*[-]+[+][-]+/) # ----+----
    {
	return 0;
    }
    if ($rows[2] !~ /^\s*[^|]*\s+\|\s+/) # value |
    {
	return 0;
    }
    # check the last row for rowcount
    if ($rows[$#rows] !~ /\(\d+\s+rows\)/)
    {
	return 0;
    }

    return 1;
}

sub is_border_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a BORDER table can start with an optional table-caption,
    # then it has a row of +------+-----+
    # then it has a row of column headings separated by |
    # then it has a row of +------+-----+
    # then it has one or more rows of column values separated by |
    # then it has a row of +------+-----+
    # Thus it must have at least 5 rows.
    # And note that it could be indented with spaces
    if (@{$rows_ref} < 5) {
	return 0;
    }

    my @rows = @{$rows_ref};
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	shift @rows;
    }
    if (@rows < 5) {
	return 0;
    }
    if ($rows[0] !~ /^\s*[+][-]+[+][-]+[+][-+]*$/) # +----+----+
    {
	return 0;
    }
    if ($rows[1] !~ /^\s*\|\s*\w+\s+\|\s+.*\|$/) # | Colname |
    {
	return 0;
    }
    if ($rows[2] !~ /^\s*[+][-]+[+][-]+[+][-+]*$/) # +----+----+
    {
	return 0;
    }
    if ($rows[3] !~ /^\s*\|\s*[^|]*\s+\|\s+.*\|$/) # | value |
    {
	return 0;
    }
    # check the last row for +------+------+
    if ($rows[$#rows] !~ /^\s*[+][-]+[+][-]+[+][-+]*$/) # +----+----+
    {
	return 0;
    }

    return 1;
} # is_border_table

sub is_delim_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a DELIM table can start with an optional table-caption,
    # then it has at least two rows which start and end and are
    # punctuated by a non-alphanumeric delimiter.
    #
    # | val1 | val2 |
    # | val3 | val4 |
    #
    # And note that it could be indented with spaces
    if (@{$rows_ref} < 2) {
	return 0;
    }

    my @rows = @{$rows_ref};
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	shift @rows;
    }
    if (@rows < 2) {
	return 0;
    }
    # figure out if the row starts with a possible delimiter
    my $delim = '';
    if ($rows[0] =~ /^\s*([^a-zA-Z0-9])/)
    {
	$delim = $1;
	# have to get rid of ^ and []
	$delim =~ s/\^//g;
	$delim =~ s/\[//g;
	$delim =~ s/\]//g;
	if (!$delim) # no delimiter after all
	{
	    return 0;
	}
    }
    else
    {
	return 0;
    }
    # There needs to be at least three delimiters in the row
    my @all_delims = ($rows[0] =~ /[${delim}]/g);
    my $total_num_delims = @all_delims;
    if ($total_num_delims < 3)
    {
	return 0;
    }
    # All rows must start and end with the delimiter
    # and have $total_num_delims number of them
    foreach my $row (@rows)
    {
	if ($row !~ /^\s*[${delim}]/)
	{
	    return 0;
	}
	if ($row !~ /[${delim}]$/)
	{
	    return 0;
	}
	@all_delims = ($row =~ /[${delim}]/g);
	if (@all_delims != $total_num_delims)
	{
	    return 0;
	}
    }

    return 1;
} # is_delim_table

sub tablestuff ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $table_type = $self->get_table_type(%args);
    if ($table_type eq $TAB_ALIGN) {
	return $self->make_aligned_table(%args);
    }
    if ($table_type eq $TAB_PGSQL) {
	return $self->make_pgsql_table(%args);
    }
    if ($table_type eq $TAB_BORDER) {
	return $self->make_border_table(%args);
    }
    if ($table_type eq $TAB_DELIM) {
	return $self->make_delim_table(%args);
    }
} # tablestuff

sub make_aligned_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # TABLES: spot and mark up tables.  We combine the lines of the
    # paragraph using the string bitwise or (|) operator, the result
    # being in $spaces.  A character in $spaces is a space only if
    # there was a space at that position in every line of the
    # paragraph.  $space can be used to search for contiguous spaces
    # that occur on all lines of the paragraph.  If this results in at
    # least two columns, the paragraph is identified as a table.

    # Note that this sub must be called before checking for preformatted
    # lines because a table may well have whitespace to the left, in
    # which case it must not be incorrectly recognised as a preformat.
    my @rows = @{$rows_ref};
    my @starts;
    my @ends;
    my $spaces;
    my $max = 0;
    my $min = $para_len;
    foreach my $row (@rows) {
        ($spaces |= $row) =~ tr/ /\xff/c;
        $min = length $row if length $row < $min;
        $max = length $row if $max < length $row;
    }
    $spaces = substr $spaces, 0, $min;
    push (@starts, 0) unless $spaces =~ /^ /;
    while ($spaces =~ /((?:^| ) +)(?=[^ ])/g) {
        push @ends,   pos($spaces) - length $1;
        push @starts, pos($spaces);
    }
    shift (@ends) if $spaces =~ /^ /;
    push (@ends, $max);

    # Two or more rows and two or more columns indicate a table.
    if (2 <= @rows and 2 <= @starts) {
        $self->{__mode} |= $TABLE;

        # For each column, guess whether it should be left, centre or
        # right aligned by examining all cells in that column for space
        # to the left or the right.  A simple majority among those cells
        # that actually have space to one side or another decides (if no
        # alignment gets a majority, left alignment wins by default).
        my @align;
        my $cell = '';
        foreach my $col (0 .. $#starts) {
            my @count = (0, 0, 0, 0);
            foreach my $row (@rows) {
                my $width = $ends[$col] - $starts[$col];
                $cell = substr $row, $starts[$col], $width;
                ++$count[($cell =~ /^ / ? 2 : 0) +
                  ($cell =~ / $/ || length($cell) < $width ? 1 : 0)];
            }
            $align[$col] = 0;
            my $population = $count[1] + $count[2] + $count[3];
            foreach (1 .. 3) {
                if ($count[$_] * 2 > $population) {
                    $align[$col] = $_;
                    last;
                }
            }
        }

        foreach my $row (@rows) {
            $row = join '', $self->get_tag('TR'), (
              map {
                  $cell = substr $row, $starts[$_], $ends[$_] - $starts[$_];
                  $cell =~ s/^ +//;
                  $cell =~ s/ +$//;

                  if ($self->{escape_HTML_chars}) {
                      $cell = escape($cell);
                  }

                  ($self->get_tag('TD', 
		    inside_tag=>($self->{xhtml}
			? $xhtml_alignments[$align[$_]]
			: ($self->{lower_case_tags}
			    ? $lc_alignments[$align[$_]]
			    : $alignments[$align[$_]]))),
		    $cell, $self->close_tag('TD'));
              } 0 .. $#starts),
              $self->close_tag('TR');
        }

        # put the <TABLE> around the rows
	my $tag;
	if ($self->{xhtml})
	{
	    $tag = $self->get_tag('TABLE', inside_tag=>' summary=""');
	}
	else
	{
	    $tag = $self->get_tag('TABLE');
	}
        $rows[0] = "${tag}\n" . $rows[0];
	$tag = $self->get_tag('TABLE', tag_type=>'end');
        $rows[$#rows] .= "\n${tag}";
        @{$rows_ref} = @rows;
        return 1;
    }
    else {
        return 0;
    }
} # make_aligned_table

sub make_pgsql_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a PGSQL table can start with an optional table-caption,
    # then it has a row of column headings separated by |
    # then it has a row of ------+-----
    # then it has one or more rows of column values separated by |
    # then it has a row-count (N rows)
    # Thus it must have at least 4 rows.
    my @rows = @{$rows_ref};
    my $caption = '';
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	$caption = shift @rows;
    }
    my @headings = split(/\s+\|\s+/, shift @rows);
    # skip the ----+--- line
    shift @rows;
    # grab the N rows line
    my $n_rows = pop @rows;

    # now start making the table
    my @tab_lines = ();
    my $tag;
    if ($self->{xhtml})
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1" summary=""');
    }
    else
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1"');
    }
    push @tab_lines, "$tag\n";
    if ($caption) {
	$caption =~ s/^\s+//;
	$caption =~ s/\s+$//;
	$tag = $self->get_tag('CAPTION');
	$caption = $tag . $caption;
	$tag = $self->get_tag('CAPTION', tag_type=>'end');
	$caption .= $tag;
	push @tab_lines, "$caption\n";
    }
    # table header
    my $thead = '';
    $tag = $self->get_tag('THEAD');
    $thead .= $tag;
    $tag = $self->get_tag('TR');
    $thead .= $tag;
    foreach my $col (@headings)
    {
	$col =~ s/^\s+//;
	$col =~ s/\s+$//;
	$tag = $self->get_tag('TH');
	$thead .= $tag;
	$thead .= $col;
	$tag = $self->get_tag('TH', tag_type=>'end');
	$thead .= $tag;
    }
    $tag = $self->get_tag('TR', tag_type=>'end');
    $thead .= $tag;
    $tag = $self->get_tag('THEAD', tag_type=>'end');
    $thead .= $tag;
    push @tab_lines, "${thead}\n";
    $tag = $self->get_tag('TBODY');
    push @tab_lines, "$tag\n";

    # each row
    foreach my $row (@rows)
    {
	my $this_row = '';
	$tag = $self->get_tag('TR');
	$this_row .= $tag;
	my @cols = split(/\|/, $row);
	foreach my $cell (@cols)
	{
	    $cell =~ s/^\s+//;
	    $cell =~ s/\s+$//;
	    if ($self->{escape_HTML_chars}) {
		$cell = escape($cell);
	    }
	    if (!$cell)
	    {
		$cell = '&nbsp;';
	    }
	    $tag = $self->get_tag('TD');
	    $this_row .= $tag;
	    $this_row .= $cell;
	    $tag = $self->get_tag('TD', tag_type=>'end');
	    $this_row .= $tag;
	}
	$tag = $self->get_tag('TR', tag_type=>'end');
	$this_row .= $tag;
	push @tab_lines, "${this_row}\n";
    }

    # end the table
    $tag = $self->get_tag('TBODY', tag_type=>'end');
    push @tab_lines, "$tag\n";
    $tag = $self->get_tag('TABLE', tag_type=>'end');
    push @tab_lines, "$tag\n";

    # and add the N rows line
    $tag = $self->get_tag('P');
    push @tab_lines, "${tag}${n_rows}\n";
    if ($self->{xhtml})
    {
	$tag = $self->get_tag('P', tag_type=>'end');
	$tab_lines[$#tab_lines] =~ s/\n/${tag}\n/;
    }

    # replace the rows
    @{$rows_ref} = @tab_lines;
} # make_pgsql_table

sub make_border_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a BORDER table can start with an optional table-caption,
    # then it has a row of +------+-----+
    # then it has a row of column headings separated by |
    # then it has a row of +------+-----+
    # then it has one or more rows of column values separated by |
    # then it has a row of +------+-----+
    my @rows = @{$rows_ref};
    my $caption = '';
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	$caption = shift @rows;
    }
    # skip the +----+---+ line
    shift @rows;
    # get the head row and cut off the start and end |
    my $head_row = shift @rows;
    $head_row =~ s/^\s*\|//;
    $head_row =~ s/\|$//;
    my @headings = split(/\s+\|\s+/, $head_row);
    # skip the +----+---+ line
    shift @rows;
    # skip the last +----+---+ line
    pop @rows;

    # now start making the table
    my @tab_lines = ();
    my $tag;
    if ($self->{xhtml})
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1" summary=""');
    }
    else
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1"');
    }
    push @tab_lines, "$tag\n";
    if ($caption) {
	$caption =~ s/^\s+//;
	$caption =~ s/\s+$//;
	$tag = $self->get_tag('CAPTION');
	$caption = $tag . $caption;
	$tag = $self->get_tag('CAPTION', tag_type=>'end');
	$caption .= $tag;
	push @tab_lines, "$caption\n";
    }
    # table header
    my $thead = '';
    $tag = $self->get_tag('THEAD');
    $thead .= $tag;
    $tag = $self->get_tag('TR');
    $thead .= $tag;
    foreach my $col (@headings)
    {
	$col =~ s/^\s+//;
	$col =~ s/\s+$//;
	$tag = $self->get_tag('TH');
	$thead .= $tag;
	$thead .= $col;
	$tag = $self->get_tag('TH', tag_type=>'end');
	$thead .= $tag;
    }
    $tag = $self->get_tag('TR', tag_type=>'end');
    $thead .= $tag;
    $tag = $self->get_tag('THEAD', tag_type=>'end');
    $thead .= $tag;
    push @tab_lines, "${thead}\n";
    $tag = $self->get_tag('TBODY');
    push @tab_lines, "$tag\n";

    # each row
    foreach my $row (@rows)
    {
	# cut off the start and end |
	$row =~ s/^\s*\|//;
	$row =~ s/\|$//;
	my $this_row = '';
	$tag = $self->get_tag('TR');
	$this_row .= $tag;
	my @cols = split(/\|/, $row);
	foreach my $cell (@cols)
	{
	    $cell =~ s/^\s+//;
	    $cell =~ s/\s+$//;
	    if ($self->{escape_HTML_chars}) {
		$cell = escape($cell);
	    }
	    if (!$cell)
	    {
		$cell = '&nbsp;';
	    }
	    $tag = $self->get_tag('TD');
	    $this_row .= $tag;
	    $this_row .= $cell;
	    $tag = $self->get_tag('TD', tag_type=>'end');
	    $this_row .= $tag;
	}
	$tag = $self->get_tag('TR', tag_type=>'end');
	$this_row .= $tag;
	push @tab_lines, "${this_row}\n";
    }

    # end the table
    $tag = $self->get_tag('TBODY', tag_type=>'end');
    push @tab_lines, "$tag\n";
    $tag = $self->get_tag('TABLE', tag_type=>'end');
    push @tab_lines, "$tag\n";

    # replace the rows
    @{$rows_ref} = @tab_lines;
} # make_border_table

sub make_delim_table ($%) {
    my $self     = shift;
    my %args = (
	rows_ref=>undef,
	para_len=>0,
	@_
    );
    my $rows_ref = $args{rows_ref};
    my $para_len = $args{para_len};

    # a DELIM table can start with an optional table-caption,
    # then it has at least two rows which start and end and are
    # punctuated by a non-alphanumeric delimiter.
    # A DELIM table has no table-header.
    my @rows = @{$rows_ref};
    my $caption = '';
    if ($rows[0] !~ /\|/ && $rows[0] =~ /^\s*\w+/) # possible caption
    {
	$caption = shift @rows;
    }
    # figure out the delimiter
    my $delim = '';
    if ($rows[0] =~ /^\s*([^a-zA-Z0-9])/)
    {
	$delim = $1;
    }
    else
    {
	return 0;
    }

    # now start making the table
    my @tab_lines = ();
    my $tag;
    if ($self->{xhtml})
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1" summary=""');
    }
    else
    {
	$tag = $self->get_tag('TABLE', inside_tag=>' border="1"');
    }
    push @tab_lines, "$tag\n";
    if ($caption) {
	$caption =~ s/^\s+//;
	$caption =~ s/\s+$//;
	$tag = $self->get_tag('CAPTION');
	$caption = $tag . $caption;
	$tag = $self->get_tag('CAPTION', tag_type=>'end');
	$caption .= $tag;
	push @tab_lines, "$caption\n";
    }

    # each row
    foreach my $row (@rows)
    {
	# cut off the start and end delimiter
	$row =~ s/^\s*[${delim}]//;
	$row =~ s/[${delim}]$//;
	my $this_row = '';
	$tag = $self->get_tag('TR');
	$this_row .= $tag;
	my @cols = split(/[${delim}]/, $row);
	foreach my $cell (@cols)
	{
	    $cell =~ s/^\s+//;
	    $cell =~ s/\s+$//;
	    if ($self->{escape_HTML_chars}) {
		$cell = escape($cell);
	    }
	    if (!$cell)
	    {
		$cell = '&nbsp;';
	    }
	    $tag = $self->get_tag('TD');
	    $this_row .= $tag;
	    $this_row .= $cell;
	    $tag = $self->get_tag('TD', tag_type=>'end');
	    $this_row .= $tag;
	}
	$tag = $self->get_tag('TR', tag_type=>'end');
	$this_row .= $tag;
	push @tab_lines, "${this_row}\n";
    }

    # end the table
    $tag = $self->get_tag('TABLE', tag_type=>'end');
    push @tab_lines, "$tag\n";

    # replace the rows
    @{$rows_ref} = @tab_lines;
} # make_delim_table

# Returns true if the passed string is considered to be preformatted
sub is_preformatted ($$) {
    my $self = shift;
    my $line = shift;

    my $pre_white_min = $self->{preformat_whitespace_min};
    my $result = (($line =~ /\s{$pre_white_min,}\S+/o)    # whitespaces
      || ($line =~ /\.{$pre_white_min,}\S+/o));    # dots
    return $result;
}

# modifies the given string,
# and returns the front preformatted part
sub split_end_explicit_preformat ($%) {
    my $self            = shift;
    my %args = (
	para_ref=>undef,
	@_
	);
    my $para_ref  = $args{para_ref};

    my $tag = '';
    my $pre_str = '';
    my $post_str = '';
    if ($self->{__mode} & $PRE_EXPLICIT) {
	my $pe_mark = $self->{preformat_end_marker};
        if (${para_ref} =~ /$pe_mark/io) {
	    ($pre_str, $post_str) = split(/$pe_mark/, ${$para_ref}, 2);
	    if ($self->{escape_HTML_chars}) {
		$pre_str = escape($pre_str);
	    }
	    $tag = $self->get_tag('PRE', tag_type=>'end');
	    $pre_str .= "${tag}\n";
            $self->{__mode} ^= (($PRE | $PRE_EXPLICIT) & $self->{__mode});
        }
	else # no end -- the whole thing is preformatted
	{
	    $pre_str = ${$para_ref};
	    if ($self->{escape_HTML_chars}) {
		$pre_str = escape($pre_str);
	    }
	    ${$para_ref} = '';
	}
    }
    return $pre_str;
} # split_end_explicit_preformat

sub endpreformat ($%) {
    my $self            = shift;
    my %args = (
	para_lines_ref=>undef,
	para_action_ref=>undef,
	ind=>0,
	prev_ref=>undef,
	@_
	);
    my $para_lines_ref  = $args{para_lines_ref};
    my $para_action_ref = $args{para_action_ref};
    my $ind		= $args{ind};
    my $prev_ref        = $args{prev_ref};

    my $tag = '';
    if ($self->{__mode} & $PRE_EXPLICIT) {
	my $pe_mark = $self->{preformat_end_marker};
        if ($para_lines_ref->[$ind] =~ /$pe_mark/io) {
	    if ($ind == 0)
	    {
		$tag = $self->get_tag('PRE', tag_type=>'end');
		$para_lines_ref->[$ind] = "${tag}\n";
	    }
	    else
	    {
		$tag = $self->get_tag('PRE', tag_type=>'end');
		$para_lines_ref->[$ind - 1] .= "${tag}\n";
		$para_lines_ref->[$ind] = "";
	    }
            $self->{__mode} ^= (($PRE | $PRE_EXPLICIT) & $self->{__mode});
	    $para_action_ref->[$ind] |= $END;
        }
        return;
    }

    if (!$self->is_preformatted($para_lines_ref->[$ind])
        && ($self->{endpreformat_trigger_lines} == 1
            || ($ind + 1 < @{$para_lines_ref}
		&& !$self->is_preformatted($para_lines_ref->[$ind + 1]))
	    || $ind + 1 >= @{$para_lines_ref} # last line of para
		)
	)
    {
	if ($ind == 0)
	{
	    $tag = $self->get_tag('PRE', tag_type=>'end');
	    ${$prev_ref} = "${tag}\n";
	}
	else
	{
	    $tag = $self->get_tag('PRE', tag_type=>'end');
	    $para_lines_ref->[$ind - 1] .= "${tag}\n";
	}
        $self->{__mode} ^= ($PRE & $self->{__mode});
	$para_action_ref->[$ind] |= $END;
    }
} # endpreformat

sub preformat ($%) {
    my $self            = shift;
    my %args = (
	mode_ref=>undef,
	line_ref=>undef,
	line_action_ref=>undef,
	prev_ref=>undef,
	next_ref=>undef,
	prev_action_ref=>undef,
	@_
	);
    my $mode_ref        = $args{mode_ref};
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};
    my $prev_ref        = $args{prev_ref};
    my $next_ref        = $args{next_ref};
    my $prev_action_ref = $args{prev_action_ref};

    my $tag = '';
    if ($self->{use_preformat_marker}) {
        my $pstart = $self->{preformat_start_marker};
        if (${$line_ref} =~ /$pstart/io) {
            if (${$prev_ref} =~ s/<P>$//)
	    {
		pop @{$self->{__tags}};
	    }
	    $tag = $self->get_tag('PRE', inside_tag=>" class='quote_explicit'");
            ${$line_ref} = "${tag}\n";
            ${$mode_ref} |= $PRE | $PRE_EXPLICIT;
            ${$line_action_ref} |= $PRE;
            return;
        }
    }

    if (!(${$line_action_ref} & $MAILQUOTE)
	&& !(${$prev_action_ref} & $MAILQUOTE)
	&& ($self->{preformat_trigger_lines} == 0
        || ($self->is_preformatted(${$line_ref})
            && ($self->{preformat_trigger_lines} == 1
                || $self->is_preformatted(${$next_ref})))
	)
       )
    {
	if (${$prev_ref} =~ s/<P>$//)
	{
	    pop @{$self->{__tags}};
	}
	$tag = $self->get_tag('PRE');
        ${$line_ref} =~ s/^/${tag}\n/;
        ${$mode_ref} |= $PRE;
        ${$line_action_ref} |= $PRE;
    }
} # preformat

sub make_new_anchor ($$) {
    my $self          = shift;
    my $heading_level = shift;

    my ($anchor, $i);

    return sprintf("%d", $self->{__non_header_anchor}++) if (!$heading_level);

    $anchor = "section";
    $self->{__heading_count}->[$heading_level - 1]++;

    # Reset lower order counters
    for ($i = @{$self->{__heading_count}} ; $i > $heading_level ; $i--) {
        $self->{__heading_count}->[$i - 1] = 0;
    }

    for ($i = 0 ; $i < $heading_level ; $i++) {
        $self->{__heading_count}->[$i] = 1
          if !$self->{__heading_count}->[$i];    # In case they skip any
        $anchor .= sprintf("_%d", $self->{__heading_count}->[$i]);
    }
    chomp($anchor);
    $anchor;
} # make_new_anchor

sub anchor_mail ($$) {
    my $self     = shift;
    my $line_ref = shift;

    if ($self->{make_anchors}) {
        my ($anchor) = $self->make_new_anchor(0);
	if ($self->{lower_case_tags}) {
	    ${$line_ref} =~ s/([^ ]*)/<a name="$anchor">$1<\/a>/;
	} else {
	    ${$line_ref} =~ s/([^ ]*)/<A NAME="$anchor">$1<\/A>/;
	}
    }
} # anchor_mail

sub anchor_heading ($$$) {
    my $self     = shift;
    my $level    = shift;
    my $line_ref = shift;

    if ($self->{dict_debug} & 8) {
	print STDERR "anchor_heading: ", ${$line_ref}, "\n";
    }
    if ($self->{make_anchors}) {
        my ($anchor) = $self->make_new_anchor($level);
	if ($self->{lower_case_tags}) {
	    ${$line_ref} =~ s/(<h.>)(.*)(<\/h.>)/$1<a name="$anchor">$2<\/a>$3/;
	} else {
	    ${$line_ref} =~ s/(<H.>)(.*)(<\/H.>)/$1<A NAME="$anchor">$2<\/A>$3/;
	}
    }
    if ($self->{dict_debug} & 8) {
	print STDERR "anchor_heading(after): ", ${$line_ref}, "\n";
    }
} # anchor_heading

sub heading_level ($$) {
    my $self = shift;

    my ($style) = @_;
    $self->{__heading_styles}->{$style} = ++$self->{__num_heading_styles}
      if !$self->{__heading_styles}->{$style};
    $self->{__heading_styles}->{$style};
} # heading_level

sub is_ul_list_line ($%) {
    my $self            = shift;
    my %args = (
	line=>undef,
	@_
	);
    my $line	= $args{line};

    my ($prefix, $number, $rawprefix, $term) = $self->listprefix($line);
    if ($prefix && !$number)
    {
	return 1;
    }
    return 0;
}

sub is_heading ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	next_ref=>undef,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $next_ref        = $args{next_ref};

    if (!is_blank(${$line_ref})
	&& !$self->is_ul_list_line(line=>${$line_ref})
	&& ${$next_ref} =~ /^\s*[=\-\*\.~\+]+\s*$/)
    {
	my ($hoffset, $heading) = ${$line_ref} =~ /^(\s*)(.+)$/;
	$hoffset = "" unless defined($hoffset);
	$heading = "" unless defined($heading);
	# Unescape chars so we get an accurate length
	$heading =~ s/&[^;]+;/X/g;
	my ($uoffset, $underline) = ${$next_ref} =~ /^(\s*)(\S+)\s*$/;
	$uoffset   = "" unless defined($uoffset);
	$underline = "" unless defined($underline);
	my ($lendiff, $offsetdiff);
	$lendiff = length($heading) - length($underline);
	$lendiff *= -1 if $lendiff < 0;

	$offsetdiff = length($hoffset) - length($uoffset);
	$offsetdiff *= -1 if $offsetdiff < 0;
	if (($lendiff <= $self->{underline_length_tolerance})
		|| ($offsetdiff <= $self->{underline_offset_tolerance}))
	{
	    return 1;
	}
    }

    return 0;

} # is_heading

# make a heading
# assumes is_heading is true
sub heading ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	next_ref=>undef,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $next_ref        = $args{next_ref};

    my ($hoffset, $heading) = ${$line_ref} =~ /^(\s*)(.+)$/;
    $hoffset = "" unless defined($hoffset);
    $heading = "" unless defined($heading);
    $heading =~ s/&[^;]+;/X/g;    # Unescape chars so we get an accurate length
    my ($uoffset, $underline) = ${$next_ref} =~ /^(\s*)(\S+)\s*$/;
    $uoffset   = "" unless defined($uoffset);
    $underline = "" unless defined($underline);

    $underline = substr($underline, 0, 1);

    # Call it a different style if the heading is in all caps.
    $underline .= "C" if $self->iscaps(${$line_ref});
    ${$next_ref} = " ";    # Eat the underline
    $self->{__heading_level} = $self->heading_level($underline);
    if ($self->{escape_HTML_chars}) {
	${$line_ref} = escape(${$line_ref});
    }
    $self->tagline("H" . $self->{__heading_level}, $line_ref);
    $self->anchor_heading($self->{__heading_level}, $line_ref);
} # heading

# check if the given line matches a custom heading
sub is_custom_heading ($%) {
    my $self            = shift;
    my %args = (
	line=>undef,
	@_
	);
    my $line  = $args{line};

    my ($i, $level);
    for ($i = 0 ; $i < @{$self->{custom_heading_regexp}} ; $i++) {
        my $reg = ${$self->{custom_heading_regexp}}[$i];
	if ($line =~ /$reg/) {
	    return 1;
	}
    }
    return 0;
} # is_custom_heading

sub custom_heading ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	@_
	);
    my $line_ref  = $args{line_ref};

    my ($i, $level);
    for ($i = 0 ; $i < @{$self->{custom_heading_regexp}} ; $i++) {
        my $reg = ${$self->{custom_heading_regexp}}[$i];
        if (${$line_ref} =~ /$reg/) {
            if ($self->{explicit_headings}) {
                $level = $i + 1;
            }
            else {
                $level = $self->heading_level("Cust" . $i);
            }
	    if ($self->{escape_HTML_chars}) {
		${$line_ref} = escape(${$line_ref});
	    }
            $self->tagline("H" . $level, $line_ref);
            $self->anchor_heading($level, $line_ref);
            last;
        }
    }
} # custom_heading

sub unhyphenate_para ($$) {
    my $self     = shift;
    my $para_ref = shift;

    # Treating this whole paragraph as one string, look for
    # 1 - whitespace
    # 2 - a word (ending in a hyphen, followed by a newline)
    # 3 - whitespace (starting on the next line)
    # 4 - a word with its punctuation
    # Substitute this with
    # 1-whitespace 2-word 4-word newline 3-whitespace
    # We preserve the 3-whitespace because we don't want to mess up
    # our existing indentation.
    ${$para_ref} =~
      /(\s*)([^\W\d_]*)\-\n(\s*)([^\W\d_]+[\)\}\]\.,:;\'\"\>]*\s*)/s;
    ${$para_ref} =~
s/(\s*)([^\W\d_]*)\-\n(\s*)([^\W\d_]+[\)\}\]\.,:;\'\"\>]*\s*)/$1$2$4\n$3/gs;
} # unhyphenate_para

sub untabify ($$) {
    my $self = shift;
    my $line = shift;

    while ($line =~ /\011/) {
	my $tw = $self->{tab_width};
        $line =~ s/\011/" " x ($tw - (length($`) % $tw))/e;
    }
    $line;
} # untabify

sub tagline ($$$) {
    my $self     = shift;
    my $tag      = shift;
    my $line_ref = shift;

    chomp ${$line_ref};    # Drop newline
    my $tag1 = $self->get_tag($tag);
    my $tag2 = $self->get_tag($tag, tag_type=>'end');
    ${$line_ref} =~ s/^\s*(.*)$/${tag1}$1${tag2}\n/;
} # tagline

sub iscaps {
    my $self = shift;
    local ($_) = @_;

    my $min_caps_len = $self->{min_caps_length};

    # This is ugly, but I don't know a better way to do it.
    # (And, yes, I could use the literal characters instead of the 
    # numeric codes, but this keeps the script 8-bit clean, which will
    # save someone a big headache when they transfer via ASCII ftp.
/^[^a-z\341\343\344\352\353\354\363\370\337\373\375\342\345\347\350\355\357\364\365\376\371\377\340\346\351\360\356\361\362\366\372\374<]*[A-Z\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\330\331\332\333\334\335\336]{$min_caps_len,}[^a-z\341\343\344\352\353\354\363\370\337\373\375\342\345\347\350\355\357\364\365\376\371\377\340\346\351\360\356\361\362\366\372\374<]*$/;
} # iscaps

sub caps {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};

    if ($self->{caps_tag}
	&& $self->iscaps(${$line_ref})) {
        $self->tagline($self->{caps_tag}, $line_ref);
        ${$line_action_ref} |= $CAPS;
    }
} # caps

# Convert very simple globs to regexps
sub glob2regexp {
    my ($glob) = @_;

    # Escape funky chars
    $glob =~ s/[^\w\[\]\*\?\|\\]/\\$&/g;
    my ($regexp, $i, $len, $escaped) = ("", 0, length($glob), 0);

    for (; $i < $len ; $i++) {
        my $char = substr($glob, $i, 1);
        if ($escaped) {
            $escaped = 0;
            $regexp .= $char;
            next;
        }
        if ($char eq "\\") {
            $escaped = 1;
            next;
            $regexp .= $char;
        }
        if ($char eq "?") {
            $regexp .= ".";
            next;
        }
        if ($char eq "*") {
            $regexp .= ".*";
            next;
        }
        $regexp .= $char;    # Normal character
    }
    "\\b" . $regexp . "\\b";
} # glob2regexp

sub add_regexp_to_links_table ($$$$) {
    my $self = shift;
    my ($key, $URL, $switches) = @_;

    # No sense adding a second one if it's already in there.
    # It would never get used.
    if (!$self->{__links_table}->{$key}) {

        # Keep track of the order they were added so we can
        # look for matches in the same order
        push (@{$self->{__links_table_order}}, ($key));

        $self->{__links_table}->{$key}        = $URL;      # Put it in The Table
        $self->{__links_switch_table}->{$key} = $switches;
	my $ind = @{$self->{__links_table_order}} - 1;
        print STDERR " (", $ind,
          ")\tKEY: $key\n\tVALUE: $URL\n\tSWITCHES: $switches\n\n"
          if ($self->{dict_debug} & 1);
    }
    else {
        if ($self->{dict_debug} & 1) {
            print STDERR " Skipping entry.  Key already in table.\n";
            print STDERR "\tKEY: $key\n\tVALUE: $URL\n\n";
        }
    }
} # add_regexp_to_links_table

sub add_literal_to_links_table ($$$$) {
    my $self = shift;
    my ($key, $URL, $switches) = @_;

    $key =~ s/(\W)/\\$1/g;    # Escape non-alphanumeric chars
    $key = "\\b$key\\b";      # Make a regexp out of it
    $self->add_regexp_to_links_table($key, $URL, $switches);
} # add_literal_to_links_table

sub add_glob_to_links_table ($$$$) {
    my $self = shift;
    my ($key, $URL, $switches) = @_;

    $self->add_regexp_to_links_table(glob2regexp($key), $URL, $switches);
} # add_glob_to_links_table

# This is the only function you should need to change if you want to
# use a different dictionary file format.
sub parse_dict ($$$) {
    my $self = shift;

    my ($dictfile, $dict) = @_;

    print STDERR "Parsing dictionary file $dictfile\n"
      if ($self->{dict_debug} & 1);

    $dict =~ s/^\#.*$//mg;           # Strip lines that start with '#'
    $dict =~ s/^.*[^\\]:\s*$//mg;    # Strip lines that end with unescaped ':'

    if ($dict =~ /->\s*->/) {
        my $message = "Two consecutive '->'s found in $dictfile\n";
        my $near;

        # Print out any useful context so they can find it.
        ($near) = $dict =~ /([\S ]*\s*->\s*->\s*\S*)/;
        $message .= "\n$near\n" if $near =~ /\S/;
        die $message;
    }

    my ($key, $URL, $switches, $options);
    while ($dict =~ /\s*(.+)\s+\-+([iehos]+\-+)?\>\s*(.*\S+)\s*\n/ig) {
        $key      = $1;
        $options  = $2;
        $options  = "" unless defined($options);
        $URL      = $3;
        $switches = 0;
	# Case insensitivity
        $switches += $LINK_NOCASE if $options =~ /i/i;
	# Evaluate as Perl code
        $switches += $LINK_EVAL if $options =~ /e/i;
	# provides HTML, not just URL
        $switches += $LINK_HTML if $options =~ /h/i;
	# Only do this link once
        $switches += $LINK_ONCE if $options =~ /o/i;
	# Only do this link once per section
        $switches += $LINK_SECT_ONCE if $options =~ /s/i;

        $key =~ s/\s*$//;                      # Chop trailing whitespace

        if ($key =~ m|^/|)                     # Regexp
        {
            $key = substr($key, 1);
            $key =~ s|/$||;    # Allow them to forget the closing /
            $self->add_regexp_to_links_table($key, $URL, $switches);
        }
        elsif ($key =~ /^\|/)    # alternate regexp format
        {
            $key = substr($key, 1);
            $key =~ s/\|$//;      # Allow them to forget the closing |
            $key =~ s|/|\\/|g;    # Escape all slashes
            $self->add_regexp_to_links_table($key, $URL, $switches);
        }
        elsif ($key =~ /\"/) {
            $key = substr($key, 1);
            $key =~ s/\"$//;    # Allow them to forget the closing "
            $self->add_literal_to_links_table($key, $URL, $switches);
        }
        else {
            $self->add_glob_to_links_table($key, $URL, $switches);
        }
    }

} # parse_dict

sub setup_dict_checking ($) {
    my $self = shift;

    # now create the replace funcs and precomile the regexes
    my ($key, $URL, $switches, $options, $tag1, $tag2);
    my ($pattern, $href, $i, $r_sw, $code, $code_ref);
    for ($i = 1 ; $i < @{$self->{__links_table_order}} ; $i++) {
        $pattern  = $self->{__links_table_order}->[$i];
        $key      = $pattern;
        $switches = $self->{__links_switch_table}->{$key};

        $href = $self->{__links_table}->{$key};

        if (!($switches & $LINK_HTML))
	{
	    $href =~ s#/#\\/#g;
	    if ($self->{lower_case_tags})
	    {
		$href = '<a href="' . $href . '">$&<\\/a>'
	    }
	    else
	    {
		$href = '<A HREF="' . $href . '">$&<\\/A>'
	    }
	}
	else
	{
	    # change the uppercase tags to lower case
	    if ($self->{lower_case_tags})
	    {
		$href =~ s#(</)([A-Z]*)(>)#${1}\L${2}${3}#g;
		$href =~ s/(<)([A-Z]*)(>)/${1}\L${2}${3}/g;
		# and the anchors
		$href =~ s/(<)(A\s*HREF)([^>]*>)/$1\L$2$3/g;
	    }
	    $href =~ s#/#\\/#g;
	}

        $r_sw = "s";    # Options for replacing
        $r_sw .= "i" if ($switches & $LINK_NOCASE);
        $r_sw .= "e" if ($switches & $LINK_EVAL);

        # Generate code for replacements.
        # Create an anonymous subroutine for each replacement,
        # and store its reference in an array.
        # We need to do an "eval" to create these because we need to
        # be able to treat the *contents* of the $href variable
        # as if it were perl code, because sometimes the $href
        # contains things which need to be evaluated, such as $& or $1,
        # not just those cases where we have a "e" switch.
        $code =
"\$self->{__repl_code}->[$i] = sub {\nmy \$al = shift;\n\$al =~ s/$pattern/$href/$r_sw;\nreturn \$al; }\n";
        print STDERR "$code" if ($self->{dict_debug} & 2);
        eval "$code";

        # compile searching pattern
        if ($switches & $LINK_NOCASE)    # i
        {
            $self->{__search_patterns}->[$i] = qr/$pattern/si;
        }
        else {
            $self->{__search_patterns}->[$i] = qr/$pattern/s;
        }
    }
} # setup_dict_checking

sub in_link_context ($$$) {
    my $self		 = shift;
    my ($match, $before) = @_;
    return 1 if $match =~ m@</?A>@i;    # No links allowed inside match

    my ($final_open, $final_close);
    if ($self->{lower_case_tags}) {
	$final_open  = rindex($before, "<a ") - $[;
	$final_close = rindex($before, "</a>") - $[;
    }
    else {
	$final_open  = rindex($before, "<A ") - $[;
	$final_close = rindex($before, "</A>") - $[;
    }

    return 1 if ($final_open >= 0)      # Link opened
      && (($final_close < 0)            # and not closed    or
        || ($final_open > $final_close)
    );    # one opened after last close

    # Now check to see if we're inside a tag, matching a tag name, 
    # or attribute name or value
    $final_open  = rindex($before, "<") - $[;
    $final_close = rindex($before, ">") - $[;
    ($final_open >= 0)    # Tag opened
      && (($final_close < 0)    # and not closed    or
        || ($final_open > $final_close)
    );    # one opened after last close
} # in_link_context

# clear the section-links flags
sub clear_section_links ($) {
    my $self            = shift;

    $self->{__done_with_sect_link} = [];
} # clear_section_links

# Check (and alter if need be) the bits in this line matching
# the patterns in the link dictionary.
sub check_dictionary_links ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};

    my ($i, $pattern, $switches, $options, $repl_func);
    my $key;
    my $s_sw;
    my $r_sw;
    my $line_link = 0;
    if (defined ${$line_action_ref}) {
	($line_link) = (${$line_action_ref} | $LINK);
    }
    else {
	warn "check_dictionary_links: \\line_action_ref undefined!\n";
    }
    my ($before, $linkme, $line_with_links);

    # for each pattern, check and alter the line
    for ($i = 1 ; $i < @{$self->{__links_table_order}} ; $i++) {
        $pattern  = $self->{__links_table_order}->[$i];
        $key      = $pattern;
        $switches = $self->{__links_switch_table}->{$key};

        # check the pattern
        if ($switches & $LINK_ONCE)    # Do link only once
        {
            $line_with_links = "";
            while (!$self->{__done_with_link}->[$i]
                && ${$line_ref} =~ $self->{__search_patterns}->[$i])
            {
                $self->{__done_with_link}->[$i] = 1;
                $line_link = $LINK if (!$line_link);
                $before    = $`;
                $linkme    = $&;

                ${$line_ref} =
                  substr(${$line_ref}, length($before) + length($linkme));
                if (!$self->in_link_context($linkme, $line_with_links . $before)) {
                    print STDERR "Link rule $i matches $linkme\n"
                      if ($self->{dict_debug} & 4);

                    # call the special subroutine already created to do
                    # this replacement
                    $repl_func = $self->{__repl_code}->[$i];
                    $linkme    = &$repl_func($linkme);
                }
                $line_with_links .= $before . $linkme;
            }
            ${$line_ref} = $line_with_links . ${$line_ref};
        }
        elsif ($switches & $LINK_SECT_ONCE)    # Do link only once per section
        {
            $line_with_links = "";
            while (!$self->{__done_with_sect_link}->[$i]
                && ${$line_ref} =~ $self->{__search_patterns}->[$i])
            {
                $self->{__done_with_sect_link}->[$i] = 1;
                $line_link = $LINK if (!$line_link);
                $before    = $`;
                $linkme    = $&;

                ${$line_ref} =
                  substr(${$line_ref}, length($before) + length($linkme));
                if (!$self->in_link_context($linkme, $line_with_links . $before)) {
                    print STDERR "Link rule $i matches $linkme\n"
                      if ($self->{dict_debug} & 4);

                    # call the special subroutine already created to do
                    # this replacement
                    $repl_func = $self->{__repl_code}->[$i];
                    $linkme    = &$repl_func($linkme);
                }
                $line_with_links .= $before . $linkme;
            }
            ${$line_ref} = $line_with_links . ${$line_ref};
        }
        else {
            $line_with_links = "";
            while (${$line_ref} =~ $self->{__search_patterns}->[$i]) {
                $line_link = $LINK if (!$line_link);
                $before    = $`;
                $linkme    = $&;

                ${$line_ref} =
                  substr(${$line_ref}, length($before) + length($linkme));
                if (!$self->in_link_context($linkme, $line_with_links . $before)) {
                    print STDERR "Link rule $i matches $linkme\n"
                      if ($self->{dict_debug} & 4);

                    # call the special subroutine already created to do
                    # this replacement
                    $repl_func = $self->{__repl_code}->[$i];
                    $linkme    = &$repl_func($linkme);
                }
                $line_with_links .= $before . $linkme;
            }
            ${$line_ref} = $line_with_links . ${$line_ref};
        }
    }
    ${$line_action_ref} |= $line_link;    # Cheaper only to do bitwise OR once.
} # check_dictionary_links

sub load_dictionary_links ($) {
    my $self = shift;
    my ($dict, $contents);
    @{$self->{__links_table_order}} = 0;
    %{$self->{__links_table}}       = ();

    foreach $dict (@{$self->{links_dictionaries}}) {
        next unless $dict;
	    open(DICT, "$dict") || die "Can't open Dictionary file $dict\n";

	    $contents = "";
	    $contents .= $_ while (<DICT>);
	    close(DICT);
	    $self->parse_dict($dict, $contents);
    }
    $self->setup_dict_checking();
} # load_dictionary_links

sub make_dictionary_links ($%) {
    my $self            = shift;
    my %args = (
	line_ref=>undef,
	line_action_ref=>undef,
	@_
	);
    my $line_ref        = $args{line_ref};
    my $line_action_ref = $args{line_action_ref};

    $self->check_dictionary_links(line_ref=>$line_ref,
	line_action_ref=>$line_action_ref);
    warn $@ if $@;
} # make_dictionary_links

# do_file_start
#    extra stuff needed for the beginning
# Args:
#   $self
#   $para
# Return:
#   processed $para string
sub do_file_start ($$$) {
    my $self      = shift;
    my $outhandle = shift;
    my $para      = shift;

    if (!$self->{extract}) {
        my @para_lines = split (/\n/, $para);
        my $first_line = $para_lines[0];

	if ($self->{doctype})
	{
	    if ($self->{xhtml})
	    {
		print $outhandle '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"', "\n";
		print $outhandle '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', "\n";
	    }
	    else
	    {
		print $outhandle '<!DOCTYPE HTML PUBLIC "' . $self->{doctype} . "\">\n";
	    }
	}
        print $outhandle $self->get_tag('HTML'), "\n";
        print $outhandle $self->get_tag('HEAD'), "\n";

        # if --titlefirst is set and --title isn't, use the first line
        # as the title.
        if ($self->{titlefirst} && !$self->{title}) {
            my ($tit) = $first_line =~ /^ *(.*)/;    # grab first line
            $tit =~ s/ *$//;                         # strip trailing whitespace
            $tit = escape($tit) if $self->{escape_HTML_chars};
            $self->{'title'} = $tit;
        }
        if (!$self->{title}) {
            $self->{'title'} = "";
        }
        print $outhandle $self->get_tag('TITLE'), $self->{title},
	    $self->get_tag('TITLE', tag_type=>'end'), "\n";

        if ($self->{append_head}) {
            open(APPEND, $self->{append_head})
              || die "Failed to open ", $self->{append_head}, "\n";
            while (<APPEND>) {
                print $outhandle $_;
            }
            close(APPEND);
        }

	if ($self->{lower_case_tags})
	{
	    print $outhandle $self->get_tag('META', tag_type=>'empty',
		inside_tag=>" name=\"generator\" content=\"$PROG v$VERSION\""),
		"\n";
	}
	else
	{
	    print $outhandle $self->get_tag('META', tag_type=>'empty',
		inside_tag=>" NAME=\"generator\" CONTENT=\"$PROG v$VERSION\""),
		"\n";
	}
	if ($self->{style_url})
	{
	    my $style_url = $self->{style_url};
	    if ($self->{lower_case_tags})
	    {
		print $outhandle $self->get_tag('LINK', tag_type=>'empty',
		    inside_tag=>" rel=\"stylesheet\" type=\"text/css\" href=\"$style_url\""),
		"\n";
	    }
	    else
	    {
		print $outhandle $self->get_tag('LINK', tag_type=>'empty',
		    inside_tag=>" REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"$style_url\""),
		"\n";
	    }
	}
        print $outhandle $self->get_tag('HEAD', tag_type=>'end'), "\n";
	if ($self->{body_deco})
	{
	    print $outhandle $self->get_tag('BODY',
		inside_tag=>$self->{body_deco}), "\n";
	}
	else
	{
	    print $outhandle $self->get_tag('BODY'), "\n";
	}
    }

    if ($self->{prepend_file}) {
        if (-r $self->{prepend_file}) {
            open(PREPEND, $self->{prepend_file});
            while (<PREPEND>) {
                print $outhandle $_;
            }
            close(PREPEND);
        }
        else {
            print STDERR "Can't find or read file ", $self->{prepend_file},
              " to prepend.\n";
        }
    }
} # do_file_start

# do_init_call
# certain things, like reading link dictionaries, need to be
# done once
sub do_init_call ($) {
    my $self     = shift;

    if (!$self->{__call_init_done}) {
	push (@{$self->{links_dictionaries}}, ($self->{default_link_dict}))
	  if ($self->{make_links} && (-f $self->{default_link_dict}));
	$self->deal_with_options();
	if ($self->{make_links}) {
	    push (@{$self->{links_dictionaries}}, ($self->{system_link_dict}))
	      if -f $self->{system_link_dict};
	    $self->load_dictionary_links();
	}
     
	# various initializations
	$self->{__non_header_anchor} = 0;
	$self->{__mode}              = 0;
	$self->{__listnum}           = 0;
	$self->{__list_nice_indent}       = '';
	$self->{__list_indent}	= [];
	$self->{__tags}		     = [];

	$self->{__call_init_done} = 1;
    }
} # do_init_call

# run this from the command line
sub run_txt2html {
    my ($caller) = @_;    # ignore all passed in arguments,
                          # because this only should look at ARGV

    my $conv = new HTML::TextToHTML(\@ARGV);

    my @args = ();

    # now the remainder must be input-files
    foreach my $df (@ARGV) {
        push @args, "--infile", $df;
    }
    $conv->txt2html(\@args);
} # run_txt2html

=head1 FILE FORMATS

There are two files which are used which can affect the outcome of the
conversion.  One is the link dictionary, which contains patterns (of how
to recognise http links and other things) and how to convert them. The
other is, naturally, the format of the input file itself.

=head2 Link Dictionary

A link dictionary file contains patterns to match, and what to convert
them to.  It is called a "link" dictionary because it was intended to be
something which defined what a href link was, but it can be used for
more than that.  However, if you wish to define your own links, it is
strongly advised to read up on regular expressions (regexes) because
this relies heavily on them.

The file consists of comments (which are lines starting with #)
and blank lines, and link entries.
Each entry consists of a regular expression, a -> separator (with
optional flags), and a link "result".

In the simplest case, with no flags, the regular expression
defines the pattern to look for, and the result says what part
of the regular expression is the actual link, and the link which
is generated has the href as the link, and the whole matched pattern
as the visible part of the link.  The first character of the regular
expression is taken to be the separator for the regex, so one
could either use the traditional / separator, or something else
such as | (which can be helpful with URLs which are full of / characters).

So, for example, an ftp URL might be defined as:

    |ftp:[\w/\.:+\-]+|      -> $&

This takes the whole pattern as the href, and the resultant link
has the same thing in the href as in the contents of the anchor.

But sometimes the href isn't the whole pattern.

    /&lt;URL:\s*(\S+?)\s*&gt;/ --> $1

With the above regex, a () grouping marks the first subexpression,
which is represented as $1 (rather than $& the whole expression).
This entry matches a URL which was marked explicity as a URL
with the pattern <URL:foo>  (note the &lt; is shown as the
entity, not the actual character.  This is because by the
time the links dictionary is checked, all such things have
already been converted to their HTML entity forms)
This would give us a link in the form
<A HREF="foo">&lt;URL:foo&gt;</A>

B<The h flag>

However, if we want more control over the way the link is constructed,
we can construct it ourself.  If one gives the h flag, then the
"result" part of the entry is taken not to contain the href part of
the link, but the whole link.

For example, the entry:

    /&lt;URL:\s*(\S+?)\s*&gt;/ -h-> <A HREF="$1">$1</A>

will take <URL:foo> and give us <A HREF="foo">foo</A>

However, this is a very powerful mechanism, because it
can be used to construct custom tags which aren't links at all.
For example, to flag *italicised words* the following
entry will surround the words with EM tags.

    /\B\*([a-z][a-z -]*[a-z])\*\B/ -hi-> <EM>$1</EM>

B<The i flag>

This turns on ignore case in the pattern matching.

B<The e flag>

This turns on execute in the pattern substitution.  This really
only makes sense if h is turned on too.  In that case, the "result"
part of the entry is taken as perl code to be executed, and the
result of that code is what replaces the pattern.

B<The o flag>

This marks the entry as a once-only link.  This will convert the
first instance of a matching pattern, and ignore any others
further on.

For example, the following pattern will take the first mention
of HTML::TextToHTML and convert it to a link to the module's home page.

    "HTML::TextToHTML"  -io-> http://www.katspace.com/tools/text_to_html/

=head2 Input File Format

For the most part, this module tries to use intuitive conventions for
determining the structure of the text input.  Unordered lists are
marked by bullets; ordered lists are marked by numbers or letters;
in either case, an increase in indentation marks a sub-list contained
in the outer list.

Headers (apart from custom headers) are distinguished by "underlines"
underneath them; headers in all-capitals are distinguished from
those in mixed case.  All headers, both normal and custom headers,
are expected to start at the first line in a "paragraph".

In other words, the following is a header:

    I am Head Man
    -------------

But the following does not have a header:

    I am not a head Man, man
    I am Head Man
    -------------

Tables require a more rigid convention.  A table must be marked as a
separate paragraph, that is, it must be surrounded by blank lines.
Tables come in different types.  For a table to be parsed, its
--table_type option must be on, and the --make_tables option must be true.

B<ALIGN Table Type>

Columns must be separated by two or more spaces (this prevents
accidental incorrect recognition of a paragraph where interword spaces
happen to line up).  If there are two or more rows in a paragraph and
all rows share the same set of (two or more) columns, the paragraph is
assumed to be a table.  For example

    -e  File exists.
    -z  File has zero size.
    -s  File has nonzero size (returns size).

becomes

    <TABLE>
    <TR><TD>-e</TD><TD>File exists.</TD></TR>
    <TR><TD>-z</TD><TD>File has zero size.</TD></TR>
    <TR><TD>-s</TD><TD>File has nonzero size (returns size).</TD></TR>
    </TABLE>

This guesses for each column whether it is intended to be left,
centre or right aligned.

B<BORDER Table Type>

This table type has nice borders around it, and will be rendered
with a border, like so:

    +---------+---------+
    | Column1 | Column2 |
    +---------+---------+
    | val1    | val2    |
    | val3    | val3    |
    +---------+---------+

The above becomes

    <TABLE border="1">
    <THEAD><TR><TH>Column1</TH><TH>Column2</TH></TR></THEAD>
    <TBODY>
    <TR><TD>val1</TD><TD>val2</TD></TR>
    <TR><TD>val3</TD><TD>val3</TD></TR>
    </TBODY>
    </TABLE>

It can also have an optional caption at the start.

         My Caption
    +---------+---------+
    | Column1 | Column2 |
    +---------+---------+
    | val1    | val2    |
    | val3    | val3    |
    +---------+---------+

B<PGSQL Table Type>

This format of table is what one gets from the output of a Postgresql
query.

     Column1 | Column2
    ---------+---------
     val1    | val2
     val3    | val3
    (2 rows)

This can also have an optional caption at the start.
This table is also rendered with a border and table-headers like
the BORDER type.

B<DELIM Table Type>

This table type is delimited by non-alphanumeric characters, and has to
have at least two rows and two columns before it's recognised as a table.

This one is delimited by the '| character:

    | val1  | val2  |
    | val3  | val3  |

But one can use almost any suitable character such as : # $ % + and so on.
This is clever enough to figure out what you are using as the delimiter
if you have your data set up like a table.  Note that the line has to
both begin and end with the delimiter, as well as using it to separate
values.

This can also have an optional caption at the start.

=head1 EXAMPLES

    use HTML::TextToHTML;
 
=head2 Create a new object

    my $conv = new HTML::TextToHTML();

    my $conv = new HTML::TextToHTML(title=>"Wonderful Things",
			    system_link_dict=>$my_link_file,
      );

    my $conv = new HTML::TextToHTML(\@ARGV);

=head2 Add further arguments

    $conv->args(short_line_length=>60,
	       preformat_trigger_lines=>4,
	       caps_tag=>"strong",
      );

=head2 Convert a file

    $conv->txt2html(infile=>[$text_file],
                     outfile=>$html_file,
		     title=>"Wonderful Things",
		     mail=>1
      );

    $conv->txt2html(["--file", $text_file,
                     "--outfile", $html_file,
		     "--title", "Wonderful Things",
			 "--mail"
      ]);

=head1 NOTES

=over 4

=item *

One cannot use "CLEAR" as a value for the cumulative arguments.

=item *

If the underline used to mark a header is off by more than 1, then 
that part of the text will not be picked up as a header unless you
change the value of --underline_length_tolerance and/or
--underline_offset_tolerance.  People tend to forget this.

=back 4

=head1 BUGS

Tell me about them.

=head1 PREREQUSITES

HTML::TextToHTML requires Perl 5.005_03 or later.

It also requires Data::Dumper (only for debugging purposes)

=head1 EXPORT

run_txt2html

=head1 AUTHOR

Kathryn Andersen, E<lt>http//www.katspace.comE<gt> 2002,2003
Original txt2html script copyright (C) 2000 Seth Golub <seth AT aigeek.com>

=head1 SEE ALSO

L<perl>.
L<txt2html>.
Data::Dumper

=cut

#------------------------------------------------------------------------
1;