aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/extras/rman/rman.c
blob: 1f0d540ba9bbb86d49c78c6a03da38b40d34e3ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
#ifdef UNDEF
static char cvsid[] = "Header: /usr/build/rman/rman-031225/phelps/RCS/rman.c,v 1.154 2003/07/26 19:00:48 phelps Exp $";
#endif

/*
   PolyglotMan by Thomas A. Phelps (phelps@ACM.org)

  accept man pages as formatted by (10)
     Hewlett-Packard HP-UX, AT&T System V, SunOS, Sun Solaris, OSF/1,
     DEC Ultrix, SGI IRIX, Linux, FreeBSD, SCO

  output as (9)
     printable ASCII, section headers only, TkMan, [tn]roff, HTML,
     LaTeX, LaTeX2e, RTF, Perl pod, MIME, DocBook XML

  written March 24, 1993
	bs2tk generalized into RosettaMan November 4-5, 1993
	source interpretation added September 24, 1996
	renamed PolyglotMan due to lawsuit by Rosetta, Inc. August 8, 1997
*/
/* $XFree86: xc/extras/rman/rman.c,v 1.18 2003/10/22 19:50:36 tsi Exp $ */

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#if defined(Lynx) || defined(__QNXNTO__)
extern int optind;
extern char *optarg;
#endif
#ifdef __CYGWIN__
#include <getopt.h>
#endif

/*** make #define's into consts? => can't because compilers not smart enough ***/
/* maximum number of tags per line */
#define MAXTAGS 50*100
#define MAXBUF 2*5000
#define MAXLINES 20000
#define MAXTOC 500
#define xputchar(c)		(fcharout? putchar(c): (c))
#define sputchar(c)		(fcharout? plain[sI++]=(char)c: (char)(c))
#define stagadd(tag)	tagadd(tag,sI,0)
enum { c_dagger='\xa7', c_bullet='\xb7', c_plusminus='\xb1' };


/*** tag management ***/

enum tagtype { NOTAG, TITLE, ITALICS, BOLD, SYMBOL, SMALLCAPS, BOLDITALICS, MONO, MANREF };	/* MANREF last */
struct { enum tagtype type; int first; int last; } tags[MAXTAGS], tagtmp;
int tagc=0;
struct { char *text; int type; int line; } toc[MAXTOC];
int tocc=0;


/* characters in this list automatically prefixed by a backslash (set in output format function */
char *escchars="";
char *vollist = VOLLIST;
const char *manvalid = "._-+:";	/* in addition to alphanumerics, valid characters to find in a man page name */
char *manrefname;
char *manrefsect;

enum command {
	NOCOMMAND=-1,

	/*BEGINCHARTAGS,*/
	CHARTAB='\t',
	CHARPERIOD='.', CHARLSQUOTE='`', CHARRSQUOTE='\'', CHARGT='>', CHARLT='<',
	CHARAMP='&', CHARBACKSLASH='\\', CHARDASH='-', CHARHAT='^', CHARVBAR='|',
 	CHARNBSP=0xa0,	CHARCENT=0xa2, CHARSECT=0xa7, CHARCOPYR=0xa9, CHARNOT=0xac,
 	CHARDAGGER=0xad, CHARREGTM=0xae, CHARDEG=0xb0, CHARPLUSMINUS=0xb1,
 	CHARACUTE=0xb4, CHARBULLET=0xb7, CHAR14=0xbc, CHAR12=0xbd, CHAR34=0xbe,
 	CHARMUL=0xd7, CHARDIV=0xf7,
	CHANGEBAR=0x100, CHARLQUOTE, CHARRQUOTE,
	/*ENDCHARTAGS,*/

	/*BEGINFONTTAGS,*/
	BEGINBOLD, ENDBOLD, BEGINITALICS, ENDITALICS, BEGINBOLDITALICS, ENDBOLDITALICS,
	BEGINSC, ENDSC, BEGINY, ENDY, BEGINCODE, ENDCODE, BEGINMANREF, ENDMANREF,
	FONTSIZE,
	/*ENDFONTTAGS*/

	/*BEGINLAYOUTTAGS,*/
	ITAB, BEGINCENTER, ENDCENTER, HR,
	/*ENDLAYOUTTAGS,*/

	/*BEGINSTRUCTTAGS,*/
	BEGINDOC, ENDDOC, BEGINCOMMENT, ENDCOMMENT, COMMENTLINE, BEGINBODY, ENDBODY,
	BEGINHEADER, ENDHEADER, BEGINFOOTER, ENDFOOTER, BEGINLINE, ENDLINE, SHORTLINE,
	BEGINSECTION, ENDSECTION, BEGINSUBSECTION, ENDSUBSECTION,
	BEGINSECTHEAD, ENDSECTHEAD, BEGINSUBSECTHEAD, ENDSUBSECTHEAD,
	BEGINBULPAIR, ENDBULPAIR, BEGINBULLET, ENDBULLET, BEGINBULTXT, ENDBULTXT,
	BEGINTABLE, ENDTABLE, BEGINTABLELINE, ENDTABLELINE, BEGINTABLEENTRY, ENDTABLEENTRY,
	BEGININDENT, ENDINDENT, BEGINCODEBLOCK, ENDCODEBLOCK,

	BEGINDIFFA, ENDDIFFA, BEGINDIFFD, ENDDIFFD
	/*,*//*ENDSTRUCTTAGS,*/
};

const char *tcltkOP[] = { "Command-Line Name", "Database Name", "Database Class" };


/* characters that need special handling in any output format, *more than just a backslash* */
/* characters in this list need a corresponding case statement in each output format */
/*char *trouble="\t.`'><&\\^|-\xa7\xb7\xb1";*/
const unsigned char trouble[]= { CHARTAB, CHARPERIOD, CHARLSQUOTE, CHARRSQUOTE,
	CHARGT, CHARLT, CHARAMP, CHARBACKSLASH, CHARDASH, CHARHAT, CHARVBAR, CHARCENT,
	CHARSECT, CHARCOPYR, CHARNOT, CHARDAGGER, CHARREGTM, CHARDEG, CHARPLUSMINUS,
	CHARACUTE, CHARBULLET, CHAR14, CHAR12, CHAR34, CHARMUL, CHARDIV,
	0 };


enum command tagbeginend[][2] = {	/* parallel to enum tagtype */
	{ NOCOMMAND, NOCOMMAND },
	{ NOCOMMAND, NOCOMMAND },
	{ BEGINITALICS, ENDITALICS },
	{ BEGINBOLD, ENDBOLD },
	{ BEGINY, ENDY },
	{ BEGINSC, ENDSC },
	{ BEGINBOLDITALICS, ENDBOLDITALICS },
	{ NOCOMMAND, NOCOMMAND },
	{ BEGINMANREF, ENDMANREF }
};

void (*fn)(enum command) = NULL;
enum command prevcmd = BEGINDOC;


/*** globals ***/

int fSource=-1;	/* -1 => not determined yet */
int finlist=0;
int fDiff=0;
FILE *difffd;
char diffline[MAXBUF];
char diffline2[MAXBUF];
char *message = NULL;
int fontdelta=0;
int intArg;

int fPara=0;			/* line or paragraph groupings of text */
int fSubsections=0;	/* extract subsection titles too? */
int fChangeleft=0;	/* move change bars to left? (-1 => delete them) */
int fReflow=0;
int fURL=0;		/* scan for URLs too? */
#if 0
int fMan=1;		/* invoke agressive man page filtering? */
#endif
int fQS=0;		/* squeeze out spaces (scnt and interword)? */
int fIQS=0;		/* squeeze out initial spaces (controlled separately from fQS) */
int fILQS=0;		/* squeeze out spaces for usual indent */
int fHeadfoot=0;	/* show canonical header and footer at bottom? */
int falluc=0;
int itabcnt=0;
int fQuiet=0;
int fTclTk=0;

/* patterns observed in section heads that don't conform to first-letter-uppercase-rest-lowercase pattern (stay all uc, or go all lc, or have subsequent uc) */
int lcexceptionslen = -1;	/* computed by system */
char *lcexceptions[] = {
/* new rule: double/all consonants == UC? */
	/* articles, verbs, conjunctions, prepositions, pronouns */
	"a", "an", "the",
	"am", "are", "is", "were",
	"and", "or",
	"by", "for", "from", "in", "into", "it", "of", "on", "to", "with",
	"that", "this",

	/* terms */
	"API", "CD", "GUI", "UI", /*I/O=>I/O already*/ "ID", "IDs", "OO",
	"IOCTLs", "IPC", "RPC",

	/* system names */
	"AWK", "cvs", "rcs", "GL", "vi", "PGP", "QuickTime", "DDD", "XPG/3",
	"NFS", "NIS", "NIS+", "AFS",
	"UNIX", "SysV",
	"Xorg", "XOrg", "X.Org", "XFree86", "ICCCM",
	"MH", "MIME",
	"TeX", "LaTeX", "PicTeX",
	"PostScript", "EPS", "EPSF", "EPSI",
	"HTML", "URL", "WWW",

	/* institution names */
	"ANSI", "CERN", "GNU", "ISO", "NCSA",

	/* Sun-specific */
	"MT-Level", "SPARC",

	NULL
};


int TabStops=8;
int hanging=0;		/* location of hanging indent (if ==0, none) */
enum { NAME, SYNOPSIS, DESCRIPTION, SEEALSO, FILES, AUTHOR, RANDOM/*last!*/ };
char *sectheadname[] = {
  "NAME:NOMBRE", "SYNOPSIS", "DESCRIPTION:INTRODUCTION", "SEE ALSO:RELATED INFORMATION", "FILES", "AUTHOR:AUTHORS", "RANDOM"
};
int sectheadid = RANDOM;
int oldsectheadid = RANDOM;

int fCodeline=0;
int fNOHY=0;		/* re-linebreak so no words are hyphenated; not used by TkMan, but gotta keep for people converting formatted text */
int fNORM=0;		/* normalize?  initial space => tabs, no changebars, exactly one blank line between sections */
const char TABLEOFCONTENTS[] = "Table of Contents";
const char HEADERANDFOOTER[] = "Header and Footer";
char manName[80] = "man page";
char manSect[10] = "1";
const char PROVENANCE[] =
	"manual page source format generated by PolyglotMan v" POLYGLOTMANVERSION;
const char HOME[] = "available at http://polyglotman.sourceforge.net/";
const char horizontalrule[] = "------------------------------------------------------------";

const int LINEBREAK = 70;
int linelen = 0;		/* length of result in plain[] */
int spcsqz;		/* number of spaces squeezed out */
int ccnt = 0;	/* # of changebars */
int scnt, scnt2;	/* counts of initial spaces in line */
int s_sum, s_cnt;
int bs_sum, bs_cnt;
int ncnt=0, oncnt=0;	/* count of interline newlines */
int CurLine=1;
int AbsLine=1-1;	/* absolute line number */
int indent=0;		/* global indentation */
int lindent=0;		/* usual local indent */
int auxindent=0;	/* aux indent */
int I;			/* index into line/paragraph */
int fcharout=1;		/* show text or not */
char lookahead;
/*int tabgram[MAXBUF];*/	/* histogram of first character positions */
char buf[MAXBUF];
char plain[MAXBUF];		/* current text line with control characters stripped out */
char hitxt[MAXBUF];		/* highlighted text (available at time of BEGIN<highlight> signal */

char header[MAXBUF];	/* complete line */
char header2[MAXBUF];	/* SGIs have two lines of headers and footers */
char header3[MAXBUF];	/* GNU and some others have a third! */
char footer[MAXBUF];
char footer2[MAXBUF];
#define CRUFTS 5
char *cruft[CRUFTS] = { header, header2, header3, footer, footer2 };

char *File, *in;		/* File = pointer to full file contents, in = current file pointer */
char *argv0;
int finTable=0;
char tableSep='\0';	/*\t';*/
/*int fTable=0;
int fotable=0;*/
char *tblcellformat;
int tblcellspan;
/*int tblspanmax;*/
int listtype=-1;	/* current list type bogus to begin with */
enum listtypes { DL, OL, UL };

int fIP=0;



/*** utility functions ***/


/* case insensitive versions of strcmp and strncmp */

static int
stricmp(const char *s1, const char *s2)
{
	assert(s1!=NULL && s2!=NULL);
	/*strincmp(s1, s2, strlen(s1)+1);*/

	while (tolower(*s1)==tolower(*s2)) {
		if (*s1=='\0' /*&& *s2=='\0'*/) return 0;
		s1++; s2++;
	}

	if (tolower(*s1)<tolower(*s2)) return -1;
	else return 1;
}

static int
lcexceptionscmp(const void *a, const void *b)
{
	return stricmp(*(char **)a, *(char **)b);
}

static int
strincmp(const char *s1, const char *s2, size_t n)
{
	assert(s1!=NULL && s2!=NULL && n>0);

	while (n>0 && tolower(*s1)==tolower(*s2)) {
		n--; s1++; s2++;
	}
	if (n==0) return 0;
	else if (tolower(*s1)<tolower(*s2)) return -1;
	else return 1;
}

/* compare string and a colon-separated list of strings */
static int
strcoloncmp2(char *candidate, int end, const char *list, int sen)
{
	const char *l = list;
	char *c,c2;

	assert(candidate!=NULL && list!=NULL);
	assert(end>=-1 && end<=255);
	assert(sen==0 || sen==1);

	if (*l==':') l++;	/* tolerate a leading colon */

	/* invariant: c and v point to start of strings to compare */
	while (*l) {
		assert(l==list || l[-1]==':');
		for (c=candidate; *c && *l; c++,l++)
			if ((sen && *c!=*l) || (!sen && tolower(*c)!=tolower(*l)))
				break;

		/* if candidate matches a valid one as far as valid goes, it's a keeper */
		if ((*l=='\0' || *l==':') && (*c==end || end==-1)) {
		  if (*c=='\b') {
		    c2 = c[-1];
		    while (*c=='\b' && c[1]==c2) c+=2;
		  }
		  /* no volume qualifiers with digits */
		  if (!isdigit(*c)) return 1;
		}

		/* bump to start of next valid */
		while (*l && *l++!=':') /* nada */;
	}

	return 0;
}

static int
strcoloncmp(char *candidate, int end, const char *list)
{
	int sen=1;
	const char *l = list;

	assert(candidate!=NULL && list!=NULL);
	assert(end>=-1 && end<=255);

	if (*l=='=') l++; else end=-1;
	if (*l=='i') { sen=0; l++; }

	return strcoloncmp2(candidate, end, l, sen);
}

/* strdup not universally available */
static char *
mystrdup(const char *p)
{
  char *q;

  if (p==NULL) return NULL;

  q = malloc(strlen(p)+1);	/* +1 gives space for \0 that is not reported by strlen */
  if (q!=NULL) strcpy(q,p);
  return q;
}


/* given line of text, return "casified" version in place:
   if word in exceptions list, return exception conversion
   else uc first letter, lc rest
*/
static void
casify(char *p)
{
	char tmpch, *q, **exp;
	int fuc;

	for (fuc=1; *p; p++) {
		if (isspace(*p) || strchr("&/",*p)!=NULL) fuc=1;
		else if (fuc) {
			/* usually */
				if (p[1] && isupper(p[1]) /*&& p[2] && isupper(p[2])*/) fuc=0;
			/* check for exceptions */
			for (q=p; *q && !isspace(*q); q++) /*nada*/;
			tmpch = *q; *q='\0';
			exp = (char **)bsearch(&p, lcexceptions, lcexceptionslen, sizeof(char *), lcexceptionscmp);
			*q = tmpch;
			if (exp!=NULL) {
				for (q=*exp; *q; q++) *p++=*q;
				fuc = 1;
			}
		} else *p=tolower(*p);
	}
}


/* add an attribute tag to a range of characters */

static void
tagadd(int /*enum tagtype--abused in source parsing*/ type, int first, int last)
{
	assert(type!=NOTAG);

	if (tagc<MAXTAGS) {
		tags[tagc].type = (enum tagtype)type;
		tags[tagc].first = first;
		tags[tagc].last = last;
		tagc++;
	}
}


/*
   collect all saves to string table one one place, so that
   if decide to go with string table instead of multiple malloc, it's easy
   (probably few enough malloc's that more sophistication is unnecessary)
*/

static void
tocadd(char *text, enum command type, int line)
{
	char *r;

	assert(text!=NULL && strlen(text)>0);
	assert(type==BEGINSECTION || type==BEGINSUBSECTION);

	if (tocc<MAXTOC) {
		r = malloc(strlen(text)+1); if (r==NULL) return;
		strcpy(r,text);
		toc[tocc].text = r;
		toc[tocc].type = type;
		toc[tocc].line = line;
		tocc++;
	}
}



char *manTitle = MANTITLEPRINTF;
char *manRef = MANREFPRINTF;
char *href;
int fmanRef=1;	/* make 'em links or just show 'em? */

static void
manrefextract(char *p)
{
  char *p0;
  static char *nonhref = "\">'";
  static char *punct = ".,:;)]}?!";

  while (*p==' ') p++;
  if (strincmp(p,"http",4)==0) {
	href="%s"; manrefname = p;
	p+=4;
	while (*p && !isspace(*p) && !strchr(nonhref,*p)) p++;
	while (strchr(punct, *(p - 1))) p--;
  } else {
	href = manRef;

	manrefname = p;
	while (*p && *p!=' ' && *p!='(') p++; *p++='\0';
	while (*p==' ' || *p=='(') p++; p0=p;
#if defined(XOrg) || defined(XFree86)
	/* Don't allow a letter after the man section number */
	p++;
#else
	while (*p && *p!=')') p++;
#endif
	manrefsect = p0;
  }
  *p='\0';
}




/*
 * OUTPUT FORMATS
 */

static void
formattedonly(void)
{
	fprintf(stderr, "The output formats for Tk and TkMan require nroff-formatted input\n");
	exit(1);
}


/*
 * DefaultFormat -- in weak OO inheritance, top of hierarchy for everybody
 */
static void
DefaultFormat(enum command cmd)
{
  int i;

  switch (cmd) {
  case ITAB:
    for (i=0; i<itabcnt; i++) putchar('\t');
    break;
  default:
    /* nada */
    break;
  }
}


/*
 * DefaultLine -- in weak OO inheritance, top of hierarchy for line-based formats
 * for output format to "inherit", have "default: DefaultLine(cmd)" and override case statement "methods"
 */

static void
DefaultLine(enum command cmd) {
	switch (cmd) {
	default:
	  DefaultFormat(cmd);
	}
}


/*
 * DefaultPara -- top of hierarchy for output formats that are formatted by their viewers
 */

static void
DefaultPara(enum command cmd)
{
	switch (cmd) {
	default:
	  DefaultFormat(cmd);
	}
}



/*
 * Tk -- just emit list of text-tags pairs
 */

static void
Tk(enum command cmd)
{
	static int skip=0;	/* skip==1 when line has no text */
	int i;

	if (fSource) formattedonly();

	/* invariant: always ready to insert text */

	switch (cmd) {
	   case BEGINDOC:
		I=0; CurLine=1;
		escchars = "\"[]$";
		printf(/*$t insert end */ "\"");
		break;
	   case ENDDOC:
		if (fHeadfoot) {
/*	grr, should have +mark syntax for Tk text widget! -- maybe just just +sect#, +subsect#
		printf("\\n\\n\" {} \"%s\\n\" {+headfoot h2}\n", HEADERANDFOOTER);
*/
			printf("\\n\\n\" {} \"%s\\n\" h2\n",HEADERANDFOOTER);
			/*printf("$t mark set headfoot %d.0\n", CurLine);*/
			CurLine++;

			for (i=0; i<CRUFTS; i++) {
				if (*cruft[i]) {
					printf(/*$t insert end */"{%s} sc \\n\n", cruft[i]);
					CurLine++;
				}
			}
		} else printf("\"\n");
		break;

	   case COMMENTLINE: printf("# "); break;

	   case BEGINLINE:
		/*I=0; -- need to do this at end of line so set for filterline() */
		/* nothing to do at start of line except catch up on newlines */
		for (i=0; i<ncnt; i++) printf("\\n");
		CurLine+=ncnt;
		/*if (fSource) for (i=0; i<indent; i++) putchar('\t');*/
		break;
	   case ENDLINE:
		/*if (!fSource) {*/
		  if (!skip) /*if (ncnt)*/ printf("\\n"); /*else xputchar(' ');*/
		  skip=0;
		  CurLine++; I=0;
		/*
		} else {
		  putchar(' '); I++;
		}
		*/
		break;

	   case ENDSECTHEAD:
		printf("\\n\" h2 \"");
		tagc=0;
		skip=1;
		break;
	   case ENDSUBSECTHEAD:
		printf("\\n\" h3 \"");	/* add h3? */
		tagc=0;
		skip=1;
		break;
	   case HR:			/*printf("\\n%s\\n", horizontalrule); CurLine+=2; I=0;*/ break;
	   case BEGINTABLEENTRY:
		/*if (fSource) putchar('\t');*/
		break;
	   case BEGINTABLELINE:
	   case ENDTABLEENTRY:
		break;
	   case ENDTABLELINE:
		printf("\" tt \"");
		/*tagadd(MONO, 0, I);*/
		break;

	   case CHANGEBAR:		putchar('|'); I++; break;
	   case CHARLQUOTE:
	   case CHARRQUOTE:
		putchar('\\'); putchar('"'); I++;
		break;
	   case CHARLSQUOTE:
	   case CHARRSQUOTE:
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARLT:
	   case CHARGT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARAMP:
	   case CHARPLUSMINUS:
	   case CHARNBSP:
 	   case CHARCENT:
 	   case CHARSECT:
 	   case CHARCOPYR:
 	   case CHARNOT:
 	   case CHARREGTM:
 	   case CHARDEG:
 	   case CHARACUTE:
 	   case CHAR14:
 	   case CHAR12:
 	   case CHAR34:
 	   case CHARMUL:
 	   case CHARDIV:
  		putchar(cmd); I++; break;
 	   case CHARDAGGER:
 		putchar('+'); I++; break;
	   case CHARBACKSLASH:	printf("\\\\"); I++; break;
	   case CHARBULLET:		printf("\" {} %c symbol \"",c_bullet); I++; break;


	   case BEGINSECTHEAD:
	   case BEGINSUBSECTHEAD:
		/*if (fSource && sectheadid!=NAME) { printf("\\n\\n"); CurLine+=2; I=0; }*/
		tagc=0;	/* section and subsection formatting controlled descriptively */
		/* no break;*/

	   case BEGINBOLD:
	   case BEGINITALICS:
	   case BEGINBOLDITALICS:
	   case BEGINCODE:
	   case BEGINY:
	   case BEGINSC:
	   case BEGINMANREF:
		/* end text, begin attributed text */
		printf("\" {} \"");
		break;

	   /* rely on the fact that no more than one tag per range of text */
	   case ENDBOLD:		printf("\" b \""); break;
	   case ENDITALICS:		printf("\" i \""); break;
	   case ENDBOLDITALICS:	printf("\" bi \""); break;
	   case ENDCODE:		printf("\" tt \""); break;
	   case ENDY:			printf("\" symbol \""); break;
	   case ENDSC:			printf("\" sc \""); break;
	   case ENDMANREF:		printf("\" manref \""); break;
		/* presentation attributes dealt with at end of line */

	   case BEGINBODY:
		/*if (fSource) { printf("\\n\\n"); CurLine+=2; I=0; }*/
		break;
	   case SHORTLINE:
		/*if (fSource) { printf("\\n"); CurLine++; I=0; }*/
		break;
	   case ENDBODY:
	   case BEGINBULPAIR: case ENDBULPAIR:
		/*if (fSource) { printf("\\n"); CurLine++; I=0; }*/
		break;
	   case BEGINBULTXT:
		/*if (fSource) putchar('\t');*/
		break;
	   case BEGINBULLET: case ENDBULLET:
	   case ENDBULTXT:
	   case BEGINSECTION: case ENDSECTION:
	   case BEGINSUBSECTION: case ENDSUBSECTION:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case BEGINTABLE: case ENDTABLE:
	   case FONTSIZE:
	   case BEGININDENT: case ENDINDENT:
		/* no action */
		break;
	   default:
		DefaultLine(cmd);
	}
}


