Source

Website Meta Language / src / wml_aux / linklint / linklint.src

Full commit
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
#!@PATH_PERL@
eval 'exec @PATH_PERL@ -S $0 ${1+"$@"}'
    if $running_under_some_shell;

#==========================================================================
#  linklint  - a fast link checker and web site maintenance tool.
#  Copyright (C) 1997 -- 2001 James B. Bowlin.  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to
#
#      Free Software Foundation, Inc.
#      59 Temple Place - Suite 330
#      Boston, MA  02111-1307, USA
#
#  Notice, that ``free software'' addresses the fact that this program
#  is __distributed__ under the term of the GNU General Public License
#  and because of this, it can be redistributed and modified under the
#  conditions of this license, but the software remains __copyrghted__
#  by the author. Don't intermix this with the general meaning of
#  Public Domain software or such a derivated distribution label.
#
#  Linklint is a total rewrite of Rick Jansen's 4/15/96 version of webxref.
#
#  Thanks to Celeste Stokely, Scott Perry, Patrick Meyer, Brian Kaminer
#  David Hull, Stephan Petersen, Todd O'Boyle, Vittal Aithal (and
#  many others!) for many excellent suggestions.
#
#  Bugs, comments, suggestions welcome: bugs@linklint.org
#  Updates available at http://www.linklint.org
#
# RECENT CHANGES (see CHANGES.txt for full list):
#
# Version 2.3.5 August 13, 2001
# -----------------------------
#   o added -no_anchors tag (for larger sites)
#   o fixed bug that prevented site checks of
#     some non port 80 sites. (Thanks Rick Perry).
#
# Version 2.3.4 August 8, 2001
# ----------------------------
#   o keep query string for http site checks
#   o added no_query_string option to disable above
#   o added "php" and "jar" file types
#   o look for .jar files from applet tags
#   o s!//+!/!g inside of UniqueUrl()
#   o -http_header and -language options
#
# Version 2.3.3 July 6, 2001
# ---------------------------
#   o added 2nd argument to mkdir() on line 921
#   o for creating url doc directory
#
# Version 2.3.2 June 22, 2001
# ---------------------------
#   o -no_warn_index for missing index file warnings
#   o -concise_url flag to suppress output of valid remote links
#     on STDOUT
#
# Version 2.3.1 June 21, 2001
# ---------------------------
#   o unified -proxy support (no conflict w/ virtual hosts now)
#     and moved it to Request() so we should support proxies
#     for site checking
#
# Version 2.3.0 June 3, 2001
# --------------------------
#   o moved home site and email address
#   o added -help_all -version -license "@"
#   o updated to GPL
#
#========================================================================

$version = "2.3.5";
$date    = "August 13, 2001";
$prog    = "linklint";

$Usage1 = <<USAGE1;
This is $prog Version $version ($date)
Copyright (c) 1997-2001 James B. Bowlin
USAGE1

$Usage3 = qq~
Use $prog with no arguments for standard usage.
Use "$prog -help_all" for a list of ALL options.
~;

$Version_Usage = <<VERSION_USAGE;
$Usage1
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

VERSION_USAGE

$LICENSE = <<LICENSE_TEXT;

		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
      59 Temple Place, Suite 330,
      Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.


		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS
LICENSE_TEXT

$Usage = <<USAGE;

Usage: linklint \@file \@\@file -flag [option] linkset linkset ...

  -root dir         Set server root to  "dir" (default ".").
  -host name[:port] Use "name" as domain name of site.
  -http             Check site remotely via http (requires -host).
  -net              Check status of remote http links found in site.
  -help             Show help. (Use "-help_all for complete usage).
  -version          Show version info.

Multi File Output:
  -doc dir          Write many output files in "dir" directory.

Single File Output:
  -error  print errors          -out file      direct output to "file"
  -warn   print warnings        -xref          cross reference
  -list   print files found     -forward       sort by referring file

linkset:
  home page only: /  (default)                   root dir only: /#
     entire site: /@                           and all subdirs: /#/#
  specific links: /link1 /link2 ...        "sub" dir and below: /sub/@
USAGE

$Help2 = <<'HELP2';
Site Checking:
  -case             Check filename case (Windows/Dos only, local only).
  -orphan           List all unused (orphan) files (local only).
  -index file       Use "file" as default index file (local only).
  -skip linkset     Don't check html files that match linkset.
  -ignore linkset   Ignore all files matching linkset.
  -limit n          Only check up to n html files (default 500).
  -map /a[=/b]      Subsitute leading /a with /b (for serverside image maps).
  -local linkset    Always get files that match linkset locally.
  -no_warn_index    Don't create "index file not found" warnings
  -http_header xxx  Specifically add header "xxx" to all HTTP requests
  -language zz      Add "Accept-Language: zz" header to all HTTP requests

Network:
  -timeout t        Timeout remote links after t seconds (default 15).
  -delay d          Delay d seconds between requests to same host (default 0).
  -redirect         Follow <meta> redirects in remote urls.
  -proxy host[:port] Send remote http requests through a proxy server.
  -password realm user:password  Authorize access to "realm".
  -concise_url      Suppress STDOUT output of valid remote links.

Remote Status Cache:
  -netmod           Put urls in cache and report modified status.
  -netset           ... and update last modified status in the cache.
  -retry            Only check urls that had host failures.
  -flush            Remove urls from cache that aren't currently being checked.
  -checksum         Exaustive check of modified status.
  -cache dir        Read/save "linklint.url" cache file in this directory.

Output:
  -quiet            Don't print progress on screen.
  -silent           Don't print summary on screen.
  -docbase exp      Overrides defaults for linking html output back to site.
  -textonly         Only write .txt files in -doc directory.
  -htmlonly         Erase .txt files after .html output files are written.
  -output_frames    Have index.html open a new window when viewing data files
  -url_doc_prefix p Prefix Remote URL output files with "p" instead of "url".
  -output_index xxx Output index files will be "xxx.txt" and "xxx.html".
  -dont_output xxx  Don't create output files that contain xxx.

Debug Flags:
  -db1              Debug input, linkset expressions.
  -db2              Show every file that gets checked (not just html).
  -db3              Debug parser. Print tags and links found.
  -db4              Debug socket connections
  -db5              not used
  -db6              Detail last-modified status for remote urls.
  -db7              Print brief debug information checking remote urls.
  -db8              Print headers while checking remote urls.
  -db9              Generate random http errors.

  @cmndfile         Read command line options from "cmndfile".
  @@file            Check status of remote http links in "file".
HELP2

$Examples = << 'EXAMPLES';
Examples:

  1) linklint -doc linkdoc -root dir
     Checks home page.  Output files go in "linkdoc" directory.

  2) linklint -doc linkdoc -root dir /@
     Checks all files under "dir".  Output files go in "linkdoc" directory.

  3) linklint -doc linkdoc -root dir /@ -net
     Checks site as (2).  Then checks all http links found in site.

  4) linklint -doc linkdoc -root dir /#
     Like (2) but only checks files in the root directory.

  5) linklint -doc linkdoc -host host /@ -http
     Same as (2) but checks site using http instead of file system.

  6) linklint -doc linkdoc @@linkdoc/remote.txt
     Check remote link status without rechecking entire site.
EXAMPLES

$ErrUsage = <<ERR_USAGE;
Use $prog with no arguments for simple usage.
Use "$prog -help_all" for a list of ALL options.
ERR_USAGE


#------------------ Start up values ----------------------------------

$URL_PREFIX   = "url";
$OUTPUT_INDEX = "index";

#----- Files to try in case of a directory reference like "/" --------

@DefIndex = (
    'home.html', 'index.html', 'index.shtml', 'index.htm', 'index.cgi',
    'wwwhome.html', 'welcome.html',
);

$DefCaseSens = '';

#----- File extensions and floormats ---------------

$HtmlExts  = 'html|shtml|htm';

$AnyCgi = '\?|^/cgi-bin/|(\.(cgi|pl)(/|$))';

$StandardMaps = '(/imagemap|/cgi-(b|w)in/(imagemap.exe|htimage))';

@fileformat = (
    'php::\.php(\?|$)',
    "cgi::$AnyCgi",
    'default index::\(default\)',
    "html::\.($HtmlExts)\$",
    'java archive::\.jar$',
    'map::\.map$',
    'image::\.(gif|jpg|jpeg|tif|tiff|pic|pict|hdf|ras|xbm)$',
    'text::\.txt$',
    'audio::\.(au|snd|wav|aif|aiff|midi|mid)$',
    'video::\.(mpg|mpeg|avi|qt|mov)$',
    'shockwave::\.dcr$',
    'applet::\.class$',
    'other::unknown',
);


@filesplit = (
   'found %3d file%s::.',
   'found %3d default index%es::\/$',
);

@lostsplit = (
   'ERROR %3d missing file%s::.',
   'ERROR %3d missing director%y::\/$',
);

foreach (@fileformat) {
    ($name,$data) = split(/::/);
    push(@filesplit,"found %3d $name file%s::$data");
    push(@lostsplit,"ERROR %3d missing $name file%s::$data");
}

@schema = ("http", "https", 'ftp', 'javascript', 'mailto', 'gopher',
    'file','news', 'view-source', 'about', 'unknown');

@schemesplit = ( "found %3d other link%s::.");

foreach (@schema) {
    push(@schemesplit, "found %3d $_ link%s::^$_:");
}

#--------------- Output Floormats ----------------------------------

#---- flags used in the printout lists below ---------------

$LIST = 001;    $NOXR = 010;    $URLDOC  = 0100;
$WARN = 002;    $XREF = 020;    # $URLDOC  = 0200;
$ERR  = 004;    $FWD  = 040;

$PrnFlag = 0;
$SumFlag = $LIST | $ERR | $WARN | $NOXR;
$DocFlag = $LIST | $ERR | $WARN | $NOXR | $XREF | $FWD | $URLDOC;

@SumPrint =  (0, 0, 1, $SumFlag);

@SiteForm = (

# file; %Data; $mask; program; @parameters

"dir;      DirList;  001; 1; found %3d director%y with files; 0",
"file;     FileList; 011; 2; filesplit; 0",
"fileX;    FileList; 021; 2; filesplit; 2",
"fileF;    Forward;  041; 1; found %3d file%s with forward links; 1; contains %d link%s:",
"remote;   ExtLink;  011; 2; schemesplit; 0",
"remoteX;  ExtLink;  021; 2; schemesplit; 2",
"anchor;   Anchor;   011; 1; found %3d named anchor%s; 0",
"anchorX;  Anchor;   021; 1; found %3d named anchor%s; 2",
"imgmap;   ImgMap;   011; 1; found %3d named image map%s; 0",
"imgmapX;  ImgMap;   021; 1; found %3d named image map%s; 2",
"ignore;   Ignored;  011; 1; ----- %3d ignored file%s; 0",
"ignoreX;  Ignored;  021; 1; ----- %3d ignored file%s; 2",
"action;   Action;   011; 1; ----- %3d action%s skipped; 0",
"actionX;  Action;   021; 1; ----- %3d action%s skipped; 2",
"skipped;  Skipped;  012; 1; ----- %3d file%s skipped; 0",
"skipX;    Skipped;  022; 1; ----- %3d file%s skipped; 2",
"orphan;   OrphList; 001; 1; ----- %3d orphan%s; 0",
"warn;     WarnList; 012; 1; warn  %3d warning%s; 0",
"warnX;    WarnList; 022; 1; warn  %3d warning%s; 2; occurred in",
"warnF;    WarnF;    042; 1; warn  %3d file%s with warnings; 1; had %d warning%s",
"case;     BadCase;  014; 1; ERROR %3d file%s mismatched case; 0",
"caseX;    BadCase;  024; 1; ERROR %3d file%s mismatched case; 2",
"caseF;    CaseF;    044; 1; ERROR %3d file%s with mismatched link(s); 1; had %d mismatched link%s",
"error;    LostFile; 014; 2; lostsplit; 0",
"errorX;   LostFile; 024; 2; lostsplit; 2",
"errorF;   ErrF;     044; 1; ERROR %3d file%s had broken links; 1; had %d broken link%s",
"errorA;   LostAnch; 014; 1; ERROR %3d missing named anchor%s; 0",
"errorAX;  LostAnch; 024; 1; ERROR %3d missing named anchor%s; 2",
"errorM;   LostMap;  014; 1; ERROR %3d missing named image map%s; 0",
"errorMX;  LostMap;  024; 1; ERROR %3d missing named image maps%s; 2",
"httpfail; HttpFail; 022; 3; ----- %3d link%s; 0; failed via http",
"httpok;   HttpOk;   022; 3; ----- %3d link%s; 0; ok via http",
"mapped;   Mapped;   022; 1; ----- %3d link%s %w mapped; 1; mapped to",

);


@UrlForm = (

"${URL_PREFIX}ok;    UrlOk;    0001; 3; found %3d url%s;  0; %w ok",
"${URL_PREFIX}moved; UrlMoved; 0002; 3; ----- %3d url%s;  0; moved",
"${URL_PREFIX}host;  HostFail; 0104; 3; ERROR %3d host%s; 0; failed; %d host%s:",
"${URL_PREFIX}fail;  UrlFail;  0014; 3; ERROR %3d url%s;  0; failed",
"${URL_PREFIX}failX; UrlFailX; 0024; 3; ERROR %3d url%s;  2; failed",
"${URL_PREFIX}failF; UrlFailF; 0044; 1; ERROR %3d file%s with failed urls; 1; had %d failed url%s",
"${URL_PREFIX}skip;  UrlWarn;  0012; 3; warn  %3d url%s;  0; not checked",
"${URL_PREFIX}mod;   UrlMod;   0000; 3; found %3d url%s;  0; %w modified",
"${URL_PREFIX}warn;  WarnList; 0012; 1; warn  %3d warning%s; 0",
"${URL_PREFIX}warnX; WarnList; 0022; 1; warn  %3d warning%s; 2; in %d url%s",
"${URL_PREFIX}warnF; WarnF;     042; 1; warn  %3d url%s with warnings; 1; had %d warning%s",
);

#----- Command Line Input ---------------

$MiscFlags = join "|", qw/

    case
    concise_url
    error
    flush
    forward
    help
    help_all
    htmlonly
    http
    license
    list
    net
    netmod
    netset
    no_anchors
    no_warn_index
    no_query_string
    orphan
    output_frames
    quiet
    redirect
    retry
    silent
    textonly
    version
    warn
    xref

    /;

$HashOpts = join "|", qw/

    dont_output
    http_header
    ignore
    index
    javascript
    language
    local
    map
    skip

    /;

$FullOpts = join "|", qw/

    cache
    delay
    doc
    docbase
    host
    limit
    out
    output_index
    proxy
    root
    timeout
    url_doc_prefix

    /;

%CheckedIn = ();

#---------------------------------------------------------------------------
# Misc. startup values
#---------------------------------------------------------------------------

$Arg{'timeout'}   = 15;        # how long to wait for a response
$Arg{'delay'}     = 0;         # how long to delay between requests

$Arg{'VERSION'}   = $version;

$Headline   = "#" . "-" x 60 . "\n"; # used to print lists