/*
 * TkMan -- Tk format wrapped with commands
 */

int linetabcnt[MAXLINES];	/* don't want to bother with realloc */
int clocnt=0, clo[MAXLINES];
int paracnt=0, para[MAXLINES];
int rebuscnt=0, rebus[MAXLINES];
int rebuspatcnt=0, rebuspatlen[25];
char *rebuspat[25];

static void
TkMan(enum command cmd)
{
	static int lastscnt=-1;
	static int lastlinelen=-1;
	static int lastsect=0;
	/*static int coalese=0;*/
	static int finflow=0;
	int i;
	char c,*p;

	/* invariant: always ready to insert text */

	switch (cmd) {
	   case BEGINDOC:
		printf("$t insert end ");	/* opening quote supplied in Tk() below */
		Tk(cmd);
		break;
	   case ENDDOC:
		Tk(ENDLINE);

		if (fHeadfoot) {
/*	grr, should have +mark syntax for Tk text widget!
		printf("\\n\\n\" {} \"%s\\n\" {+headfoot h2}\n", HEADERANDFOOTER);
*/
			printf("\\n\\n\" {} \"%s\\n\" h2\n", HEADERANDFOOTER);
/*			printf("$t mark set headfoot end-2l\n");*/
			CurLine++;

			for (i=0; i<CRUFTS; i++) {
				if (*cruft[i]) {
					printf("$t insert end {%s} sc \\n\n", cruft[i]);
					CurLine++;
				}
			}
		} else printf("\"\n");

/*
		printf("$t insert 1.0 {");
		for (i=0; i<MAXBUF; i++) if (tabgram[i]) printf("%d=%d, ", i, tabgram[i]);
		printf("\\n\\n}\n");
*/

		printf("set manx(tabcnts) {"); for (i=1; i<CurLine; i++) printf("%d ", linetabcnt[i]); printf("}\n");
		printf("set manx(clo) {"); for (i=0; i<clocnt; i++) printf("%d ", clo[i]); printf("}\n");
		printf("set manx(para) {"); for (i=0; i<paracnt; i++) printf("%d ", para[i]); printf("}\n");
		printf("set manx(reb) {"); for (i=0; i<rebuscnt; i++) printf("%d ", rebus[i]); printf("}\n");

		break;

	   case BEGINCOMMENT: fcharout=0; break;
	   case ENDCOMMENT: fcharout=1; break;
	   case COMMENTLINE: break;

	   case ENDSECTHEAD:
	   case ENDSUBSECTHEAD:
		lastsect=1;
		Tk(cmd);
		break;

	   case BEGINLINE:
	     Tk(cmd);
		linetabcnt[CurLine] = itabcnt;
		/* old pattern for command line options "^\\|*\[ \t\]+-\[^-\].*\[^ \t\]" */
		c = plain[0];
		if (linelen>=2 && ((c=='-' || c=='%' || c=='\\' || c=='$' /**/ /* not much talk of money in man pages so reasonable */) && (isalnum(plain[1]) /*<= plain[1]!='-'*//*no dash*/ || ncnt/*GNU long option*/) && plain[1]!=' ') ) clo[clocnt++] = CurLine;
		/*
		   would like to require second letter to be a capital letter to cut down on number of matches,
		   but command names usually start with lowercase letter
		   maybe use a uppercase requirement as secondary strategy, but probably not
		*/
		if ((ncnt || lastsect) && linelen>0 && scnt>0 && scnt<=7/*used to be <=5 until groff spontaneously started putting in 7*/) para[paracnt++] = CurLine;
		lastsect=0;


		/* rebus too, instead of search through whole Tk widget */
		if (rebuspatcnt && scnt>=5 /* not sect or subsect heads */) {
			for (p=plain; *p && *p!=' '; p++) /*empty*/;	/* never first word */
			while (*p) {
				for (i=0; i<rebuspatcnt; i++) {
					if (tolower(*p) == tolower(*rebuspat[i]) && strincmp(p, rebuspat[i], rebuspatlen[i])==0) {
						/* don't interfere with man page refs */
						for (; *p && !isspace(*p); p++) if (*p=='(') continue;
						rebus[rebuscnt++] = CurLine;
						p="";	/* break for outer */
						break;	/* just locating any line with any rebus, not exact positions */
					}
				}
				/* just check start of words, though doesn't have to be full word (if did, could use strlen rather than strnlen) */
				while (*p && *p!=' ') p++;
				while (*p && *p==' ') p++;
			}
		}


		if (fReflow && !ncnt && (finflow || lastlinelen>50) && (abs(scnt-lastscnt)<=1 || abs(scnt-hanging)<=1)) {
		  finflow=1;
		  putchar(' ');
		} else {
		  Tk(ENDLINE);
		  /*if ((CurLine&0x3f)==0x3f) printf("\"\nupdate idletasks\n$t insert end \""); blows up some Tk text buffer, apparently, on long lines*/
		  if ((CurLine&0x1f)==0x1f) printf("\"\nupdate idletasks\n$t insert end \"");
		  finflow=0;

		  /*if (fCodeline) printf("CODE");*/
		}
		lastlinelen=linelen; lastscnt=scnt;
		break;

	   case ENDLINE:
		/* don't call Tk(ENDLINE) */
		break;

	   default:	/* if not caught above, it's the same as Tk */
		Tk(cmd);
	}
}




/*
 * ASCII
 */

static void
ASCII(enum command cmd)
{
	int i;

	switch (cmd) {
	   case ENDDOC:
		if (fHeadfoot)	{
			printf("\n%s\n", HEADERANDFOOTER);
			for (i=0; i<CRUFTS; i++) if (*cruft[i]) printf("%s\n", cruft[i]);
		}
		break;
	   case CHARRQUOTE:
	   case CHARLQUOTE:
		putchar('"');
		break;
	   case CHARLSQUOTE:
		putchar('`');
		break;
	   case CHARRSQUOTE:
	   case CHARACUTE:
		putchar('\'');
		break;
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARLT:
	   case CHARAMP:
	   case CHARBACKSLASH:
	   case CHARGT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARNBSP:
		putchar(cmd); break;
	   case CHARDAGGER:	putchar('+'); break;
	   case CHARBULLET:	putchar('*'); break;
	   case CHARPLUSMINUS: printf("+-"); break;
	   case CHANGEBAR:	putchar('|'); break;
 	   case CHARCENT:	putchar('c'); break;
 	   case CHARSECT:	putchar('S'); break;
 	   case CHARCOPYR:	printf("(C)"); break;
 	   case CHARNOT:	putchar('~'); break;
 	   case CHARREGTM:	printf("(R)"); break;
 	   case CHARDEG:	putchar('o'); break;
 	   case CHAR14:		printf("1/4"); break;
 	   case CHAR12:		printf("1/2"); break;
 	   case CHAR34:		printf("3/4"); break;
 	   case CHARMUL:	putchar('X'); break;
 	   case CHARDIV:	putchar('/'); break;
	   case HR:		printf("\n%s\n", horizontalrule); break;

	   case BEGINLINE:
		for (i=0; i<ncnt; i++) putchar('\n');
		break;
	   case BEGINBODY:
	   case SHORTLINE:
		if (!fSource) break;
	   case ENDLINE:
		putchar('\n');
		CurLine++;
		break;

	   case BEGINDOC:
	   case ENDBODY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case BEGINSECTION: case ENDSECTION:
	   case BEGINSECTHEAD: case ENDSECTHEAD:
	   case BEGINSUBSECTHEAD: case ENDSUBSECTHEAD:
	   case BEGINBULPAIR: case ENDBULPAIR:
	   case BEGINBULLET: case ENDBULLET:
	   case BEGINBULTXT: case ENDBULTXT:
	   case BEGINSUBSECTION: case ENDSUBSECTION:

	   case BEGINTABLE: case ENDTABLE:
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
	   case BEGINBOLD: case ENDBOLD:
	   case BEGINCODE: case ENDCODE:
	   case BEGINITALICS: case ENDITALICS:
	   case BEGINMANREF: case ENDMANREF:
	   case BEGINBOLDITALICS: case ENDBOLDITALICS:
	   case BEGINY: case ENDY:
	   case BEGINSC: case ENDSC:
		/* nothing */
		break;
	   default:
		DefaultLine(cmd);
	}
}



/*
 * Perl 5 pod ("plain old documentation")
 */

static void
pod(enum command cmd)
{
	static int curindent=0;
	int i;

	if (hanging==-1) {
		if (curindent) hanging=curindent; else hanging=5;
	}


	if (cmd==BEGINBULPAIR) {
		/* want to have multiply indented text */
		if (curindent && hanging!=curindent) printf("\n=back\n\n");
		if (hanging!=curindent) printf("\n=over %d\n\n",hanging);
		curindent=hanging;
	} else if (cmd==ENDBULPAIR) {
		/* nothing--wait until next command */
	} else if (cmd==BEGINLINE && !scnt) {
		if (curindent) printf("\n=back\n\n");
		curindent=0;
	} else if (cmd==BEGINBODY) {
		if (curindent) {
			printf("\n=back\n\n");
			curindent=0;
			auxindent=0;
		}
	}
/*
	   case BEGINBULPAIR:
		printf("=over %d\n\n", hanging);
		break;
	   case ENDBULPAIR:
		printf("\n=back\n\n");
		break;
*/
	switch (cmd) {
	   case BEGINDOC: I=0; break;

	   case BEGINCOMMENT: fcharout=0; break;
	   case ENDCOMMENT: fcharout=1; break;
	   case COMMENTLINE: break;

	   case CHARRQUOTE:
	   case CHARLQUOTE:
		putchar('"');
		break;
	   case CHARLSQUOTE:
		putchar('`');
		break;
	   case CHARRSQUOTE:
	   case CHARACUTE:
		putchar('\'');
		break;
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARLT:
	   case CHARAMP:
	   case CHARBACKSLASH:
	   case CHARGT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARNBSP:
		putchar(cmd); break;
	   case CHARDAGGER:	putchar('+'); break;
	   case CHARPLUSMINUS: printf("+-"); break;
	   case CHANGEBAR:	putchar('|'); break;
 	   case CHARCENT:	putchar('c'); break;
 	   case CHARSECT:	putchar('S'); break;
 	   case CHARCOPYR:	printf("(C)"); break;
 	   case CHARNOT:	putchar('~'); break;
	   case CHARREGTM:	printf("(R)"); break;
 	   case CHARDEG:	putchar('o'); break;
 	   case CHAR14:	printf("1/4"); break;
 	   case CHAR12:	printf("1/2"); break;
 	   case CHAR34:	printf("3/4"); break;
 	   case CHARMUL:	putchar('X'); break;
 	   case CHARDIV:	putchar('/'); break;
	   case HR:		printf("\n%s\n", horizontalrule); break;
	   case CHARBULLET:	putchar('*'); break;

	   case BEGINLINE:
		for (i=0; i<ncnt; i++) putchar('\n');
		CurLine+=ncnt;
		break;
	   case ENDLINE:
		putchar('\n');
		CurLine++;
		I=0;
		break;

	   case BEGINSECTHEAD:	printf("=head1 "); break;
	   case BEGINSUBSECTHEAD:	printf("=head2 "); break;

	   case ENDSECTHEAD:
	   case ENDSUBSECTHEAD:
		printf("\n");
		break;

	   case BEGINCODE:
	   case BEGINBOLD:		printf("B<"); break;
	   case BEGINITALICS:	printf("I<"); break;
	   case BEGINMANREF:	printf("L<"); break;

	   case ENDBOLD:
	   case ENDCODE:
	   case ENDITALICS:
	   case ENDMANREF:
		printf(">");
		break;

	   case BEGINBULLET:
		printf("\n=item ");
		break;
	   case ENDBULLET:
		printf("\n\n");
		fcharout=0;
		break;
	   case BEGINBULTXT:
		fcharout=1;
		auxindent=hanging;
		break;
	   case ENDBULTXT:
		auxindent=0;
		break;


	   case ENDDOC:
	   case BEGINBODY: case ENDBODY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case BEGINSECTION: case ENDSECTION:
	   case BEGINSUBSECTION: case ENDSUBSECTION:
	   case BEGINBULPAIR: case ENDBULPAIR:

	   case SHORTLINE:
	   case BEGINTABLE: case ENDTABLE:
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
	   case BEGINBOLDITALICS: case ENDBOLDITALICS:
	   case BEGINY: case ENDY:
	   case BEGINSC: case ENDSC:
		/* nothing */
		break;
	   default:
		DefaultLine(cmd);
	}
}



static void
Sections(enum command cmd)
{

	switch (cmd) {
	   case ENDSECTHEAD:
	   case ENDSUBSECTHEAD:
		putchar('\n');
	   case BEGINDOC:
		fcharout=0;
		break;

	   case BEGINCOMMENT: fcharout=0; break;
	   case ENDCOMMENT: fcharout=1; break;
	   case COMMENTLINE: break;

	   case BEGINSUBSECTHEAD:
		printf("  ");
		/* no break */
	   case BEGINSECTHEAD:
		fcharout=1;
		break;
	   case CHARRQUOTE:
	   case CHARLQUOTE:
		xputchar('"');
		break;
	   case CHARLSQUOTE:
		xputchar('`');
		break;
	   case CHARRSQUOTE:
	   case CHARACUTE:
		xputchar('\'');
		break;
	   case BEGINTABLE: case ENDTABLE:
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
		break;
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARBACKSLASH:
	   case CHARLT:
	   case CHARGT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARAMP:
	   case CHARNBSP:
		xputchar(cmd); break;
	   case CHARDAGGER:	xputchar('+'); break;
	   case CHARBULLET:	xputchar('*'); break;
	   case CHARPLUSMINUS: xputchar('+'); xputchar('-'); break;
 	   case CHARCENT:	xputchar('c'); break;
 	   case CHARSECT:	xputchar('S'); break;
	   case CHARCOPYR:	xputchar('('); xputchar('C'); xputchar(')'); break;
 	   case CHARNOT:	xputchar('~'); break;
 	   case CHARREGTM:	xputchar('('); xputchar('R'); xputchar(')'); break;
 	   case CHARDEG:	xputchar('o'); break;
 	   case CHAR14:	xputchar('1'); xputchar('/'); xputchar('4'); break;
 	   case CHAR12:	xputchar('1'); xputchar('/'); xputchar('2'); break;
 	   case CHAR34:	xputchar('3'); xputchar('/'); xputchar('4'); break;
 	   case CHARMUL:	xputchar('X'); break;
 	   case CHARDIV:	xputchar('/'); break;
	   case ITAB:		DefaultLine(cmd); break;


	   default:
		/* nothing */
		break;
	}
}



static void
Roff(enum command cmd)
{
	switch (cmd) {
	   case BEGINDOC:
		I=1;
		printf(".TH %s %s \"generated by PolyglotMan\" UCB\n", manName, manSect);
		printf(".\\\"  %s,\n", PROVENANCE);
		printf(".\\\"  %s\n", HOME);
		CurLine=1;
		break;
	   case BEGINBODY:		printf(".LP\n"); break;

	   case BEGINCOMMENT:
	   case ENDCOMMENT:
		break;
	   case COMMENTLINE: printf("'\\\" "); break;

	   case BEGINSECTHEAD:	printf(".SH "); break;
	   case BEGINSUBSECTHEAD:printf(".SS "); break;
	   case BEGINBULPAIR:	printf(".IP "); break;
	   case SHORTLINE:		printf("\n.br"); break;
	   case BEGINBOLD:		printf("\\fB"); break;	/* \n.B -- grr! */
	   case ENDCODE:
	   case ENDBOLD:		printf("\\fR"); break;	/* putchar('\n'); */
	   case BEGINITALICS:	printf("\\fI"); break;
	   case ENDITALICS:		printf("\\fR"); break;
	   case BEGINCODE:
	   case BEGINBOLDITALICS:printf("\\f4"); break;
	   case ENDBOLDITALICS:	printf("\\fR"); break;

	   case CHARLQUOTE:		printf("\\*(rq"); break;
	   case CHARRQUOTE:		printf("\\*(lq"); break;
	   case CHARNBSP:		printf("\\|"); break;
	   case CHARLSQUOTE:	putchar('`');	break;
	   case CHARRSQUOTE:	putchar('\'');	break;
	   case CHARPERIOD:		if (I==1) printf("\\&"); putchar('.'); I++; break;
	   case CHARDASH:		printf("\\-"); break;
	   case CHARTAB:
	   case CHARLT:
	   case CHARGT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARAMP:
		putchar(cmd); break;
	   case CHARBULLET:		printf("\\(bu"); break;
	   case CHARDAGGER:		printf("\\(dg"); break;
	   case CHARPLUSMINUS:	printf("\\(+-"); break;
	   case CHANGEBAR:		putchar('|'); break;
 	   case CHARCENT:		printf("\\(ct"); break;
 	   case CHARSECT:		printf("\\(sc"); break;
 	   case CHARCOPYR:		printf("\\(co"); break;
 	   case CHARNOT:		printf("\\(no"); break;
 	   case CHARREGTM:		printf("\\(rg"); break;
 	   case CHARDEG:		printf("\\(de"); break;
 	   case CHARACUTE:		printf("\\(aa"); break;
 	   case CHAR14:		printf("\\(14"); break;
 	   case CHAR12:		printf("\\(12"); break;
 	   case CHAR34:		printf("\\(34"); break;
 	   case CHARMUL:		printf("\\(mu"); break;
 	   case CHARDIV:		printf("\\(di"); break;
	   case HR:			/*printf("\n%s\n", horizontalrule);*/ break;
	   case CHARBACKSLASH:	printf("\\\\"); break;  /* correct? */

	   case BEGINLINE:
		/*for (i=0; i<ncnt; i++) putchar('\n');*/
		break;

	   case BEGINBULLET:	putchar('"'); break;
	   case ENDBULLET:		printf("\"\n"); break;

	   case ENDLINE:
		CurLine++;
		I=1;
		/* no break */
	   case ENDSUBSECTHEAD:
	   case ENDSECTHEAD:
	   case ENDDOC:
		putchar('\n');
		break;

	   case BEGINCODEBLOCK:	printf(".nf\n");
	   case ENDCODEBLOCK:	printf(".fi\n");

	   case ENDBODY:
	   case ENDBULPAIR:
	   case BEGINBULTXT: case ENDBULTXT:
	   case BEGINSECTION: case ENDSECTION:
	   case BEGINSUBSECTION: case ENDSUBSECTION:
	   case BEGINY: case ENDY:
	   case BEGINSC: case ENDSC:
	   case BEGINTABLE: case ENDTABLE:
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case BEGINMANREF: case ENDMANREF:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}



/*
 * HTML
 */

static void
HTML(enum command cmd)
{
	static int pre=0;
	int i;
	int lasttoc;

	/* always respond to these signals */
	switch (cmd) {
	   case CHARNBSP:	printf("&nbsp;"); I++; break;
	   case CHARTAB:	printf("<tt>&#32;</tt>&nbsp;<tt>&#32;</tt>&nbsp;");	break;
#if defined(XOrg) || defined(XFree86)
	   /* using named entities for ASCII quote characters is redundant */
	   case CHARLQUOTE:
	   case CHARRQUOTE:
	   case CHARLSQUOTE:
	   case CHARRSQUOTE:
		putchar(cmd); break;
#else
	   case CHARLQUOTE:	printf("&ldquo;"); break;
	   case CHARRQUOTE:	printf("&rdquo;"); break;
	   case CHARLSQUOTE:	printf("&lsquo;"); break;
	   case CHARRSQUOTE:	printf("&rsquo;"); break;
#endif
	   case CHARPERIOD:
	   case CHARDASH:
	   case CHARBACKSLASH:
	   case CHARVBAR:	/*printf("&brvbar;"); -- broken bar no good */
	   case CHARHAT:
		 putchar(cmd);
		 break;
	   case CHARDAGGER:	printf("&dagger;"); break;
	   case CHARBULLET:	if (I>0 || !finlist) printf("&#183;"/*"&middot;"*//*&sect;--middot hardly visible*/);
		break;
	   case CHARPLUSMINUS:	printf("&plusmn;"); break;
	   case CHARGT:		printf("&gt;"); break;
	   case CHARLT:		printf("&lt;"); break;
	   case CHARAMP:	printf("&amp;"); break;
	   case CHARCENT:	printf("&cent;"); break;
 	   case CHARSECT:	printf("&sect;"); break;
 	   case CHARCOPYR:	printf("&copy;"); break;
 	   case CHARNOT:	printf("&not;"); break;
 	   case CHARREGTM:	printf("&reg;"); break;
 	   case CHARDEG:	printf("&deg;"); break;
 	   case CHARACUTE:	printf("&acute;"); break;
 	   case CHAR14:		printf("&frac14;"); break;
 	   case CHAR12:		printf("&frac12;"); break;
 	   case CHAR34:		printf("&frac34;"); break;
 	   case CHARMUL:	printf("&#215;"); break;
 	   case CHARDIV:	printf("&#247;"); break;
	   default:
		break;
	}

	/* while in pre mode... */
	if (pre) {
		switch (cmd) {
		   case ENDLINE:	I=0; CurLine++; if (!fPara && scnt) printf("<br>"); printf("\n"); break;
		   case ENDTABLE:
			if (fSource) {
			  printf("</table>\n");
			} else {
			  printf("</pre><br>\n"); pre=0; fQS=fIQS=fPara=1;
			}
			break;
		   case ENDCODEBLOCK: printf("</pre>"); pre=0; break;
		   case SHORTLINE:
		   case ENDBODY:
			printf("\n");
			break;
	   	   case BEGINBOLD:		printf("<b>"); break;
	   	   case ENDBOLD:		printf("</b>"); break;
	   	   case BEGINITALICS:		printf("<i>"); break;
	   	   case ENDITALICS:		printf("</i>"); break;
		   default:
			/* nothing */
			break;
		}
		return;
	}

	/* usual operation */
	switch (cmd) {
	   case BEGINDOC:
		/* escchars = ...  => HTML doesn't backslash-quote metacharacters */
		printf("<!-- %s, -->\n", PROVENANCE);
		printf("<!-- %s -->\n\n", HOME);
		printf("<html>\n<head>\n");
/*		printf("<isindex>\n");*/
		/* better title possible? */
		printf("<title>"); printf(manTitle, manName, manSect); printf("</title>\n");
#if defined(XOrg) || defined(XFree86)
		printf("</head>\n<body bgcolor='#efefef' text='black' "
			"link='blue' vlink='#551A8B' alink='red'>\n");
#else
		printf("</head>\n<body bgcolor='white'>\n");
#endif
		printf("<a href='#toc'>%s</a><p>\n", TABLEOFCONTENTS);
		I=0;
		break;
	   case ENDDOC:
		/* header and footer wanted? */
		printf("<p>\n");
		if (fHeadfoot) {
			printf("<hr><h2>%s</h2>\n", HEADERANDFOOTER);
			for (i=0; i<CRUFTS; i++) if (*cruft[i]) printf("%s<br>\n", cruft[i]);
		}

		if (!tocc) {
			/*printf("\n<h1>ERROR: Empty man page</h1>\n");*/
		} else {
			printf("\n<hr><p>\n");
			printf("<a name='toc'><b>%s</b></a><p>\n", TABLEOFCONTENTS);
			printf("<ul>\n");
			for (i=0, lasttoc=BEGINSECTION; i<tocc; lasttoc=toc[i].type, i++) {
				if (lasttoc!=toc[i].type) {
					if (toc[i].type==BEGINSUBSECTION) printf("<ul>\n");
					else printf("</ul>\n");
				}
				printf("<li><a name='toc%d' href='#sect%d'>%s</a></li>\n", i, i, toc[i].text);
			}
			if (lasttoc==BEGINSUBSECTION) printf("</ul>");
			printf("</ul>\n");
		}
		printf("</body>\n</html>\n");
		break;
	   case BEGINBODY:
		printf("<p>\n");
		break;
	   case ENDBODY:		break;

	   case BEGINCOMMENT: printf("\n<!--\n"); break;
	   case ENDCOMMENT: printf("\n-->\n"); break;
	   case COMMENTLINE: printf("  "); break;

	   case BEGINSECTHEAD:
		printf("\n<h2><a name='sect%d' href='#toc%d'>", tocc, tocc);
		break;
	   case ENDSECTHEAD:
		printf("</a></h2>\n");
		/* useful extraction from FILES, ENVIRONMENT? */
		break;
	   case BEGINSUBSECTHEAD:
		printf("\n<h3><a name='sect%d' href='#toc%d'>", tocc, tocc);
		break;
	   case ENDSUBSECTHEAD:
		printf("</a></h3>\n");
		break;
	   case BEGINSECTION:	break;
	   case ENDSECTION:
		if (sectheadid==NAME && message!=NULL) printf(message);
		break;
	   case BEGINSUBSECTION:	break;
	   case ENDSUBSECTION:	break;

	   case BEGINBULPAIR:
		if (listtype==OL) printf("\n<ol>\n");
		else if (listtype==UL) printf("\n<ul>\n");
		else printf("\n<dl>\n");
		break;
	   case ENDBULPAIR:
		if (listtype==OL) printf("\n</ol>\n");
		else if (listtype==UL) printf("\n</ul>\n");
		else printf("</dl>\n");
		break;
	   case BEGINBULLET:
		if (listtype==OL || listtype==UL) fcharout=0;
		else printf("\n<dt>");
		break;
	   case ENDBULLET:
		if (listtype==OL || listtype==UL) fcharout=1;
		else printf("</dt>");
		break;
	   case BEGINBULTXT:
		if (listtype==OL || listtype==UL) printf("<li>");
		else printf("\n<dd>");
		break;
	   case ENDBULTXT:
		if (listtype==OL || listtype==UL) printf("</li>");
		else printf("</dd>\n");
		break;

	   case BEGINLINE:
		/*		if (ncnt) printf("<p>\n"); -- if haven't already generated structural tag */
		if (ncnt) printf("\n<p>");

		/* trailing spaces already trimmed off, so look for eol now */
		if (fCodeline) {
		  printf("<code>");
		  for (i=0; i<scnt-indent; i++) printf("&nbsp;"/*&#160;*/);		/* ? */
		  tagc=0;

		  /* already have .tag=BOLDITALICS, .first=0 */
		  /* would be more elegant, but can't print initial spaces before first tag
		  tags[0].last = linelen;
		  tagc=1;
		  fIQS=0;
		  */
		}

		break;

	   case ENDLINE:
		/*if (fCodeline) { fIQS=1; fCodeline=0; }*/
		if (fCodeline) { printf("</code><br>"); fCodeline=0; }
		I=0; CurLine++; if (!fPara && scnt) printf("<br>"); printf("\n");
		break;

	   case SHORTLINE:
		if (fCodeline) { printf("</code>"); fCodeline=0; }
		if (!fIP) printf("<br>\n");
		break;


	   case BEGINTABLE:
		if (fSource) {
		  /*printf("<center><table border>\n");*/
		  printf("<table border='0'>\n");
		} else {
		  printf("<br><pre>\n"); pre=1; fQS=fIQS=fPara=0;
		}
		break;
	   case ENDTABLE:
		if (fSource) {
		  printf("</table>\n");
		} else {
		  printf("</pre><br>\n"); pre=0; fQS=fIQS=fPara=1;
		}
		break;
	   case BEGINTABLELINE:		printf("<tr>"); break;
	   case ENDTABLELINE:		printf("</tr>\n"); break;
	   case BEGINTABLEENTRY:
		printf("<td align='");
		switch (tblcellformat[0]) {
		case 'c':	printf("center"); break;
		case 'n':	/*printf("decimal"); break;  -- fall through to right for now */
		case 'r':	printf("right"); break;
		case 'l':
		default:
		  printf("left");
		}
		if (tblcellspan>1) printf(" colspan=%d", tblcellspan);
		printf("'>");
		break;
	   case ENDTABLEENTRY:
		printf("</td>");
		break;

	   /* something better with CSS */
	   case BEGININDENT:		printf("<blockquote>"); break;
	   case ENDINDENT:			printf("</blockquote>\n"); break;

	   case FONTSIZE:
		/* HTML font step sizes are bigger than troff's */
		if ((fontdelta+=intArg)!=0) printf("<font size='%c1'>", (intArg>0)?'+':'-'); else printf("</font>\n");
		break;

	   case BEGINBOLD:		printf("<b>"); break;
	   case ENDBOLD:		printf("</b>"); break;
	   case BEGINITALICS:	printf("<i>"); break;
	   case ENDITALICS:		printf("</i>"); break;
	   case BEGINBOLDITALICS:
	   case BEGINCODE:		printf("<code>"); break;
	   case ENDBOLDITALICS:
	   case ENDCODE:		printf("</code>"); break;
	   case BEGINCODEBLOCK:	printf("<pre>"); pre=1; break;	/* wrong for two-column lists in kermit.1, pine.1, perl4.1 */
	   case ENDCODEBLOCK:	printf("</pre>"); pre=0; break;
	   case BEGINCENTER:		printf("<center>"); break;
	   case ENDCENTER:		printf("</center>"); break;
	   case BEGINMANREF:
		manrefextract(hitxt);
		if (fmanRef) { printf("<a href='"); printf(href, manrefname, manrefsect); printf("'>"); }
		else printf("<i>");
		break;
	   case ENDMANREF:
		if (fmanRef) printf("</a>\n"); else printf("</i>");
		break;
	   case HR:		printf("\n<hr>\n"); break;

		/* U (was B, I), strike -- all temporary until HTML 4.0's INS and DEL widespread */
	   case BEGINDIFFA: printf("<ins><u>"); break;
	   case ENDDIFFA: printf("</u></ins>"); break;
	   case BEGINDIFFD: printf("<del><strike>"); break;
	   case ENDDIFFD: printf("</strike></del>"); break;

	   case BEGINSC: case ENDSC:
	   case BEGINY: case ENDY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case CHANGEBAR:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}



/*
 * DocBook XML
 * improvements by Aaron Hawley applied 2003 June 5
 *
 * N.B. The framework for XML is in place but not done.  If you
 * are familiar with the DocBook DTD, however, it shouldn't be
 * too difficult to finish it.  If you do so, please send your
 * code to me so that I may share the wealth in the next release.
 */

const char *DOCBOOKPATH = "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd";

static void
XML(enum command cmd)
{
	static int pre=0;
	int i;
	char *p;
	static int fRefEntry=0;
	static int fRefPurpose=0;
	/*static char *bads => XML doesn't backslash-quote metacharacters */

/*
*/

	/* always respond to these signals */
	switch (cmd) {
	   case CHARLQUOTE: case CHARRQUOTE: printf("&quot;"); break;
	   case CHARBULLET: printf("&bull;"); break;
	   case CHARDAGGER: printf("&dagger;"); break;
	   case CHARPLUSMINUS: printf("&plusmn;"); break;
 	   case CHARCOPYR: printf("&copy;"); break;
 	   case CHARNOT: printf("&not;"); break;
 	   case CHARMUL: printf("&times;"); break;
 	   case CHARDIV: printf("&divide;"); break;
	   case CHARAMP: printf("&amp;"); break;
	   case CHARDASH:
		if (sectheadid==NAME && !fRefPurpose) {
			printf("</refname><refpurpose>");
			fRefPurpose=1;
		} else putchar('-');
		break;
	   case CHARBACKSLASH: putchar('\\'); break;
	   case CHARGT: printf("&gt;"); break;
	   case CHARLT: printf("&lt;"); break;
	   case CHARLSQUOTE:
	   case CHARRSQUOTE:
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARNBSP:
 	   case CHARCENT:
 	   case CHARSECT:
 	   case CHARREGTM:
 	   case CHARDEG:
 	   case CHARACUTE:
 	   case CHAR14:
 	   case CHAR12:
 	   case CHAR34:
		 putchar(cmd);
		 break;
	   default:
		break;
	}

	/* while in pre mode... */
	if (pre) {
		switch (cmd) {
		   case ENDLINE:	I=0; CurLine++; if (!fPara && scnt) putchar(' '); break;
		   case ENDTABLE:
			if (fSource) printf("</table>\n");
			else { printf("</literallayout>\n"); pre=0; fQS=fIQS=fPara=1; }
			break;
		   default:
			/* nothing */
			break;
		}
		return;
	}

	/* usual operation */
	switch (cmd) {
	   case BEGINDOC:
		printf("\n<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.1.2//EN\"\n");
		printf("  \"%s\">\n", DOCBOOKPATH);

		printf("<!--\n\n\tI am looking for help to finish DocBook XML.\n\n-->\n");

		printf("<!-- %s\n", PROVENANCE);
		printf("     %s -->\n\n",HOME);
		/* better title possible? */
		for (p=manName; *p; p++) *p = tolower(*p);
		printf("<refentry id='%s.%s'>\n", manName, manSect);
		printf("<refmeta>\n<refentrytitle>%s</refentrytitle>\n", manName);
		printf("<manvolnum>%s</manvolnum>\n</refmeta>\n\n", manSect);

		I=0;
		break;

	   case ENDDOC:
		/* header and footer wanted? */
		if (fHeadfoot) {
			printf("\n<refsect1>\n<title>%s</title>\n", HEADERANDFOOTER);
			for (i=0; i<CRUFTS; i++) if (*cruft[i]) printf("<para>%s</para>\n", cruft[i]);
			printf("\n</refsect1>");
		}

		/* table of contents, such as found in HTML, can be generated automatically by XML software */

		printf("</refentry>\n");
		break;
	   case BEGINBODY:
		 if (fPara) printf("\n</para>");
		 printf("<para>"); fPara = 1;
		 break;
	   case ENDBODY:
		 if (fRefPurpose) { printf("</refpurpose>"); fRefPurpose=0; }
		 else { printf("\n</para>"); fPara=0; }
		 break;

	   case BEGINCOMMENT: printf("\n<!--\n"); break;
	   case ENDCOMMENT: printf("\n-->\n"); break;
	   case COMMENTLINE: break;

	   case BEGINSECTHEAD:
	   case BEGINSUBSECTHEAD:
		if (sectheadid != NAME && sectheadid != SYNOPSIS) printf("<title>");
		break;
	   case ENDSECTHEAD:
	   case ENDSUBSECTHEAD:
		if (sectheadid == NAME) printf("<refname>");
		else if (sectheadid == SYNOPSIS) {}
		else { printf("</title>\n<para>"); fPara=1; }
		break;

	   case BEGINSECTION:
		if (sectheadid==NAME) printf("<refnamediv>\n");
			/*printf("<RefEntry>");  -- do lotsa parsing here for RefName, RefPurpose*/
		else if (sectheadid==SYNOPSIS) printf("<refsynopsisdiv>\n<cmdsynopsis>\n");
		else printf("\n<refsect1>\n");
		break;
	   case ENDSECTION:
		if (sectheadid==NAME) {
		  if (fRefPurpose) { printf("</refpurpose>"); fRefPurpose=0; }
		  printf("\n</refnamediv>\n\n");
		} else if (sectheadid==SYNOPSIS) printf("\n</cmdsynopsis>\n</refsynopsisdiv>\n");
		else {
		  if (fPara) { printf("\n</para>"); fPara=0; }
		  printf("\n</refsect1>\n");
		}
		break;

	   case BEGINSUBSECTION:	printf("\n<refsect2>"); break;
	   case ENDSUBSECTION:	printf("\n</refsect2>"); break;

	   /* need to update this for enumerated and plain lists */
	   case BEGINBULPAIR:	printf("<variablelist>\n"); break;
	   case ENDBULPAIR:		printf("</variablelist>\n"); break;
	   case BEGINBULLET:	printf("<term>"); break;
	   case ENDBULLET:		printf("</term>\n"); break;
	   case BEGINBULTXT:	printf("<listitem>\n<para>"); break;
	   case ENDBULTXT:		printf("\n</para></listitem>\n"); break;

	   case BEGINLINE:
		/* remember, get BEGINBODY call at start of paragraph */
		if (fRefEntry) {
			if (fRefPurpose) {
				for (p=plain; *p!='-'; p++) {
					/* nothing?! */
				}
			}
		}

		break;

	   case ENDLINE:
		/*if (fCodeline) { fIQS=1; fCodeline=0; }*/
		if (fCodeline) { printf("</code>"); fCodeline=0; } /*  */
		I=0; CurLine++; if (!fPara && scnt) printf("<sbr/>"); else putchar(' ');
		break;

	   case SHORTLINE:
		if (fCodeline) { printf("</code>"); fCodeline=0; }
		if (!fIP && !fPara) printf("<sbr/>\n");
		break;

	   case BEGINTABLE:
		if (fSource) printf("<table>\n");
		else { printf("<literallayout>\n"); pre=1; fQS=fIQS=fPara=0; }
		break;
	   case ENDTABLE:
		if (fSource) printf("</table>\n");
		else { printf("</literallayout>\n"); pre=0; fQS=fIQS=fPara=1; }
		break;
	   case BEGINTABLELINE:		printf("<row>"); break;
	   case ENDTABLELINE:		printf("</row>\n"); break;
	   case BEGINTABLEENTRY:		printf("<entry>"); break;
	   case ENDTABLEENTRY:		printf("</entry>"); break;

	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
		break;

	   /* have to make some guess about bold and italics */
	   case BEGINBOLD:		printf("<command>"); break;
	   case ENDBOLD:		printf("</command>"); break;
	   case BEGINITALICS:	printf("<emphasis>"); break;	/* could be literal or arg */
	   case ENDITALICS:		printf("</emphasis>"); break;
	   case BEGINBOLDITALICS: case BEGINCODE:	printf("<literal>"); break;
	   case ENDBOLDITALICS: case ENDCODE:	printf("</literal>"); break;
	   case BEGINMANREF:
		manrefextract(hitxt);
		if (fmanRef) { printf("<link linkend='"); printf(href, manrefname, manrefsect); printf("'>"); }
		break;
	   case ENDMANREF:
		if (fmanRef) printf("</link>");
		break;

	   case HR:
	   case BEGINSC: case ENDSC:
	   case BEGINY: case ENDY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case CHANGEBAR:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}



/* generates MIME compliant to RFC 1563 */

static void
MIME(enum command cmd)
{
	static int pre=0;
	int i;

	/* always respond to these signals */
	switch (cmd) {
	   case CHARDASH:
	   case CHARAMP:
	   case CHARPERIOD:
	   case CHARTAB:
		putchar(cmd); break;
	   case CHARLSQUOTE:	putchar('`'); break;
	   case CHARACUTE:
	   case CHARRSQUOTE:	putchar('\''); break;
	   case CHARBULLET:		putchar('*'); break;
	   case CHARDAGGER:		putchar('|'); break;
	   case CHARPLUSMINUS:	printf("+-"); break;
	   case CHARNBSP:		putchar(' '); break;
 	   case CHARCENT:	putchar('c'); break;
 	   case CHARSECT:	putchar('S'); break;
 	   case CHARCOPYR:	printf("(C)"); break;
 	   case CHARNOT:	putchar('~'); break;
 	   case CHARREGTM:	printf("(R)"); break;
 	   case CHARDEG:	putchar('o'); break;
 	   case CHAR14:		printf("1/4"); break;
 	   case CHAR12:		printf("1/2"); break;
 	   case CHAR34:		printf("3/4"); break;
 	   case CHARMUL:	putchar('X'); break;
 	   case CHARDIV:	putchar('/'); break;
	   case CHARLQUOTE:
	   case CHARRQUOTE:
		putchar('"');
		break;
	   case CHARBACKSLASH:	/* these should be caught as escaped chars */
	   case CHARGT:
	   case CHARLT:
#if 0
		assert(1);
#endif
		break;
	   default:
		break;
	}

	/* while in pre mode... */
	if (pre) {
		switch (cmd) {
		   case ENDLINE:	I=0; CurLine++; if (!fPara && scnt) printf("\n\n"); break;
		   case ENDTABLE:	printf("</fixed>\n\n"); pre=0; fQS=fIQS=fPara=1; break;
		   default:
			/* nothing */
			break;
		}
		return;
	}

	/* usual operation */
	switch (cmd) {
	   case BEGINDOC:
		printf("Content-Type: text/enriched\n");
		printf("Text-Width: 60\n");
		escchars = "<>\\";

		I=0;
		break;
	   case ENDDOC:
		/* header and footer wanted? */
		printf("\n\n");
		if (fHeadfoot) {
			printf("\n");
			MIME(BEGINSECTHEAD); printf("%s",HEADERANDFOOTER); MIME(ENDSECTHEAD);
			for (i=0; i<CRUFTS; i++) if (*cruft[i]) printf("\n%s\n", cruft[i]);
		}

/*
		printf("\n<comment>\n");
		printf("%s\n%s\n", PROVENANCE, HOME);
		printf("</comment>\n\n");
*/

/*
		printf("\n<HR><P>\n");
		printf("<A NAME=\"toc\"><B>%s</B></A><P>\n", TABLEOFCONTENTS);
		printf("<UL>\n");
		for (i=0, lasttoc=BEGINSECTION; i<tocc; lasttoc=toc[i].type, i++) {
		  if (lasttoc!=toc[i].type) {
		    if (toc[i].type==BEGINSUBSECTION) printf("<UL>\n");
		    else printf("</UL>\n");
		  }
		  printf("<LI><A NAME=\"toc%d\" HREF=\"#sect%d\">%s</A></LI>\n", i, i, toc[i].text);
		}
		if (lasttoc==BEGINSUBSECTION) printf("</UL>");
		printf("</UL>\n");
		printf("</BODY></HTML>\n");
*/
		break;
	   case BEGINBODY:
		printf("\n\n");
		break;
	   case ENDBODY:		break;

	   case BEGINCOMMENT: fcharout=0; break;
	   case ENDCOMMENT: fcharout=1; break;
	   case COMMENTLINE: break;

	   case BEGINSECTHEAD:
		printf("\n<bigger><bigger><underline>");
		/*A NAME=\"sect%d\" HREF=\"#toc%d\"><H2>", tocc, tocc);*/
		break;
	   case ENDSECTHEAD:
		printf("</underline></bigger></bigger>\n\n<indent>");
		/* useful extraction from files, environment? */
		break;
	   case BEGINSUBSECTHEAD:
		printf("<bigger>");
		/*\n<A NAME=\"sect%d\" HREF=\"#toc%d\"><H3>", tocc, tocc);*/
		break;
	   case ENDSUBSECTHEAD:
		printf("</bigger>\n\n</indent>");
		break;
	   case BEGINSECTION:
	   case BEGINSUBSECTION:
		break;
	   case ENDSECTION:
	   case ENDSUBSECTION:
		printf("</indent>\n");
		break;

	   case BEGINBULPAIR:	break;
	   case ENDBULPAIR:		break;
	   case BEGINBULLET:	printf("<bold>"); break;
	   case ENDBULLET:		printf("</bold>\t"); break;
	   case BEGINBULTXT:
	   case BEGININDENT:
		printf("<indent>");
		break;
	   case ENDBULTXT:
	   case ENDINDENT:
		printf("</indent>\n");
		break;

	   case FONTSIZE:
		if ((fontdelta+=intArg)==0) {
		  if (intArg>0) printf("</smaller>"); else printf("</bigger>");
		} else {
		  if (intArg>0) printf("<bigger>"); else printf("<smaller>");
		}
		break;

	   case BEGINLINE:		/*if (ncnt) printf("\n\n");*/ break;
	   case ENDLINE:		I=0; CurLine++; printf("\n"); break;
	   case SHORTLINE:		if (!fIP) printf("\n\n"); break;
	   case BEGINTABLE:		printf("<nl><fixed>\n"); pre=1; fQS=fIQS=fPara=0; break;
	   case ENDTABLE:		printf("</fixed><nl>\n"); pre=0; fQS=fIQS=fPara=1; break;
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
		break;
		/* could use a new list type */

	   case BEGINBOLD:		printf("<bold>"); break;
	   case ENDBOLD:		printf("</bold>"); break;
	   case BEGINITALICS:	printf("<italics>"); break;
	   case ENDITALICS:		printf("</italics>"); break;
	   case BEGINCODE:
	   case BEGINBOLDITALICS:printf("<bold><italics>"); break;
	   case ENDCODE:
	   case ENDBOLDITALICS:	printf("</bold></italics>"); break;
	   case BEGINMANREF:
		printf("<x-color><param>blue</param>");
/* how to make this hypertext?
   		manrefextract(hitxt);
		if (fmanRef) { printf("<A HREF=\""); printf(href, manrefname, manrefsect); printf("\">\n"); }
		else printf("<I>");
		break;
*/
		break;
	   case ENDMANREF:
		printf("</x-color>");
		break;

	   case HR:		printf("\n\n%s\n\n", horizontalrule); break;

	   case BEGINSC: case ENDSC:
	   case BEGINY: case ENDY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case CHANGEBAR:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}



/*
 * LaTeX
 */

static void
LaTeX(enum command cmd)
{

	switch (cmd) {
	   case BEGINDOC:
		escchars = "$&%#_{}"; /* and more to come? */
		printf("%% %s,\n", PROVENANCE);
		printf("%% %s\n\n", HOME);
		/* definitions */
		printf(
		  "\\documentstyle{article}\n"
		  "\\def\\thefootnote{\\fnsymbol{footnote}}\n"
		  "\\setlength{\\parindent}{0pt}\n"
		  "\\setlength{\\parskip}{0.5\\baselineskip plus 2pt minus 1pt}\n"
		  "\\begin{document}\n"
			  );
		I=0;
		break;
	   case ENDDOC:
		/* header and footer wanted? */
		printf("\n\\end{document}\n");

		break;
	   case BEGINBODY:
		printf("\n\n");
		break;
	   case ENDBODY:		break;

	   case BEGINCOMMENT:
	   case ENDCOMMENT:
		break;
	   case COMMENTLINE: printf("%% "); break;


	   case BEGINSECTION:	break;
	   case ENDSECTION:		break;
	   case BEGINSECTHEAD:	printf("\n\\section{"); tagc=0; break;
	   case ENDSECTHEAD:
		printf("}");
/*
		if (CurLine==1) printf("\\footnote{"
		  "\\it conversion to \\LaTeX\ format by PolyglotMan "
		  "available via anonymous ftp from {\\tt ftp.berkeley.edu:/ucb/people/phelps/tcltk}}"
			  );
*/
		/* useful extraction from files, environment? */
		printf("\n");
		break;
	   case BEGINSUBSECTHEAD:printf("\n\\subsection{"); break;
	   case ENDSUBSECTHEAD:
		printf("}");
		break;
	   case BEGINSUBSECTION:	break;
	   case ENDSUBSECTION:	break;
	   case BEGINBULPAIR:	printf("\\begin{itemize}\n"); break;
	   case ENDBULPAIR:		printf("\\end{itemize}\n"); break;
	   case BEGINBULLET:	printf("\\item ["); break;
	   case ENDBULLET:		printf("] "); break;
	   case BEGINLINE:		/*if (ncnt) printf("\n\n");*/ break;
	   case ENDLINE:		I=0; putchar('\n'); CurLine++; break;
	   case BEGINTABLE:		printf("\\begin{verbatim}\n"); break;
	   case ENDTABLE:		printf("\\end{verbatim}\n"); break;
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
		break;
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
		break;
	   case SHORTLINE:		if (!fIP) printf("\n\n"); break;
	   case BEGINBULTXT:	break;
	   case ENDBULTXT:		putchar('\n'); break;

	   case CHARLQUOTE:		printf("``"); break;
	   case CHARRQUOTE:		printf("''"); break;
	   case CHARLSQUOTE:
	   case CHARRSQUOTE:
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARNBSP:
		putchar(cmd); break;
	   case CHARBACKSLASH:	printf("$\\backslash$"); break;
	   case CHARGT:		printf("$>$"); break;
	   case CHARLT:		printf("$<$"); break;
	   case CHARHAT:		printf("$\\char94{}$"); break;
	   case CHARVBAR:		printf("$|$"); break;
	   case CHARAMP:		printf("\\&"); break;
	   case CHARBULLET:		printf("$\\bullet$ "); break;
	   case CHARDAGGER:		printf("\\dag "); break;
	   case CHARPLUSMINUS:	printf("\\pm "); break;
 	   case CHARCENT:		printf("\\hbox{\\rm\\rlap/c}"); break;
 	   case CHARSECT:		printf("\\S "); break;
 	   case CHARCOPYR:		printf("\\copyright "); break;
 	   case CHARNOT:		printf("$\\neg$"); break;
 	   case CHARREGTM:		printf("(R)"); break;
 	   case CHARDEG:		printf("$^\\circ$"); break;
 	   case CHARACUTE:		putchar('\''); break;
 	   case CHAR14:		printf("$\\frac{1}{4}$"); break;
 	   case CHAR12:		printf("$\\frac{1}{2}$"); break;
 	   case CHAR34:		printf("$\\frac{3}{4}$"); break;
 	   case CHARMUL:		printf("\\times "); break;
 	   case CHARDIV:		printf("\\div "); break;

	   case BEGINCODE:
	   case BEGINBOLD:		printf("{\\bf "); break; /* } */
	   case BEGINSC:		printf("{\\sc "); break; /* } */
	   case BEGINITALICS:	printf("{\\it "); break; /* } */
	   case BEGINBOLDITALICS:printf("{\\bf\\it "); break; /* } */
	   case BEGINMANREF:	printf("{\\sf "); break; /* } */
	   case ENDCODE:
	   case ENDBOLD:
	   case ENDSC:
	   case ENDITALICS:
	   case ENDBOLDITALICS:
	   case ENDMANREF: /* { */
		putchar('}');
		break;
	   case HR:		/*printf("\n%s\n", horizontalrule);*/ break;

	   case BEGINY: case ENDY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case CHANGEBAR:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}


static void
LaTeX2e(enum command cmd)
{
	switch (cmd) {
		/* replace selected commands ... */
	   case BEGINDOC:
		escchars = "$&%#_{}";
		printf("%% %s,\n", PROVENANCE);
		printf("%% %s\n\n", HOME);
		/* definitions */
		printf(
		  "\\documentclass{article}\n"
		  "\\def\\thefootnote{\\fnsymbol{footnote}}\n"
		  "\\setlength{\\parindent}{0pt}\n"
		  "\\setlength{\\parskip}{0.5\\baselineskip plus 2pt minus 1pt}\n"
		  "\\begin{document}\n"
			  );
		I=0;
		break;
	   case BEGINCODE:
	   case BEGINBOLD:		printf("\\textbf{"); break; /* } */
	   case BEGINSC:		printf("\\textsc{"); break; /* } */
	   case BEGINITALICS:	printf("\\textit{"); break; /* } */
	   case BEGINBOLDITALICS:printf("\\textbf{\\textit{"); break; /* }} */
	   case BEGINMANREF:	printf("\\textsf{"); break; /* } {{ */
	   case ENDBOLDITALICS:	printf("}}"); break;

		/* ... rest same as old LaTeX */
	   default:
		LaTeX(cmd);
	}
}



/*
 * Rich Text Format (RTF)
 */

/* RTF could use more work */

static void
RTF(enum command cmd)
{

	switch (cmd) {
	   case BEGINDOC:
		escchars = "{}";
		/* definitions */
		printf(
		  /* fonts */
		  "{\\rtf1\\deff2 {\\fonttbl"
		  "{\\f20\\froman Times;}{\\f150\\fnil I Times Italic;}"
		  "{\\f151\\fnil B Times Bold;}{\\f152\\fnil BI Times BoldItalic;}"
		  "{\\f22\\fmodern Courier;}{\\f23\\ftech Symbol;}"
		  "{\\f135\\fnil I Courier Oblique;}{\\f136\\fnil B Courier Bold;}{\\f137\\fnil BI Courier BoldOblique;}"
		  "{\\f138\\fnil I Helvetica Oblique;}{\\f139\\fnil B Helvetica Bold;}}"
		  "\n"

		  /* style sheets */
		  "{\\stylesheet{\\li720\\sa120 \\f20 \\sbasedon222\\snext0 Normal;}"
		  "{\\s2\\sb200\\sa120 \\b\\f3\\fs20 \\sbasedon0\\snext2 section head;}"
		  "{\\s3\\li180\\sa120 \\b\\f20 \\sbasedon0\\snext3 subsection head;}"
		  "{\\s4\\fi-1440\\li2160\\sa240\\tx2160 \\f20 \\sbasedon0\\snext4 detailed list;}}"
		  "\n"

/* more header to come--do undefined values default to nice values? */
			   );
		I=0;
		break;
	   case ENDDOC:
		/* header and footer wanted? */
		printf("\\par{\\f150 %s,\n%s}", PROVENANCE, HOME);
		printf("}\n");
		break;
	   case BEGINBODY:
		printf("\n\n");
		break;
	   case ENDBODY:
		CurLine++;
		printf("\\par\n");
		tagc=0;
		break;

	   case BEGINCOMMENT: fcharout=0; break;
	   case ENDCOMMENT: fcharout=1; break;
	   case COMMENTLINE: break;

	   case BEGINSECTION:	break;
	   case ENDSECTION:		printf("\n\\par\n"); break;
	   case BEGINSECTHEAD:	printf("{\\s2 "); tagc=0; break;
	   case ENDSECTHEAD:
		printf("}\\par");
		/* useful extraction from files, environment? */
		printf("\n");
		break;
	   case BEGINSUBSECTHEAD:printf("{\\s3 "); break;
	   case ENDSUBSECTHEAD:
		printf("}\\par\n");
		break;
	   case BEGINSUBSECTION:	break;
	   case ENDSUBSECTION:	break;
	   case BEGINLINE:		/*if (ncnt) printf("\n\n");*/ break;
	   case ENDLINE:		I=0; putchar(' '); /*putchar('\n'); CurLine++;*/ break;
	   case SHORTLINE:		if (!fIP) printf("\\line\n"); break;
	   case BEGINBULPAIR:	printf("{\\s4 "); break;
	   case ENDBULPAIR:		printf("}\\par\n"); break;
	   case BEGINBULLET:	break;
	   case ENDBULLET:		printf("\\tab "); fcharout=0; break;
	   case BEGINBULTXT:	fcharout=1; break;
	   case ENDBULTXT:		break;

	   case CHARLQUOTE:		printf("``"); break;
	   case CHARRQUOTE:		printf("''"); break;
	   case CHARLSQUOTE:
	   case CHARRSQUOTE:
	   case CHARPERIOD:
	   case CHARTAB:
	   case CHARDASH:
	   case CHARBACKSLASH:
	   case CHARGT:
	   case CHARLT:
	   case CHARHAT:
	   case CHARVBAR:
	   case CHARAMP:
	   case CHARNBSP:
 	   case CHARCENT:
 	   case CHARSECT:
 	   case CHARCOPYR:
 	   case CHARNOT:
 	   case CHARREGTM:
 	   case CHARDEG:
 	   case CHARACUTE:
 	   case CHAR14:
 	   case CHAR12:
 	   case CHAR34:
 	   case CHARMUL:
 	   case CHARDIV:
		putchar(cmd); break;
	   case CHARBULLET:		printf("\\bullet "); break;
	   case CHARDAGGER:		printf("\\dag "); break;
	   case CHARPLUSMINUS:	printf("\\pm "); break;

	   case BEGINCODE:
	   case BEGINBOLD:		printf("{\\b "); break; /* } */
	   case BEGINSC:		printf("{\\fs20 "); break; /* } */
	   case BEGINITALICS:	printf("{\\i "); break; /* } */
	   case BEGINBOLDITALICS:printf("{\\b \\i "); break; /* } */
	   case BEGINMANREF:	printf("{\\f22 "); break; /* } */
	   case ENDBOLD:
	   case ENDCODE:
	   case ENDSC:
	   case ENDITALICS:
	   case ENDBOLDITALICS:
	   case ENDMANREF: /* { */
		putchar('}');
		break;
	   case HR:		printf("\n%s\n", horizontalrule); break;

	   case BEGINY: case ENDY:
	   case BEGINHEADER: case ENDHEADER:
	   case BEGINFOOTER: case ENDFOOTER:
	   case BEGINTABLE: case ENDTABLE:
	   case BEGINTABLELINE: case ENDTABLELINE: case BEGINTABLEENTRY: case ENDTABLEENTRY:
	   case BEGININDENT: case ENDINDENT:
	   case FONTSIZE:
	   case CHANGEBAR:
		/* nothing */
		break;
	   default:
		DefaultPara(cmd);
	}
}



/*
 * pointers to existing tools
 */

static void
PostScript(enum command cmd)
{
	fprintf(stderr, "Use groff or psroff to generate PostScript.\n");
	exit(1);
}


static void
FrameMaker(enum command cmd)
{
	fprintf(stderr, "FrameMaker comes with filters that convert from roff to MIF.\n");
	exit(1);
}




/*
 * Utilities common to both parses
 */


/*
 level 0: DOC - need match
 level 1: SECTION - need match
 level 2: SUBSECTION | BODY | BULLETPAIR
 level 3: BODY (within SUB) | BULLETPAIR (within SUB) | BULTXT (within BULLETPAIR)
 level 4: BULTXT (within BULLETPAIR within SUBSECTION)

 never see: SECTHEAD, SUBSECTHEAD, BULLET
*/

int Psect=0, Psub=0, Pbp=0, Pbt=0, Pb=0, Pbul=0;

static void
pop(enum command cmd)
{
	assert(cmd==ENDINDENT || cmd==BEGINBULLET || cmd==BEGINBULTXT || cmd==BEGINBULPAIR || cmd==BEGINBODY || cmd==BEGINSECTION || cmd==BEGINSUBSECTION || cmd==ENDDOC);
/*
	int i;
	int p;
	int match;

	p=cmdp-1;
	for (i=cmdp-1;i>=0; i--)
		if (cmd==cmdstack[i]) { match=i; break; }
*/

	/* if match, pop off all up to and including match */
	/* otherwise, pop off one level*/

	if (Pbul) {
	  (*fn)(ENDBULLET); Pbul=0;
	  if (cmd==BEGINBULLET) return;
	} /* else close off ENDBULTXT */

	if (Pbt) { (*fn)(ENDBULTXT); Pbt=0; }
	if (cmd==BEGINBULTXT || cmd==BEGINBULLET) return;

	if (Pb && cmd==BEGINBULPAIR) { (*fn)(ENDBODY); Pb=0; }	/* special */
	if (Pbp) { (*fn)(ENDBULPAIR); Pbp=0; }
	if (cmd==BEGINBULPAIR || cmd==ENDINDENT) return;

	if (Pb) { (*fn)(ENDBODY); Pb=0; }
	if (cmd==BEGINBODY) return;

	if (Psub) { (*fn)(ENDSUBSECTION); Psub=0; }
	if (cmd==BEGINSUBSECTION) return;

	if (Psect) { (*fn)(ENDSECTION); Psect=0; }
	if (cmd==BEGINSECTION) return;
}


static void
poppush(enum command cmd)
{
	assert(cmd==ENDINDENT || cmd==BEGINBULLET || cmd==BEGINBULTXT || cmd==BEGINBULPAIR || cmd==BEGINBODY || cmd==BEGINSECTION || cmd==BEGINSUBSECTION);

	pop(cmd);

	switch (cmd) {
	   case BEGINBULLET: Pbul=1; break;
	   case BEGINBULTXT: Pbt=1; break;
	   case BEGINBULPAIR: Pbp=1; break;
	   case BEGINBODY: Pb=1; break;
	   case BEGINSECTION: Psect=1; break;
	   case BEGINSUBSECTION: Psub=1; break;
	   default:
		if (!fQuiet) fprintf(stderr, "poppush: unrecognized code %d\n", cmd);
	}

	(*fn)(cmd);
	prevcmd = cmd;
}



/*
 * PREFORMATTED PAGES PARSING
 */

/* wrapper for getchar() that expands tabs, and sends maximum of n=40 consecutive spaces */

static int
getchartab(void)
{
	static int tabexp = 0;
	static int charinline = 0;
	static int cspccnt = 0;
	char c;

	c = lookahead;
	if (tabexp) tabexp--;
	else if (c=='\n') {
		charinline=0;
		cspccnt=0;
	} else if (c=='\t') {
		tabexp = TabStops-(charinline%TabStops); if (tabexp==TabStops) tabexp=0;
		lookahead = c = ' ';
	} else if (cspccnt>=40) {
		if (*in==' ') {
			while (*in==' '||*in=='\t') in++;
			in--;
		}
		cspccnt=0;
	}

	if (!tabexp && lookahead) lookahead = *in++;
	if (c=='\b') charinline--; else charinline++;
	if (c==' ') cspccnt++;
	return c;
}


/* replace gets.  handles hyphenation too */
static char *
la_gets(char *buf)
{
	static char la_buf[MAXBUF];	/* can lookahead a full line, but nobody does now */
	static int fla=0, hy=0;
	char *ret,*p;
	int c,i;

	assert(buf!=NULL);

	if (fla) {
		/* could avoid copying if callers used return value */
		strcpy(buf,la_buf); fla=0;
		ret=buf;	/* correct? */
	} else {
		/*ret=gets(buf); -- gets is deprecated (since it can read too much?) */
		/* could do this...
		ret=fgets(buf, MAXBUF, stdin);
		buf[strlen(buf)-1]='\0';
		... but don't want to have to rescan line with strlen, so... */

		i=0; p=buf;

		/* recover spaces if re-linebreaking */
		for (; hy; hy--) { *p++=' '; i++; }

		while (lookahead && (c=getchartab())!='\n' && i<MAXBUF) { *p++=c; i++; }
		assert(i<MAXBUF);

#if 0
		lookahead=ungetc(getchar(), stdin);	/* only looking ahead one character for now */
#endif

		/* very special case: if in SEE ALSO section, re-linebreak so references aren't linebroken
		   (also do this if fNOHY flag is set) -- doesn't affect lookahead */
		/* 0xad is an en dash on Linux? */
		if ((fPara || sectheadid==SEEALSO || fNOHY) && p>buf && p[-1]=='-' && isspace(lookahead)) {
			p--;	/* zap hyphen */
			/* zap boldfaced hyphens, gr! */
			while (p[-1]=='\b' && p[-2]=='-') p-=2;

			/* start getting next line, spaces first ... */
			while (lookahead && isspace(lookahead) && lookahead!='\n') { getchartab(); hy++; }

			/* ... append next nonspace string to previous ... */
			while (lookahead && !isspace(lookahead) && i++<MAXBUF) *p++=getchartab();

			/* gobble following spaces (until, perhaps including, end of line) */
			while (lookahead && isspace(lookahead) && lookahead!='\n') getchartab();
			if (lookahead=='\n') { getchartab(); hy=0; }
		}

		*p='\0';
		ret=(lookahead)?buf:NULL;
	}

	AbsLine++;
	return ret;	/* change this to line length? (-1==old NULL) */
}


/*** Kong ***/

char phrase[MAXBUF];	/* first "phrase" (space of >=3 spaces) */
int phraselen;

static void
filterline(char *buf, char *plain)
{
	char *p,*q,*r;
	char *ph;
	int iq;
	int i,j;
	int hl=-1, hl2=-1;
	int iscnt=0;	/* interword space count */
	int tagci;
	int I0;
	int etype;
	int efirst;
	enum tagtype tag = NOTAG;
	int esccode;

	assert(buf!=NULL && plain!=NULL);

	etype=NOTAG;
	efirst=-1;
	tagci=tagc;
	ph=phrase; phraselen=0;
	scnt=scnt2=0;
	s_sum=s_cnt=0;
	bs_sum=bs_cnt=0;
	ccnt=0;
	spcsqz=0;

	/* strip only certain \x1b's and only at very beginning of line */
	for (p=buf; *p=='\x1b' && (p[1]=='8'||p[1]=='9'); p+=2)
		/* nop */;

	strcpy(plain,p);
	q=&plain[strlen(p)];

	/*** spaces and change bars ***/
	for (scnt=0,p=plain; *p==' '; p++) scnt++;	/* initial space count */
	if (scnt>200) scnt=130-(q-p);

	assert(*q=='\0');
	q--;
	if (fChangeleft)
		for (; q-40>plain && *q=='|'; q--)	{	/* change bars */
			if (fChangeleft!=-1) ccnt++;
			while (q-2>=plain && q[-1]=='\b' && q[-2]=='|') q-=2;	/* boldface changebars! */
		}

	/*if (q!=&plain[scnt-1])*/			/* zap trailing spaces */
		for (; *q==' ' && q>plain; q--) /* nop */;

	/* second changebar way out east! HACK HACK HACK */
	if (q-plain>100 && *q=='|') {
	  while (*q=='|' && q>plain) { q--; if (fChangeleft!=-1) ccnt++; }
	  while ((*q==' ' || *q=='_' || *q=='-') && q>plain) q--;
	}

	for (r=q; (*r&0xff)==CHARDAGGER; r--) *r='-';	/* convert daggers at end of line to hyphens */

	if (q-plain < scnt) scnt = q-plain+1;
	q[1]='\0';

	/* set I for tags below */
	if (indent>=0 && scnt>=indent) scnt-=indent;
	if (!fPara && !fIQS) {
		if (fChangeleft) I+=(scnt>ccnt)?scnt:ccnt;
		else I+=scnt;
	}
	I0=I;

	/*** tags and filler spaces ***/

	iq=0; falluc=1;
	for (q=plain; *p; p++) {

		iscnt=0;
		if (*p==' ') {
			for (r=p; *r==' '; r++) { iscnt++; spcsqz++; }
			s_sum+=iscnt; s_cnt++;
			if (iscnt>1 && !scnt2 && *p==' ') scnt2=iscnt;
			if (iscnt>2) { bs_cnt++; bs_sum+=iscnt; }	/* keep track of large gaps */
			iscnt--;		/* leave last space for tail portion of loop */

			/* write out spaces */
			if (fQS && iscnt<3) { p=r-1;	iscnt=0; } /* reduce strings of <3 spaces to 1 */
			/* else if (fQS && iscnt>=3) { replace with tab? } */
			else {
				for (i=0; i<iscnt; i++) { p++; *q++=' '; }
			}
		} /* need to go through if chain for closing off annotations */

		/** backspace-related filtering **/

		if (*p=='\b' && p[1]=='_' && q>plain && q[-1]=='+') {
			/* bold plus/minus(!) */
			q[-1]=c_plusminus;
			while (*p=='\b' && p[1]=='_') p+=2;
			continue;
		} else if ((*p=='_' && p[1]=='\b' && p[2]!='_' && p[3]!='\b')
			|| (*p=='\b' && p[1]=='_')) {
			/* italics */
			if (tag!=ITALICS && hl>=0) { tagadd(tag, hl, I+iq); hl=-1; }
			if (hl==-1) hl=I+iq;
			tag=ITALICS;
			p+=2;
		} else if (*p=='_' && p[2]==p[4] && p[1]=='\b' && p[3]=='\b' && p[2]!='_') {
			/* bold italics (for Solaris) */
			for (p+=2; *p==p[2] && p[1]=='\b';) p+=2;
			if (tag!=BOLDITALICS && hl>=0) { tagadd(tag, hl, I+iq); hl=-1; }
			if (hl==-1) hl=I+iq;
			tag=BOLDITALICS;
		} else if (*p==p[2] && p[1]=='\b') {
			/* boldface */
			while (*p==p[2] && p[1]=='\b') p+=2;
			if (tag!=BOLD && hl>=0) { tagadd(tag, hl, I+iq); hl=-1; }
			if (hl==-1) hl=I+iq;
			tag=BOLD;
		} else if (p[1]=='\b' &&
				 ((*p=='o' && p[2]=='+') ||
				  (*p=='+' && p[2]=='o')) ) {
			/* bullets */
			p+=2;
			while (p[1]=='\b' && (*p=='o' || p[2]=='+') ) p+=2;		/* bold bullets(!) */
			*q++=c_bullet; iq++;
			continue;
		} else if (*p=='\b' && p>plain && p[-1]=='o' && p[1]=='+') {
			/* OSF bullets */
			while (*p=='\b' && p[1]=='+') p+=2;	/* bold bullets(!) */
			q[-1]=c_bullet; p--;
			continue;
		} else if (p[1]=='\b' && *p=='+' && p[2]=='_') {
			/* plus/minus */
			p+=2;
			*q++=c_plusminus; iq++;
			continue;
		} else if (p[1]=='\b' && *p=='|' && p[2]=='-') {
			/* dagger */
			*q++=c_dagger; iq++;
			p+=2; continue;
		} else if (*p=='\b') {
			/* supress unattended backspaces */
			continue;
		} else if (*p=='\x1b') {
			p++;
			if (*p=='[' && isdigit(p[1])) {	/* 0/1/22/24/.../8/9/... */
				esccode=0; for (p++; isdigit(*p); p++) esccode = esccode * 10 + *p - '0';

				if (efirst>=0 /*&& (esccode==0 || esccode==1 || esccode==4 || esccode==22 || esccode==24) **&& hl>=0 && hl2==-1 && tags[MAXTAGS].first<I+iq*/) {
					/* doesn't catch tag if spans line -- just make tag and hl static? */
					/*tagadd(tags[MAXTAGS].type, tags[MAXTAGS].first, I+iq);*/
					if (hl==-1 && hl2==-1 && efirst!=-1/*<I+iq*/)
						tagadd(etype, efirst, I+iq);
					efirst=-1;
				}

				if (esccode==1 /*&& hl==-1*/) {
					/* stash attributes in "invalid" array element */
					efirst=I+iq; etype=BOLD;
					/*hl=I+iq; tag=BOLD; -- faces immediate end of range */
				} else if (esccode==4 /*&& hl==-1*/) {
					efirst=I+iq; etype=ITALICS;

				} /* else skip unrecognized escape codes like 8/9 */
			}

			/*assert(*p=='m'); OR if (*p == 'm') ? */
			/*p++;	** ending 'm' -- inc done in overarching for */
			continue;

		} else if ((isupper(*p) /*|| *p=='_' || *p=='&'*/) &&
				 (hl>=0 || isupper(p[1]) || (p[1]=='_' && p[2]!='\b') || p[1]=='&')) {
			if (hl==-1 && efirst==-1) { hl=I+iq; tag=SMALLCAPS; }
		} else {
			/* end of tag, one way or another */
			/* collect tags in this pass, interspersed later if need be */
			/* can't handle overlapping tags */
			if (hl>=0) {
				if (hl2==-1) tagadd(tag, hl, I+iq);
				hl=-1;
			}
		}

		/** non-backspace related filtering **/
		/* case statement here in place of if chain? */
/* Tk 3.x's text widget tabs too crazy
		if (*p==' ' && strncmp("     ",p,5)==0) {
			xputchar('\t'); i+=5-1; ci++; continue;
		} else
*/
/* copyright symbol: too much work for so little
		if (p[i]=='o' && (strncmp("opyright (C) 19",&p[i],15)==0
				    || strncmp("opyright (c) 19",&p[i],15)==0)) {
			printf("opyright \xd3 19");
			tagadd(SYMBOL, ci+9, ci+10);
			i+=15-1; ci+=13; continue;
		} else
*/
		if (*p=='(' && q>plain && (isalnum(q[-1])||strchr(manvalid/*"._-+"*/,q[-1])!=NULL)
		    && strcoloncmp(&p[1],')',vollist)
		    /* && p[1]!='s' && p[-1]!='`' && p[-1]!='\'' && p[-1]!='"'*/ ) {
			hl2=I+iq;
			for (r=q-1; r>=plain && (isalnum(*r)||strchr(manvalid/*"._-+:"*/,*r)!=NULL); r--)
				hl2--;
			/* else ref to a function? */
			/* maybe save position of opening paren so don't highlight it later */
		} else if (*p==')' && hl2!=-1) {
			/* don't overlap tags on man page references */
			while (tagc>0 && tags[tagc-1].last>hl2) tagc--;
			tagadd(MANREF, hl2, I+iq+1);
			hl2=hl=-1;
		} else if (hl2!=-1) {
			/* section names are alphanumic or '+' for C++ */
			if (!isalnum(*p) && *p!='+') hl2=-1;
		}


		/*assert(*p!='\0');*/
		if (!*p) break;	/* not just safety check -- check out sgmls.1 */

		*q++=*p;
/*		falluc = falluc && (isupper(*p) || isspace(*p) || isdigit(*p) || strchr("-+&_'/()?!.,;",*p)!=NULL);*/
		falluc = falluc && !islower(*p);
		if (!scnt2) { *ph++=*p; phraselen++; }
		iq+=iscnt+1;
	}
	if (hl>=0) tagadd(tag, hl, I+iq);
	else if (efirst>=0) tagadd(etype, efirst, I+iq);
	*q=*ph='\0';
	linelen=iq+ccnt;


	/* special case for Solaris:
	   if line has ONLY <CODE> tags AND they SPAN line, convert to one tag */
	fCodeline=0;
	if (tagc && tags[0].first==0 && tags[tagc-1].last==linelen) {
		fCodeline=1;
		j=0;
		/* invariant: at start of a tag */
		for (i=0; fCodeline && i<tagc; i++) {
			if (tags[i].type!=BOLDITALICS /*&& tags[i].type!=BOLD*/) fCodeline=0;
			else if ((j=tags[i].last)<linelen) {
			  for (; j < tags[i+1].first ; j++)
			  	if (!isspace(plain[j])) { fCodeline=0; break; }
			}
		}
	}


	/* verify tag lists -- in production, compiler should kill with dead code elimination */
	for (i=tagci; i<tagc; i++) {
		/* verify valid ranges */
		assert(tags[i].type>NOTAG && tags[i].type<=MANREF);
		assert(tags[i].first>=I0 && tags[i].last<=linelen+I0);
		assert(tags[i].first<=tags[i].last);

		/* verify for no overlap with other tags */
		for (j=i+1; j<tagc; j++) {
			assert(tags[i].last<=tags[j].first /*|| tags[i].first>=tags[j].last*/);
		}
	}
}


/*
  buf[] == input text (read only)
  plain[] == output (initial, trailing spaces stripped; tabs=>spaces;
     underlines, overstrikes => tag array; spaces squeezed, if requested)
  ccnt = count of changebars
  scnt = count of initial spaces
  linelen = length result in plain[]
*/

int fHead=0;
int fFoot=0;

static void
preformatted_filter(void)
{
	const int MINRM=50;		/* minimum column for right margin */
	const int MINMID=20;
	const int HEADFOOTSKIP=20;
	const int HEADFOOTMAX=25;
	int curtag;
	char *p,*r;
	char head[MAXBUF]="";		/* first "word" */
	char foot[MAXBUF]="";
	int header_m=0, footer_m=0;
	int headlen=0, footlen=0;
/*	int line=1-1; */
	int i,j,k,l,off;
	int sect=0,subsect=0,bulpair=0,osubsect=0;
	int title=1;
	int oscnt=-1;
	int empty=0;
	int fcont=0;
	int Pnew=0,I0;
	float s_avg=0.0;
	int spaceout;
	int skiplines=0;
	int c;

	/* try to keep tabeginend[][] in parallel with enum tagtype */
	assert(tagbeginend[ITALICS][0]==BEGINITALICS);
	assert(tagbeginend[MANREF][1]==ENDMANREF);
	in++;	/* lookahead = current character, in points to following */

	/*	for (i=0; i<MAXBUF; i++) tabgram[i]=0;*/

	/*if (fMan) */indent=-1;
	I=1;
	CurLine=1;
	(*fn)(BEGINDOC); I0=I;

	/* run through each line */
	while (la_gets(buf)!=NULL) {
		if (title) I=I0;
		/* strip out Ousterhout box: it's confusing the section line counts in TkMan outlining */
		if (fNORM && *buf=='_'
		    && strncmp(buf,"_________________________________________________________________",65)==0) {
			fTclTk = 1;
			if (fChangeleft==0) fChangeleft=1;
			skiplines = 2;
		}
		if (skiplines) { skiplines--; AbsLine++; continue; }
		filterline(buf,plain);	/* ALL LINES ARE FILTERED */

#if 0
		/* dealing with tables in formatted pages is hopeless */
		finTable = fTable &&
			((!ncnt && fotable) ||
			(ncnt && bs_cnt>=2 && bs_cnt<=5 && ((float) bs_sum / (float) bs_cnt)>3.0));
		if (finTable) {
			if (!fotable) (*fn)(BEGINTABLE);
		} else if (fotable) {
			(*fn)(ENDTABLE);
			I=I0; tagc=0; filterline(buf,plain);	/* rescan first line out of table */
		}
#endif

		s_avg=(float) s_sum;
		if (s_cnt>=2) {
			/* don't count large second space gap */
			if (scnt2) s_avg= (float) (s_sum - scnt2) / (float) (s_cnt-1);
			else s_avg= (float) (s_sum) / (float) (s_cnt);
		}

		p=plain;	/* points to current character in plain */

		/*** determine header and global indentation ***/
		if (/*fMan && (*/!fHead || indent==-1/*)*/) {
			if (!linelen) continue;
			if (!*header) {
				/* check for missing first header--but this doesn't catch subsequent pages */
				if (stricmp(p,"NAME")==0 || stricmp(p,"NOMBRE")==0) {	/* works because line already filtered */
					indent=scnt; /*filterline(buf,plain);*/ scnt=0; I=I0; fHead=1;
				} else {
					fHead=1;
					(*fn)(BEGINHEADER);
					/* grab header and its first word */
					strcpy(header,p);
					if ((header_m=HEADFOOTSKIP)>linelen) header_m=0;
					strcpy(head,phrase); headlen=phraselen;
					la_gets(buf); filterline(buf,plain);
					if (linelen) {
						strcpy(header2,plain);
						if (strincmp(plain,"Digital",7)==0 || strincmp(plain,"OSF",3)==0) {
							fFoot=1;
							fSubsections=0;
						}
					}
					(*fn)(ENDHEADER); tagc=0;
					continue;
				}
			} else {
				/* some idiot pages have a *third* header line, possibly after a null line */
				if (*header && scnt>MINMID) { strcpy(header3,p); ncnt=0; continue; }
				/* indent of first line ("NAME") after header sets global indent */
				/* check '<' for Plan 9(?) */
				if (*p!='<') {
					indent=scnt; I=I0; scnt=0;
				} else continue;
			}
/*			if (indent==-1) continue;*/
		}
		if (!lindent && scnt) lindent=scnt;
/*printf("lindent = %d, scnt=%d\n", lindent,scnt);*/


		/**** for each ordinary line... *****/

		/*** skip over global indentation */
		empty=(linelen==0);
		if (empty) {ncnt++; continue;}

		/*** strip out per-page titles ***/

		if (/*fMan && (*/scnt==0 || scnt>MINMID/*)*/) {
/*printf("***ncnt = %d, fFoot = %d, line = %d***", ncnt,fFoot,AbsLine);*/
			if (!fFoot && !isspace(*p) && (scnt>5 || (*p!='-' && *p!='_')) &&
			    /* don't add ncnt -- AbsLine gets absolute line number */
			    (((ncnt>=2 && AbsLine/*+ncnt*/>=61/*was 58*/ && AbsLine/*+ncnt*/<70)
				 || (ncnt>=4 && AbsLine/*+ncnt*/>=59 && AbsLine/*+ncnt*/<74)
				 || (ncnt && AbsLine/*+ncnt*/>=61 && AbsLine/*+ncnt*/<=66))
				 && (/*lookahead!=' ' ||*/ (s_cnt>=1 && s_avg>1.1) || !falluc) )
			    ) {
				(*fn)(BEGINFOOTER);
				/* grab footer and its first word */
				strcpy(footer,p);
/*				if ((footer_m=linelen-HEADFOOTSKIP)<0) footer_m=0;*/
				if ((footer_m=HEADFOOTSKIP)>linelen) footer_m=0;
				/*grabphrase(p);*/ strcpy(foot,phrase); footlen=phraselen;
				/* permit variations at end, as for SGI "Page N", but keep minimum length */
				if (footlen>3) footlen--;
				la_gets(buf); filterline(buf,plain); if (linelen) strcpy(footer2,plain);
				title=1;
				(*fn)(ENDFOOTER); tagc=0;

				/* if no header on first page, try again after first footer */
				if (!fFoot && *header=='\0') fHead=0;	/* this is dangerous */
				fFoot=1;
				continue;
			} else
				/* a lot of work, but only for a few lines (about 4%) */
				if (fFoot && (scnt==0 || scnt+indent>MINMID) &&
					 (   (headlen && strncmp(head,p,headlen)==0)
					  || strcmp(header2,p)==0 || strcmp(header3,p)==0
					  || (footlen && strncmp(foot,p,footlen)==0)
					  || strcmp(footer2,p)==0
					  /* try to recognize lines with dates and page numbers */
					  /* skip into line */
					  || (header_m && header_m<linelen &&
						 strncmp(&header[header_m],&p[header_m],HEADFOOTMAX)==0)
					  || (footer_m && footer_m<linelen &&
						 strncmp(&footer[footer_m],&p[footer_m],HEADFOOTMAX)==0)
					  /* skip into line allowing for off-by-one */
					  || (header_m && header_m<linelen &&
						 strncmp(&header[header_m],&p[header_m+1],HEADFOOTMAX)==0)
					  || (footer_m && footer_m<linelen &&
						 strncmp(&footer[footer_m],&p[footer_m+1],HEADFOOTMAX)==0)
					  /* or two */
					  || (header_m && header_m<linelen &&
						 strncmp(&header[header_m],&p[header_m+2],HEADFOOTMAX)==0)
					  || (footer_m && footer_m<linelen &&
						 strncmp(&footer[footer_m],&p[footer_m+2],HEADFOOTMAX)==0)
					  /* or with reflected odd and even pages */
					  || (headlen && headlen<linelen &&
						 strncmp(head,&p[linelen-headlen],headlen)==0)
					  || (footlen && footlen<linelen &&
						 strncmp(foot,&p[linelen-footlen],footlen)==0)
					  )) {
				tagc=0; title=1; continue;
			}

			/* page numbers at end of line */
			for(i=0; p[i] && isdigit(p[i]); i++)
				/* empty */;
			if (&p[i]!=plain && !p[i]) {title=1; fFoot=1; continue;}
		}

		/*** interline spacing ***/
		/* multiple \n: paragraph mode=>new paragraph, line mode=>blank lines */
		/* need to chop up lines for Roff */

		/*tabgram[scnt]++;*/
		if (title) ncnt=(scnt!=oscnt || (/*scnt<4 &&*/ isupper(*p)));
		itabcnt = scnt/5;
		if (CurLine==1) {ncnt=0; tagc=0;} /* gobble all newlines before first text line */
		sect = (scnt==0 && isupper(*p));
		subsect = (fSubsections && (scnt==2||scnt==3));
		if ((sect || subsect) && ncnt>1) ncnt=1; /* single blank line between sections */
		(*fn)(BEGINLINE);
		if (/*fPara &&*/ ncnt) Pnew=1;
		title=0; /*ncnt=0;--moved down*/
		/*if (finTable) (*fn)(BEGINTABLELINE);*/
		oscnt=scnt; /*fotable=finTable;*/

/* let output modules decide what to do at the start of a paragraph
		if (fPara && !Pnew && (prevcmd==BEGINBODY || prevcmd==BEGINBULTXT)) {
			putchar(' '); I++;
		}
*/

		/*** identify structural sections and notify fn */

		/*if (fMan) {*/
/*			bulpair = (scnt<7 && (*p==c_bullet || *p=='-'));*/
			/* decode the below */
			bulpair = ((!auxindent || scnt!=lindent+auxindent) /*!bulpair*/
					 && ((scnt>=2 && scnt2>5) || scnt>=5 || (tagc>0 && tags[0].first==scnt) ) /* scnt>=2?? */
					 && (((*p==c_bullet || strchr("-+.",*p)!=NULL || falluc) && (ncnt || scnt2>4)) ||
					  (scnt2-s_avg>=2 && phrase[phraselen-1]!='.') ||
					  (scnt2>3 && s_cnt==1)
					  ));
			if (bulpair) {
				if (tagc>0 && tags[0].first==scnt) {
					k=tags[0].last;
					for (l=1; l<tagc; l++) {
						if (tags[l].first - k <=3)
							k=tags[l].last;
						else break;
					}
					phraselen=k-scnt;
					for (k=phraselen; plain[k]==' ' && k<linelen; k++) /* nothing */;
					if (k>=5 && k<linelen) hanging=k; else hanging=-1;
				} else if (scnt2) hanging=phraselen+scnt2;
				else hanging=5;
			} else hanging=0;

/*			hanging = bulpair? phraselen+scnt2 : 0;*/
/*if (bulpair) printf("hanging = %d\n", hanging);*/
			/* maybe, bulpair=0 would be best */
			/*end fMan}*/

		/* certain sections (subsections too?) special, like SEE ALSO */
		/* to make canonical name as plain, all lowercase */
		if (sect /*||subsect -- no widespread subsection names*/) {
		  for (j=0; (sectheadid=j)<RANDOM; j++) if (strcoloncmp2(plain,'\0',sectheadname[j],0)) break;
		}

		/* normalized section headers are put into mixed case */
		if (/*fNORM &&*/falluc && (sect || subsect)) casify(plain);

		if (sect) {
			poppush(BEGINSECTION); (*fn)(BEGINSECTHEAD);
			tocadd(plain, BEGINSECTION, CurLine);
		} else if (subsect && !osubsect) {
			poppush(BEGINSUBSECTION); (*fn)(BEGINSUBSECTHEAD);
			tocadd(plain, BEGINSUBSECTION, CurLine);
		} else if (bulpair) {
			/* used to be just poppush(BEGINBULPAIR); */
			if (!Pbp) poppush(BEGINBULPAIR);
			(poppush)(BEGINBULLET);
			fIP=1; /*grabphrase(plain);*/
		} else if (Pnew) {
			poppush(BEGINBODY);
		}
		Pnew=0;
		oldsectheadid = sectheadid;


		/* move change bars to left */
		if (fChangeleft && !fNORM) {
			if (fPara) (*fn)(CHANGEBAR);
			/* replace initial spaces with changebars */
			else for (i=0; i<ccnt; i++) { /*xputchar('|'); */ (*fn)(CHANGEBAR); }
		}

		/* show initial spaces */
		if (!fIQS && fcharout) {
			spaceout = (scnt>ccnt)?(scnt-ccnt):0;
			if (fILQS) { if (spaceout>=lindent) spaceout-=lindent; else spaceout=0; }
			if (auxindent) { if (spaceout>=auxindent) spaceout-=auxindent; else spaceout=0; }
			if (fNORM) {
			  	if (itabcnt>0) (*fn)(ITAB);
				for (i=0; i<(scnt%5); i++) putchar(' ');
			} else printf("%*s",spaceout,"");
		}


		/*** iterate over each character in line, ***/
		/*** handling underlining, tabbing, copyrights ***/

		off=(!fIQS&&!fPara)?scnt:0;
		for (i=0, p=plain, curtag=0, fcont=0; *p; p++,i++,fcont=0) {
			/* interspersed presentation signals */
			/* start tags in reverse order of addition (so structural first) */
			if (curtag<tagc && i+I0+off==tags[curtag].first) {
				for (r=hitxt, j=tags[curtag].last-tags[curtag].first, hitxt[j]='\0'; j; j--)
					hitxt[j-1]=p[j-1];
				(*fn)(tagbeginend[tags[curtag].type][0]);
			}

			/* special characters */
			switch(*p) {
			   case '"':
				if (p==plain || isspace(p[-1])) { (*fn)(CHARLQUOTE); fcont=1; }
				else if (isspace(p[1])) { (*fn)(CHARRQUOTE); fcont=1; }
				break;
			   case '\'':
				if (p==plain || isspace(p[-1])) { (*fn)(CHARLSQUOTE); fcont=1; }
				else if (isspace(p[1])) { (*fn)(CHARRSQUOTE); fcont=1; }
				break;
			   case '-':
				/* check for -opt => \-opt */
				if (p==plain || (isspace(p[-1]) && !isspace(p[1]))) {
				  (*fn)(CHARDASH); fcont=1;
				}
				break;
			}

			/* troublemaker characters */
			c = (*p)&0xff;
			if (!fcont && fcharout) {
				if (strchr(escchars,c)!=NULL) {
					putchar('\\'); putchar(c); I++;
				} else if (strchr((char *)trouble,c)!=NULL) {
					(*fn)((enum command)c); fcont=1;
				} else {
					putchar(c); I++;
				}
			}

/*default:*/
			if (curtag<tagc && i+I0+off+1==tags[curtag].last) {
				(*fn)(tagbeginend[tags[curtag].type][1]);
				curtag++;
			}

			if (fIP && ((*p==' ' && i==phraselen) || *p=='\0')) {
				p++;  /* needed but why? */
				(*fn)(ENDBULLET); fIP=0;
				if (*p!='\0') {
					/*oscnt+=phraselen;*/
					oscnt+=i;
					for (r=p; *r==' '; r++) {
						oscnt++;
/*
						i++;
						if (fQS || !fcharout) p++;
*/
					}
				}
				p--;	/* to counteract increment in loop */

				poppush(BEGINBULTXT);
			}
		}


		/*** end of line in buf[] ***/
		/*** deal with section titles, hyperlinks ***/

		if (sect) { (*fn)(ENDSECTHEAD); Pnew=1; }
		else if (subsect) { (*fn)(ENDSUBSECTHEAD); Pnew=1; }
		else if (fIP) { (*fn)(ENDBULLET); fIP=0; poppush(BEGINBULTXT); }
/* oscnt not right here */
		else if (scnt+linelen+spcsqz<MINRM /*&& ncnt*/ && lookahead!='\n'
			    && prevcmd!=BEGINBULTXT && prevcmd!=ENDSUBSECTHEAD && prevcmd!=ENDSUBSECTHEAD)
			(*fn)(SHORTLINE);
		osubsect=subsect;

		/*if (finTable) (*fn)(ENDTABLELINE);*/
		/*if (!fPara)*/ (*fn)(ENDLINE); tagc=0;
		ncnt=0;
		I0=I;	/* save I here in case skipping lines screws it up */
	}

	/* wrap up at end */
	pop(ENDDOC);	/* clear up all tags on stack */
	(*fn)(ENDDOC);
}



/*
 * SOURCE CODE PARSING
 *    for better transcription short of full nroff interpreter
 *
 *    Macros derived empirically, except for weird register ones that were looked up in groff
 *
 * buffer usage
 *    buf = incoming text from man page file
 *    plain = "second pass" buffer used to identify man page references
 *
 * test pages
 *    Solaris: fdisk.1m, fcntl.2, curs_getwch.3x, locale.5 (numbered lists),
 *		getservbyname.3n (font size changes)
 */

/* macros */
/* put as much in here, as opposed to in code, as possible.
   less expensive and here they can be overridden by other macros */
/*const int macromax=100; -- dumb compiler */
#define MACROMAX 1000
struct { char *key; char *subst; } macro[MACROMAX] = {
  /* Solaris */
  {"NA", ".SH NAME"},
  {"SB", "\\s-2\\fB\\$1\\fR\\s0"},
  /* HP-UX */
#if 0
  {"SM", "\\s-2\\$1\\s0"},
  {"C", "\\f3\\$1\\fR"},
  {"CR", "\\f3\\$1\\fR\\$2"},
  {"CI", "\\f3\\$1\\fI\\$2\\fR"},
  {"RC", "\\fR\\$1\\f3\\$2\\fR"},
#endif
  /* SGI -- doesn't ship man page source */

  /* 4.4BSD  -  http://intergate.sonyinteractive.com/cgi-bin/manlink/7/mdoc */
  /* scads more, but for them definition in -mandoc is sufficient */
#if 0
  {"Dt", ".TH \\$1 \\$2 \\$3"},
  {"Sh", ".SH \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9"},
  {"Ss", ".SS \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9"},
  {"Pp", ".P"},
  {"Nm", ".BR \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9"},	/* name */
  {"Ar", ".IR \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9"},
#endif
  { NULL, NULL }
};
/* what all can be represented as a macro? */
int macrocnt=-1;	/* length of table counted at start */

char *macnotfound[MACROMAX];
int macnotcnt=0;

#define SUBSTMAX 1000
/* "*" or "*(" prefixed */
struct { char *key; char *subst; } subst[SUBSTMAX] = {
  {"rq", "'"}, {"lq", "`"}, {"L\"", "``"}, {"R\"", "''"},
  {"L", "\\f3"}, {"E", "\\f2"}, {"V", "\\f4"}, {"O", "\\f1"}
};
int substcnt=8;

#define REGISTERMAX 1000
struct { char *name; char *value; } reg[REGISTERMAX];
int regcnt=0;

/* special characters */
const struct { char key[4]; unsigned char subst[4]; } spec[] = {
  { "**", "*" },
  { "+-", { CHARPLUSMINUS, '\0' }},
  { "12", { CHAR12, '\0' }},
  { "14", { CHAR14, '\0' }},
  { "34", { CHAR34, '\0' }},
  { "aa", { CHARACUTE, '\0' }},
  { "ap", "~" },
  { "br", "|" },
  { "bu", { CHARBULLET, '\0' }},
  { "bv", "|" },
  { "ci", "O" },
  { "co", { CHARCOPYR, '\0' }},
  { "ct", { CHARCENT, '\0' }},
  { "de", { CHARDEG, '\0' }},
  { "dg", { CHARDAGGER, '\0' }},
  { "di", { CHARDIV, '\0' }},
  { "em", "--" },
  { "eq", "=" },
  { "hy", "-" },
  { "mi", "-" },
  { "mu", { CHARMUL, '\0' }},
  { "no", { CHARNOT, '\0' }},
  { "or", "|" },
  { "pl", "+" },
  { "rg", { CHARREGTM, '\0' }},
  { "ru", "_" },
  { "sc", { CHARSECT, '\0' }},
  { "sl", "/" },
  { "ua", "^" },
  { "ul", "_" }
};
#define speccnt (sizeof spec / sizeof spec[0])

/* tbl line descriptions */
char *tbl[20][20];	/* space enough for twenty description lines, twenty parts each */
int tblc=0;
int tbli;

int fsourceTab = 0, fosourceTab=0;
int supresseol=0;
int finitDoc=0;
int sublevel=0;

static char *
source_gets(void)
{
  char *p,*q;
  char *ret = (*in)?buf:NULL;
  int i;
  char *begin;
  char tmpbuf[MAXBUF];
  char name[3];

  if (!sublevel) AbsLine++;

  p = tmpbuf;
  falluc = 1;
  while (1) {
    /* collect characters in line */
    while (*in && *in!='\n') {
	 if (p[0]=='\\' && p[1]=='\n') p+=2;	/* \<newline> */
	 falluc = falluc && !islower(*in);
	 *p++ = *in++;
    }
    if (*in) in++;
    *p='\0';

    /* normalize commands */
    p=tmpbuf; q=buf;	/* copy from tmpbuf to buf */
    /* no spaces between command-initiating period and command letters */
    if (*p=='\'') { *p='.'; }	/* what's the difference? */
    if (*p=='.') { *q++ = *p++; while (isspace(*p)) p++; }


    /* convert lines with tabs to tables? */
    fsourceTab=0;

    /* if comment at start of line, OK */
    /* dynamically determine iff Tcl/Tk page by scanning comments */
    begin = p;
    if (*p=='\\' && *(p+1)=='"') {
	if (!fTclTk && strstr(p+1,"supplemental macros used in Tcl/Tk")!=NULL) fTclTk=1;
	if (fTclTk)
	    p+=2;
    }

    while (*p) {
	 if (*p=='\t') fsourceTab++;
	 if (*p=='\\') {
	   p++;
	   if (*p=='n') {
		p++;
		if (*p=='(') {
		  p++; name[0]=*p++; name[1]=*p++; name[2]='\0';
		} else {
		  name[0]=*p++; name[1]='\0';
		}
		*q='0'; *(q+1)='\0';	/* defaults to 0, in case doesn't exist */
		for (i=0; i<regcnt; i++) {
		  if (strcmp(reg[i].name,name)==0) {
		    strcpy(q, reg[i].value);
		    break;
		  }
		}
		q+=strlen(q);
	   } else if (*p=='"' && (p != begin+1)) {	/* comment in Digital UNIX, OK elsewhere? */
		*p='\0';
		q--; while (q>buf && isspace(*q)) q--;	/* trim tailing whitespace */
		q++; *q='\0';
	   } else {
		/* verbatim character (often a backslash) */
		*q++ = '\\';	/* postpone interpretation (not the right thing but...) */
		*q++ = *p++;
	   }
	 } else *q++ = *p++;
    }

    /* dumb Digital--later */
    /*if (q-3>plain && q[-1]=='{' && q[-2]=='\\' && q[-3]==' ') q[-3]='\n'; }*/

    /* close off buf */
    *q='\0';

#if 0
    if (q>buf && q[-1]=='\\' && *in=='.') /* append next line * / else break;*/
#endif
    break;
  }

  /*printf("*ret = |%s|\n", ret!=NULL?ret : "NULL");*/
  return ret;
}


/* dump characters from buffer, signalling right tags along the way */
/* all this work to introduce an internal second pass to recognize man page references */
/* now for HTTP references too */

int sI=0;
/* use int linelen from up top */
int fFlush=1;

static void
source_flush(void)
{
  int i,j;
  char *p,*q,*r;
  int c;
  int manoff,posn;

  if (!sI) return;
  plain[sI] = '\0';

  /* flush called often enough that all man page references are at end of text to be flushed */
  /* find man page ref */
  if (sI>=4/*+1*/ && (plain[sI-(manoff=1)-1]==')' || plain[sI-(manoff=0)-1]==')')) {
    for (q=&plain[sI-manoff-1-1]; q>plain && isalnum(*q) && *q!='('; q--) /* nada */;
    if (*q=='(' && strcoloncmp(&q[1],')',vollist)) {
	 r=q-1;
	 if (*r==' ' && (sectheadid==SEEALSO || /*single letter volume */ *(q+2)==')' || *(q+3)==')')) r--;	/* permitted single intervening space */
	 for ( ; r>=plain && (isalnum(*r) || strchr(manvalid,*r)!=NULL); r--) /* nada */;
	 r++;
	 if (isalpha(*r) && r<q) {
	   /* got one: clear out tags and spaces to make normalized form */
	   posn = r-plain;
	   /*while (tagc && tags[tagc-1].first >= posn) tagc--;*/

	   /* add MANREF tags */
	   strcpy(hitxt,r);
	   tagadd(BEGINMANREF, posn, 0);
	   /* already generated other start tags, so move BEGINMANREF to start in order to be well nested (ugh) */
	   tagtmp = tags[tagc-1]; for (j=tagc-1; j>0; j--) tags[j]=tags[j-1]; tags[0]=tagtmp;
	   tagadd(ENDMANREF, sI-manoff-1+1, 0);
	 }
    }

  /* HTML hyperlinks */
  } else if (fURL && sI>=4 && (p=strstr(plain,"http"))!=NULL) {
    i = p-plain;
    tagadd(BEGINMANREF, i, 0); tagtmp = tags[tagc-1]; for (j=tagc-1; j>0; j--) tags[j]=tags[j-1]; tags[0]=tagtmp;
    for (j=0; i<sI && !isspace(*p) && *p!='"' && *p!='>'; i++,j++) hitxt[j] = *p++;
    hitxt[j]='\0';
    tagadd(ENDMANREF, i, 0);
  }

  if (!fFlush) return;

  /* output text */
  for (i=0,j=0,p=plain; i<sI && *p; i++,p++) {
    if (!linelen) (*fn)(BEGINLINE);	/* issue BEGINLINE when know will be chars on line */

    /* dump tags */
    /*for ( ; j<tagc && tags[j].first == i; j++) (*fn)(tags[j].type);*/
    for (j=0; j<tagc; j++) if (tags[j].first == i) (*fn)((enum command)tags[j].type);

    /* dump text */
    c = (*p)&0xff;	/* just make c unsigned? */
    if (strchr(escchars,c)!=NULL) {
	 xputchar('\\'); xputchar(c);
	 if (fcharout) linelen++;
    } else if (strchr((char *)trouble,c)!=NULL) {
	 (*fn)((enum command)c);
    } else if (linelen>=LINEBREAK && c==' ') { (*fn)(ENDLINE); linelen=0;
    } else {		/* normal character */
	 xputchar(c);
	 if (fcharout) linelen++;
    }

    /*if (linelen>=LINEBREAK && c==' ') { (*fn)(ENDLINE); linelen=0; } -- leaves space at end of line*/
  }
  /* dump tags at end */
  /*for ( ; j<tagc && tags[j].first == sI; j++) (*fn)(tags[j].type);*/
  for (j=0; j<tagc; j++) if (tags[j].first==sI) (*fn)((enum command)tags[j].type);

  sI=0; tagc=0;
}


/* source_out stuffs characters in a buffer */
static char *
source_out0(const char *pin, char end)
{
  /* stack of character formattings */
  static enum tagtype styles[20];
  static int style=-1;
  int funwind=0;
  int i, j;
  int len;
  int sign;
  char *p, *pstart;

  pstart = p = mystrdup(pin);
  while (*p && *p!=end) {
    if (*p=='\\') {	/* escape character */
	 switch (*++p) {
 	 case '&':	/* no space.  used as a no-op sometimes */
 	 case '^':	/* 1/12 em space */
 	 case '|':      /* 1/6 em space */
 	 case '%':      /* hyphenation indicator */
 	   /* just ignore it */
 	   p++;
 	   break;
 	 case '0':	/* digit width space */
 	   p++;
 	   sputchar(' ');
 	   break;
 	 case ' ':	/* unpaddable space */
 	   stagadd(CHARNBSP);	/* nonbreaking space */
 	   /*sputchar(' ');*/
 	   p++;
 	   break;
 	 case 's':	/* font size change */
	   p++;
	   sign=1;
	   if (*p=='-' || *p=='+') if (*p++=='-') sign=-1;
	   intArg = sign * ((*p++)-'0');
	   if (intArg==0) intArg = -fontdelta;	/* s0 returns to normal height */
	   if (fontdelta || intArg) { source_flush(); (*fn)(FONTSIZE); }
	   break;
 	 case 'v':	/* vertical motion */
 	 case 'h':	/* horizontal motion */
 	 case 'L':	/* vertical line */
 	 case 'l':	/* horizontal line */
	   /* ignore */
	   p++;
	   if (*p=='\'') { p++; while (*p++!='\''); }
	   break;
	 case '"':	/* comment */
	   *p='\0';	/* rest of line is comment */
	   break;
	 case 'f':
	   p++;
	   switch (*p++) {
	   case '3': case 'B':		/* boldface */
		styles[++style] = BOLD;
		stagadd(BEGINBOLD);
		break;
	   case '2': case 'I':		/* italics */
		styles[++style] = ITALICS;
		stagadd(BEGINITALICS);
		break;
	   case '4':	 /* bolditalics mode => program code */
		styles[++style] = BOLDITALICS;
		stagadd(BEGINBOLDITALICS);
		break;
	   case '1': case '0': case 'R': case 'P':	/* back to Roman */
		/*sputchar(' '); -- taken out; not needed, I hope */
		funwind=1;
		break;
	   case '-':
		p++;
		break;
	   }
	   break;
	 case '(':	/* multicharacter macros */
	   p++;
	   for (i=0; (unsigned)i<speccnt; i++) {
		if (p[0]==spec[i].key[0] && p[1]==spec[i].key[1]) {
		  p+=2;
		  for (j=0; spec[i].subst[j]; j++) sputchar(spec[i].subst[j]);
		  break;
		}
	   }
	   break;
	 case '*':	/* strings */
	   p++;
 	   if (*p!='(') {	/* single character */
 	     for (i=0; i<substcnt; i++) {
		  if (*p==subst[i].key[0] && subst[i].key[1]=='\0') {
		    source_out0(subst[i].subst,'\0');
		    break;
		  }
 	     }
 	     p++;
	   } else {	/* multicharacter macros */
		p++;
		for (i=0; i<substcnt; i++) {
		  len = strlen(subst[i].key);
		  if (strncmp(p,subst[i].key,len)==0) {
		    source_out0(subst[i].subst,'\0');
		    p+=len;
		    break;
		  }
		}
	   }
	   break;
#if 0
	 case '|':
	   stagadd(CHARNBSP);	/* nonbreaking space */
#if 0
	   sputchar(' ');
#endif
	   p++;
#endif
	 case 'e':		/* escape */
	   sputchar('\\');
	   p++;
	   break;
	 case 'c':
		/* supress following carriage return-induced space */
	   /* handled in source_gets(); ignore within line => can't because next line might start with a command */
	   supresseol=1;
	   p++;
	   break;
	 case '-':		/* minus sign */
	   sputchar(CHARDASH);
	   p++;
	   break;
#if 0
	 case '^':
	   /* end stylings? (found in Solaris) */
	   p++;
#endif
	 case 'N':
	   p++;
	   if (*p == '\'') {
	     char *tmp;
	     p++;
	     if ((tmp = strchr(p, '\'')) != NULL) {
	       sputchar(atoi(p));
	       p = tmp + 1;
	     }
	   }
	   break;
	 case 0:
	     /* ignore */
	     break;
	 default:		/* unknown escaped character */
	   sputchar(*p++);
	 }

    } else {		/* normal character */
	 if (*p) sputchar(*p++);
    }


    /* unwind character formatting stack */
    if (funwind) {
	 for ( ; style>=0; style--) {
	   if (styles[style]==BOLD) stagadd(ENDBOLD);
	   else if (styles[style]==ITALICS) stagadd(ENDITALICS);
	   else stagadd(ENDBOLDITALICS);
	 } /* else error */
	 assert(style==-1);

	 funwind=0;
    }

    /* check for man page reference and flush buffer if safe */
    /* postpone check until after following character so catch closing tags */
    if ((sI>=4+1 && plain[sI-1-1]==')') ||
	   /*  (plain[sI-1]==' ' && (q=strchr(plain,' '))!=NULL && q<&plain[sI-1])) */
	 (sI>=2 && plain[sI-1]==' ' && !isalnum(plain[sI-1-1]))) {
	 /* regardless, flush buffer */
	 source_flush();
    }
  }

  if (*p && *p!=' ') p++;		/* skip over end character */
  free(pstart);
  return (char *)pin + (p - pstart);

}

/* oh, for function overloading.  inlined by compiler, probably */
static char *
source_out(const char *p)
{
  return source_out0(p,'\0');
}


static char *
source_out_word(const char *p)
{
  char end = ' ';

  while (*p && isspace(*p)) p++;
  if (*p=='"' /* || *p=='`' ? */) {
    end = *p;
    p++;
  }
  p = source_out0(p,end);
  /*while (*p && isspace(*p)) p++;*/
  return (char *)p;
}


static void
source_struct(enum command cmd)
{
  source_out("\\fR\\s0");	/* don't let run-on stylings run past structural units */
  source_flush();
  if (cmd==SHORTLINE) linelen=0;
  (*fn)(cmd);
}

#define checkcmd(str)	strcmp(cmd,str)==0

int finnf=0;

static void source_line(char *p);

static void
source_subfile(char *newin)
{
  char *p;
  char *oldin = in;

  sublevel++;

  in = newin;
  while ((p=source_gets())!=NULL) {
    source_line(p);
  }
  in = oldin;

  sublevel--;
}

/* have to delay acquisition of list tag */
static void
source_list(void)
{
  static int oldlisttype;	/* OK to have just one because nested lists done with RS/RE */
  char *q;
  int i;

  /* guard against empty bullet */
  for (i=0, q=plain; i<sI && isspace(*q); q++,i++) /* empty */;
  if (i==sI) return;

  assert(finlist);

  fFlush=1;

  /* try to determine type of list: DL, OL, UL */
  q=plain; plain[sI]='\0';
  if (/*c==CHARBULLET || q=='-' -- command line opts! ||*/ *q=='.' || *q&0x80) {
    listtype=UL;
    q++;
  } else {
    if (strchr("[(",*q)) q++;
    while (isdigit(*q)) { listtype=OL; q++; }	/* I hope this gives the right number */
    if (*q=='.') q++;
    if (strchr(")]",*q)) q++;
    if (*q=='.') q++;
    while (isspace(*q)) q++;
    if (*q) listtype=DL;
  }
  oldlisttype = listtype;

  /* interpretation left to output formats based on listtype (HTML: DL, OL, UL) */
  i = sI; sI=0;
  if (!Pbp || listtype!=oldlisttype) poppush(BEGINBULPAIR);
  poppush(BEGINBULLET);
  /*if (tphp) source_line(p); else source_out_word(p);*/
  /*if (listtype!=OL && listtype!=UL)*/ sI=i;
  source_struct(ENDBULLET); Pbul=0; /* handled immediately below */
  poppush(BEGINBULTXT);

  finlist=0;
}

static int inComment=0;
static int isComment=0;

static void
source_command(char *p)
{
  static int lastif=1;
  int mylastif;
  char *cmd=p;
  char *q;
  int i,j,endch;
  int fid;
  struct stat fileinfo;
  char *sobuf;
  char *macroArg[9];
  char endig[10];
  int err=0;
  char ch;
  int tphp=0;
  int ie=0;
  int cond,invcond=0;
  char delim,op;
  char if0[MAXBUF], if1[MAXBUF];
  float nif0, nif1;
  int insertat;
  char macrobuf[MAXBUF];		/* local so can have nested macros */
  static char ft='\0';
  static int fTableCenter=0;

  /* should centralize command matching (binary search?), pointer bumping here
     if for no other reason than to catch conflicts -- and allow overrides? */
  /* parse out command */
  while (*p && !isspace(*p)) p++;
  if (*p) { *p='\0'; p++; }
  /* should set up argv, argc for command arguments--it's regular enough that everyone doesn't have to do it itself */

  isComment = (/*checkcmd("") ||*/ !strncmp(cmd, "\\\"", 2) || /*DEC triple dot*/checkcmd(".."));
  if (inComment && !isComment) { source_struct(ENDCOMMENT); inComment=0; }	/* special case to handle transition */

  if (isComment) {
    /* maybe have BEGINCOMMENT, ENDCOMMENT, COMMENTLINE */
    supresseol=0;
    if (!inComment) { source_flush(); source_struct(BEGINCOMMENT); inComment=1; }
    source_struct(COMMENTLINE);
    printf("%s\n", p);	/* could contain --> or other comment closer, but unlikely */

  /* structural commands */
  } else if (checkcmd("TH")) {
    /* sample: .TH CC 1 "Dec 1990" */
    /* overrides command line -- should fix this */
    if (!finitDoc) {
	 while (isspace(*p)) p++;
	 if (*p) {
	   /* name */
	   q=strchr(p, ' '); if (q!=NULL) *q++='\0';
	   strcpy(manName, p);
	   /* number */
	   p = q;
	   if (p!=NULL) {
		 while (isspace(*p)) p++;
		 if (*p) { q=strchr(p,' '); if (q!=NULL) *q++='\0'; }
	   }
	   strcpy(manSect, p!=NULL? p: "?");
	 }
	 sI=0;
	 finitDoc=1;
	 (*fn)(BEGINDOC);
	 /* emit information in .TH line? */
    } /* else complain about multiple definitions? */

  } else if (checkcmd("SH") || checkcmd("Sh")) {	/* section title */
    while (indent) { source_command("RE"); }
    source_flush();

    pop(BEGINSECTION);	/* before reset sectheadid */

    if (*p) {
	 if (*p=='"') { p++; q=p; while (*q && *q!='"') q++; *q='\0'; }
	 finnf=0;
	 for (j=0; (sectheadid=j)<RANDOM; j++) if (strcoloncmp2(p,'\0',sectheadname[j],0)) break;
	 if (!finitDoc) {
	   /* handle missing .TH */
	   /* if secthead!=NAME -- insist on this?
	   fprintf(stderr, "Bogus man page: no .TH or \".SH NAME\" lines\n");
	   exit(1);
	   */
	   (*fn)(BEGINDOC);
	   finitDoc=1;
	 }
	 poppush(BEGINSECTION); source_struct(BEGINSECTHEAD);
	 fFlush=0;
	 if (falluc) casify(p);
	 source_out(p);		/* people forget the quotes around multiple words */
	 while (isspace(plain[--sI])) /*nada*/;
	 plain[++sI]='\0'; tocadd(plain, BEGINSECTION, CurLine);	/* flushed with source_struct above */
	 fFlush=1;
	 source_struct(ENDSECTHEAD);
    }
  } else if (checkcmd("SS")) {	/* subsection title */
    while (indent) { source_command("RE"); }
    source_flush();

    if (*p) {
	 if (*p=='"') { p++; q=p; while (*q && *q!='"') q++; *q='\0'; }
	 finnf=0;
	 source_flush();
	 poppush(BEGINSUBSECTION); source_struct(BEGINSUBSECTHEAD);
	 fFlush=0;

	 if (falluc) casify(p);
	 source_out(p);		/* people forget the quotes around multiple words */
	 while (isspace(plain[--sI])) /*nada*/;
	 plain[++sI]='\0'; tocadd(plain, BEGINSUBSECTION, CurLine);
	 fFlush=1;
	 source_struct(ENDSUBSECTHEAD);
    }

  } else if (checkcmd("P") || checkcmd("PP") || checkcmd("LP")) {	 /* new paragraph */
    source_flush();
    poppush(BEGINBODY);

  } else if ((tphp=checkcmd("TP")) || (tphp=checkcmd("HP")) || checkcmd("IP") || checkcmd("LI")) {
    /* TP, HP: indented paragraph, tag on next line (DL list) */
    /* IP, LI: tag as argument */
    source_flush();
    fFlush=0;
    finlist=1;
    if (!tphp) { source_out_word(p); source_list(); }
    /* lists terminated only at start of non-lists */
  } else if (checkcmd("RS")) {	/* set indent */
    source_struct(BEGININDENT);
    indent++;
  } else if (checkcmd("RE")) {
    if (indent) indent--;
    pop(ENDINDENT);
    source_struct(ENDINDENT);
#if 0
  } else if (checkcmd("Xr")) {
    /* 4.4BSD man ref */
    supresseol=0;
    p=source_out_word(p);
    source_out("(");
    p=source_out_word(p);
    source_out(")");
#endif

  } else if (checkcmd("nf")) {
    source_struct(SHORTLINE);
    finnf=1;
    source_struct(BEGINCODEBLOCK);
  } else if (checkcmd("fi")) {
    source_struct(ENDCODEBLOCK);
    finnf=0;
  } else if (checkcmd("br")) {
    source_struct(SHORTLINE);
  } else if (checkcmd("sp") || checkcmd("SP")) {	/* blank lines */
    /*if (!finTable) {*/
	 if (finnf) source_struct(SHORTLINE); else source_struct(BEGINBODY);
	 /*}*/
  } else if (checkcmd("ta")) {	/* set tab stop(s?) */
    /* argument is tab stop -- handle these as tables => leave to output format */
    /* HTML handles tables but not tabs, Tk's text tabs but not tables */
    /* does cause a linebreak */
    stagadd(BEGINBODY);
  } else if (checkcmd("ce")) {
	  /* get line count, recursively filter for that many lines */
	  if (sscanf(p, "%d", &i)) {
		  source_struct(BEGINCENTER);
		  for (; i>0 && (p=source_gets())!=NULL; i--) source_line(p);
		  source_struct(ENDCENTER);
	  }

  /* limited selection of control structures */
  } else if (checkcmd("if") || (checkcmd("ie"))) {	/* if <test> cmd, if <test> command and else on next line */
    supresseol=1;
    ie = checkcmd("ie");
    mylastif=lastif;

    if (*p=='!') { invcond=1; p++; }

    if (*p=='n') { cond=1; p++; }		/* masquerading as nroff the right thing to do? */
    else if (*p=='t') { cond=0; p++; }
    else if (*p=='(' || *p=='-' || *p=='+' || isdigit(*p)) {
	 if (*p=='(') p++;
	 nif0=atof(p);
	 if (*p=='-' || *p=='+') p++; while (isdigit(*p)) p++;
	 op = *p++;	/* operator: =, >, < */
	 if (op==' ') {
	   cond = (nif0!=0);
	 } else {
	   nif1=atoi(p);
	   while (isdigit(*p)) p++;
	   if (*p==')') p++;
	   if (op=='=') cond = (nif0==nif1);
	   else if (op=='<') cond = (nif0<nif1);
	   else /* op=='>' -- ignore >=, <= */ cond = (nif0>nif1);
	 }
    } else if (!isalpha(*p)) {	/* usually quote, ^G in Digital UNIX */
	 /* gobble up comparators between delimiters */
	 delim = *p++;
	 q = if0;
	 while (*p && *p!=delim) {
	   *q++=*p++;
	 }
	 *q='\0';
	 p++;
	 q = if1;
	 while (*p && *p!=delim) {
	   *q++=*p++;
	 }
	 *q='\0';
	 p++;
	 cond = (strcmp(if0,if1)==0);
    } else cond=0;	/* a guess, seems to be right bettern than half the time */
    if (invcond) cond=1-cond;
    while (isspace(*p)) p++;

    lastif = cond;
    if (strncmp(p,"\\{",2)==0) {	/* rather than handle groups here, have turn on/off output flag? */
	    p+=2; while (isspace(*p)) p++; /* {{ */
	    while (strncmp(p,".\\}",3)!=0 || strncmp(p,"\\}",2)!=0 /*Solaris*/) {
		    if (cond) source_line(p);
		    if ((p=source_gets())==NULL) break;
	    }
    } else if (cond) source_line(p);

    if (ie) source_line(source_gets());		/* do else part with prevailing lastif */

    lastif=mylastif;

  } else if (checkcmd("el")) {
    mylastif=lastif;

    /* should centralize gobbling of groups */
    cond = lastif = !lastif;
    if (strncmp(p,"\\{",2)==0) {
	 p+=2; while (isspace(*p)) p++;
	 while (strncmp(p,".\\}",3)!=0 || strncmp(p,"\\}",2)!=0 /*Solaris*/) {
	   if (cond) source_line(p);
	   if ((p=source_gets())==NULL) break;
	 }
    } else if (cond) source_line(p);

    lastif=mylastif;

  } else if (checkcmd("ig")) {	/* "ignore group" */
    strcpy(endig,".."); if (*p) { endig[0]='.'; strcpy(&endig[1],p); }
    while ((p=source_gets())!=NULL) {
	 if (strcmp(p,endig)==0) break;
	 if (!lastif) source_line(p);		/* usually ignore line, except in one weird case */
    }


  /* macros and substitutions */
  } else if (checkcmd("de")) {
    /* grab key */
    q=p; while (*q && !isspace(*q)) q++; *q='\0';

    /* if already have a macro of that name, override it */
    /* could use a good dictionary class */
    for (insertat=0; insertat<macrocnt; insertat++) {
	 if (strcmp(p,macro[insertat].key)==0) break;
    }
    if (insertat==macrocnt) macrocnt++;

    /* should replace one with same name, if one exists */
    macro[insertat].key = mystrdup(p);

    /* build up macro in plain[] ... */
    /* everything until ".." line part of macro */
    q=plain; i=0;
    while ((p=source_gets())!=NULL) {
	 if (strcmp(p,"..")==0) break;
	 while (*p) {	/* append string, interpreting quotes along the way--just double backslash to single now */
	   if (*p=='\\' && p[1]=='\\') p++;
	   *q++=*p++;
	 }
	 *q++='\n';
    }
    *q='\0';

    /* ... then copy once have whole thing */
    macro[insertat].subst = mystrdup(plain);
    /*fprintf(stderr, "defining macro %s as %s\n", macro[insertat].key, macro[insertat].subst);*/
    sI=0;

  } else if (checkcmd("rm")) {	/* remove macro definition, can have multiple arguments */
    for (i=0; i<macrocnt; i++) {	/* moot as new definitions replace old when conflicts */
	 if (strcmp(p,macro[i].key)) {
	   macro[i] = macro[--macrocnt];
	   break;
	 }
    }

  } else if (checkcmd("ds")) {	/* text substitutions (like macros) */
    /* /usr/sww/man/man1/CC.1 a good test of this */
    q = strchr(p,' ');
    if (q!=NULL) {
	 *q='\0'; q++;
#if 0
	 while (*++q) /*nada*/;
#endif
	 if (*q=='"') q++;
	 if (substcnt<SUBSTMAX) {
	   subst[substcnt].key = mystrdup(p); subst[substcnt].subst = mystrdup(q); substcnt++;
	 }
	 /*fprintf(stderr, "defining substitution: name=%s, body=%s\n", p, q);*/
    }

  } else if (checkcmd("so")) {
    /* assuming in .../man like nroff, source in file and execute it as nested file, */
    /* so nested .so's OK */

	err = 1;	/* assume error unless successful */
	if (fTclTk) {
		err=0;
	} else if (stat(p, &fileinfo)==0) {
		sobuf = malloc(fileinfo.st_size + 1);
		if (sobuf!=NULL) {
			/* suck in entire file */
			fid = open(p, O_RDONLY);
			if (fid!=-1) {
				if (read(fid, sobuf, fileinfo.st_size) == fileinfo.st_size) {
				  sobuf[fileinfo.st_size]='\0';
				  /* dumb Digital puts \\} closers on same line */
				  /* {{ */
				  for (q=sobuf; (q=strstr(q," \\}"))!=NULL; q+=3) *q='\n';
				  source_subfile(sobuf);
				  err = 0;
				}
				close(fid);
			}
			free(sobuf);
		}
	}

	if (err) {
		fprintf(stderr, "%s: couldn't read in referenced file %s.\n", argv0, p);
		if (strchr(p,'/')==NULL) {
		  fprintf(stderr, "\tTry cd'ing into same directory of man page first.\n");
		} else if (strchr(p,'/')==strrchr(p,'.')) {
		  fprintf(stderr, "\tTry cd'ing into parent directory of man page first.\n");
		} else {
		  fprintf(stderr, "\tTry cd'ing into ancestor directory that makes relative path valid first.\n");
		}
		exit(1);
	}


  /* character formatting */
  /* reencode m/any as macro definitions? would like to but the below don't have "words" */
  } else if (checkcmd("ft")) {	/* change font, next char is R,I,B.  P=previous not supported */
    if (ft=='B') stagadd(ENDBOLD); else if (ft=='I') stagadd(ENDITALICS);
    ft = *p++;
    if (ft=='B') stagadd(BEGINBOLD); else if (ft=='I') stagadd(BEGINITALICS);
  } else if (checkcmd("B")) {
    supresseol=0;
    stagadd(BEGINBOLD); p = source_out_word(p); source_out(p); stagadd(ENDBOLD);
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("I")) {
    supresseol=0;
    stagadd(BEGINITALICS); p = source_out_word(p); stagadd(ENDITALICS);
    source_out(p);
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("BI")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINBOLD); p = source_out_word(p); stagadd(ENDBOLD);
	 if (*p) { stagadd(BEGINITALICS); p = source_out_word(p); stagadd(ENDITALICS); }
    }
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("IB")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINITALICS); p = source_out_word(p); stagadd(ENDITALICS);
	 if (*p) { stagadd(BEGINBOLD); p = source_out_word(p); stagadd(ENDBOLD); }
    }
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("RB")) {
    supresseol=0;
    while (*p) {
	 p = source_out_word(p);
	 if (*p) { stagadd(BEGINBOLD); p = source_out_word(p); stagadd(ENDBOLD); }
    }
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("BR")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINBOLD); p = source_out_word(p); stagadd(ENDBOLD);
	 p = source_out_word(p);
    }
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("IR")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINITALICS); p=source_out_word(p); stagadd(ENDITALICS);
	 p=source_out_word(p);
    }
    if (finnf) source_struct(SHORTLINE);
  } else if (checkcmd("RI")) {
    supresseol=0;
    while (*p) {
	 p=source_out_word(p);
	 stagadd(BEGINITALICS); p=source_out_word(p); stagadd(ENDITALICS);
    }
    if (finnf) source_struct(SHORTLINE);


  /* HP-UX */
  } else if (checkcmd("SM")) {
    supresseol=0; source_out("\\s-1"); while (*p) p=source_out(p); source_out("\\s0");
  } else if (checkcmd("C")) {
    supresseol=0;
    stagadd(BEGINCODE); while (*p) p=source_out_word(p); stagadd(ENDCODE);
  } else if (checkcmd("CR")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINCODE); p=source_out_word(p); stagadd(ENDCODE);
	 if (*p) p=source_out_word(p);
    }
  } else if (checkcmd("RC")) {
    supresseol=0;
    while (*p) {
	 p=source_out_word(p);
	 if (*p) { stagadd(BEGINCODE); p=source_out_word(p); stagadd(ENDCODE); }
    }
  } else if (checkcmd("CI")) {
    supresseol=0;
    while (*p) {
	 stagadd(BEGINCODE); p=source_out_word(p); stagadd(ENDCODE);
	 if (*p) { stagadd(BEGINITALICS); p=source_out_word(p); stagadd(ENDITALICS); }
    }


  /* tables */
  } else if (checkcmd("TS")) {
    tblc=0; /*tblspanmax=0;*/ tableSep='\0';		/* need to reset each time because tabbed lines (.ta) made into tables too */
    while ((p = source_gets())!=NULL) {
	 if ((q=strstr(p,"tab"))!=NULL) {	/* "tab(" or "tab (".  table entry separator */
	   p=(q+3); while (isspace(*p)) p++;
	   p++;	/* jump over '(' */
	   tableSep=*p;
	   continue;
	 }
	 if (strincmp(p,"center",strlen("center"))==0) {	/* center entire table; should look for "left" and "right", probably */
	   fTableCenter=1; source_struct(BEGINCENTER);
	   p+=strlen("center"); while (isspace(*p)) p++;
	   continue;
	 }
	 if (p[strlen(p)-1]==';') { tblc=0; continue; }	/* HP has a prequel terminated by ';' */

	 for (i=0; *p; i++,p=q) {
	   if (*p=='.') break;
	   if (*p=='f') p+=2;	/* DEC sets font here */
	   q=p+1;
	   if (strchr("lrcn",*q)==NULL) {	/* dumb DEC doesn't put spaces between them */
		while (*q && *q!='.' && !isspace(*q)) q++;
	   }
	   ch=*q; *q='\0';
	   tbl[tblc][i] = mystrdup(p);
	   tbl[tblc][i+1] = "";	/* mark end */
	   *q=ch;
	   while (*q && isspace(*q)) q++;
	 }
	 /*if (i>tblspanmax) tblspanmax=i;*/
	 tbl[tblc++][i]="";		/* mark end */
	 if (*p=='.') break;
    }
    tbli=0;
    source_struct(BEGINTABLE);

    while ((p=source_gets())!=NULL) {
	 if (strncmp(p,".TE",3)==0) break;
	 if (*p=='.') { source_line(p); continue; }

	 /* count number of entries on line.  if >1, can use to set tableSep */
	 insertat=0; for (j=0; *tbl[tbli][j]; j++) if (*tbl[tbli][j]!='s') insertat++;
	 if (!tableSep && insertat>1) { if (fsourceTab) tableSep='\t'; else tableSep='@'; }
	 source_struct(BEGINTABLELINE);
	 if (strcmp(p,"_")==0 || /* double line */ strcmp(p,"=")==0) {
	   source_out(" ");
	   /*stagadd(HR);*/	/* empty row -- need ROWSPAN for HTML */
	   continue;
	 }

	 for (i=0; *tbl[tbli][i] && *p; i++) {
	   tblcellspan=1;
	   tblcellformat = tbl[tbli][i];
	   if (*tblcellformat=='^') {	/* vertical span => blank entry */
		tblcellformat="l";
	   } else if (*tblcellformat=='|') {
		/* stagadd(VBAR); */
		continue;
	   } else if (strchr("lrcn", *tblcellformat)==NULL) {
		tblcellformat="l";
		/*continue;*/
	   }

	   while (strncmp(tbl[tbli][i+1],"s",1)==0) { tblcellspan++; i++; }

	   source_struct(BEGINTABLEENTRY);
	   if (toupper(tblcellformat[1])=='B') stagadd(BEGINBOLD);
	   else if (toupper(tblcellformat[1])=='I') stagadd(BEGINITALICS);
	   /* not supporting DEC's w(<num><unit>) */

	   if (strcmp(p,"T{")==0) {	/* DEC, HP */
		while (strncmp(p=source_gets(),"T}",2)!=0) source_line(p);
		p+=2; if (*p) p++;
	   } else {
		p = source_out0(p, tableSep);
	   }
	   if (toupper(tblcellformat[1])=='B') stagadd(ENDBOLD);
	   else if (toupper(tblcellformat[1])=='I') stagadd(ENDITALICS);
	   source_struct(ENDTABLEENTRY);
	 }
	 if (tbli+1<tblc) tbli++;
	 source_struct(ENDTABLELINE);
    }
    source_struct(ENDTABLE);
    if (fTableCenter) { source_struct(ENDCENTER); fTableCenter=0; }


  } else if (checkcmd("nr")) {
    q=p; while (*q && !isspace(*q)) q++; *q='\0'; q++;

    for (insertat=0; insertat<regcnt; insertat++) {
	 if (strcmp(reg[insertat].name,p)==0) break;
    }
    if (insertat==regcnt) { regcnt++; reg[insertat].name = mystrdup(p); } /* else use same name */
    p=q;
    if (*q=='+' || *q=='-') q++;	/* accept signed, floating point numbers */
    if (*q=='.') q++;
    if (!*q || isspace(*q)) { *q++='0'; *q++='\0'; }
    while (isdigit(*q)) { q++; } *q='\0'; /* ignore units */
    reg[insertat].value = mystrdup(p);

  } else if (checkcmd("EQ")) {	/* eqn not supported */
    source_out("\\s-1\\fBeqn not supported\\fR\\s0");
    while ((p=source_gets())!=NULL) {
	 if (strncmp(p,".EN",3)==0) break;
    }



  /* Tcl/Tk macros */
  } else if (fTclTk && (checkcmd("VS") || checkcmd("VE"))) {
	  /* nothing for sidebars */
  } else if (fTclTk && checkcmd("OP")) {
    source_struct(BEGINBODY);
    for (i=0; i<3; i++) {
	 if (fcharout) { source_out(tcltkOP[i]); source_out(": "); }
	 stagadd(BEGINBOLD); p=source_out_word(p); stagadd(ENDBOLD);
	 source_struct(SHORTLINE);
    }
    source_struct(BEGINBODY);

  } else if (fTclTk && checkcmd("BS")) {	/* box */
    /*source_struct(HR); -- ugh, no Ouster box */
  } else if (fTclTk && checkcmd("BE")) {
    /*source_struct(HR);*/

  } else if (fTclTk && (checkcmd("CS")||checkcmd("DS"))) {	/* code excerpt */
    /* respect line ends, set in teletype */
    /* source_struct(SHORTLINE); -- done as part of CS's ENDLINE */
    finnf=1;
    source_struct(SHORTLINE);
    if (checkcmd("DS")) source_line(".P");
    stagadd(BEGINCODE);
  } else if (fTclTk && (checkcmd("CE")||checkcmd("DE"))) {
    stagadd(ENDCODE);
    finnf=0;

  } else if (fTclTk && checkcmd("SO")) {
    source_struct(BEGINSECTION);
    source_struct(BEGINSECTHEAD); source_out("STANDARD OPTIONS"); source_struct(ENDSECTHEAD);
    tblc=1; tbl[0][0]=tbl[0][1]=tbl[0][2]="l"; tbl[0][3]="";
    source_struct(BEGINTABLE);
    while (1) {
	 p = source_gets();
	 if ((strncmp(p,".SE",3))==0) break;
	 tblcellformat = "l";
	 source_struct(BEGINTABLELINE);
	 if (*p=='.') {
	   source_command(p);
	 } else {
	   while (*p) {
		source_struct(BEGINTABLEENTRY);
		p = source_out0(p, '\t');
		source_struct(ENDTABLEENTRY);
	   }
	 }
	 source_struct(ENDTABLELINE);
    }
    source_struct(ENDTABLE);
    source_struct(ENDSECTION);

  } else if (fTclTk && checkcmd("AP")) {	/* arguments */
    source_struct(BEGINBODY);
    p = source_out_word(p); source_out("   ");
    stagadd(BEGINITALICS); p = source_out_word(p); stagadd(ENDITALICS); source_out("\t");
    source_out("("); p = source_out_word(p); source_out(")");
    source_struct(SHORTLINE);
    source_out("\t");
  } else if (fTclTk && checkcmd("AS")) {	/* arguments */

#if 0
/* let these be defined as macros.  if they're not, they're just caught as unrecognized macros */
  } else if (checkcmd("ll") || checkcmd("IX") ||
		   checkcmd("nh")||checkcmd("hy")||checkcmd("hc")||checkcmd("hw")	/* hyphenation */
	) {	/* unsupported macros -- usually roff specific */

    fprintf(stderr, "macro \"%s\" not supported -- ignoring\n", cmd);
#endif

  } else {		/* could be a macro definition */
    supresseol=0;

    for (i=0; i<macrocnt; i++) {
	 if (macro[i].key == NULL) continue;	/* !!! how does this happen? */
	 if (checkcmd(macro[i].key)) {

	   /* it is, collect arguments */
	   for (j=0; j<9; j++) macroArg[j]="";
	   for (j=0; p!=NULL && *p && j<9; j++, p=q) {
		endch=' '; if (*p=='"') { endch='"'; p++; }
		q = strchr(p,endch);
		if (q!=NULL) {
		  *q++='\0';
		  if (*q && endch!=' ') q++;
		}
		macroArg[j] = p;
	   }

	   /* instantiate that text, substituting \\[1-9]'s */
	   p = macro[i].subst;
	   q = macrobuf;	/* allocated on stack */
	   while (*p) {
		if (*p=='\\') {
		  p++;
		  if (*p=='t') {
		    *q++ = '\t';
		    p++;
		  } else if (*p=='$' && isdigit(p[1])) {
		    j = p[1]-'0'-1;	/* convert to ASCII and align with macroArg array */
		    p+=2;
		    /* *q++='"'; -- no */
		    strcpy(q, macroArg[j]); q += strlen(q);
		    /* *q++='"'; -- no */

		  } else {
		    *q++ = '\\';
		  }
		} else {
		  *q++ = *p++;
		}
	   }
	   *q='\0';

	   /* execute that text */
	   /*fprintf(stderr, "for macro %s, substituted text is \n%s\n", macro[i].key, macrobuf);*/
	   source_subfile(macrobuf);

	   break;
	 }
    }

    /* macro not found */
    if (i==macrocnt) {
	   /* report missing macros only once */
	   for (j=0; j<macnotcnt; j++) if (strcmp(macnotfound[j],cmd)==0) break;
	   if (j==macnotcnt) {
		  if (!fQuiet) fprintf(stderr, "macro \"%s\" not recognized -- ignoring\n", cmd);
		  q = malloc(strlen(cmd)+1); strcpy(q,cmd);
		  macnotfound[macnotcnt++] = q;
	   }
    }
  } /* else command is unrecognized -- ignore it: we're not a complete [tn]roff implementation */

  /* popular but meaningless commands: .ne (need <n> lines--on infinite scroll */
}