$ATTRIB = q~\s*=\s*("\s*([^"]*[^"\s])\s*"|'\s*([^']*[^"\s])\s*'|([^\s"']+))~;

#----- prevent warnings ---------------

%HttpOk = %HttpFail = %CaseF = %WarnF = ();
%UrlWarn = %Ignored = %UrlFailX = %UrlFailF = %LostMap = ();

$UrlOk = $Abort = 0;


###########################################################################
#
# Main code starts here
#
###########################################################################


    @ARGV or exit_with($Usage1, $Usage);
    @infiles = &ReadArgs(@ARGV);

    $OUTPUT_INDEX = $Arg{output_index} if $Arg{output_index};

    @UrlHtml = (
        "${URL_PREFIX}sum",
        "${URL_PREFIX}${OUTPUT_INDEX}",
        "${URL_PREFIX}log",
        "Index of Linklint results for remote urls",
    );

    @SiteHtml = (
        'summary',
        $OUTPUT_INDEX,
        'log',
        "Index of Linklint results ",
    );

    $Arg{'DOS'} = $Dos = $^O ?
        ($^O =~ /win32/i ? 1 : '') :
        ($ENV{'windir'}  ? 1 : '') ;

    $pwdprog = $Dos ? 'cd' : 'pwd';        # program to pwd

    $HOME = &GetCwd;     # this is done twice.

#---------------- Command Line Arguments -------------------------

    foreach(@HttpFiles) {
        push(@infiles, &ReadHttp($_));
    }

    $Arg{'doc'} && ! $DB{1} && do {
        ($DocDir = $Arg{'doc'} ) =~ s#\\#\/#g;
        $DocDir =~ m#^/# || ($DocDir = "$HOME/$DocDir" );

        -d $DocDir || mkdir($DocDir, 0777) ||
            &Error(qq~invalid output directory: "$DocDir"~, 'sys');
        $SiteLog = "$DocDir/log.txt";
        $UrlLog  = "$DocDir/${URL_PREFIX}log.txt";
        $LogProgress++;
    };

    $Arg{'out'} && !$DB{1} && do {
        $OutLog = $Arg{'out'};
        $OutLog =~ m#^/# || ($OutLog = "$HOME/$OutLog" );
    };

    $Arg{version}    and exit_with($Version_Usage);
    $Arg{license}    and exit_with($Usage1, $LICENSE);
    $Arg{'help_all'} and exit_with($Version_Usage, $Usage, $Help2, $Examples);
    $Arg{'help'}     and exit_with($Usage1, $Examples, $Usage3);


    ($LogDir = $Arg{'cache'} || $ENV{'LINKLINT'} || $ENV{'HOME'} || $HOME) =~ s#/$##;
    $StatFile = $LogDir . "/linklint.url";

#----- Link Spec's ---------------

    $Arg{'case'} && do {
        $Dos || &Error("can only check case under Windows/Dos");
        $CheckCase++;
    };

    $IgnoreCase = ($Dos && ! $CheckCase && ! $Arg{'http'} ) ? 1 : 0;

    foreach(@infiles) {
        s#^http:#http:#i && (push(@CheckUrls, $_), next);
        $_ = "/$_" unless m#^/#;
        $IgnoreCase && tr/A-Z/a-z/;
        $LinkSet{$_}++;
    };

    %LinkSet || do {
        %LinkSet = ( '/', '1');
        $Hints{ 'Use a linkset of /@ to check entire site.'}++;
    };

    foreach(keys %LinkSet) {
        m%[\@\#]% || ($Seeds{$_}++, next);     # literals
        m%^([^\@\#]*/)% && $Seeds{$1}++;       # directories
    }

    %LinkSet && ! %Seeds and die("\nError: Could not form any seeds from the linksets.\n");

    $LinkSet = &LinkSet("linkset", *LinkSet);

#----- Flags and Options ---------------

    &WantNumber($Arg{'limit'},      "-limit");
    &WantNumber($Arg{'timeout'},    "-timeout");
    &WantNumber($Arg{'delay'},      "-delay");

    $Arg{'error'}   && ($PrnFlag |= ($NOXR | $ERR));
    $Arg{'warn'}    && ($PrnFlag |= ($NOXR | $WARN));
    $Arg{'list'}    && ($PrnFlag |= ($NOXR | $LIST));
    $Arg{'xref'}    && ($PrnFlag |= $XREF, $PrnFlag &= ~ $NOXR);
    $Arg{'forward'} && ($PrnFlag |= $FWD,  $PrnFlag &= ~ ($NOXR | $XREF));

    $Arg{'quiet'}  && $Quiet++;
    $Arg{'silent'} && $Silent++;
    $DB{2} && $DbLink++;
    $DB{3} && $DbP++;

    $CacheNet = $Arg{'retry'}  || $Arg{'flush'} || $Arg{'netmod'}
        || $Arg{'netset'};

    $CheckNet = $Arg{'netmod'} || $Arg{'netset'} || $Arg{'net'};

    $CacheNet && !$CheckNet && !@CheckUrls && do {

        $Arg{'flush'} &&
            print STDERR "ERROR: -flush requires -net or -netmod or -netset\n";

        $Arg{'retry'} &&
            print STDERR "ERROR: -retry requires -net or -netmod or -netset\n";

        die($ErrUsage);
    };


    $Limit = $Arg{'limit'} = $Arg{'limit'} || 500; # check at most 500 files

    $Arg{'root'} && do {
        $DB{1} || chdir($Arg{'root'}) ||
            &Error(qq~invalid root directory: "$Arg{'root'}"~, 'sys');
        &GetCwd;
        $HeaderRoot = $CWD;
    };
    $ServerRoot = $CWD;

    $IgnoreCase && $ServerRoot =~ tr/A-Z/a-z/;

    $ServerHost = $Arg{'host'} || '';

    #---- get base for links in html files in -doc directory

    $DocDir && do {
        $DocBase = defined $Arg{'docbase'} ? $Arg{'docbase'} :
           $Arg{'http'} ? "http://$ServerHost" :
               $Dos ? "file:///$DosDrive|$ServerRoot" : "file://$ServerRoot";
    };

    $Arg{'tilde'} && do {
        ($ServerTilde = $Arg{'tilde'} ) =~ s/#/\$1/g;
        $ServerTilde = '"' . $ServerTilde . '"';
    };

    %IGNORE && do {
        $Ignore = &LinkSet('ignore', *IGNORE);
    };

    %INDEX && do {
        grep(m/[A-Z]/, @DefIndex = keys %INDEX) && $DefCaseSens++;
        $Arg{'index'} = join(" ", @DefIndex);
    };

    %JAVASCRIPT && do {
        foreach( keys %JAVASCRIPT) {
            &SetProtoJS($_);
        }
    };

    %MAP && do {
        local(@maps);
        foreach ( keys %MAP ) {
            $NewMap{$_} = s/=([^=]*)$// ? $1 : '';
            push(@maps, &Regular($_) );
        }
        $Arg{'map'} = $ServerMap = join( '|', @maps);

    };

    !%LOCAL && $LOCAL{'@.map'}++;  # default to *.map

    %LOCAL && ($Local = &LinkSet("local", *LOCAL));

    %DONT_OUTPUT and ( $Dont_Output = join "|", keys %DONT_OUTPUT);

    %SKIP && ($Skip    = &LinkSet("skip",  *SKIP));

    $Use_QS = ($Arg{'http'} and not $Arg{no_query_string}) ? 1 : 0;

    %LANGUAGE and
        $HTTP_HEADER{"Accept-Language: " . join ", ", sort keys %LANGUAGE} = 1;

    $Arg{'http'} && do {
        $ServerHost || &Error("must set -host when using -http");
        &HttpInit(*Arg, *DB, *PASSWORD, *HTTP_HEADER, 'spider');
        $Http++;
        ($Arg{'case'} || $Arg{'orphan'} ) &&
            $Hints{"-case and -orphan don't work in -http mode."}++;
    };

    $DB{1} && do {
        foreach ( sort keys %Arg) {
            printf "%10s %s\n", $_, &Abbrev(60, $Arg{$_});
        }
        %PASSWORD  || exit;
        print "Passwords:\n";
        foreach (sort keys %PASSWORD) {
            print qq~"$_" $PASSWORD{$_}\n~;
        }
        exit;
    };

#--------------- Local/Remote Site Checking ---------------------

    ! @CheckUrls && do {

        &LogFile( $OutLog || $SiteLog);

        &Progress( $Http ? "\nChecking links via http://$ServerHost"
                         : "\nChecking links locally in $ServerRoot");
        &Progress("that match: " . join(" ", keys %LinkSet));
        &Progress(&Plural(scalar keys %Seeds, "%d seed%s: ") .
            join(" ", sort keys %Seeds));

        $Time = -time;
        &SetBase("/");
        foreach (sort keys %Seeds) {
            $_ = &UniqueUrl($_);
            &Progress("\nSeed:    $_");
            &WasCached($_, "\n") || &LinkLint(0, $_, "\n");
        }
        $Time += time;

        $DirList = keys %DirList;

        &CheckOrphan(*DirList,*OrphList,*BadCase, $Arg{'orphan'}, $CheckCase);

        &ProcessLocal;

        &PrintOutput(*SiteForm, *SiteSummary, $DocDir, @SiteHtml);
    };

    $CheckNet && push(@CheckUrls, grep( m#^http://#i, keys %ExtLink));

    @CheckUrls || exit;

#--------------- Remote Url Checking ---------------------

   $URL_PREFIX &&= $Arg{url_doc_prefix};
    $DocDir and $URL_PREFIX =~ m~/~ and do {
        $url_doc_dir = "$DocDir/$URL_PREFIX";
        $url_doc_dir =~ s~/[^/]+$~~;
        -d $url_doc_dir or mkdir($url_doc_dir, 0777) or
            Error("Could not mkdir($url_doc_dir)");
    };

    %WarnList = ();

    &LogFile( $OutLog || $UrlLog);

    &HttpInit(*Arg, *DB, *PASSWORD, *HTTP_HEADER, 'checkonly');

    $CacheNet && &Http'OpenCache($StatFile);

    $Arg{'flush'} && &Http'FlushCache(@CheckUrls);

    $Arg{'retry'} &&
        ! (@CheckUrls = &Http'Recheck(@CheckUrls)) &&
            die("No urls need to be retried.\n");

    %UrlStatus = &Http'CheckURLS(@CheckUrls);
    &Http'WriteCaches;

    ($CheckedUrls = keys %UrlStatus) || exit;

    &Http'StatusMsg(*UrlStatus, *UrlOk, *UrlFail, *UrlWarn);

    $UrlRetry = &Http'RetryCount(*UrlStatus);

    foreach( keys %ExtLink) {
        $UrlFail{$_} || next;
        $UrlFailX{$_} = $UrlFail{$_};
        $UrlFailXX{"$_&cr;        $UrlFailX{$_}"} = $ExtLink{$_};
    }

    &HashUnique(*WarnList);
    &InvertKeys(*WarnList, *WarnF);

    $UrlFailedF = &InvertKeys(*UrlFailXX, *UrlFailF);

    &Http'OtherStatus(*UrlMod, *HostFail, *UrlMoved, *UrlRedirect);

    &PrintOutput(*UrlForm, *UrlSummary, $DocDir, @UrlHtml);

    exit;

###########################################################################
#
# Site Checking Routines
#
###########################################################################

#--------------------------------------------------------------------------
# UniqueUrl($url)
#
#    Make a URL Unique.  Decode "/../" and "." in the path of full URL's
#    Do same for relative URL's But also completes the path
#    if it does not start with a "/".
#--------------------------------------------------------------------------

sub UniqueUrl
{
    local($_) = @_;
    local($scheme, $host, $local);

    $DbP && $ErrTag && print $ErrTag;

    s#^([\w\.\-\+]+):## && do {                     # specified scheme
        ($scheme = $1) =~ tr/A-Z/a-z/;              # lower case scheme
        $scheme =~ /^https?$|^ftp$/ || do {
            $DbP && print "==> LINK $scheme:$_\n\n";
            return "$scheme:$_";
        };
    };

    s#^//([^/]*)## && ($host = $1);             # specified host

    ($scheme && $host) || ($scheme = $BaseScheme) && do {
        $host || $BasePath || m#^/# || ($host = $_, $_ = '');
        $host || ($host = $BaseHost) && m#^/# || ($_ = $BasePath . $_);
    };

    (($host && $host ne $ServerHost) || ($scheme && $scheme !~ /http/i )) ||
    do {
        m#^/# || ($_ = $CurPath . $_);
        s/\#.*$//;                                  # strip local anchor
        $local++;
        $Use_QS or s#\?.*$##;                       # strip query string
    };


    m/&/ && do {
        s/&amp;/&/g;                                # expand &amp; etc
        s/&lt;/</g;
        s/&gt;/>/g;
        s/&quot;/"/g;
        s/&nbsp;/ /g;
        s/&#(\d\d?\d?);/pack("c",$1)/ge;
    };

   # s/%([0-9a-zA-Z]{2})/pack("c",hex($1))/ge;

    s#\\#/#g && &Warn("\\ converted to / in $_[0]", $link);
    s#//+#/#g && &Warn("// converted to / in $_[0]", $link);

    #----- make path unique by expanding /.. and /.

    m#/\.# && do {
        while (s#/\./#/#) {;}              #  /./        ->  /
        while (s#/[^/]*/\.\./#/#) {;}      #  /dir/../   ->  /
        s#/.$##;                           # trailing /.
        s#/[^/]*/\.\.$#/#;                 # trailing /dir/../   ->  /
    };

     $local || do {
        $scheme = $scheme || 'http';
        $host = $host ? "//$host" : '';
        $DbP && print "==> LINK $scheme:$host$_\n\n";
        return "$scheme:$host$_";
    };

    $IgnoreCase && tr/A-Z/a-z/;
    $DbP && $ErrTag && print "==> LOCAL LINK $_\n\n";
    $_ || '/';
}

#--------------------------------------------------------------------------
# WasCached($link, $referer)
#
#     Does some quick checks on $link.  Return 1 if we are done with it.
#     Return 0 if it should be checked further.  Also bails out early
#     If we know we will not have to process any further.
#--------------------------------------------------------------------------

sub WasCached
{
    local($link, $referer) = @_;

    $referer ne "\n" && &AppendList(*Forward, $referer, $link);

    $LostFile{$link} &&
        (($LostFile{$link} .= "\n$referer"), return '1');

    $FileList{$link} && do {
        $Skipped{$link} && ($Skipped{$link} .= "\n$referer");
        $FileList{$link} .= "\n$referer";
        return '1';
    };

    $Action{$link} && return '1';

    $link =~ m#^(\w+):# && do {
        &AppendList(*ExtLink, $link, $referer);
        return '1';
    };

    $Ignore && $link =~ m/$Ignore/o && do {
        &AppendList(*Ignored, $link, $referer);
        return '1';
    };

    '';
}

#--------------------------------------------------------------------------
# LinkLint($level, $link, $referer)
#
#     $level    keeps track of depth of recursion.
#     $link     is the URL or file to check
#     $referer  is the file that referenced $link.
#     Recursively get all referenced files from a file.
#     NOTE: $link is assumed to be anchored at the server root.
#--------------------------------------------------------------------------

sub LinkLint
{
    local($level, $link, $referer) = @_;
    local(%newlinks);

    $DbLink && &Progress("getting  $link");

    ($ServerMap || $ServerTilde) && do {
        ($link = &MapLink($link, $referer)) || return '';
    };

    $link = $Http && $link !~ m/$Local/o ?
        &LinkRemote($link, $referer) :
        &LinkLocal($link, $referer);

    $link || return;

    $Forward{$link} = "\n";          # this primes forward

    #----- recurse into all links found in this file

    foreach $new (keys %newlinks) {
        &WasCached($new, $link) || &LinkLint($level+1, $new, $link);
    }
}

#--------------------------------------------------------------------------
# LinkLocal($link, $referer)
#
#     Does the local equivalent of what the server does.
#--------------------------------------------------------------------------

sub LinkLocal
{
    local($link, $referer) = @_;
    $link =~ s/\?.*$//;                 # strip local queries

    local($lastdir);                    # for directory listings

    -d "$ServerRoot$link" && $link !~ m#/$# && ( $link .= '/' );

    local($path) = $link;               # for index files

    if ( $link =~ m#/$#) {

        if (&LookupDir($link) ) {
            $path = &LookupDir($link);
            $PrintAddenda{$link} = "[file: $path]";
        }
        else {
            $LASTDIR || do {
                &AppendList(*LostFile, $link, $referer);
                return '';
            };
            $lastdir = '1';
            $Arg{no_warn_index} or &Warn("index file not found", $link);
            $PrintAddenda{$link} = "[directory listing]";
        }
    }
    elsif ( -f _ )  {
        ((stat(_))[2] & 4 == 0) && &Warn("not world readable", $link);
    }
    else {
        &AppendList(*LostFile, $link, $referer);

        $ServerTilde || $link =~ m#(^/~[^/]*)# &&
            $Hints{qq~use -http to resolve "$1" links.~}++;

        $ServerMap || $link =~ /^($StandardMaps)/o &&
            $Hints{qq~use "-map $1" to resolve imagemaps.~}++;

        return '';
    }

    &AppendList(*FileList, $link, $referer);
    &CacheDir($link);

    $lastdir && do {
        &StopRecursion($link, $referer) && return '';
        &Progress("checking $link");
        %newlinks = %LASTDIR;
        return $link;
    };

    $path =~ /\.($HtmlExts|map)$/io || return ''; # only parse html & .map

    &StopRecursion($link, $referer) && return '';

    &Progress("checking $link");

    open($path, "$ServerRoot$path") || do {
        &Warn(qq~could not open file: "$ServerRoot$path"\n~, 'sys');
        return '';
    };

    $path =~ /\.map$/i ?
        &ParseMap($path, *newlinks) :
        &ParseHtml($path, $link, *newlinks);

    close($path);
    $link;
}

#--------------------------------------------------------------------------
# MapLink($link, $referer)
#
#     Resolves my server maps for $link.  Returns new $link or '' if
#     the new link was already cached.
#--------------------------------------------------------------------------

sub MapLink
{
    local($link, $referer) = @_;
    local(%checked, $old);
    $old = $link;
    while ( ($ServerMap   && $link =~ s#^($ServerMap)#$NewMap{$1}#o) ||
            ($ServerTilde && $link =~ s#^/~([^/]*)#$ServerTilde#oee) ) {

        $checked{$link}++ || next;
        &Warn("infinite mapping loop", $link);
        return $link;
    }

    ($old eq $link || "$old/" eq $link) && return $link;

    $PrintAddenda{$link} = "($old)";
    $Mapped{$old} = $link;
    $DbLink && &Progress("mapped $old\n    => $link");
    &WasCached($link, $referer) && return '';
    $link;
}


#--------------------------------------------------------------------------
# StopRecursion($link, $referer)
#
#      Stops recursion as needed.  Also records skipped files.
#--------------------------------------------------------------------------

sub StopRecursion
{
    local($link, $referer) = @_;

	$Parsed{$link} && return '1';

    $Abort || $link !~ /$LinkSet/o || ($Skip && $link =~ /$Skip/o) ||
    ++$Parsed > $Limit || do {
        $Parsed{$link}++;
        return '';
    };

    &AppendList(*Skipped, $link, $referer);
    push(@Skipped, $link);
    &Progress("-----    $link");
    return '1';
}

#--------------------------------------------------------------------------
# LinkRemote($link, $referer)
#
#     Checks $link via http.  If it is an html file it is parsed and
#     the results go into local lists maintained by LinkLink().
#--------------------------------------------------------------------------

sub LinkRemote
{
    local($oldlink, $referer) = @_;

    #---- check url and parse into local arrays in LinkLint().

    $Fetched{$oldlink}++ && return '';

    ($flag, $link) = &Http'Parse($ServerHost, $oldlink, $referer, *newlinks);

    $flag == -5000 && return '';        # user interrupt

    $flag == -4000 && do {              # moved to different host
        &AppendList(*ExtLink, $link, $referer);
        return '';
    };

    $link ne $oldlink && $link ne "$oldlink/" && do {
        $PrintAddenda{$link} = "($oldlink)";
        $Mapped{$oldlink} = $link;
    };

    $flag || return '';                 # new url was already cached

    local($msg) = &Http'ErrorMsg($flag);

    &Http'FlagWarn($flag) && do {
        &AppendList(*Ignored, $link, $referer);
        &AppendList(*HttpFail, $link, $msg);
        &Warn($msg, $link);
        return '';
    };

    &Http'FlagOk($flag) || do {
        &AppendList(*LostFile, $link, $referer);
        &AppendList(*HttpFail, $link, $msg);
        return '';
    };

    &AppendList(*HttpOk, $link, $msg);

    $flag == -2000 || return '';

    $link;
}

#--------------------------------------------------------------------------
# CacheDir($link)
#
#    Save a list of directories for orphan and case checking.
#--------------------------------------------------------------------------

sub CacheDir
{
    local($dir) = @_;
    $dir =~ s#/[^/]*$##;
    local($absdir) = $ServerRoot . $dir;
    $dir = $dir || '(root)';
    ($DirList{$dir} || $LostDir{$dir}) && return;
    &AppendList( -d $absdir ? *DirList : *LostDir, $dir, "\n");
}

#--------------------------------------------------------------------------
# ParseHtml(*HANDLE, $link, *list)
#
#     Extracts all (?) links from the file by setting %list{link} = "1".
#     Links are expanded to full unique URL's or paths.
#     %Anchor    named anchors found
#     %ImgMap    named image maps found
#     %WantAnch  named anchors to find
#     %WantMap   named image maps to find
#--------------------------------------------------------------------------

sub ParseHtml
{
    local(*HANDLE, $link, *list) = @_;
    local($code, $tag, $temp, $url, $att, $term, $anch);

    &SetBase($link);

    $DbP && print "\n" , '=' x 60, "\nFILE     $link\n\n";

    $/ = "<";                                # use "<" as newline separator

TAG:
    while (<HANDLE>) {

       /^\!\-\-/ && do {
            while ($_ !~ /\-\-\!?>/ ) {        # ignore tags inside comments
               defined($_ = <HANDLE>) && next;
               &Warn(q~missing end comment "-->"~, $link);
               last TAG;
            }
            next TAG;
        };

        m/^(\w+)(\s*("[^"]*"|'[^']*'|[^>"'])*)(>?)/ || next;

        $tag  = $1;
        $att  = $2;
        $term = $4;

        while ( ! $term  ) {
             $att .= $_;
            ($term, $att) = &FixTag(*HANDLE, $att);
             $term eq 'next' && next TAG;
             $term eq 'last' && last TAG;
        };

        ($_ = $tag) =~ tr/A-Z/a-z/;          # convert tag to lower case

        if ( /^script$/ ) {
            $att =~ /\ssrc${ATTRIB}/io && $list{&UniqueUrl($+)}++;
            while ( $_ = <HANDLE> ) { m#^/script#i && next TAG;  }
            &Warn("missing </script>", $link);
            last TAG;
        }

        $att || next TAG;

        $DbP && $att && do {
            ($ErrTag = "<$tag$att>") =~ s/\s+/ /;
            $ErrTag .= "\n";
        };

        if ( /^a$/ )
        {
            $att =~ s/\sname${ATTRIB}//io && ! $Arg{no_anchors} &&
                ($Anchor{"$CurFile#$+"} = "\n");

            $att =~ /\shref${ATTRIB}/io || next;

            $temp = $+;
            $temp =~ /^#/ && ($temp = "$BaseFile$temp");

            $anch = $temp =~ /(#.*)$/ ? $1 : '';
            $url = &UniqueUrl($temp);
            $list{$url}++;

            %ProtoJS && $url =~ /^javascript:/ && &ProtoJS($url, $referer);

            $anch && $url =~ m#^/# && ! $Arg{no_anchors} &&
                &AppendList(*WantAnch, "$url$anch", $link);
        }
        elsif ( /^base$/ ) {
            $att =~ /\shref${ATTRIB}/io || next;
            $DbP && print $ErrTag;
            &BaseTag($+);
        }
        elsif ( /^bgsound$|^frame$|^input$|^embed$/ ) {
            $att =~ /\ssrc${ATTRIB}/io && $list{&UniqueUrl($+)}++;
        }
        elsif ( /^area$/ ) {
            $att =~ /\shref${ATTRIB}/io && $list{&UniqueUrl($+)}++;
        }
        elsif ( /^body$/ ) {
            $att =~ /\sbackground${ATTRIB}/io && $list{&UniqueUrl($+)}++;
        }
        elsif ( /^img$/ ) {
            $att =~ s/\ssrc${ATTRIB}//io    && $list{&UniqueUrl($+)}++;
            $att =~ s/\slowsrc${ATTRIB}//io && $list{&UniqueUrl($+)}++;
            $att =~ /\sdynsrc${ATTRIB}/io   && $list{&UniqueUrl($+)}++;
            $att =~ /\susemap${ATTRIB}/io || next;

            $temp = $+;
            $temp =~ /^#/ && ($temp = "$BaseFile$temp");

            $anch = $temp =~ /(#.*)$/ ? $1 : '';
            $url = &UniqueUrl($temp);
            $list{$url}++;

            $anch && $url =~ m#^/# &&
                &AppendList(*WantMap, "$url$anch", $link);
        }
        elsif ( /^map$/ ) {
            $att =~ s/\sname${ATTRIB}//io &&
                ($ImgMap{"$CurFile#$+"} = "\n");
        }
        elsif ( /^form$/ ) {
            $att =~ /\saction${ATTRIB}/io || next;
            $temp = &UniqueUrl($+);
            &AppendList(*Action, $temp, $link);
            $list{$temp}++;
        }
        elsif ( /^applet$/ ) {
            $att =~ /\scode${ATTRIB}/io or next;
            $code = $+;
            $code =~ /\.class$/i || ( $code .= ".class" );

            my ($jar, $base);
            $att =~ /\sarchive${ATTRIB}/io and $jar = $+;
            my $file = $jar || $code || next;

            $att =~ /\scodebase${ATTRIB}/io and do {
                ($base = $+) =~ s#/$##;
                $file = "$base/$file";
            };
            $list{&UniqueUrl($file)}++;
        }
        elsif ( /^meta$/ ) {
            $att =~ /\shttp-equiv${ATTRIB}/io || next;
            $+ =~ /^refresh$/i || next;
            $att =~ /\scontent\s*=\s*"([^"]*)"/i || next;
            $1 =~ /url=([^"\s]+)/i || next;
            $temp = $1;
            $temp =~ m#^\w+://# ||
                &Warn("re-direct should be absolute", $link);
            $url = &UniqueUrl($temp);
            $list{$url}++;
        }
    }

    $/ = "\n";          # reset line seperator to "\n"
    $DbP or return;
    print '=' x 60 , "\n\n";
    $ErrTag = '';
}

#--------------------------------------------------------------------------
# SetBase($link)
#
#    Clears globals: BaseScheme, BaseFile, BasePath,
#    Sets CurFile and CurPath
#--------------------------------------------------------------------------

sub SetBase
{
    ($CurFile) = @_;
    $BaseScheme = '';
    $BaseHost   = '';
    $BasePath   = '';
    $BaseFile   = $CurFile;
    ($CurPath = $CurFile) =~ s#(\?.*)$##;     # strip query off of path
    $CurPath =~ s#([^/]+)$##;                 # strip file off of path
    $CurPath = $CurPath || "/";               # default to root
}

sub ProtoJS
{
    local($link, $referer) = @_;
    local($place, %place, $cnt);
    $link =~ s#javascript:([^\(\)]+)\(## || return;
    ($place = $ProtoJS{$1}) || return;
    grep( $place{$_}++, split("\n", $place));
    while ($link =~ s/^\s*("([^"]*)"|'([^']*)'|([^"'\)]+))\s*[,\)]//) {
        $place{++$cnt} && $list{&UniqueUrl($+)}++;
    }
}

sub SetProtoJS
{
    local($proto) = @_;
    local(@place, $name, $cnt);
    $proto =~ s#^([^\(\)]+)\(## || return;
    $name = $1;
    while ($proto =~ s#^([^\),]*)[,\)]##) {
        $cnt++;
        $+ eq 'url' && push(@place, $cnt);
    }
    $ProtoJS{$name} = join("\n", @place);
    $DB{1} && print "javascript:$name $ProtoJS{$name}\n";
}

#--------------------------------------------------------------------------
# FixTag(*HANDLE, $att)
#
#    Reads in the remainder of a tag if there was a  bare "<" inside the
#    the tag.  Only works if "<" was inside of single or double quotes.
#    This is slow but we only get here on rare occasions.
#--------------------------------------------------------------------------

sub FixTag
{
    local(*HANDLE, $att) = @_;
    local($erratt, $temp, $quot);

    $DbP && print "attrb = [$att]\n";

    ($erratt = substr($att, 0, 20)) =~ s/\s+/ /;   # for error msg
    $temp = $att;
    $temp =~ s/"[^"]*"|'[^']*'//g;                 # strip leading ".."

    $DbP && print "tail  = [$temp]\n";

    $temp = m/(['"])/ || do {                      # should have ' or "

        &Warn(qq~unquoted "<" in <$tag$erratt~, $link);
        return 'next';
    };

    $quot = $1;                                    # last ' or "
    $DbP && print "quot  = [$quot]\n";

    $_ = '';                                       # prime the pump
    do {
        $att .= $_;
        $DbP && print "append1 [$_]\n";            # add new lines ...
        defined($_ = <HANDLE>) || do {
            &Warn("unterminated <$tag$erratt", $link);
            return 'last';
         };

    } until (($quot eq '"' && s/^([^"]*")//) ||    # until we close quote
             ($quot eq "'" && s/^([^']*')//)  );

    $att .= $1;                                    # got it
    $DbP && print "append2 [$1]\n";

    m/^(("[^"]*"|'[^']*'|[^>])*)(>?)/ && ($att .= $1);

    $DbP && print "append3 [$1]\n";

    $term = $3;
    $DbP && print "term  = [$term]\n";
    ! $term && ($att .= $_);
    ($term, $att);
}

#--------------------------------------------------------------------------
# BaseTag($url)
#
#     Set Global $BaseHost, $BasePath and $BaseFile defined in $url
#     Only set BaseHost if a scheme is given!
#     $BasePath will always start and end with "/"
#--------------------------------------------------------------------------

sub BaseTag
{
    local($_) = @_;

    $BaseFile = $_;

    s#^([\w\-]+):## && do  {
        ($BaseScheme = $1) =~ tr/A-Z/a-z/;
        $BaseFile = "$BaseScheme:$_";
        $BaseHost = $1 if s#^//([^/]*)##;   # can't have host without scheme
    };
    s#([^/]+)$##;                           # strip file first
    $BasePath = $_ if m#^/#;                # only if absolute

#    $ServerHost && $BaseFile =~ s#^http://$ServerHost##o;

    $DbP || return;
    print "\nBaseScheme $BaseScheme\n";
    print "BaseHost   $BaseHost\n";
    print "BasePath   $BasePath\n";
    print "BaseFile   $BaseFile\n\n";
}


#--------------------------------------------------------------------------
# ParseMap(*HANDLE, *list)
#     Reads a map file and tries to extract all http links.
#--------------------------------------------------------------------------

sub ParseMap
{
    local(*HANDLE, *list) = @_;
    &SetBase("/");
    while (<HANDLE>) {
        next unless m#(http://[^\s"]+)#i; # strip any junk around an http://
        $list{&UniqueUrl($1)}++;
    }
}

#--------------------------------------------------------------------------
#  $url = ParseRedirect(*HANDLE, $link)
#
#     Reads text from FILE until end of <head> element.  Uses $link for
#     error messages.  Returns $url with redirected $url if given otherwise
#     returns ''.
#--------------------------------------------------------------------------

sub ParseRedirect
{
    local(*HANDLE, $link) = @_;

    &SetBase($link);

    local($url) = '';
    $/ = "<";                           # use "<" as newline separator

REDIR:
    while (<HANDLE>) {

        $DbP && print;

        /^\!\-\-/ && do {
            while ($_ !~ /\-\-\!?>/ ) {        # ignore tags inside comments
               defined($_ = <HANDLE>) && next;
               &Warn(q~missing end comment "-->"~, $link);
               last REDIR;
            }
            next REDIR;
        };

        last if m#^(/head|body|h\d|font)#i;
        s/^meta//i || next;
        /\shttp-equiv\s*=\s*"?refresh/i || next;
        /\scontent\s*=\s*"([^"]*)"/i || next;
        $1 =~ /url\s*=\s*([^"\s]+)/i || next;
        $url = &UniqueUrl($1);
        $url =~ m#^\w+://# ||
            &Warn("re-direct $url should be absolute", $link);
        last;
    }
    $/ = "\n";                          # use "\n" as newline separator
    return $url;                        # return value
}

#--------------------------------------------------------------------------
# $path = LookupDir($dir)
#
#     $dir and $path are both relative to server root.
#     Find a default index file in $dir. Returns $path of default file
#     on success or return 0 on failure. Caches results in $DefDir.
#     Fills %LASTDIR with last successful directory listing.
#--------------------------------------------------------------------------

sub LookupDir
{
    local($absdir) = @_;
    $absdir =~ s#/$##;
    local($dir) = $absdir . '/';

    defined $DefDir{$dir} && return $DefDir{$dir};     # was cached

    local(%file, $lc);

    &Progress("looking for $dir(default)");

    opendir(DIR, "$ServerRoot$absdir") ||
        return $DefDir{$dir} = $LASTDIR = '';

    %LASTDIR = ();
    foreach (grep(!/^\./, readdir(DIR))) {   # all files in directory

        ($lc = $_) =~ tr/A-Z/a-z/;           # lower case version
        $IgnoreCase && ($_ = $lc);
        $LASTDIR{ "$dir$_" }++;
        $file{$DefCaseSens ? $_ : $lc} = $_;
    }

    closedir(DIR);
    $LASTDIR = '1';

    foreach (@DefIndex) {
        next unless $file{$_} && -f "$ServerRoot$dir$file{$_}";
        return $DefDir{$dir} = "$dir$file{$_}";
    }
    return $DefDir{$dir} = '';
}

#--------------------------------------------------------------------------
# CheckOrphan(*dirlist, *orphlist, *badcase, $checkorphan, $checkcase)
#
#     Checks every directory in dirlist and creates a list of
#     all files that have not been checked by linklint.
#
#     If CheckCase is set we first check the case of all found files
#     in that directory.
#--------------------------------------------------------------------------

sub CheckOrphan
{
    local(*dirlist, *orphlist, *badcase, $checkorphan, $checkcase) = @_;

    %dirlist || return;
    $checkorphan || $checkcase || return;

    local($msg) = '    for';
    $msg .= " orphans" if $checkorphan;
    $msg .= " and"    if $checkorphan && $checkcase;
    $msg .= " case mismatch"   if $checkcase;

    local(@files, %files, $file, $link, $absdir, $reldir);

    foreach $dir (sort keys %dirlist) {

        &Progress("checking $dir");
        &Progress($msg);

        $reldir = $dir eq '(root)' ? '' : $dir;
        $absdir = $ServerRoot . $reldir;

        &PushDir($absdir) || next;
        opendir(DIR, '.') || do {
            &Warn(qq~could not read directory "$absdir"~, 'sys');
            next;
        };

        @files = grep(!/^\./, readdir(DIR));
        $IgnoreCase && grep( tr/A-Z/a-z/ && 0, @files);
        closedir(DIR);

        $checkcase && do {

            %files = ();
            grep($files{"$reldir/$_"}++, @files);

            foreach $link ( grep( m#^$reldir/[^/]+$#i, keys %FileList) ) {
                next if $files{$link};
                ($file) = grep(/$link/i, keys %files); # get "real" filename
                $file = $file || $link;                # just in case
                $badcase{$file} = $FileList{$link};    # add to list
            }
        };
        next unless $checkorphan;

        foreach $file (@files) {
            $link = "$reldir/$file";
            next if $FileList{$link} || $dirlist{$link} ||
                $badcase{$link};

            -d $file && ($link .= "/");       # let them know it's a dir
            $orphlist{$link} = "\n";

            next unless $link =~ /\.($HtmlExts)$/io;

            #----- parse html files for possible redirects

            open($file, $file) || do {
                &Warn(qq~could not open orphan "$link"~, 'sys');
                next;
            };
            local($equiv) = &ParseRedirect($file, $link);
            close($file);
            $equiv && ($PrintAddenda{$link} = "  => $equiv");
        }
        &PopDir;
    }
}

#--------------------------------------------------------------------------
# ProcessLocal()
#
#     Does the work needed between gathering links and printing.
#--------------------------------------------------------------------------

sub ProcessLocal {
    local($file, $anch, $ref);

    &Progress("\nProcessing ...");

    #---- Resolve named anchors

    $Arg{no_anchors} or do {
        &HashUnique(*WantAnch);
        &ResolveAnch(*WantAnch, *Anchor, *LostAnch);
    };

    #---- resolve named image maps

    &HashUnique(*WantMap);
    &ResolveAnch(*WantMap, *ImgMap, *LostMap);

    &HashUnique(*FileList);   # pathinfo and dirlookup can cause extras.
    &HashUnique(*LostFile);   # pathinfo and dirlookup can cause extras.
    &HashUnique(*Action);
    &HashUnique(*Forward);

    &InvertKeys(*LostFile, *ErrF);
    &InvertKeys(*BadCase,  *CaseF);
    &InvertKeys(*WarnList, *WarnF);

    $Parsed = keys %Parsed;

    $Parsed >= $Limit && ! $Arg{'limit'} &&
        $Hints{"use -limit to check more than $Limit files."}++;

    @PRINTFORM = @SiteForm;
    &PrintFiles(0, 0, 0, 0);  # count elements in local arrays

    $ErrTot = $LostFile + $LostAnch + $BadCase;
    $Fetched = keys %Fetched;
}

###########################################################################
#
#                          PRINTING ROUTINES
#
# Entry through PrintOutput() function.
#
###########################################################################

#--------------------------------------------------------------------------
# PrintOutput(*form, *summary, $docdir, $sumfile, $indexfile, $title)
#
#     A wrapper for a printing routines. Computes counts of # of elements
#     in all hashes (need scalars).  Inverts some hashes for forward
#     results. Prints output to files in $DocDir or to "std" output.
#--------------------------------------------------------------------------

sub PrintOutput
{
    local(*printform) = shift;
    @PRINTFORM = @printform;        # used globally below
    local(*SUMMARY) = @_;           # Summary routine: used and passed on.

    &PrintFiles(0, 0, 0, 0);        # count elements in all hashes

    &PrintDocDir(@_);               # All -doc files

    $LogFile && do {
        print "\n";
        &PrintFiles(@SumPrint);     # summary list of results
        print "\n";
        &SUMMARY;                   # text summary at top of file zz ?
        print "\n";
    };

    &PrintFiles(0,0,0, $PrnFlag);   # print as user requested

    return if $Silent;              # -silent: no summary on screen

    $lastsel = select(STDERR);
    print "\n";
    &PrintFiles(@SumPrint);         # list summary
    print "\n";
    &SUMMARY;                       # text summary at bottom of screen
    select($lastsel);
}

#--------------------------------------------------------------------------
# PrintFiles($DocDir, $DOCHEAD, $SUM, $flags)
#
#     Prints all or part of the output according to the flags supplied.
#     If $DocDir is supplied output goes to the files specified in the
#     OpenDoc() calls, otherwise output goes to currently selected output.
#     PrintFile is called several times to print lists to STDOUT,
#     doc files, summary, and summary file. Passes globals to OpenDoc(),
#     PrintLISTS() and PrintList().
# where to print:
#     $DocDir    send output to seperate files in $DocDir.
# summarize:
#     $DOCHEAD   add filenames to headers.
#     $SUM       1: summary form, 2: summarize printLISTS to one line
#
#--------------------------------------------------------------------------

sub PrintFiles
{
    local($docdir, $DOCHEAD, $SUM, $flags) = @_;
    local($file, $data, $mask, $prog, @params);
    foreach (@PRINTFORM) {
        ($file, $data, $mask, $prog, @params) = split(/;\s*/, $_);
        $Dont_Output and $file =~ m/$Dont_Output/o and next;
        $mask = oct($mask);
        $flags || (eval("\$$data = \$$data || keys \%$data"), next);
        &OpenDoc($docdir, $file, $data) || next;
        next unless ($flags & $mask) == $mask;
        $prog == 1 && &PrintList($data, @params);
        $prog == 2 && &PrintLISTS($data, @params);
        $prog == 3 && &PrintUrl($data, @params);
    }
}

#--------------------------------------------------------------------------
# $flag = OpenDoc($docdir, $file, *list)
#
#     A co-conspirator with PrintFiles().
#     $file is the name of a file (sans extension) to be written in
#     $DocDir.  $anydata tells us if there is any data to be written
#     to the file.  Always erase old copies of all the files but save
#     a backup copy if the file might be theirs.
#     If $DocDir is 0 then create the filename $DOCFILE and return
#     $anydata. If $anydata is 0 don't create a new file and return ''.
#--------------------------------------------------------------------------

sub OpenDoc
{
    local($docdir, $name, *data) = @_;
    local($anydata) = $data || ($data = scalar keys %data);
    $DOCFILE = "$name.txt";             # global used in PrintList()
    return $anydata unless $docdir;     # and output will to current select()

    local($htmlfile) = $name;
    $htmlfile .= $Dos ? '.htm' : '.html';

#    $Clean && do {
        -e $DOCFILE && unlink($DOCFILE);
        -e $htmlfile && unlink($htmlfile);
#    };

    return '' unless $anydata;           # don't create new file w/ no data

##    print STDERR ">>>$DOCFILE\n";

    open(DOC, ">$DOCFILE") || do {
        &Warn(qq~could not open "$DOCFILE" for output~, 'sys');
        return '';
    };

    $DOCFILES++;                        # count files created
    $DOCFILES{$DOCFILE} = $htmlfile;    # keep a list of .txt files
    select(DOC);                        # print's will default to DOC
    print "file: $DOCFILE\n";           # indentify filename
    print &Preamble;                    # print a file header
}

sub Preamble
{
    $TimeStr = $TimeStr || &TimeStr('(local)');

    join('',
        $HeaderRoot ? "root: $HeaderRoot\n" : '',
        $ServerHost ? "host: $ServerHost\n" : '',
        "date: $TimeStr\n",
        "Linklint version: $version\n",
        "\n"
    );
}

#--------------------------------------------------------------------------
# SiteSummary
#
#     Prints the textual summary of what has happened.
#--------------------------------------------------------------------------

sub SiteSummary
{
    %Hints && print "hint: ", join("\nhint: ", keys %Hints), "\n\n";

    $FileList && print
        "Linklint found ",
        &Plural($FileList, "%d file%s"),
        $DirList ? &Plural($DirList,  " in %d director%y") : '',
        $Parsed  ? &Plural($Parsed, " and checked %d html file%s") : '',
        ".\n";

    $CheckCase && $BadCase == 0 &&
        print &Plural($BadCase, "There %w %n file%s with mismatched case.\n");

    $CheckOrphan && $OrphList == 0 &&
        print &Plural($OrphList, "There %w %n director%y with orphans.\n");

    print &Plural($LostFile, "There %w %n missing file%s.");
    print &Plural($ErrF, " %N file%s had broken links.\n");

    print &Plural($ErrTot, "%N error%s, ");
    print &Plural($WarnList, "%n warning%s.");

    $Http || $Time && $Parsed && $Time > 4 &&
        printf("  Parsed ~ %1.1f files/second.", $Parsed /$Time);

    print "\n";
}

#--------------------------------------------------------------------------
# PrintDocDir(*SUMMARY, $docdir, $sumfile, $indexfile, $title)
#
#     Prints complete documentation in $DocDir directory.
#--------------------------------------------------------------------------

sub PrintDocDir
{
    local(*SUMMARY, $docdir, $sumfile, $indexfile, $logfile, $title) = @_;
    $docdir && &PushDir($docdir) || return;

    local($indexhtml) = $indexfile;
    $indexhtml .= $Dos ? ".htm" : ".html";

    $DOCFILES = 0;
    %DOCFILES = ();

    &Progress("\nwriting files to $Arg{'doc'}");  # abbreviated $DocDir

    local($lastselect) = select;             # save "std" output

    &PrintFiles($docdir, 0, 0, $DocFlag);    # print almost all doc files

    local($dum) = '1';                         # used to fool OpenDoc()

    &OpenDoc($docdir, $sumfile, *dum) && do {
        &SUMMARY;                            # text summary at top of file
        print "\n";
        &PrintFiles(@SumPrint);              # list summary
    };

    &OpenDoc($docdir, $indexfile, *dum) && do {
        printf("%12s: %s\n", "$sumfile.txt", 'summary of results');
        $Arg{'out'} || printf("%12s: %s\n", "$logfile.txt", 'log of progress');
        &PrintFiles('', 1, 2, $DocFlag);     # list index to all files
    };

    close(DOC);                              # close the last one
    select($lastselect);                     # restore "std" output

    &Progress(&Plural($DOCFILES, "wrote %n txt file%s"));

    $Arg{'textonly'} || do {

        delete $DOCFILES{"$sumfile.txt"};
        delete $DOCFILES{"$indexfile.txt"};
        delete $DOCFILES{"dir.txt"};

        foreach $txt (keys %DOCFILES) {
            &HtmlDoc($txt, $DOCFILES{$txt}, *DefDir, *Action, $DocBase );
            $Arg{'htmlonly'} && $txt !~ /^remote/ && unlink($txt);
        };

        &Progress(&Plural(scalar keys %DOCFILES, "wrote %n html file%s"));

        &HtmlSummary("${indexfile}.txt", $indexhtml, $title, *DOCFILES) &&
            &Progress("wrote index file $indexhtml");
        $Arg{'htmlonly'} && unlink("${indexfile}.txt");
    };

    &PopDir;
}


#--------------------------------------------------------------------------
# HtmlDoc($in, $out, *map, *skip, $base)
#
#     Reads txt file $in, writes html file $out, adding anchors
#     to lines that start with "/" or "scheme:".  Sets the base
#     to $base if provided, maps links found in %map, does not
#     add anchors to links found in *skip.
#--------------------------------------------------------------------------

sub HtmlDoc
{
    local($in, $out, *map, *skip, $base) = @_;
    local($title) = "Linklint - $out";

    #---- Open files

    open(IN, $in) || do {
        &Warn(qq~\ncould not read back "$infile"~, 'sys');
        return '';
    };

###    print STDERR ">> HTML >> $out\n";

    open(OUT, ">$out") || do {
        &Warn(qq~\ncould not open "$outfile" for output~, 'sys');
        close(IN);
        return '';
    };

    my $base_tag = $Arg{output_frames} ? "<base target=LinkLint_site>" : "";

    #----- print html header

    print OUT  "<html><head><title>\n$title\n</title>\n";
    print OUT $base_tag;
    print OUT "</head><body>\n\n<pre>\n";

    #---- read/print text file header

    $_ = <IN>;                    # skip "file: filename.txt"

    while (<IN>) {
        print OUT $_;
        last unless /\S/;
    }

    #---- read/print out the list with anchor tags

    local($file);

    while(<IN>) {
        s/^(\s+)// && print OUT $1;
        s/^(=>\s*)// && print OUT $1;
        m#^(/|\w+:).*# || do { print OUT $_; next; };
        s/\s+$//;
        $file = $map{$_} || $_;
        $skip{$file} && do { print OUT "$_\n"; next; };
        $file =~ m#^/# && ($file = $base .$file);
        print OUT qq~<a href="$file">$_</a>\n~;
    }

    close(IN);

    print OUT @tab, "</pre></body></html>\n";
    close(OUT);

    return 1;
}

#--------------------------------------------------------------------------
# TimeStr($gmt, $time)
#
#     Returns a string formated "weekday, month day year hh:mm:ss"
#--------------------------------------------------------------------------

sub TimeStr
{
    local($gmt, $time) = @_;
    defined $time || ($time = time);
    local($sec, $min, $hour, $mday, $mon, $year, $wday ) =
        ($gmt =~ m/GMT/) ? gmtime($time) : localtime($time);

    local(@mon) = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
        'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    local(@wday) = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );

    $year < 50 && ($year += 2000);
    $year < 1900 && ($year += 1900);

    sprintf("$wday[$wday], %02d $mon[$mon] $year %02d:%02d:%02d %s",
        $mday, $hour, $min, $sec, $gmt);
}

#--------------------------------------------------------------------------
# HtmlSummary($infile, $outfile, $title, $docfiles)
#
#     Creates a simple html summary file by reading back the linklint.txt
#     file that was already created.
#--------------------------------------------------------------------------

sub HtmlSummary
{
    local($infile, $outfile, $title, *docfiles)  = @_;

    local(%head);
    open(IN, $infile) || do {
        &Warn(qq~\ncould not read back "$infile"~, 'sys');
        return '';
    };

    open(OUT,">$outfile") || do {
        &Warn(qq~\ncould not open "$outfile" for output~, 'sys');
        close(IN);
        return '';
    };

    while (<IN>) {
        last unless /\S/;
        /\s*(\S+):\s*(\S+.*\S+)\s*$/ && ($head{$1} = $2);
    }

    local($title2) = $title;
    $head{'root'} && ($title2 .= "for $head{'root'}");
    my $target = $Arg{output_frames} ? "<base target=LinkLint>" : "";

    print OUT  qq~<html><head><title>\n
$title\n
</title>

$target

</head><body>
<font size=4>\n
$title2<br>\n
</font>\n
$head{'date'}<br>
Linklint version: $version
<pre>~;

    local($file);
    while(<IN>) {
        last unless /\S/;
        s|(ERROR )|<font color=#cc0000>$1</font>|;
        s|^\s*(\S+):||;
        $file = $docfiles{$1} || $1;
        $file =~ s~[^/]+/~~;

        print OUT " " x (13 - length($file));
        print OUT "<a href=$file>$file</a>:", $_;
    }

    close(IN);

    print OUT @tab, "\n\n</pre></body></html>\n";

    close(OUT);
    return 1;
}

#--------------------------------------------------------------------------
# Plural($cnt,$msg)
#
#     Returns a pluralized version of $msg.
#
#     %w  -> was : were           %d ->   $cnt
#     %s  ->     :    s           %n ->  no : $cnt
#     %y  ->   y :  ies           %N ->  No : $cnt
#     %es ->     :   es
#--------------------------------------------------------------------------

sub Plural
{
    local($cnt,$_) = @_;
    $cnt == 1 ? s/\%w/was/g : s/\%w/were/g;   # %w -> 'was' or 'were'
    $cnt == 1 ? s/\%s//g    : s/\%s/s/g;      # %s -> ''    or 's'
    $cnt == 1 ? s/\%y/y/g   : s/\%y/ies/g;    # %y -> 'y'   or 'ies'
    $cnt == 1 ? s/\%es//g   : s/\%es/es/g;    # %y -> 'y'   or 'ies'
    s/\%n/\%d/ && ($cnt = $cnt || 'no' );     # %n -> "no"  or $cnt
    s/\%N/\%d/ && ($cnt = $cnt || 'No' );     # %N -> "No"  or $cnt
    s/\%d/$cnt/;                              # %d -> $cnt
    s/(\%\d+d)/sprintf($1,$cnt)/e;            # %3d -> $cnt
    return $_;
}

#--------------------------------------------------------------------------
# PrintList(*list, $header, $xref, $subhead)
#
#     Print out keys (and values if $xref) of %list.  Prepend "$DOCFILE: "
#     to header if $DOCHEAD is set.  Append "(cross referenced)" to header
#     if $xref == 2.  Only print header if $SUM is set.
#--------------------------------------------------------------------------

sub PrintList
{
    local(*list, $header, $xref, $subhead) = @_;
    $subhead = $subhead || "used in %d file%s:";
    return unless %list;
    local(@major) = sort keys %list;

    local($headtext) = &Plural(scalar @major, $header);
    $xref == 2 && ($headtext .= " (cross referenced)");
    $DOCHEAD && ($headtext = sprintf("%13s: ", $DOCFILE) . $headtext);

    $SUM && do { print "$headtext\n"; return; };

    print "$Headline# $headtext\n$Headline";

    foreach (@major) {
        s/&cr;/\n/g;
        print "$_\n";
        $PrintAddenda{$_} && print "$PrintAddenda{$_}\n";
        $xref && &PrintSubList($list{$_}, $subhead, 4);
    }
    print "\n" unless $xref;
}

#--------------------------------------------------------------------------
# PrintSubList($sublist, $subhead, $indent)
#
#     Prints out all elements of $sublist split by "\n".  Prints out the
#     number of elements in pluralized $subhead.
#--------------------------------------------------------------------------

sub PrintSubList
{
    local($sublist, $subhead, $indent) = @_;
    $indent = " " x $indent;
    $sublist =~ s/^\n+//;
    $sublist || return;
    (local(@items) = sort split(/\n+/,$sublist)) || return;
    grep( s/&cr;/\n/g, @items);
    print $indent , &Plural(scalar @items, $subhead), "\n", $indent;
    print join("\n$indent", @items) , "\n\n";
}

#--------------------------------------------------------------------------
# PrintLISTS(*list, *heads, $xref)
#
#     Split %list into sublists and then prints each sublist.  The
#     splitting is controlled by @heads. Each line of @heads must be in the
#     form "$heading::$regexp"  All keys of %list that match %regexp are
#     printed out under the heading $heading.  If regexp contains 'unknown'
#     then all remaining items in %list are printed out under its $heading.
#     If $SUM == 2 then a summary of all keys %list is printed using the
#     first heading format which is otherwise ignored.
#--------------------------------------------------------------------------

sub PrintLISTS
{
    local(*listname, *heads, $xref) = @_;
    local(%sublist, @items, $heading, $regexp);
    local(%list) = %listname;

    foreach ( $SUM == 2 ? @heads[0 .. 0] : @heads[1 .. $#heads] ) {
        ($heading,$regexp) = split(/::/, $_);

        (@items = $regexp =~ /unknown/ ? keys %list
            : grep(/$regexp/i, keys %list)) || next;

        %sublist = ();
        foreach ( @items ) {
            $sublist{$_} = $list{$_};         # transfer to %temp
            delete $list{$_};                 # and delete from %list
        }
        &PrintList(*sublist, $heading, $xref);
    }
}

#--------------------------------------------------------------------------
# PrintUrl(*list, $header, $xref, $posthead, $subhead)
#
#     Prints out URLs (and references if $xref) in %list.
#--------------------------------------------------------------------------

sub PrintUrl
{
    local(*list, $header, $xref, $posthead, $subhead) = @_;
    ($list = $list || scalar keys %list) || return;
    $header .= ':';
    local(@items, %invert);
    local($headtext) = &Plural($list, $header);
    $DOCHEAD && ($headtext = sprintf("%13s: ", $DOCFILE) . $headtext);
    $headtext .= " " . &Plural($list, $posthead);

    $subhead = $subhead || "%d url%s:";
    $xref == 2 && ($headtext .= " (cross referenced)");

    $SUM == 2 && ((print "$headtext\n"), return);

    &InvertKeys(*list, *invert);

    $SUM || print "$Headline# $headtext\n$Headline";

    foreach (sort keys %invert) {
        @items = sort split(/\n/, $invert{$_} );
        print &Plural(scalar @items, $SUM ? $header : $subhead), " $_\n";
        $SUM && next;
        &PrintSubUrl(*items, $xref);
    }
    print "\n" unless $SUM;
}

#--------------------------------------------------------------------------
# PrintSubUrl
#
#     Prints out all elements of $sublist split by "\n".  Prints out the
#     number of elements in pluralized $subhead.
#--------------------------------------------------------------------------

sub PrintSubUrl
{
    local(*items, $xref) = @_;
    foreach ( @items ) {
        print "    ", $_;
        &PrintUrlRedir($_);
        print "\n";
        ($xref && defined $ExtLink{$_} ) || next;
        &PrintSubList($ExtLink{$_}, "used in %d file%s:", 8);
    }
    print "\n" unless $xref && defined $ExtLink{$_};
}

#---------------------------------------------------------------------------
# PrintUrlRedir($url)
#
#     Prints "linked list" of where $url was moved to due to 3XX status
#     codes.  Always returns if an infinite loop ( a -> b -> a ...)
#     occurs.
#---------------------------------------------------------------------------

sub PrintUrlRedir
{
    local($url) = @_;
    local(%checked);
    while ( $url = $UrlRedirect{$url} ) {
        $checked{$url}++ && return;
        print "\n      => ", $url;
    }
}

#---------------------------------------------------------------------------
# UrlSummary()
#
#     Print Textual summary of checking remote url status.
#---------------------------------------------------------------------------

sub UrlSummary
{
    $TotFail = $UrlFail;

    $CheckedUrls && print
        &Plural($CheckedUrls, "Linklink checked %d url%s:\n"),
        &Plural($UrlOk,"    %d %w ok, "),
        $TotFail, " failed",
        $UrlMoved ? &Plural($UrlMoved, ". %N url%s moved") : '',
        ".\n";

    $HostFail && print
        &Plural($HostFail, "    %n host%s failed:"),
        &Plural($UrlRetry, " %N url%s could be retried.\n");

    %ExtLink && print &Plural($UrlFailedF , "%N file%s had failed urls.\n");

    $ErrF && $UrlFailF && print
        &Plural($ErrF + $UrlFailedF,
            "There were %n file%s with broken links.\n");

    $CacheNet && print
        &Plural($UrlMod,"    %N url%s %w modified since last reset.\n");
}

#---------------------------------------------------------------------------
# Abbrev($max, $str)
#
#---------------------------------------------------------------------------

sub Abbrev
{
    local($max, $str) = @_;
    length($str) > $max &&  ($str =  substr($str, 0, $max - 4) . " ...");
    $str;
}

#---------------------------------------------------------------------------
# LogFile($filename)
#
#     Changes log file to filename for logging progress.
#---------------------------------------------------------------------------

sub LogFile
{
    local($name) = @_;
    $name || return;

    $LogFile && $LogFile eq $name && return;  # don't reopen same file.

    select(STDERR);
    $LogFile && close($LogFile);
    $LogFile = $name;

    open($LogFile, ">$LogFile") ||
       &Error(qq~could not open file "$LogFile" for output~, 'sys');
    select($LogFile);
}


###########################################################################
#
#    Utilities
#
###########################################################################


#---------------------------------------------------------------------------
# $outcnt = InvertKeys(*in, *out)
#
#     Assumes %in is filled with values like "file1\nfile2\n..."
#     Fills %out with keys file1, file2, ... and each key has values
#     of the keys from %in that refer to it.
#---------------------------------------------------------------------------

sub InvertKeys
{
    local(*in, *out) = @_;
    %in || return %out ? scalar keys %out : 0;

    local(%temp);
    foreach $in (keys %in) {
        %temp = ();
        grep( $temp{$_}++, split(/\n+/, $in{$in}));
        foreach (keys %temp) {
            /\S/ || next;
            $out{$_} ? ($out{$_} .= "\n$in") : ($out{$_} = $in);
        }
    }
    scalar keys %out;
}

#--------------------------------------------------------------------------
# ResolveAnch(*want, *found, *lost)
#
#     named anchors wanted: %want{link#frag} = "ref1 \n ref2 \n ..."
#     named anchors found:  %found{link#frag} = 1
#     Fills *found and *lost as appropriate for found and lost named
#     anchors.  Works for named maps too.
#--------------------------------------------------------------------------

sub ResolveAnch
{
    local(*want, *found, *lost) = @_;

    foreach ( keys %want) {
        /^([^#]*)(#.*)/;                       # $1 will contain filename
        $file = $1;
        $anch = $2;
        $Ignore && $url =~ /$Ignore/o && next; # ignore ignored files
        $Skipped{$file} && next;               # skip anchors in skipped files
        $ref = $want{$_};
        $Mapped{$file} && do {
            $file = $Mapped{$file};
            $Ignore && $url =~ /$Ignore/o && next; # ignore ignored files
            $Skipped{$file} && next;               # skip skipped files
            $_ = "$file$anch";
        };
        $found{$_} ? ($found{$_} = $ref) : ($lost{$_} = $ref);
    }
}

#--------------------------------------------------------------------------
# HashUnique(*hash)
#
#     Assumes values in hash are "val1 \n val2 \n ..."
#     Ensures that each val occurs at most once in each hash value.
#--------------------------------------------------------------------------

sub HashUnique
{
    local(*hash) = @_;
    local(%temp, $key, $val);
    while ( ($key, $val) = each %hash) {
        %temp = ();
        grep($temp{$_}++, split(/\n+/, $val));
        $hash{$key} = join("\n", keys %temp);
    }
}

#--------------------------------------------------------------------------
# Warn(@msg)
#
#     Registers this warning in %Warn.  If $link is supplied we cross
#     reference the warning to $link.
#--------------------------------------------------------------------------

sub Warn
{
    local($msg, $link) = @_;
    (!$link || $link eq 'sys') && do {
        $WarnList{$msg} = "\n";
        &Progress("WARNING: $msg");
        $link && $! && print STDERR "    System message: $!\n";
        return;
    };
    &AppendList(*WarnList,$msg, $link);
}

#--------------------------------------------------------------------------
# WantNumber($val, $flag)
#--------------------------------------------------------------------------

sub WantNumber
{
    local($val, $flag) = @_;
    $val || return;
    $val =~ /^\d+$/ && return;
    &Error("$flag must be followed by an integer");
}

#--------------------------------------------------------------------------
# exit_with(@msg)
#--------------------------------------------------------------------------

sub exit_with { print @_; exit;}

#--------------------------------------------------------------------------
# Error(@msg)
#      Print @msg and exit.
#--------------------------------------------------------------------------

sub Error
{
    local($msg, $flag) = @_;
    print STDERR "\n$prog error: $msg\n";
    @_ > 1 && $flag eq 'sys' && $! && (print STDERR "\nSystem message: $!\n");
    exit;
}

#--------------------------------------------------------------------------
# Progress(@msg)
#--------------------------------------------------------------------------

sub Progress
{
    local($msg) = @_;
    $LogProgress && print $msg, "\n";
    $Quiet && return;
    print STDERR &Abbrev(75, $msg), "\n";
}

#--------------------------------------------------------------------------
# AppendList(*list, $key, $value)
#
#     Adds $value to $list{$key} separates values with "\n" as needed.
#--------------------------------------------------------------------------

sub AppendList
{
    local(*list, $key, $value) = @_;
    $list{$key} ? ( $list{$key} .= "\n$value" ) : ($list{$key} = $value);
}

#--------------------------------------------------------------------------
# PushDir($newdir)
#
#     Pushes current directory onto a stack @DIRS and then
#     chdir's to $newdir.  We Assume that $newdir is a full path!
#     Returns O if there is an error.
#--------------------------------------------------------------------------

sub PushDir
{
    local($new) = @_;
    push(@DIRS,$CWD);
    return $CWD if $new eq $CWD;
    chdir($new) || do {
        &Warn(qq~(pushdir) could not chdir to "$new"~, 'sys');
        return '';
    };
    return($CWD = $new);
}

#--------------------------------------------------------------------------
# PopDir
#
#     Pops most recent directory off of stack @DIRS and
#     changes $CWD and current directory accordingly.
#--------------------------------------------------------------------------

sub PopDir
{
    local($new) = pop(@DIRS);
    return $CWD if $new eq $CWD;
    chdir($new) || do {
         &Warn(qq~(popdir) could not chdir to "$new"~, 'sys');
         return '';
    };
    $CWD = $new;
}

#--------------------------------------------------------------------------
# GetCwd
#
#     Returns a string containing the current working directory
#     "\" is changed to "/" for consistency if $DOS.
#     Sets $CWD to the current working directory.
#--------------------------------------------------------------------------

sub GetCwd
{
    local($_) = `$pwdprog`;   # different prog's for Dos/Unix
    $Dos && do {
        s|\\|\/|g;            # replace \ with /
        s/^([a-zA-Z])://;     # remove drive:
        $DosDrive = $1;       # save drive letter for dochtml printout
    };

    s/\n$//;                  # remove trailing \n
    $CWD = $_;
}

#--------------------------------------------------------------------------
# Regular($exp, $flag)
#
#--------------------------------------------------------------------------

sub Regular
{
    local($exp) = @_;
    $exp =~ s#([^\w/])#\\$1#g;
    $exp;
}

#--------------------------------------------------------------------------
# LinkSet($flag, *in)
#
#     Fills $out with regular exppression made out that is the or'ed
#     of the the specs in @in.  Fills %out with all of the keys
#     that were literal expresions.
#--------------------------------------------------------------------------

sub LinkSet
{
    local($flag, *in) = @_;

    %in = ( '/*', '1' ) if $in{'/*'};     # keep it simple
    local($out) = join( '|', grep( $_ = &LinkSet1($_, $flag),  keys %in));
    $Arg{$flag} = $out;
    $out;
}


#--------------------------------------------------------------------------
# LinkSet1($exp)
#
#    If $exp does not contain ()[]^| or $  then it is converted to a
#    literal expression.  If this expression contains ? or * then these
#    are converted to [^/]* and .* and the whole thing is anchored to the
#    start and end. Otherwise check $exp  to be a valid regular expression.
#--------------------------------------------------------------------------

sub LinkSet1
{
    local($_, $flag) = @_;

    s!([^\w\@#/])!\\$1!g;      # protect special characters

    s!\@!.*!g;          # @ to .* (match any)
    s!#/!#/?!g;         # make / behind # optional
    s!#![^/]*!g;        # '#' to [^/]* (match any but /)

    $_ = "^$_\$";
}

###########################################################################
#
# User Input Routines
#
###########################################################################


#--------------------------------------------------------------------------
# @linkset = ReadFile($file)
#
#     Every infile that starts with "@" is read and its contents are
#     are added to the end of the @infiles list. If an @file contains
#     lines starting with - then the entire line is read in as commands.
#--------------------------------------------------------------------------

sub ReadFile
{
    local($file) = @_;
    local(@argv, @out);
    local($lastarg, $lastflag, $arg);

    $CheckedIn{$file}++ && next;
    if ($file eq "STDIN") {
        $file = \*STDIN;
    }
    elsif ($file) {
        open($file, $file) || &Error(qq~could not open file-list "$file"~, 'sys');
    }
    else {
        $file = \*STDIN;
    }

    while (<$file>) {
        s/^#! ?// && do {print STDERR $_; next; };  # print comments
        m/^#/ && next;
        s/\s+$//;                                # trailing whitespace
        s/^\s+//;                                # leading whitespace

        s/^@@// && ( push(@HttpFiles, $_), next);
        s/^@//  && ( push(@out, &ReadFile($_)), next);

        m/^-/ || (push(@out,  split(/\s+/, $_)), next);

        while( s/("([^"]*)"|(\S+))\s*//) {
            $arg = $+;
            $arg =~ /^-/ && (push(@argv, $lastflag = $lastarg = $arg), next);
            $lastflag && $lastarg !~ /^-/ && $lastflag =~ /-($HashOpts)/o &&
                push(@argv, $lastflag);
            push(@argv, $lastarg = $arg);
        }
    }
    close($file);

    @argv && &ReadArgs(@argv);
    @out;
}

#--------------------------------------------------------------------------
# ReadHttp($file)
#
#     Reads $file and returns every "http://..." it can find.
#     returns the list of links in an array.
#--------------------------------------------------------------------------

sub ReadHttp
{
    local($file) = @_;
    local(@out);

    $file || do {
        $Arg{'doc'} || &Error("@@ must be preceded by -doc linkdoc");
        $file = "$Arg{'doc'}/remoteX.txt";
    };

    $CheckedIn{$file}++ && return;

    open($file, $file) || &Error(qq~could not open http-list "$file"~, 'sys');

    while (<$file>) {
        /^file: remoteX.txt/ && $. == 1 && return &ReadBack($file);
        while ( s#(http://[^\s"><']+)##i) { push(@out, $1); }
    }
    close($file);
    @out;
}

#--------------------------------------------------------------------------
# ReadBack($file)
#
#     Reads in $file as if it were the remoteX.txt file generated by
#     Linklint.  %ExtLink if filled with the cross references found
#     in the file.  Returns a list of all urls found.
#--------------------------------------------------------------------------

sub ReadBack
{
    local($file) = @_;
    local($url, @out);
    while (<$file>) {
        /^#/ && ($url = '', next);                     # new section
        s/\s+$//;                                      # trailing \n
        /^http:/ && (push(@out, $url = $_), next);     # a url to check
        s#^    ## || next;                             # sublist indent
        m#^/# && &AppendList(*ExtLink, $url, $_);      # local link
    }
    close($file);
    @out;
}
#--------------------------------------------------------------------------
# SetHash('name', $key, $value)
#
#     Sets $name{$key} = $value.
#--------------------------------------------------------------------------

sub SetHash
{
    local(*hash, $key, $val) = @_;
    $hash{$key} = $val;
}

#--------------------------------------------------------------------------
# ReadArgs(@args)
#
#     Reads arguments from @args (all start with "-") returns the
#     remainder of @args.   We first check for full flags and options.
#     If these don't match exactly we go through the argument looking
#     for short flags and options 'globbed' together.  Flags set
#     $Arg{'X'} to 1.  For short flags X is the flag, for full flags X
#     is the first character.  Short options set $Arg{'X'} to the next
#     argument.  Full options set $X to the next argument where X
#     is the value from %fullopts. ZZZ Has been modified.
#--------------------------------------------------------------------------

sub ReadArgs
{
    local($name, @out);

    while ( @_ && ($_ = shift)) {
        s/^@@// && ( push(@HttpFiles, $_), next);
        s/^@//  && ( push(@out, &ReadFile($_)), next);
        (m#^/# || m#\.html?$#i || s#^http://#http://#i ) &&
            (push(@out, $_), next);

        s/^-// || &Error( qq~at "$_"~ .
           qq~\nexpected: "-flag" or "/linkset" or "http: ..."\n~ . $ErrUsage);

        if ( /^($MiscFlags)$/o ) {
            $Arg{$1}++;
        }
        elsif (/^($FullOpts)$/o)  {
            (@_ < 1 || $_[0] =~/^-/) &&
                &Error("expected parameter after -$_\n" . $ErrUsage);
            $Arg{$_} =  shift;
        }
        elsif (/^($HashOpts)$/o)  {
            (@_ < 1 || $_[0] =~/^-/) &&
                &Error("expected parameter after -$_\n" . $ErrUsage);
            ($name = $_) =~ tr/a-z/A-Z/;
            &SetHash( $name , shift, 1);
        }
        elsif (/^password$/) {
            (@_ < 2 || $_[0] =~ /^-/ || $_[1] =~ /^-/ ) &&
                &Error("expected 2 parameters after -$_\n" . $ErrUsage);
                $_[1] =~ /:/ ||
                    &Error(qq~expected username:password at "$_[1]"\n~ .
                        $ErrUsage);
                $PASSWORD{$_[0]} = $_[1];
                shift; shift;
        }
        elsif (s/^db//) {
            while($_) {
                s/^([\d])// ||
                    &Error("expected a digit after -db\n" . $ErrUsage);
                $DB{$1}++;
            }
        }
        else {
            &Error("unknown flag -$_\n" . $ErrUsage);
        }
    }
    return (@out, @_);
}

sub HttpInit
{
    local($arg, $db, $pw, $headers, $agent) = @_;
    defined &Http'Init || do {
        unshift(@INC, $HOME);
        require "linkhttp.pl";
    };
    &Http'Init($arg, $db, $pw, $headers, $agent);
}

#==========================================================================
# End of linklint
#==========================================================================



###########################################################################
#
# Http Package
#
# Init(*arg, *db, *pw, *headers, $agent);
#     'timeout'    abort request after timeout seconds
#     'delay'      delay between requests to same host
#     'netset'     resets last modified state in cache
#     'redirect'   search for redirects in files
#     'ignore'
#     'VERSION'
#     'DOS'
#
# OpenBot($botfile)
#
# OpenCache($cachefile)
#
# FlushCache(*validurls)
#
# UrlsFromCache($ok, $retry, $fail)
#     Returns @urls with urls from cache depending on status in cache.
#
# CheckURLS(*urls)
#     Check all http:// urls in @urls and returns %UrlStatus
#     filled with urls and status code.
#
# StatusMsg(*status, *ok, *fail, *warn)
#     Fills %ok, %fail %warn, with urls and error messages
#     from *status.
#
# OtherStatus(*urlmod, *urlmoved, *hostfail, *redirect)
#     Fills hashes with modified, moved, and host fail messeges
#     Fills *redirect with redirected urls and destinations.
#
# WriteCaches()
#
###########################################################################

package Http;

use Socket;

#--------------------------------------------------------------------------
# Init(*arg, *db, *pw, *headers, $agent)
#
#     Sets up global variables. Can be called more than once.
#--------------------------------------------------------------------------

sub Init
{
    local(*arg, *db, *pw, *headers, $agent) = @_;
    %Arg = %arg;
    %DB  = %db;

    @Base64 = ('A'..'Z', 'a'..'z', '0'..'9', '+', '/');

    foreach(keys %pw) {
        $PassWord{$_} = &Base64Encode($pw{$_});
    }

    $TimeOut = $Arg{'DOS'} ? 0 : $Arg{'timeout'} || 0;

    $Delay      = $Arg{'delay'};
    $ResetCache = $Arg{'netset'};

    $UserAgent = "LinkLint-$agent";
    $Arg{'VERSION'} && ($UserAgent .= "/$Arg{'VERSION'}");

    $Proxy = $Arg{'proxy'} || '';
    $Proxy_Port = ($Proxy and $Proxy  =~ s/:(\d*)$//)  ? $1 : '';

    ($DB{7} || $DB{8}) && do {
        print "TimeOut: $TimeOut\n";
        print "User-Agent: $UserAgent\n";
        $Proxy && print "Proxy: $Proxy\n";
        $Proxy_Port && print "Proxy Port: $Proxy_Port\n";
    };

    $TimeOut && do {
        $SIG{'ALRM'} = *AlarmHandler;
        $SIG{'INT'}  = *IntHandler;
    };

    $Init++ && return;

    $CRLF = $Arg{'DOS'} ? "\n" : pack("cc", 13, 10);

    for my $header_line (keys %headers) {
        my ($name, $value) = $header_line =~ m/^([\w\-]+):\s*(.*)/;
        $name && $value or do {
            &main'Warn("Could not parse -http_header $header_line");
            next;
         };
        $name = join "-", map ucfirst, map lc, split /-/, $name;
        $USER_REQ_HEAD{$name} = $value;
        $USER_HEADERS .=  "${CRLF}$name: $value";
    };

    $StatType = "url last-modified cache";
    $BotType  = "robot exclusion cache";

    $NOW = time;

    %FlagOk = (
        200, 'ok (200)',
        201, 'ok created (201)',
        202, 'ok accepted (202)',
        304, 'ok not modified (304)',
      -2000, 'ok parsed html',
      -2001, 'ok skipped',
      -3005, 'ok last-modified date unchanged',
      -3006, 'ok did not compute checksum',
      -3007, 'ok checksum matched',
    );

    %FlagNotMod = (
        304, 1,
      -3005, 1,
      -3006, 1,
      -3007, 1,
    );

    %FlagMoved = (
        301, 'moved permanently (301)',
        302, 'moved temporarily (302)',
      -3003, 'redirected',
    );

    %FlagRetry = (
         -1, 'could not find ip address',
         -2, 'could not open socket',
         -3, 'could not bind socket',
         -4, 'could not connect to host',
         -5, 'timed out waiting for data',
         -8, 'malformed status line',
        -12, 'timed out before anything could happen',
        -14, 'timed out connecting to host',
        -15, 'timed out waiting for data',
        -16, 'timed out reading status',
        -17, 'timed out reading header',
        -18, 'timed out reading data',
        -19, 'timed out getting host ip address',
        502, 'server temporarily overloaded (502)',
        503, 'gateway timeout (503)',
    );

    %FlagWarn = (
         -6, 'not an http link',
         -7, 'no status. Will try GET method',
        -10, 'Disallowed by robots.txt',
        -11, 'infinite redirect loop',
        401, 'access not authorized (401)',
      -4000, 'moved to non-local server',
      -4010, 'invalid username/password (401)',
      -4020, 'unknown authorization scheme (401)',
      -5000, 'user interrupt',
      -6000, 'unknown internal error',
    );

    %FlagFail = (
        204, 'had no content (204)',
        301, 'moved permanently, no new URL (301)',
        302, 'moved temporarily, no new URL (302)',
        400, 'bad request (400)',
        403, 'access forbidden (403)',
        404, 'not found (404)',
        500, 'internal server error (500)',
        501, 'service not implemented on server (501)',
    );

    %FlagBad = (%FlagRetry, %FlagWarn, %FlagFail);
    @FlagDebug = (
        keys %FlagOk, keys %FlagMoved, keys %FlagRetry, keys %FlagFail,
        keys %FlagWarn,
    );
}

#--------------------------------------------------------------------------
# OpenBot($botfile)
#
#     Reads cache of robot exclusion info from $botfile filling %BotExclude.
#     Must be run after Init.
#--------------------------------------------------------------------------

sub OpenBot
{
    local($botfile) = @_;
    &ReadCache($botfile, $BotType, *BotExclude);
}

#--------------------------------------------------------------------------
# OpenCache($cachefile)
#
#     Reads status/last-modified cache from $cachefile int %StatCache
#--------------------------------------------------------------------------

sub OpenCache
{
    local($statfile) = @_;
    &ReadCache($statfile, $StatType, *StatCache);
}

#--------------------------------------------------------------------------
# FlushCache(@valid)
#
#     Removes all entrys in StatCache that do not also occur in *valid
#--------------------------------------------------------------------------

sub FlushCache
{
    @_ || do {
        &main'Warn("Won't flush entire cache.");
        return;
    };
    local(%valid);

    grep( $valid{$_}++, @_);
    local(@delete) = grep( !$valid{$_}, keys %StatCache);
    foreach( @delete) {
        delete $StatCache{$_};
    }
    local($cnt) = scalar @delete;
    &main'Progress("Deleted $cnt entries from cache.");
    @delete && $TaintCache{$StatType}++;
}

#--------------------------------------------------------------------------
# CheckURLS(@urls)
#
#    Checks all http links in @urls
#    Returns hash of urls and status codes.
#--------------------------------------------------------------------------

sub CheckURLS
{
    local($flag, %http);
    grep(s#^http://#http://#i && $http{$_}++, @_);
    local(%checked);

    &main'Progress(
        &main'Plural(scalar keys %http, "\nchecking %d url%s ...\n"));

    foreach $url (sort keys %http) {
        next unless $url =~ m#^http://#i;
        $Arg{'ignore'} && $url =~ m/$Arg{'ignore'}/o && next;
        next if $checked{$url}++;
        $flag = &CheckUrl($url, 0);
        $flag = &UrlMoved($flag, $url);
        $UrlStatus{$url} = $flag;
        if ($Arg{concise_url}) {
            $FlagBad{$flag} and do {
                &main'Progress($url);
                &main'Progress("  " . &ErrorMsg($flag));
            };
        }
        else {
            &main'Progress("  " . &ErrorMsg($flag) );
        }
    }
    %UrlStatus;
}

#--------------------------------------------------------------------------
# $flag = UrlMoved($flag, $url)
#
#     Process 3XX status.  Recheck $url given back in Location field
#     of HEADER.  Continue until
#     a) non-3XX status,  b) infinite loop  c) already checked.
#--------------------------------------------------------------------------

sub UrlMoved
{
    local($flag, $url) = @_;
    local(%checked, $next);

    while ( $FlagMoved{$flag} ) {
        $checked{$url}++ && return -11;                     # infinite loop
        ($next = $HEADER{'location'}) || return $flag;      # this is an error
        $UrlMoved{$url} = $FlagMoved{$flag};
        $Redirect{$url} = $next;
        $UrlStatus{$next} && return $UrlStatus{$next};
        $flag = &CheckUrl($url = $next, 1);
    }
    return $flag;
}

#--------------------------------------------------------------------------
# Parse($host, $link, $referer, *list, *anchlist, *wantanchor)
#
#
#--------------------------------------------------------------------------

sub Parse
{
    local($thishost, $oldlink, $REFERER, @param) = @_;
    local($port) = $thishost =~ s/:(\d+)$// ? $1 : 80;
    local($host) = $thishost;
    local($scheme);
    local($LINK) = $oldlink;
    local($url) = "http://$thishost:$port$LINK";  # for warning messages

#    $HostError{$host} && return ($HostError{$host}, $LINK);

    local(%checked);

    ($flag = &Disallowed($url, 0.5)) && return ($flag, $LINK);

    $flag = &Request($host, $port, $LINK, 'GET', *GetParse, @param);

    while ( $FlagMoved{$flag} ) {
        $checked{$LINK}++ && return (-11, $LINK);         # infinite loop
        ($url = $HEADER{'location'}) || return ($flag, $LINK);

        ($scheme, $host, $port, $LINK) = &SplitUrl($url);
        ($host ne $thishost) && return (-4000, $url);     # non-local server

        &main'WasCached($LINK, $REFERER) && return (0, $LINK);

        $flag = &Request($host, $port, $LINK, 'GET', *GetParse, @param);
    }

    return($flag, $LINK);
}

#--------------------------------------------------------------------------
# $flag = CheckUrl($url, $recheck)
#
#     Returns status of a URL.  Uses the robots.txt protocol.
#     If $Arg{'redirect'} uses "GET" with html files otherwise
#     tries a "HEAD" first and if that fails tries "GET".
#--------------------------------------------------------------------------

sub CheckUrl
{
    local($url, $recheck) = @_;
    local($scheme, $host, $port, $path) = &SplitUrlQ($url);

    return -6 if $scheme ne "http";

    $REQHEAD{'Host'} = $host;

    if ($Arg{concise_url}) {
    }
    elsif ($recheck) {
        &main'Progress("  moved");
        &main'Progress("  $host$path");
    }
    else {
        &main'Progress("$host$path");
    }

    $OpenedCache{$StatType} && ! $recheck && return &CheckModified($url);

    return $Arg{'redirect'} ?
        &Request($host, $port, $path, 'GET', "GetRedirect", $url)
        : &Request($host, $port, $path, "GET" );
}

#--------------------------------------------------------------------------
# CheckModified($url)
#
#     Outer wrapper to see if $url has been modified.
#     Always update status in cache. Always update cache for new entries.
#     Update time, last-mod, checksum if new entry or reset.
#--------------------------------------------------------------------------

sub CheckModified
{
    local($url) = @_;
    local($flag);
    local($_, $time, $mod, $csum) = $StatCache{$url} ?
        split(/\s+/, $StatCache{$url}) : ('0', '0', '0', '0');

    local($nmod, $ncsum) = ($mod, $csum);

    $TIMESTR = &main'TimeStr('GMT', $time);  # for http header

    if ( $mod ne '0') {                      # only check last-mod date

        $flag = &Request($host, $port, $path, "GET" );

        $FlagOk{$flag} && do {

            if ($HEADER{'last-modified'}) {
                ($nmod = $HEADER{'last-modified'}) =~ tr/ /_/;
                $flag = -3005 if ($nmod eq $mod);
            }
            else {  $mod = $nmod = '0';  }
        };
    }

    else {
        $REQHEAD{'if-Modified-Since'} = $TIMESTR;
        $flag = &Request($host, $port, $path, 'GET', "GetModified");
    }

    $csum = -1 if $flag == 304;  # -1: server obeys "if-mod"

    $FlagNotMod{$flag}  || !$FlagOk{$flag} ||
        ($UrlMod{$url} = "modified since " . &main'TimeStr('(local)', $time));

   #---- update cache if -reset or 1st time we get something new

    $FlagOk{$flag} && do {
        $time = $NOW   if $ResetCache || $time eq '0';
        $csum = $ncsum if $ResetCache || $csum eq '0';
        $mod  = $nmod  if $ResetCache || $mod  eq '0';
    };

    local($temp) = join(" ", $flag, $time, $mod, $csum); # create new entry

    #---- update entry in cache if needed

    (!$StatCache{$url} || $StatCache{$url} ne $temp) && do {
        $StatCache{$url} = $temp;
        $TaintCache{$StatType}++;
    };

    $flag;
}

#--------------------------------------------------------------------------
# GetModified($flag, *S)
#
#     Passed to request4().  Only get here if file was modified or
#     "If-Modified-Since" was ignored.  Check last-mod date 1st.
#     then check checksum only if they ask and if the $time was > 0.
#     If $csum == -1 then don't bother with checksum.
#--------------------------------------------------------------------------

sub GetModified
{
    local($flag, *S) = @_;

    $HEADER{'last-modified'} && do {                     # use this info
        ($nmod = $HEADER{'last-modified'}) =~ tr/ /_/;
        return $flag if $mod ne '0' && ($nmod ne $mod);  # modified
        return -3005;                                    # not modified
    };

    $csum == -1 && return $flag;    # modified: obeyed "if-mod" before

    return -3006 unless $Arg{'checksum'} && $time != 0; # don't checksum

    &main'Progress("    computing checksum");

    $ncsum = 0;

    while (<S>) {  $ncsum += unpack("%32C*", $_);  }     # compute csum

    return $flag if $csum ne '0' && ($ncsum != $csum);   # modified
    return -3007;                                        # not modified
}

#--------------------------------------------------------------------------
# UrlsFromCache($ok, $retry, $fail)
#
#    Returns @urls with urls from the cache depending on the last
#    status of the url in the cache.
#--------------------------------------------------------------------------

sub UrlsFromCache
{
    local($ok, $retry, $fail) = @_;
    local(@urls);
    $OpenedCache{$StatType} || &main'Warn("No url cache to read from.");

    local($url, $cache, $flag);
    while( ($url, $cache) = each %StatCache ) {
        ($flag) = split(" ", $cache);
        push(@urls, $url) if
            ($fail  && $FlagWarn{$flag}  ) ||
            ($fail  && $FlagFail{$flag}  ) ||
            ($ok    && $FlagOk{$flag}    ) ||
            ($retry && $FlagRetry{$flag} );
    }
    @urls;
}

#--------------------------------------------------------------------------
# Recheck(@urls)
#
#     Returns only those urls that need to be retried.
#--------------------------------------------------------------------------

sub Recheck
{
    local(%retry);
    grep( $retry{$_}++, &UrlsFromCache(0, 1, 0));
    grep( $retry{$_}, @_);
}

#--------------------------------------------------------------------------
# $flag = Disallowed($url)
#
#     Checks robots.txt file for $url.  Results are cached for each host.
#     Returns:
#        -10  if access is excluded by robots.txt
#          0  if access is allowed
#        < 0  if < 0 (non-http) error occured
#--------------------------------------------------------------------------

sub Disallowed
{
    local($url, $expire) = @_;
    local($scheme, $host, $port, $path) = &SplitUrl($url);
    local($flag);

    $BotExclude{$host} && do  {
        local($time, $xpath) = split(/\s+/, $BotExclude{$host});
        local($secs) = 60 * 60 * 24 * ($expire || 30);
        $time + $secs >= $NOW && do {
            $xpath eq 'ok' && return 0;
            return ($path =~ m/^$xpath/) ? -10 : 0;
        };
    };

    &main'Progress("    checking robots.txt for $host");
    $flag = &Request($host, $port, "/robots.txt", "GET", "GetText", 100);

    return $flag if $FlagRetry{$flag};

    $BotExclude{$host} = time . " ok";    # default value
    $TaintCache{$BotType}++;              # need to write a new file

    return 0 unless $FlagOk{$flag};

    $_ = join("", @DATA);
    s/\r\n?/\n/g;                 # end-of-line = \r | \n | \r\n
    @DATA = split(/\n/, $_);
    local(@agents, @disallow);
    push(@DATA, " ");             # ensure last group gets proccessed
    foreach (@DATA) {
        next if /^\s*#/;
        s/\s+$//;
        if ( /^$/ ) {
           if (@disallow && @agents) {
               $_ = join(" ", @disallow);   # prepare for use as regexp
               s#([^\w\s/])#\\$1#g;         # literal search (pretty)
               s/\s+/\|/g;
               $BotExclude{$host} = "$NOW $_";
               last if grep(/linklint/i, @agents);
           }
           @agents = @disallow = ();
           next;
        }

        s/\s*#.*$//;   # trailing comments

        if ( m/^\s*(User.?Agent|Robot)s?\s*:\s+(\S+.*\S?)\s*$/i) {
            push(@agents, $2);
        }
        elsif ( m/^\s*Disallow\s*:\s+(\S+.*\S?)\s*$/i) {
           next unless grep(/(linklint|\*)/i, @agents);
           push(@disallow, $1);
        }
    }
    return &Disallowed(@_);   # only recurse once. Relies on BotExclude{host}
}


#--------------------------------------------------------------------------
# GetParse($flag, *S, $link, *newlinks, *Anchor, *wantanch);
#
#     Parse html via remote http connection.
#--------------------------------------------------------------------------

sub GetParse
{
    local($flag) = shift;
    local($handle) = shift;

    &main'AppendList(*main'FileList, $LINK, $REFERER);
#    &main'CacheDir($LINK);

    $HEADER{'content-type'} =~ m#^text/html#i || return $flag;

    &main'StopRecursion($LINK, $REFERER) && return -2001;
    &main'Progress("Checking $LINK");
    &main'ParseHtml($handle, $LINK, @_);

    return -2000;           # parsed the file
}


#--------------------------------------------------------------------------
# GetRedirect($flag, 'S', $url)
#
#     Passed to request4() by CheckUrl() to parse for redirects in header.
#--------------------------------------------------------------------------

sub GetRedirect
{
    local($flag) = shift;
    $HEADER{'content-type'} =~ m#^text/html#i || return $flag;

    local($redir) = &main'ParseRedirect(@_);
    $redir || return $flag;
    $HEADER{'location'} = $redir;
    return -3003;
}

#--------------------------------------------------------------------------
# GetText($flag, *S, $lines)
#
#     Passed to request4() to read $lines of text into @DATA.
#     For now @DATA is a global.
#--------------------------------------------------------------------------

sub GetText
{
    local($flag, *S, $lines) = @_;

    $HEADER{'content-type'} =~ /^text/ || return $flag;

    while ( <S> ) {                    # read $lines into @DATA
        push(@DATA, $_);
        $lines && (--$lines || last);
    }
    $flag;
}

#--------------------------------------------------------------------------
# $flag = Request($host, $port, $path, $method, *getmethod, @params)
#
#     Handles host errors. Flags bad hosts. Caches host errors.
#     Calls Request2(). Will retry if more than one IP address is given
#     by gethostbyname() and we get StatRetry errors.
#
#     Use subroutine getmethod($flag, 'S', @params) if given
#     to read data after the header.  I don't have a great method for
#     sending data back at the moment.  Use globals for now.
#--------------------------------------------------------------------------

sub Request
{
    my ($host, $port, $path, @other) = @_;
    my $flag;

    $REQHEAD{Host} = $host;
    if ($Proxy) {
        my $v_url = "http://$host";
        $port and $v_url .= ":$port";
        $v_url .= $path;

        $flag = Request2($Proxy, $Proxy_Port, $v_url, @other);
    }
    else {
        $flag = &Request2(@_);
    }
    %REQHEAD = ();
    return $flag;
}

sub Request2
{
    local($_,  $flag, $realm, $pw, $auth);
    $flag = &Request3(@_);
    $flag == 401 || return $flag;

    ($auth = $HEADER{'www-authenticate'}) || do {
        &main'Warn(qq~missing authentication~, $url);
        return -4020;
    };

    $auth =~ m/\s*basic\s+realm\s*=\s*"([^"]*)"/i || do {
        &main'Warn(qq~unknown authorization scheme: $auth~, $url);
        return -4020;
    };

    $realm = $1;

    if ( $pw = $PassWord{$realm} || $PassWord{'DEFAULT'} ) {
        $REQHEAD{'Authorization'} = "Basic $pw";
        $flag = &Request3(@_);
        $flag != 401 && return $flag;
        &main'Warn(qq~invalid password for "$realm"~);
        return -4010;
    }
    else {
        &main'Warn(qq~need password for "$realm"~);
        return $flag;
    }
}

sub Request3
{
    local($host) = shift;

    local($flag) = &Request4($host, @_);

    return $flag unless $FlagRetry{$flag};

    $IpAddr2{$host} || return &HostError($host, $flag);

    #----- try alternate ip addresses

    foreach (split(/\n/, $IpAddr2{$host})) {
        &main'Progress("Warning: $host $IpAddr{$host}");
        &main'Progress("    Error: $FlagRetry{$flag}");

        &main'Progress("    checking server $_");

        $flag = &Request4($_, @_);
        next if $FlagRetry{$flag};

        $IpAddr{$host} = $_;         # save good one as the default
        return $flag;
    }
    &HostError($host, $flag);        # all servers for this host are down
}

#--------------------------------------------------------------------------
# HostError($host, $flag)
#
#     Fills %HostError with $flag, fills %HostFail with error message.
#     Returns $flag.
#--------------------------------------------------------------------------

sub HostError
{
    local($host, $flag) = @_;
    $HostFail{$host} = &ErrorMsg($flag);
    $HostError{$host} = $flag;
}

#--------------------------------------------------------------------------
# $flag = Request4($host, $port, $path, $method, 'getmethod', @params)
#
#     Fills %HEADER with header info,
#     Uses globals set by Init().
#     $flag is error (or success) flag see %Httpxxx for details.
#     Will use getmethod($flag, 'S', @params) to read data.
#--------------------------------------------------------------------------

sub Request4
{
    local($host, $port, $path, $method, $getmethod, @params) = @_;
    local($request, $ipaddr, $flag);
    $port = $port || 80;

    %HEADER = ();             # global %HEADER holds http header info.

    $DB{9} && do {
#        $HEADER{'location'} = 'http://dum/dum';
        return $flag = $FlagDebug[ int (rand(@FlagDebug)) ];
    };

    (($ipaddr,$flag) = &GetIpAddress($host));
    $flag && return $flag;

    $Delay && sleep($Delay);

    $DB{7} && print
        "\n$method http://$host$path\n",
        "host ip: $IpAddr{$host}\n";

    $request = "$method $path HTTP/1.0";

    $USER_HEADERS and $request .= $USER_HEADERS;

    $REQHEAD{"User-Agent"} = $UserAgent;

    for my $name (sort keys %REQHEAD) {
        $USER_REQ_HEAD{$name} and next;
        $request .= "${CRLF}$name: $REQHEAD{$name}";
    }

    $ALARMFLAG = -12;

    $@ = '';

    $TimeOut && alarm($TimeOut);

    $SOCKETOPEN = 0;

    eval {
        $flag = &FragileRequest($ipaddr, $request, $getmethod || \NUL, @params);
    };

    $TimeOut && alarm(0);

    $SOCKETOPEN && close(S);
    $SOCKETOPEN = 0;
    $@ || return $flag;
    $@ =~ /^timeout/ && return $ALARMFLAG;
    $@ =~ /^user interrupt/ || return -6000;
    print STDERR "\nUser Interrupt.\n",
        "Interrupt again to abort or wait 2 seconds for linklint to resume\n";
    sleep(2);
    return -5000;
}


#--------------------------------------------------------------------------
# FragileRequest($ipaddr, $request, *getmethod, @params)
#
#    Actually sends $request, and reads status, header and data from socket.
#    Should be called from within an eval() to implement timeout.
#--------------------------------------------------------------------------

sub FragileRequest
{
    local($ipaddr, $request, *getmethod, @params) = @_;

    my $iaddr = inet_aton($ipaddr);
    my $paddr = sockaddr_in($port, $iaddr);

    my $proto    = getprotobyname('tcp');
    socket(S, PF_INET, SOCK_STREAM, $proto) or
      return -2;

    $SOCKETOPEN = 1;

    $ALARMFLAG = -14;                  # "connecting to host"

    $DB{4} && &main'Progress("    Connecting");

    connect(S, $paddr) || return -4;    # -4: could not connect

    $DB{4} && &main'Progress("    Connect successful");

    $ALARMFLAG = -15;                  # "waiting for data";

    local($lastsel) = select(S); $| = 1; select($lastsel);

    $DB{8} && print "\n$request\n\n";

    print S "$request$CRLF$CRLF";

#    $TimeOut && do {
#        local($rin) = '';
#        vec($rin, fileno(S), 1 ) = 1;
#        select($rin, undef, undef, $TimeOut ) || return -5;
#        $ALARMFLAG = -16;  # "reading status"
#    };

    $_ = <S>;                          # read status line
    $_ || return -7;                   # -7: no status  (will try GET)

    $TimeOut && alarm($TimeOut);

    s/\s*$//;

    $flag = /^\s*\S+\s+(\d+)/ ? $1 : -8;  # -8: Malformed status line

    ($DB{7} || $DB{8}) && print "$_\n";

    $flag == -8 && return $flag;

    $ALARMFLAG = -17; # "reading header";

    local($name);
    while  ( <S> ) {                      # put header info into %HEADER
        s/\s*$//;
        $DB{8} && print "$_\n";
        ($DB{7} && $DB{8}) && next;
        last unless m/\w/;
        next unless m/(\S+):\s+(\S*.*\S*)\s*$/;
        ($name = $1) =~ tr/A-Z/a-z/;
        $HEADER{$name} = $2;
    }

    $flag == 200 && @_ > 2 && defined &getmethod && do {


        $ALARMFLAG = -18;                        # "reading data"
        return &getmethod($flag, *S, @params);
    };

    return $flag;
}

sub AlarmHandler
{
   die "timeout";
}

sub IntHandler
{
   die "user interrupt";
}

#--------------------------------------------------------------------------
# GetIpAddress($host)
#
#     Returns UNpacked IP address for host. Caches the address in
#     $IpAddr{$host}, caches alternate IP addresses in $IpAddr2{$host}.
#--------------------------------------------------------------------------

sub GetIpAddress
{
    local($host) = @_;

    local($_, @addrlist);

    $host =~ m/(\d+)\.(\d+)\.(\d+)\.(\d+)/ &&
        ($IpAddr{$host} = $host);

    $IpAddr{$host} && return ($IpAddr{$host}, 0);     # use cached ip address

    $TimeOut && alarm($TimeOut);

    eval('($_,$_,$_,$_, @addrlist) = gethostbyname($host)');
    $TimeOut && alarm(0);
    $@ && $@ =~ /^timeout/ && return (0, -19);


    @addrlist ||  return (0, -1);                      # could not find host

    grep($_ = join(".", unpack("C4", $_) ), @addrlist);

    $IpAddr{$host} = shift @addrlist;            # 1st one is default
    $IpAddr2{$host} = join("\n", @addrlist);     # save others just in case
    return ($IpAddr{$host}, 0);
}

#--------------------------------------------------------------------------
# SplitUrl($url)
#
#     Split the given URL into its component parts according to HTTP rules.
#     returns ($scheme, $host, $port, $path, $query, $frag)
#--------------------------------------------------------------------------

sub SplitUrl
{
    local($_)     = $_[0];
    local($scheme)  = s#^(\w+):## ? $1 : '';
    local($host)    = s#^//([^/]*)##        ? $1 : '';
    local($port)    = $host =~ s/:(\d*)$//  ? $1 : '';
    local($query)   = s/\?(.*)$//           ? $1 : '';
    local($frag)    = s/#([^#]*)$//         ? $1 : '';
    $scheme =~ tr/A-Z/a-z/;
    $_ = $_ || '/';
    return ($scheme, $host, $port, $_, $query, $frag);
}

#--------------------------------------------------------------------------
# SplitUrl($url)
#
#     Split the given URL into its component parts according to HTTP rules.
#     returns ($scheme, $host, $port, $path, $query, $frag)
#--------------------------------------------------------------------------

sub SplitUrlQ
{
    local($scheme, $host, $port, $path, $query) = &SplitUrl(@_);
    $query && ( $path .= "?" . $query);
    return ($scheme, $host, $port, $path);
}

#--------------------------------------------------------------------------
# StatusMsg(*all, *ok, *fail, *warn)
#
#    Fills %ok, %fail, %retry with urls and error MESSAGES from
#    urls and error FLAGS in %all.
#--------------------------------------------------------------------------

sub StatusMsg
{
    local(*all, *ok, *fail, *warn) = @_;
    while ( ($url, $flag) = each %all) {
        $msg = &ErrorMsg($flag);
        $FlagOk{$flag}    && ($ok{$url}    = $msg,  next);
        $FlagWarn{$flag}  && ($warn{$url}  = $msg,  next);
        $fail{$url} = $msg;
    }
}

sub RetryCount
{
    local(*flags) = @_;
    scalar grep($FlagRetry{$_}, values %flags);
}

#--------------------------------------------------------------------------
# ErrorMsg($flag)
#
#    Returns the error message associated with flag.
#--------------------------------------------------------------------------

sub ErrorMsg
{
    local($flag) = @_;

    $DB{6} || ($FlagOk{$flag} && return 'ok');

    $FlagOk{$flag}    ||
    $FlagFail{$flag}  ||
    $FlagWarn{$flag}  ||
    $FlagRetry{$flag} ||
    "unknown error ($flag)";
}

#--------------------------------------------------------------------------
# OtherStatus(*urlmod, *hostfail, *urlmoved, *redirect)
#
#     Fills hashes with modified, moved, and host fail messeges
#     Fills *redirect with redirected urls and destinations.
#--------------------------------------------------------------------------

sub OtherStatus
{
    local(*urlmod, *hostfail, *urlmoved, *redirect) = @_;
    %urlmod   = %UrlMod;
    %urlmoved = %UrlMoved;
    %hostfail = %HostFail;
    %redirect = %Redirect;
}


#--------------------------------------------------------------------------
# ReadCache($file, $type, *hash)
#
#     Reads $file, looking for key val1 on each line.
#     Fills hash{key} = val1.  Skips entries that have expired.
#     Sets $OpenedCache{$type} to $file for writing later.
#     Also used to only read the cache file once.
#--------------------------------------------------------------------------

sub ReadCache
{
    local($file, $type, *hash) = @_;
    $OpenedCache{$type} && return;
    $OpenedCache{$type} = $file;
    open(CACHE, $file) || return;

    ($DB{7} || $DB{8}) && &main'Progress(qq~reading $type from "$file"~);

    foreach (<CACHE>) {
        /^#/ && next;
        /^(\S+)\s+(\S+)\s+(\S.*\S)\s*$/ || next;
        $hash{$1} = "$2 $3";
    }
    close(CACHE);
}

#--------------------------------------------------------------------------
# WriteCaches()
#--------------------------------------------------------------------------

sub WriteCaches
{
    &WriteCache($BotType,  *BotExclude);
    &WriteCache($StatType, *StatCache);
}

#--------------------------------------------------------------------------
# WriteCache($type, *hash)
#
#     Writes key(hash1) value(hash1) to file.  Preceded by $header.
#     Will only write if cache was opened via ReadCache() and if the
#     cache has been tainted via %TaintCache.
#--------------------------------------------------------------------------

sub WriteCache
{
    local($type, *hash) = @_;
    local($file) = $OpenedCache{$type} || return;
    ($TaintCache{$type} && %hash) || return;

    open(CACHE, ">$file") || do {
        &main'Warn(qq~Could not write $type to "$file"\n~, 'sys');
        return;
    };

    local($header) =
        "# $type created by linklint\n" .
        "# Use -cache flag or set environment variable LINKLINT to\n" .
        "# to change this file's directory.\n\n";

    print CACHE $header;

    foreach ( sort keys %hash ) {
        print CACHE "$_ $hash{$_}\n";
    }

    close CACHE;
    &main'Progress(qq~\nWrote $type to "$file"~);
}

sub FlagOk
{
    $FlagOk{$_[0]} ? 1 : 0;
}

sub FlagWarn
{
    $FlagWarn{$_[0]} ? 1 : 0;
}


sub Base64Encode
{
    local($plain) = @_;
    local($out, @out);
    local(@bits) = split(//, unpack('B*', $plain));
    while (@bits > 0) {
       $out = join('', splice(@bits, 0, 6));
       while (length($out) < 6) { $out .= '0' };
       push(@out, $Base64[hex(unpack('H*', pack('B8', "00$out")))]);
    }
    while ( @out % 4) { push(@out, "="); }
    join('', @out);
}

sub d_u_m_m_y { $main'FileList = 0 }

1;                     # required packages must return true

=encoding utf8

=head1 NAME

Linklint - fast link checker and website maintenance tool

=head1 SYNOPSIS

B<linklint>
[B<-cache I<directory>>]
[B<-case>]
[B<-checksum>]
[B<-concise_url>]
[B<-db1..9>]
[B<-delay I<d>>]
[B<-doc>]
[B<-docbase I<base>>]
[B<-dont_output I<xxxx>>]
[B<-error>]
[B<-flush>]
[B<-forward>]
[B<-help>]
[B<-help_all>]
[B<-host I<hostname:port>>]
[B<-host I<hostname>>]
[B<-htmlonly>]
[B<-http>]
[B<-http_header I<name:value>>]
[B<-ignore I<ignoreset>>]
[B<-index I<file>>]
[B<-language I<zz>>]
[B<-limit I<n>>]
[B<-list>]
[B<-local I<linkset>>]
[B<-map I</a=[/b]>>]
[B<-net>]
[B<-netmod>]
[B<-netset>]
[B<-no_anchors>]
[B<-no_query_string>]
[B<-no_warn_index>]
[B<-orphan>]
[B<-out I<file>>]
[B<-output_frames>]
[B<-output_index I<filename>>]
[B<-password I<realm user:password>>]
[B<-proxy I<hostname[:port]>>]
[B<-quiet>]
[B<-redirect>]
[B<-retry>]
[B<-silent>]
[B<-skip I<skipset>>]
[B<-textonly>]
[B<-timeout I<t>>]
[B<-url_doc_prefix I<url/>>]
[B<-version>]
[B<-warn>]
[B<-xref>]
I<linkset>

=head1 VERSION

2.3.5 August 13, 2001

=head1 DESCRIPTION

This manual page documents briefly the Linklint program, which is an
Open Source Perl program that checks local and remote HTML links.

This manual page was written for the Debian distribution because the
original program does not have a manual page.  Instead, it has
documentation in the HTML format; see below.

=head1 OPTIONS

=head2 Input File Selection

Whether you are doing a local site check or an HTTP site check, you
specify which directories (presumably containing HTML files) to check
with one or more linksets. A linkset uses two wildcard characters
@ and #.
Each linkset specifies one or more directories much like the standard
* and ? wildcard characters are used to specify the characters in the
* names of files in one directory.

The @ character matches any string of characters (this kind of acts like
"*"), and the # character (which is kind of like "?") matches any string
of characters except "/" . The best way to understand how @ and # work
is to look at a few examples:

                          the entire site /@
              the homepage only (default) /
         files in the root directory only /#
             . . . and one directory down /#/#
          files in the sub directory only /sub/#
     files in the sub directory and below /sub/@
                           specific files /file1 /file2 ...
                  specific subdirectories /sub1/@ /sub2/@ ...

If you specify more than one linkset, files matching any of the linksets
will be checked. HTML files that don't match any of the linksets will be
skipped. Linklint will see if they exist but won't check any of their
links.

=head2 Other File Selection Options

=over 4

=item B<-skip> I<skipset>

Skips HTML files that match I<skipset>.  C<Linklint> will make sure
these files exist but won't add any of their links to the list of files
to check.  Multiple I<skipsets> are allowed, but each must be preceded
with B<-skip> on the command line. Skipsets use the same wildcard
characters as linksets.

=item B<-ignore> I<ignoreset>

Ignores files matching I<ignoreset>.  C<Linklint> doesn't even check to
see if these files exist.  Multiple I<ignoresets> are allowed, but each
must be preceded with B<-ignore> on the command line.  Ignoresets use
the same wildcard characters as linksets.

=item B<-limit> I<n>

Limits checking to I<n> HTML files (default 500).  All HTML files after
the first I<n> are skipped.

=back

=head2 Local Site Checking

If you are developing HTML pages on a computer that does not have an
http server, or if you are developing a simple site that does not use
Server Redirection or extensive CGI, you should use local site checking.

     linklint /@

Checks all HTML files in the current directory and below. Assumes that
the current directory is the server root directory so links starting
with "/" default to this directory. You must specify B</@> to check the
entire site. See Which Files to Check for details.

     linklint -root dir /@

Checks all HTML files in dir and below. This is useful if you want to
check several sites on the same machine or if you don't want to run
Linklint in your public HTML directory.

=head2 Other Local Site Options

=over 4

=item B<-host> I<hostname>

By default C<Linklint> assumes all links on your site that start with
C<http://> are remote links to other sites.  If you have absolute links
to your own site, give C<Linklint> your hostname and links starting with
C<http://hostname> will be treated as local files.  If you specify
B<-host hostname:port,> only http links to this hostname and port will
be treated as local files.

=item B<-case>

Makes sure that the filename (upper/lower) case used links inside of
html tags matches the case used by the file system.  This is for
Windows only and is very handy if you are porting a site to a Unix
host.

=item B<-orphan>

Checks all directories that contain files used on the site for unused
(orphan) files.

=item B<-index> I<file>

Uses I<file> as the default index file instead of the default list used
by C<Linklint>. You can specify more than one file but each one must be
preceded by B<-index> on the command line.  If a default index file is
not found, C<Linklint> uses a listing of the entire directory. See the
Default File section for details.

=item B<-map> I</a=[/b]>

Substitutes leading I</a> with I</b>.  For server-side image maps or to
simulate Server Redirection.

=item B<-no_warn_index>

Turns of the "index file not found" warning.  Applies to local site
checking only.

=item B<-no_anchors>

Tells C<Linklint> to ignore named anchors.  This could ease memory
problems for people with large sites who are primarily interested in
missing pages and not missing named anchors.  This option works for
both HTTP and local site checks.

=back

=head2 HTTP Site Checking

If you have a complicated site that uses lots of CGI or Server
Redirection, you should use HTTP site checking. Even though an HTTP
site check reads pages via your HTTP server, you will get the best
performance if you do your checking on a machine that has a high speed
connection to your server.

     linklint -http -host www.site.com /@

The B<-http> flag tells C<Linklint> to check HTML files on the site
www.site.com via a remote http connection. You must specify a -host
whenever you do an HTTP site check (otherwise Linklint won't where to
get your pages). You can specify B</@> to check the entire site.  See Which
Files to Check for details.

=head2 HTTP Site Check Options

=over 4

=item B<-http>

This flag tells Linklint to perform an HTTP site check instead of a
local site check.  All files (except server side image maps) will be
read via the HTTP protocol from your web server.

=item B<-host> I<hostname:port>

If you include I<:port> at the end of your
hostname, Linklint uses this port for the HTTP site check.

=item B<-password> I<realm user:password>

Uses I<user> and I<password> as authorization to enter password
protected I<realm.> Realms are named areas of a site that share a common
set of usernames and passwords.  If passwords are needed to check your
site, Linklint will tell you which realms need passwords in warning
messages.  Enclose the realm in double quotes if it contains spaces.  If
no password is given for a specific realm, Linklint will try using the
password for the "C<DEFAULT>" realm if it was provided.

=item B<-timeout> I<t>

Times out after I<t> seconds (default 15) when
getting files via http.  Once data is received, an additional
I<t> seconds is allowed.  The timeout is
disabled on Windows machines since the Windows port of Perl does not
support the C<alarm()> function.

=item B<-delay> I<d>

Delays I<d> seconds between requests to the same
host (default 0).  This is a friendly thing to do especially if you are
checking many links on the same host.

=item B<-local> I<linkset>

Gets files that match I<linkset> locally.  The default B<-local>
I<linkset> is B<@.map> (which matches any link ending in F<.map>).  This
allows Linklint to follow links through server-side image maps.  The
default is ignored if you specify your own B<-local> expressions.  You
need to specify the B<-root> directory for this option to work propery.

=item B<-map> I</a=[/b]>

Substitutes leading I</a> with I</b>.  For server-side image maps or to
simulate Server Redirection.

=item B<-no_anchors>

Tells C<Linklint> to ignore named anchors.

=item B<-no_query_string>

Up until version 2.3.4, Linklint did not use query strings while doing
HTTP site checks.  Query strings were removed before making HTTP
requests.  As of 2.3.4 query strings in links are used in the
requests.  Use the B<-no_query_string> flag to get back the "old"
behavior.

=item B<-http_header> I<Name:value>

Adds the HTTP header I<Name: value> to all HTTP requests
generated by Linklint.  You will need to use quotation marks to hide
spaces in the header line from the command line interpreter. Linklint
will automatically add a space after the first colon if there is not
one there already.  Multiple (unique) header lines are allowed.

=item B<-language> I<zz>

This option is only useful if you are checking a site that uses
content negotiation to present the same URL in different languages.

Creates an HTTP Request header of the form
B<Accept-Language: zz> that is included as part of all HTTP
requests generated by Linklint.  Multiple B<-language>
specifications are allowed.  This will result in a single
B<Accept-Language:> header that lists all of the languages you
have specified in alphabetical order.  Some web sites can use this
information to return pages to you in a specific language.

If you need to get more complicated than this, use the more general
purpose B<-http_header> to create your own header.  There is a partial
list of language abbreviations (taken from Debian) included as part of
the Linklint documentation.

=back

=head2 Remote URL Checking

A remote URL check is used to see if a remote URL exists (or has been
recently modified). Links in the remote pages are not checked nor does
Linklint look for named anchors in remote URLs.
     
Remote URL checking can be used to check all of the "remote" links on
your site (those that link to pages on other sites) or it can check a
list of URLs. There are several ways to specify which remote URLs to
check:
     
     linklint http://somehost/file.html

Checks to see if F</file.html> exists on somehost. Multiple URLs can be
entered on the command line, in an I<@commandfile>, or in an
I<@@httpfile>.  Every URL to be checked must begin with C<http://>. This
will disable site checking.
     
     linklint @@httpfile

Checks all the remote http URLs found in httpfile. Anything in the file
starting with C<http://> is considered to be a URL. If the file looks
like a F<remoteX.txt> file generated by Linklint then all failed URLs will
be cross referenced.
     
     linklint @@ -doc linkdoc

Assuming you have already done a site check and used B<-doc linkdoc> to
put all of your output files in the linkdoc directory, Linklint will
check all the remote links that were found on your site and cross
reference all failed URLs without doing a site check. You can use the
B<-netmod> or B<-netset> flags to enable the status-cache.
     
     linklint -net [site check options]

The B<-net> flag tells Linklint to check all remote links after doing
either a local or HTTP site check site. If you are having memory
problems, don't use the B<-net> option, instead use one of the B<@@>
options above.

=head2 Other Remote URL Options

=over 4

=item B<-timeout> I<t>

Times out after I<t> seconds (default 15) when getting files via http.
Once data is received, an additional I<t> seconds is allowed.  The
timeout is disabled on Windows machines since the Windows port of Perl
does not support the C<alarm()> function.

=item B<-delay> I<d>

Delays I<d> seconds between requests to the same host (default 0).  This
is a friendly thing to do especially if you are checking many links on
the same host.

=item B<-redirect>

Checks for E<lt>metaE<gt> redirects in the headers of remote  URLs that
are html files.  If a redirect is found it is followed.  This feature is
disabled if the status cache is used.

=item B<-proxy> I<hostname[:port]>

Sends all remote HTTP requests through the proxy server I<hostname> and
the optional I<port>.  This allows you to check remote URLs or (new with
version 2.3.1) your entire site from within a firewall that has an http
proxy server.  Some error messages (relating to host errors) may not be
available through a proxy server.

=item B<-concise_url>

Turns off printing successful URLs to STDOUT during remote link
checking.

=back

=head2 Status Cache Options

The Status Cache is a very powerful feature. It allows you to keep track
of recent changes in all of the remote (off-site) pages you link to. You
can then use the Linklint output files to quickly check changed pages to
see if they still meet your needs.
     
The flags below make use of the status cache file linklint.url (kept in
your HOME or LINKLINT directory). This file keeps track of the
modification dates of all the remote URLs that you check.

=over 4

=item B<-netmod>

Operates just like B<-net> but makes use of the status cache.  Newly
checked URLs will be entered in the cache.  Linklint will tell you which
(previously cached) URLs have been modified since the last B<-netset>.

=item B<-netset>

Like B<-netmod> but also resets the last modified status in the cache
for all URLs that checked ok.  If you always use B<-netset>, modified
URLs will be reported just once.

=item B<-retry>

Only checks URLs that have a host fail status in the cache.  Sometimes a
URL fails because its host is temporarily down.  This flag enables you
to recheck just those links.  An easy way to recheck all the cached URLs
with host failures is C<linklint @@ -retry>.  Use
C<linklint @@linkdoc/remoteX.txt -retry> if you want failed URLs to be
cross referenced.

=item B<-flush>

Removes all URLs from the cache that are not currently being checked.
The B<-retry> flag has no effect on which URLs are flushed.

=item B<-checksum>

Ensures that every URL that has been modified is reported as such.  This
flag can make the remote checking take longer.  Many of the pages that
require a checksum are dynamically generated and will always be reported
as modified.

=item B<-cache> I<directory>

Reads and writes the F<linklint.url> cache file in this directory.  The
default directory is set by your LINKLINT or HOME environment variables.

=back

=head2 Output Options

No output files are generated by default, only progress and a brief
summary of the results are printed to the screen. You can produce
complete documentation (split up into separate files) in a B<-doc>
directory or put selected output in a single B<-out> file or by
redirecting the standard output to a file. See the Output File
Specification section for a detailed description of all output files.

=head2 Multi File Output

=over 4

=item B<-doc> I<linkdoc>

Sends all output to the I<linkdoc> directory.  The output is divided
into separate F<.txt> and F<.html> files.  Complete documentation is
always produced regardless of the single file flags.

The file F<index.txt> contains an index to all the other files;
F<index.html> is an HTML version of the index.  The index files for
remote URL checking are F<ur_lindex.txt> and F<url_index.html>.

=item B<-textonly>

Prevents any HTML files from being created in the B<-doc> directory.

=item B<-htmlonly>

Erases redundant text files in the B<-doc> directory after they have
been used to create the HTML output files.  The files F<remote.txt> and
F<remoteX.txt> are not erased since they can be used by Linklint to
recheck remote URLs.

=item B<-docbase> I<base>

Overrides the default I<base> expression used for directing a browser to
the resources listed in the output HTML files.  The base is prepended to
local links in the output HTML files.  This only affects the links in
HTML output files, it has no effect on what is displayed in these files.
Ordinarily this flag would only be used during a local site check to set
the base to C<http://host>.

=item B<-output_frames>

All HTML output data files are linked to from F<index.html>.  If you use
this flag then the the data files will be opened up in a new frame
(window) which can be handy in some cases since it always leaves the
F<index.html> file open in its own window.

=item B<-output_index> I<filename>

The output index files were previously named F<linklint.txt> and
F<linklint.html>.  These have now been changed to F<index.txt> and
F<index.html>.  You can use the B<-output_index> option to change this
name back to C<linklint> or to something else.

=item B<-url_doc_prefix> I<url/>

By default, the output files associate with remote URL checking all
start with "url".  You can change this with the B<-url_doc_prefix>
option.  If the url_doc_prefix contains a "/" character then the
appropriate directory will be created (as a subdirectory of the -doc
directory).

=item B<-dont_output> I<xxxx>

Don't create output files that contain "xxxx".  Can be repeated.
Example:

        -dont_output "X$"

will supress the output of all cross reference files.

=back

=head2 Single File Output

=over 4

=item B<-error>

Lists missing files and other errors.

=item B<-out> I<file>

Sends list output and summary information to I<file>.

=item B<-list>

Lists all found files, links, directories etc.

=item B<-warn>

Lists all warnings.

=item B<-xref>

Adds cross references to the lists.

=item B<-forward>

Sorts lists by referring file.

=back

=head2 Debug and other Flags

=over 4

=item B<-db1>

Debugs command line input and linkset expressions.

=item B<-db2>

Prints the name of every file that gets checked (not just HTML files).

=item B<-db3>

Debugs HTML parser, prints out tags and resulting links.

=item B<-db4>

Debugs socket connection (kind of).

=item B<-db5>

Not used.

=item B<-db6>

Details last-modified status for remote URLs (requires B<-netset> or
B<-netmod>).

=item B<-db7>

Prints brief debug information while checking remote URLs.

=item B<-db8>

Prints all http headers while checking remote URLs.

=item B<-db9>

Generates random http errors.

=item B<-version>

Gives version information.

=item B<-help>

Lists a few simple examples of how to use Linklint.

=item B<-help_all>

Lists all help (contained in program) including every input option.

=item B<-quiet>

Disables printing progress to the screen.

=item B<-silent>

Disables printing summarys to the screen.

=back

=head1 AUTHOR

Linklint is written by James B. Bowlin E<lt>jbowlin@linklint.orgE<gt>.
This manual page was written by Denis Barbier
E<lt>barbier@debian.orgE<gt> for the Debian system (but may be used by
others) by cut'n'paste from original documentation written in HTML.

=cut

#==========================================================================
# End of linkhttp.pl
#==========================================================================