static void
source_line(char *p)
{
  /*stagadd(BEGINLINE);*/
  char *cmd=p;
  if (p==NULL) return;	/* bug somewhere else, but where? */

#if 0
  if (*p!='.' && *p!='\'' && !finlist) {
    if (fsourceTab && !fosourceTab) {
	 tblc=1; tbli=0; tableSep='\t';
	 tbl[0][0]=tbl[0][1]=tbl[0][2]=tbl[0][3]=tbl[0][4]=tbl[0][5]=tbl[0][6]=tbl[0][7]=tbl[0][8]="l";
	 source_struct(BEGINTABLE); finTable=1;
    } else if (!fsourceTab && fosourceTab) {
	 source_struct(ENDTABLE); finTable=0;
    }
    fosourceTab=fsourceTab;
  }
#endif

  if (*p=='.' /*|| *p=='\''  -- normalized */) {	/* command == starts with "." */
    p++;
    supresseol=1;
    source_command(p);

  } else if (!*p) {		/* blank line */
    /*source_command("P");*/
    ncnt=1; source_struct(BEGINLINE); ncnt=0;	/* empty line => paragraph break */

#if 0
  } else if (fsourceTab && !finlist /* && pmode */) {	/* can't handle tabs, so try tables */
    source_struct(BEGINTABLE);
    tblcellformat = "l";
    do {
	 source_struct(BEGINTABLELINE);
	 while (*p) {
	   source_struct(BEGINTABLEENTRY);
	   p = source_out0(p, '\t');
	   source_struct(ENDTABLEENTRY);
	 }
	 source_struct(ENDTABLELINE);
    } while ((p=source_gets())!=NULL && fsourceTab);
    source_struct(ENDTABLE);
    source_line(p);
#endif

  } else {			/* otherwise normal text */
    source_out(p);
    if (finnf || isspace(*cmd)) source_struct(SHORTLINE);
  }

  if (!supresseol && !finnf) { source_out(" "); if (finlist) source_list(); }
  supresseol=0;
  /*stagadd(ENDLINE);*/
}


static void
source_filter(void)
{
  char *p = in, *q;
  char *oldv,*newv,*shiftp,*shiftq,*endq;
  int lenp,lenq;
  int i,on1,on2,nn1,nn2,first;
  int insertcnt=0, deletecnt=0, insertcnt0;
  int nextDiffLine=-1;
  char diffcmd, tmpc, tmpendq;

  AbsLine=0;

  /* just count length of macro table! */
  for (i=0; macro[i].key!=NULL; i++) /*empty*/;
  macrocnt = i;

  /* {{ dumb Digital puts \\} closers on same line */
  for (p=in; (p=strstr(p," \\}"))!=NULL; p+=3) *p='\n';

  sI=0;
  /* (*fn)(BEGINDOC); -- done at .TH or first .SH */


  /* was: source_subfile(in); */
  while (fDiff && fgets(diffline, MAXBUF, difffd)!=NULL) {
	  /* requirements: no context lines, no errors in files, ...
		 change-command: 8a12,15 or 5,7c8,10 or 5,7d3
		 < from-file-line
		 < from-file-line...
		 --
		 > to-file-line
		 > to-file-line...
	  */
	  for (q=diffline; ; q++) { diffcmd=*q; if (diffcmd=='a'||diffcmd=='c'||diffcmd=='d') break; }
	  if (sscanf(diffline, "%d,%d", &on1,&on2)==1) on2=on1-1+(diffcmd=='d'||diffcmd=='c');
	  if (sscanf(++q, "%d,%d", &nn1,&nn2)==1) nn2=nn1-1+(diffcmd=='a'||diffcmd=='c');

	  deletecnt = on2-on1+1;
	  insertcnt = nn2-nn1+1;

	  nextDiffLine = nn1;
	  /*assert(nextDiffLine>=AbsLine); -- can happen if inside a macro? */
	  if (nextDiffLine<AbsLine) continue;

	  while (AbsLine<nextDiffLine && (p=source_gets())!=NULL) {
		  source_line(p);
	  }

	  insertcnt0=insertcnt+1;	/* eat duplicate insert lines and '---' too */
	  diffline2[0] = '\0';
	  while (insertcnt && deletecnt) {
		  if (ungetc(fgetc(difffd),difffd)=='<') { fgetc(difffd); fgetc(difffd); }	/* skip '<' */
		  /* fill buffer with old line -- but replace if command */
		  /* stay away from commands -- too careful if .B <word> */
		  do {
			  p = oldv = fgets(diffline, MAXBUF, difffd);
			  p[strlen(p)-1]='\0';	/* fgets's \n ending => \0 */
			  deletecnt--;
		  } while (deletecnt && *p=='.');	/* throw out commands in old version */

		  q = newv = source_gets();
		  insertcnt--;
		  while (insertcnt && *q=='.') {
			  source_line(q);
			  insertcnt--;
		  }

		  if (*p=='.' || *q=='.') break;


		  /* make larger chunk for better diff -- but still keep away from commands */
		  lenp=strlen(p); lenq=strlen(q);
		  while (deletecnt && MAXBUF-lenq>80*2) {
			  fgetc(difffd); fgetc(difffd);	/* skip '<' */
			  if (ungetc(fgetc(difffd),difffd)=='.') break;
			  p=&diffline[lenp]; *p++=' '; lenp++;
			  fgets(p, MAXBUF-lenp, difffd); p[strlen(p)-1]='\0'; lenp+=strlen(p);
			  deletecnt--;
		  }

		  while (insertcnt && *in!='.' && MAXBUF-lenq>80*2) {
			  if (newv!=diffline2) { strcpy(diffline2,q); newv=diffline2; }
			  q=source_gets(); diffline2[lenq]=' '; lenq++;
			  strcpy(&diffline2[lenq],q); lenq+=strlen(q);
			  insertcnt--;
		  }

		  /* common endings */
		  p = &p[strlen(oldv)]; q=&q[strlen(newv)];
		  while (p>oldv && q>newv && p[-1]==q[-1]) { p--; q--; }
		  if ((p>oldv && p[-1]=='\\') || (q>newv && q[-1]=='\\'))
			  while (*p && *q && !isspace(*p)) { p++; q++; }	/* steer clear of escapes */
		  tmpendq=*q; *p=*q='\0'; endq=q;

		  p=oldv; q=newv;
		  while (*p && *q) {
			  /* common starts */
			  newv=q; while (*p && *q && *p==*q) { p++; q++; }
			  if (q>newv) {
				  tmpc=*q; *q='\0'; source_line(newv); *q=tmpc;
			  }

			  /* too hard to read */
			  /* difference: try to find hunk of p in remainder of q */
			  if (strlen(p)<15 || (shiftp=strchr(&p[15],' ') /*|| shiftp-p>30*/)==NULL) break;
			  shiftp++; /* include the space */
			  tmpc=*shiftp; *shiftp='\0'; shiftq=strstr(q,p); *shiftp=tmpc;	/* includes space */
			  if (shiftq!=NULL) {
			  	/* call that part of q inserted */
				tmpc=*shiftq; *shiftq='\0';
				stagadd(BEGINDIFFA); source_line(q); stagadd(ENDDIFFA); source_line(" ");
				*shiftq=tmpc; q=shiftq;
			  } else {
				/* call that part of p deleted */
				shiftp--;	*shiftp='\0';	/* squash the trailing space */
				stagadd(BEGINDIFFD); source_line(p); stagadd(ENDDIFFD); source_line(" ");
				p=shiftp+1;
			  }
/*#endif*/
		  }

		  if (*p) { stagadd(BEGINDIFFD); source_line(p); stagadd(ENDDIFFD); }
		  if (*q) { stagadd(BEGINDIFFA); source_line(q); stagadd(ENDDIFFA); }
		  if (tmpendq!='\0') { *endq=tmpendq; source_line(endq); }
		  source_line(" ");
	  }

	  /* even if diffcmd=='c', could still have remaining old version lines */
	  first=1;
	  while (deletecnt--) {
		  fgets(diffline, MAXBUF, difffd);
		  if (diffline[2]!='.') {
			  if (first) { stagadd(BEGINDIFFD); first=0; }
			  source_line(&diffline[2]);	/* don't do commands; skip initial '<' */
		  }
	  }
	  if (!first) { stagadd(ENDDIFFD); source_line(" "); }

	  /* skip over duplicated from old */
	  if (diffcmd=='c') while (insertcnt0--) fgets(diffline, MAXBUF, difffd);

	  /* even if diffcmd=='c', could still have remaining new version lines */
	  first=1;
	  nextDiffLine = AbsLine + insertcnt;
	  while (insertcnt--) fgets(diffline, MAXBUF, difffd);	/* eat duplicate text of above */
	  while (/*insertcnt--*/AbsLine<nextDiffLine && (p=source_gets())!=NULL) {
		  if (first && *p!='.') { stagadd(BEGINDIFFA); first=0; }
		  source_line(p);
	  }
	  if (!first) { stagadd(ENDDIFFA); source_line(" "); }
  }
  /* finish up remainder (identical to both) */
  while ((p=source_gets())!=NULL) {
	  source_line(p);
  }

  source_flush();
  pop(ENDDOC); (*fn)(ENDDOC);
}



/*
 * STARTUP
 */

static int
setFilterDefaults(char *outputformat)
{
	static struct {
		void (*fn)(enum command);
		int fPara; int fQS; int fIQS; int fNOHY; int fChangeleft; int fURL; char *names;
		/* (could set parameters at BEGINDOC call...) */
	} format[] = {
		/*{default	0par 0qs	0iqs	0hy	0cl	0url	"name"},*/
		{ ASCII,		0,	0,	0,	0,	0,	0,	"ASCII" },
		{ TkMan,		0,	0,	0,	0,	0,	0,	"TkMan" },
		{ Tk,		0,	0,	0,	0,	0,	0,	"Tk:Tcl" },
		{ Sections,	0,	0,	0,	0,	0,	0,	"sections" },
		{ Roff,		0,	1,	1,	1,	-1,	0,	"roff:troff:nroff" },
		{ HTML,		1,	1,	1,	1,	1,	1,	"HTML:WWW:htm" },
		{ XML,		1,	1,	1,	1,	1,	1,	"XML:docbook:DocBook" },
		{ MIME,		1,	1,	1,	1,	1,	0,	"MIME:Emacs:enriched" },
		{ LaTeX,		1,	1,	1,	1,	1,	0,	"LaTeX:LaTeX209:209:TeX" },
		{ LaTeX2e,	1,	1,	1,	1,	1,	0,	"LaTeX2e:2e" },
		{ RTF,		1,	1,	1,	1,	1,	0,	"RTF" },
		{ pod,		0,	0,	1,	0,	-1,	0,	"pod:Perl" },

		{ PostScript,	0,	0,	0,	0,	0,	0,	"PostScript:ps" },
		{ FrameMaker,	0,	0,	0,	0,	0,	0,	"FrameMaker:Frame:Maker:MIF" },

		{ NULL,		0,	0,	0,	0,	0,	0,	NULL }
	};

	int i, found=0;
	for (i=0; format[i].fn!=NULL; i++) {
		if (strcoloncmp2(outputformat,'\0',format[i].names,0)) {
			fn = format[i].fn;
			fPara = format[i].fPara;
			fQS = format[i].fQS;
			fIQS = format[i].fIQS;
			fNOHY = format[i].fNOHY;
			fChangeleft = format[i].fChangeleft;
			fURL = format[i].fURL;
			found=1;
			break;
		}
	}

	return (found==0);
}


/* read in whole file.  caller responsible for freeing memory */
static char *
filesuck(FILE *in)
{
  const int inc=1024*100;	/* what's 100K these days? */
  int len=0,cnt;
  char *file = malloc(1);  /*NULL -- relloc on NULL not reducing to malloc on some machines? */

  do {
    file = realloc(file, len+inc+1);	/* what's the ANSI way to find the file size? */
    cnt = fread(&file[len], 1, inc, in);
    len+=cnt;
  } while (cnt==inc);
  file[len]='\0';

  return file;
}

int
main(int argc, char *argv[])
{
	int c;
	int i,j;
	char *p,*oldp;
	int fname=0;
	const int helpbreak=75;
	const int helpispace=4;
	int helplen=0;
	int desclen;
	char **argvch;	/* remapped argv */
/*	FILE *macros; -- interpret -man macros? */

	char strgetopt[80];
	/* options with an arg must have a '<' in the description */
	static struct { char letter; int arg; char *longnames; char *desc; } option[] = {
		{ 'f', 1, "filter", " <ASCII|roff|TkMan|Tk|Sections|HTML|XML|MIME|LaTeX|LaTeX2e|RTF|pod>" },
		{ 'S', 0, "source", "(ource of man page passed in)" },	/* autodetected */
		{ 'F', 0, "formatted:format", "(ormatted man page passed in)" },	/* autodetected */

		{ 'r', 1, "reference:manref:ref", " <man reference printf string>" },
		{ 'l', 1, "title", " <title printf string>" },
		{ 'V', 1, "volumes:vol", "(olume) <colon-separated list>" },
		{ 'U', 0, "url:urls", "(RLs as hyperlinks)" },

		/* following options apply to formatted pages only */
		{ 'b', 0, "subsections:sub", " (show subsections)" },
		{ 'k', 0, "keep:head:foot:header:footer", "(eep head/foot)" },
		{ 'n', 1, "name", "(ame of man page) <string>" },
		{ 's', 1, "section:sect", "(ection) <string>" },
		{ 'p', 0, "paragraph:para", "(aragraph mode toggle)" },
		{ 't', 1, "tabstop:tabstops", "(abstops spacing) <number>" },
		{ 'N', 0, "normalize:normal", "(ormalize spacing, changebars)" },
		{ 'y', 0, "zap:nohyphens", " (zap hyphens toggle)" },
		{ 'K', 0, "nobreak", " (declare that page has no breaks)" },	/* autodetected */
		{ 'd', 1, "diff", "(iff) <file> (diff of old page source to incorporate)" },
		{ 'M', 1, "message", "(essage) <text> (included verbatim at end of Name section)" },
		/*{ 'l', 0, "number lines", "... can number lines in a pipe" } */
		/*{ 'T', 0, "tables", "(able agressive parsing ON)" },*/
/*		{ 'c', 0, "changeleft:changebar", "(hangebarstoleft toggle)" }, -- default is perfect */
		/*{ 'R', 0, "reflow", "(eflow text lines)" },*/
		{ 'R', 1, "rebus", "(ebus words for TkMan)" },
		{ 'C', 0, "TclTk", " (enable Tcl/Tk formatting)" },	/* autodetected */

		/*{ 'D', 0, "debug", "(ebugging mode)" }, -- dump unrecognized macros, e.g.*/
		{ 'o', 0, "noop", " (no op)" },
		{ 'O', 0, "noop", " <arg> (no op with arg)" },
		{ 'q', 0, "quiet", "(uiet--don't report warnings)" },
		{ 'h', 0, "help", "(elp)" },
		/*{ '?', 0, "help", " (help)" },	-- getopt returns '?' as error flag */
		{ 'v', 0, "version", "(ersion)" },
		{ '\0', 0, "", NULL }
	};

	/* calculate strgetopt from options list */
	for (i=0,p=strgetopt; option[i].letter!='\0'; i++) {
		*p++ = option[i].letter;
		/* check for duplicate option letters */
		assert(strchr(strgetopt,option[i].letter)==&p[-1]);
		if (option[i].arg) *p++=':';
	}
	*p='\0';

	/* spot check construction of strgetopt */
	assert(p<strgetopt+80);
	assert(strlen(strgetopt)>10);
	assert(strchr(strgetopt,'f')!=NULL);
	assert(strchr(strgetopt,'v')!=NULL);
	assert(strchr(strgetopt,':')!=NULL);

	/* count, sort exception strings */
	for (lcexceptionslen=0; (p=lcexceptions[lcexceptionslen])!=NULL; lcexceptionslen++) /*empty*/;
	qsort(lcexceptions, lcexceptionslen, sizeof(char*), lcexceptionscmp);

	/* map long option names to single letters for switching */
	/* (GNU probably has a reusable function to do this...) */
	/* deep six getopt in favor of integrated long names + letters? */
	argvch = malloc(argc * sizeof(char*));
	p = malloc(argc*3 * sizeof(char));	/* either -<char>'\0' or no space used */
	for (i=0; i<argc; i++) argvch[i]=argv[i];	/* need argvch[0] for getopt? */
	argv0 = mystrdup(argv[0]);
	for (i=1; i<argc; i++) {
		if (argv[i][0]=='-' && argv[i][1]=='-') {
			if (argv[i][2]=='\0') break;	/* end of options */
			for (j=0; option[j].letter!='\0'; j++) {
				if (strcoloncmp2(&argv[i][2],'\0',option[j].longnames,0)) {
					argvch[i] = p;
					*p++ = '-'; *p++ = option[j].letter; *p++ = '\0';
					if (option[j].arg) i++;	/* skip arguments of options */
					break;
				}
			}
			if (option[j].letter=='\0') fprintf(stderr, "%s: unknown option %s\n", argv[0], argv[i]);
		}
	}



	/* pass through options to set defaults for chosen format */
	setFilterDefaults("ASCII");		/* default to ASCII (used by TkMan's Glimpse indexing */

	/* initialize header/footer buffers (save room in binary) */
	for (i=0; i<CRUFTS; i++) { *cruft[i] = '\0'; }	/* automatically done, guaranteed? */
	/*for (i=0; i<MAXLINES; i++) { linetabcnt[i] = 0; } */

	while ((c=getopt(argc,argvch,strgetopt))!=-1) {

		switch (c) {
		   case 'k': fHeadfoot=1; break;
		   case 'b': fSubsections=1; break;
/*		   case 'c': fChangeleft=1; break; -- obsolete */
			/* case 'R': fReflow=1; break;*/
		   case 'n': strcpy(manName,optarg); fname=1; break;	/* name & section for when using stdin */
		   case 's': strcpy(manSect,optarg); break;
		   /*case 'D': docbookpath = optarg; break;*/
		   case 'V': vollist = optarg; break;
		   case 'l': manTitle = optarg; break;
		   case 'r': manRef = optarg;
			if (strlen(manRef)==0 || strcmp(manRef,"-")==0 || strcmp(manRef,"off")==0) fmanRef=0;
			break;
		   case 't': TabStops=atoi(optarg); break;
		   /*case 'T': fTable=1; break;	-- if preformatted doesn't work, if source automatic */
		   case 'p': fPara=!fPara; break;
		   case 'K': fFoot=1; break;
		   case 'y': fNOHY=1; break;
		   case 'N': fNORM=1; break;

		   case 'f': /* set format */
			if (setFilterDefaults(optarg)) {
				fprintf(stderr, "%s: unknown format: %s\n", argv0, optarg);
				exit(1);
			}
			break;
		   case 'F': fSource=0; break;
		   case 'S': fSource=1; break;

		   case 'd':
			difffd = fopen(optarg, "r");
			if (difffd==NULL) { fprintf(stderr, "%s: can't open %s\n", argv0, optarg); exit(1); }
/* read in a line at a time
			diff = filesuck(fd);
			fclose(fd);
*/
			fDiff=1;
			break;

		   case 'M': message = optarg; break;

		   case 'C': fTclTk=1; break;
		   case 'R':
			p = malloc(strlen(optarg)+1);
			strcpy(p, optarg);	/* string may not be in writable address space */
			oldp = "";
			for (; *p; oldp=p, p++) {
				if (*oldp=='\0') rebuspat[rebuspatcnt++] = p;
				if (*p=='|') *p='\0';
			}
			for (i=0; i<rebuspatcnt; i++) rebuspatlen[i] = strlen(rebuspat[i]);	/* for strnlen() */
			break;

		   case 'q': fQuiet=1; break;
		   case 'o': /*no op*/ break;
		   case 'O': /* no op with arg */ break;
		   case 'h':
			printf("rman"); helplen=strlen("rman");

			/* linebreak options */
			assert(helplen>0);
			for (i=0; option[i].letter!='\0'; i++) {
			  desclen = strlen(option[i].desc);
			  if (helplen+desclen+5 > helpbreak) { printf("\n%*s",helpispace,""); helplen=helpispace; }
			  printf(" [-%c%s]", option[i].letter, option[i].desc);
			  helplen += desclen+5;
			}
			if (helplen>helpispace) printf("\n");
			printf("%*s [<filename>]\n",helpispace,"");
			exit(0);

		   case 'v': /*case '?':*/
			printf("PolyglotMan v" POLYGLOTMANVERSION "\n");
			exit(0);

		   default:
			fprintf(stderr, "%s: unidentified option -%c (-h for help)\n",argvch[0],c);
			exit(2);
		}
	}



	/* read from given file name(s) */
	if (optind<argc) {
		if (!fname) {	/* if no name given, create from file name */
			/* take name from tail of path */
			if ((p=strrchr(argvch[optind],'/'))!=NULL) p++; else p=argvch[optind];
			strcpy(manName,p);

			/* search backward from end for final dot. split there */
			if ((p=strrchr(manName,'.'))!=NULL) {
				strcpy(manSect,p+1);
				*p='\0';
			}
		}

		strcpy(plain,argvch[optind]);

		if (freopen(argvch[optind], "r", stdin)==NULL) {
			fprintf(stderr, "%s: can't open %s\n", argvch[0], argvch[optind]);
			exit(1);
		}
	}

	/* need to read macros, ok if fail; from /usr/lib/tmac/an => needs to be set in Makefile, maybe a searchpath */
	/*
	if ((macros=fopen("/usr/lib/tmac/an", "r"))!=NULL) {
		in = File = filesuck(macros);
		lookahead = File[0];
		source_filter();
		free(File);
	}
	*/

	/* suck in whole file and just operate on pointers */
	in = File = filesuck(stdin);


	/* minimal check for roff source: first character dot command or apostrophe comment */
	/* MUST initialize lookahead here, BEFORE first call to la_gets */
	if (fSource==-1) {
		lookahead = File[0];
		fSource = (lookahead=='.' || lookahead=='\'' || /*dumb HP*/lookahead=='/'
		    /* HP needs this too but causes problems || isalpha(lookahead)--use --source flag*/);
	}

	if (fDiff && (!fSource || fn!=HTML)) {
		fprintf(stderr, "diff incorporation supported for man page source, generating HTML\n");
		exit(1);
	}

	if (fSource) source_filter(); else preformatted_filter();
	if (fDiff) fclose(difffd);
	/*free(File);	-- let system clean up, perhaps more efficiently */

	return 0;
}