File: webmagick.in

package info (click to toggle)
webmagick 1.45-2
  • links: PTS
  • area: main
  • in suites: potato
  • size: 3,164 kB
  • ctags: 719
  • sloc: perl: 5,942; sh: 448; makefile: 237
file content (3750 lines) | stat: -rwxr-xr-x 121,553 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
#! @PERL@
# -*- Mode: Perl -*-
#
# $Id: webmagick.in,v 1.45 1998/12/19 22:03:12 bfriesen Exp $
#
# You are looking at the main PERL script for WebMagick, a package to
# intelligently create HTML and JavaScript index files and imagemaps
# corresponding to a directory tree of image files.
#
# Copyright Bob Friesenhahn (bfriesen@simple.dallas.tx.us) 1996, 1997,
# 1998
#
# This work may be used for any purpose, public or private, provided
# that this work or derivations thereof are attributed to its author.
# Full copyrights to this work are maintained by its author to ensure
# that rights so bestowed are not abridged.
#
# NOTE: This program has a substantial manual.  Considerable time has
# been spent writing it so please at least skim through it before
# asking questions.
#
# Requires the ImageMagick, PerlMagick, and PERL 5 packages.  May
# possibly execute correctly (but with reduced performance) with
# package versions as old as:
#  ImageMagick -- 3.8.4
#  PerlMagick  -- 1.12
#  PERL        -- 5.003
#
# But always tested by the author with recent versions.  At the last
# update of these notes (December 19, 1998) the latest versions tested
# were:
#  ImageMagick -- 4.1.6
#  PerlMagick  -- 1.55
#  PERL        -- 5.004_04
#
# While some effort is made to ensure that WebMagick will execute under
# older package versions, the author does not use these versions so
# he will only know to correct incompatabilities if they are brought
# to his attention.
#
# The latest version of WebMagick is always available from the URL
# "http://www.cyberramp.net/~bfriesen/webmagick/dist/" or via FTP from
# "ftp://ftp.wizards.dupont.com/pub/ImageMagick/perl/".  Keep track of
# the latest WebMagick developments by visiting the WebMagick web page
# at "http://www.cyberramp.net/~bfriesen/webmagick/index.html".
#
# Obtain ImageMagick from "ftp://ftp.wizards.dupont.com/pub/ImageMagick"
# or visit the ImageMagick web page at
# "http://www.wizards.dupont.com/cristy/ImageMagick.html".
#
# Obtain PerlMagick from
# "ftp://ftp.wizards.dupont.com/pub/ImageMagick/perl" or visit the
# PerlMagick web page at
# "http://www.wizards.dupont.com/cristy/www/perl.html".
#
# ImageMagick and PerlMagick are written by John Cristy (cristy@dupont.com).
# WebMagick would not be possible without his wonderful software.  The
# author greatly appreciates Cristy's assistance with ironing out PerlMagick's
# (or WebMagick's bugs) during the development of WebMagick.
#
# Suggestions, moral support, and patches were provided by Anthony
# Thyssen (anthony@cit.gu.edu.au). His help is very much appreciated.
#

# If your PERL barfs, you may need to comment one or more of the following
# lines out:
use strict 'refs';	# Be picky about references
use strict 'subs';	# Be picky about subroutines
use strict 'vars';	# Be picky about variable scope (explicit globals)

#
# Global variable declarations
#
my (
    %RGBDB,		# RGB color database
    @allFiles,		# List of files in current directory
    @allImageFiles,	# List of all source file names in directory
    @cacheFiles,	# List of files in the image cache
    @calendarMonths,	# List of months in the year (January, February, etc.
    $currentDirectory,	# Current directory (absolute)
    $doMontage,		# Set to true if montage must be generated
    $doPageHtml,	# Set to true if per-page HTML files must be generated
    %dirOrder,		# Order directories are listed in dirindex file
    %dirTitles,		# Directory name to title index
    %fileNames,		# Hash of generated file names
    %frameTargets,	# Frame targets
    @global_option_files, # List of rc files to source before all others
    $haveImages,	# Set to true if there are images in directory
    $haveReadme,	# Set to true if there is a README file in directory
    %htmlOpts,		# Options that effect HTML output
    $htmlParams,	# String form of HTML parameters
    %iconImageSizes,	# Size of icons
    %iconImageUrls,	# URLs for icons
    $icon_base_url,	# URL to icon directory
    $icon_dir_path,	# Path to icon directory
    %icon_paths,	# Paths to icon files
    @imageThumbCoords,	# Thumbnail imagemap coordinates
    $imageFrameLink,	# URL to use as source for image frame
    %imageLabels,	# Labels to use for images (if specified)
    %imageOrder,	# Order that images occur in imgindex file
    $inChild,		# Set to true if this process is a child
    $dateDay,		# Day of the month
    $dateMonth,		# Month of the year
    $dateYear,		# Year
    @montageImages,	# List of per-page montage image names
    @montageImageSizes,	# List of per-page montage image sizes
    $montageArguments,	# PerlMagick Montage() arguments
    $montageParameters,	# Montage() arguments plus others that effect montage output
    $netscapeColormap,	# PerlMagick image object representing Netscape color cube
    $numPages,		# Number of pages to represent current directory
    $opt_address,
    $opt_anonymous,
    $opt_cache,
    $opt_cachedir,
    $opt_cacheformat,
    $opt_cachegeom,
    $opt_cachemin,
    $opt_coloralink,
    $opt_colorback,
    $opt_colorfore,
    $opt_colorlink,
    $opt_colorvlink,
    $opt_columns,
    $opt_debug,
    $opt_dircoloralink,
    $opt_dircolorback,
    $opt_dircolorfore,
    $opt_dircolorlink,
    $opt_dircolorvlink,
    $opt_dirfmt,
    $opt_dirindexname,
    $opt_forcecache,
    $opt_forcegif,
    $opt_forcejpeg,
    $opt_forcehtml,
    $opt_forcemontage,
    $opt_frame_name_dirview,
    $opt_frame_name_imageview,
    $opt_frame_name_thumbview,
    $opt_frame_name_top,
    $opt_frameborder,
    $opt_framebordersize,
    $opt_frameddirfmt,
    %opt_framefmt,
    %opt_framefmt_frames,
    $opt_framemarginheight,
    $opt_framemarginwidth,
    $opt_framestyle,
    $opt_htmlext,
    $opt_header,
    $opt_footer,
    $opt_help,
    $opt_htimage,
    $opt_iconpath,
    %opt_icons,
    $opt_ignore,
    $opt_imgindexname,
    $opt_indexname,
    $opt_javascript,
    $opt_mapnetscape,
    $opt_maptype,
    $opt_maxgif,
    $opt_metaauthor,
    $opt_metaclassification,
    $opt_metadescription,
    $opt_metaexpires,
    $opt_metakeywords,
    $opt_pageindexname,
    $opt_prefixpath,
    $opt_prune,
    $opt_readfailhook,
    $opt_readme,
    $opt_readmevisible,
    $opt_recurse,
    $opt_rgbdb,
    $opt_rootpath,
    $opt_rows,
    $opt_skip,
    $opt_srcdir,
    $opt_thumbbackground,
    $opt_thumbbordercolor,
    $opt_thumbborderwidth,
    $opt_thumbcompose,
    $opt_thumbfont,
    $opt_thumbforeground,
    $opt_thumbframe,
    $opt_thumbframebgcolor,
    $opt_thumbframecolor,
    $opt_thumbgeometry,
    $opt_thumbgravity,
    $opt_thumblabel,
    $opt_thumblabelwidth,
    $opt_thumbmattecolor,
    $opt_thumbposthook,
    $opt_thumbprehook,
    $opt_thumbshadow,
    $opt_thumbtexture,
    $opt_thumbtransparent,
    $opt_title,
    $opt_verbose,
    $opt_version,
    $opt_webmagickrc,	# Per-directory WebMagick rc file name
    $opt_zoomfilter,
    $opt_pichtml,
    $opt_pichtmlext,
    $opt_pichtmltarget,
    $opt_pichtmltop,
    $opt_pichtmlbottom,
    $pageStatusTime,	# Time status file last modified
    $pageNumber,	# Current page number
    $perlVarsLoaded,	# Set to one when directory status file sourced
    %relativePathCache, # Relative path cache
    $sourceDirectory,	# Directory to process
    @imageNames,	# List of source file names for current page
    $startTime,		# Clock time when program started
    %dirJsLink,		# Link name to use when changing directories via JavaScript
    @dirNames,		# List of directories under this directory
    $pageTitle,		# Title for current page
    %webmagickInfo	# WebMagick version information as a hash
    );


###########################################################################
#                     Internal Default Options
###########################################################################
#
#WebMagickRcTop  -- Don't remove this line
#
# Copy the webmagickrc file to your home directory under the name
# .webmagickrc. Any default definitions you want to override should be
# uncommented in this file and modified.
#
# Navigation Icon Paths and URLs
# Specify the path and file name for the navigation icons.
# !!!MUST EDIT OR OVERRIDE!!!
#
$opt_rootpath	= '@ROOTPATH@';	# Directory Path to top of html tree
				# Needed to determine relative paths to images
$opt_prefixpath	= '@PREFIXPATH@'; # Path or URL to prepend to root URL
				# Not used if local relative paths used
$opt_iconpath	= '@ICONPATH@';
				# Relative path under rootpath / prefixpath

#
# Server-side imagemap settings
# !!!MAY NEED TO EDIT OR OVERRIDE!!!
# 
$opt_htimage='@HTIMAGE@';	# Base URL to server-side imagemap CGI
				#  On some systems this is  /cgi-bin/imagemap
				#  Set to '' to use a ".map" URL with relative
                                # URLs (latest NCSA & Apache)
$opt_maptype='@MAPTYPE@';	# Maptype must be 'cern' or 'ncsa'. If you are
				# using Apache, specify 'ncsa'.

#
# RC files
#
#
# Name of per-directory rc file
$opt_webmagickrc	= '.webmagickrc';
# global rc files
@global_option_files    = ("@sysconfdir@/webmagickrc", "$ENV{'HOME'}/${opt_webmagickrc}");


# File naming
$opt_indexname		= 'index.html';	# Per-directory master index file 
$opt_readme		= 'README.html';# Name of welcome page README file ('' = none)
$opt_pageindexname	= '.index';	# Base name of secondary index files
$opt_dirindexname	= '.dirindex';	# Subdirectory Title cross-reference
					#  dirname   Directory Title
$opt_imgindexname	= '.imgindex';	# Image name to label cross-reference file

#
# HTML color and background image related options
#
# X11 RBG color database (rgb.txt) location
# Entries in this file have the form:
#        Red Green Blue  Color-name
# where color intensities are specified in decimal.
#  e.g.  250 240 230     linen
$opt_rgbdb='@RGBDB@';
#
# Page Frame & non-framed pages
$opt_colorback		= '#CCCCCC';	# Color -- Background
$opt_colorfore		= 'black';	# Color -- Foreground

$opt_coloralink		= '#FF0000';	# Color -- Active link
$opt_colorlink		= '#0000EE';	# Color -- Link
$opt_colorvlink		= '#551A8B';	# Color -- Visited link
#
# Directory frame (Leave options empty ('') to use page frame colors
$opt_dircolorback	= '#B2B2B2';	# Color -- Background
$opt_dircolorfore	= 'black';	# Color -- Foreground
$opt_dircoloralink	= '';		# Color -- Active link
$opt_dircolorlink	= '';		# Color -- Link
$opt_dircolorvlink	= '';		# Color -- Visited link


# General options
$opt_anonymous		= 0;	# Don't show address & copyright info on pages
$opt_debug		= 0;	# Debug flag (default off)
$opt_recurse		= 0;	# Recursivally apply webmagick (default off)
$opt_prune		= 0;	# Do Not recurse into subdirectories (off)
$opt_ignore		= 0;	# Do not webmagick this directory
				#    but still recurse into sub-directories
$opt_srcdir		= '.';	# Source directory path (current directory)
$opt_verbose		= 0;	# Verbose flag (default off)
$opt_forcecache		= 0;	# Force update of cached thumbnails
$opt_forcehtml		= 0;	# Force HTML files to be generated (default off)
$opt_forcemontage	= 0;	# Force montage (default off)
$opt_forcegif		= 0;	# Force GIF imagemaps (default off)
$opt_forcejpeg          = 0;    # Force JPEG imagemaps (default off)
$opt_help		= 0;	# Display usage message
$opt_version		= 0;	# Display version info
$opt_htmlext            = '.html'; # Use .shtml for SSI
$opt_header		= '';	# Imagemap extra page header (HTML)
$opt_footer             = '';   # Imagemap extra page footer (HTML)
$opt_javascript		= 1;	# Enable JavaScript output
$opt_readmevisible	= 0;	# Make README.html be first page.
$opt_title		= '';	# Page title (blank provides default title)
$opt_address		= '';	# Additonal address info for bottom of
                                #    imagemap page
$opt_pichtml            = 0;    # Write separate HTML for each picture
$opt_pichtmlext         = '.html'; # Use .shtml for SSI
$opt_pichtmltarget      = '';
$opt_pichtmltop         = '';
$opt_pichtmlbottom      = '';

#				
# ImageMagick Montage settings
#
$opt_maxgif		= 30000;	# Maximum GIF imagemap size before
					#  trying JPEG
$opt_columns		= 6;		# Max number of columns in montage grid
$opt_rows		= 4;		# Max number of rows in montage grid
$opt_mapnetscape	= 0;		# Map GIFs to Netscape 216-color cube
$opt_thumbtexture	= 'false';	# Texture to tile onto the image background
$opt_thumbbackground	= '#CCCCCC';	# Montage background color
$opt_thumbborderwidth	= 0;		# Thumbnail border width (pixels)
$opt_thumbframebgcolor	= 'black';	# Inside of Frame color.  Unused if no frame
$opt_thumbframecolor	= '#CCCCCC';	# Color -- Frame Color
$opt_thumbtransparent	= $opt_thumbbackground;	# Color -- Image Transparency
$opt_thumbcompose	= 'Replace';	# Thumbnail image composition operation
$opt_thumbfont		= '@DEFAULTFONT@'; # Label font
$opt_thumbforeground	= 'black';	# Montage foreground color
$opt_thumbframe		= 'false';	# Geometry of frame around thumbnail
					#    (default false)
$opt_thumbgeometry	= '106x80+2+2>'; # Size of thumbnail images (width x height)
$opt_thumbgravity	= 'Center';	# Direction thumbnail gravitates to
					#    (default Center)
$opt_thumblabel		= '%f\n%wx%h\n%b'; # Default format for thumbnail text label
$opt_thumblabelwidth	= 13;		# Label width past which truncation occurs

$opt_thumbshadow	= 'false';	# Enable decorative shadow under thumbnail
					#    (default disabled)
$opt_zoomfilter		= 'Mitchell';	# Zoom (size reduction) filter
					#  (Box/Triangle/Mitchell)

#
# Hooks to add code to key places in WebMagick
#
$opt_thumbprehook	= '';		# PerlMagick commands to execute on original
					#  prior reducing to thumbnail size
$opt_thumbposthook	= '';		# PerlMagick commands to execute on image
					#  after reduction to thumbnail size
$opt_readfailhook	= '';		# PERL commands to execute if reading image
					#  fails due to image corruption

#
# Caching related options
#
# Note: See below about sharing cache with 'xv'

# If caching is turned on, the montage grid will continue to be
# controlled by opt_thumbgeometry but the thumbnail size will be
# controlled by opt_cachegeom

$opt_cache		= 1;		# Cache thumbnails
$opt_cachedir		= '.cache';	# Subdirectory to cache thumbnails in
$opt_cacheformat	= 'JPEG';	# Format to use for thumbnails
$opt_cachegeom		= $opt_thumbgeometry; # Thumbnail geometry
$opt_cachemin		= 300*200;	# Smallest image to cache in total pixels
					#  (width * height).  Images smaller than
					#  this size will not be cached.



# Uncomment these options to share cache with John Bradley's 'xv'
# (Visual Schnauzer format) NOTE: The 'xv' thumbnail format only
# supports 128 absolute colors so expect some montage thumbnail
# degradation when using 'xv' thumbnails.
#
#
# $opt_cacheformat	= 'P7';		# 'xv's thumbnail format
# $opt_cachegeom	= '80x60';	# 'xv's default thumbnail geometry is 80x60
# $opt_cachedir		= '.xvpics';	# 'xv's thumbnail cache directory
# $opt_cachemin		= 0;		# Cache all thumbnails
#
# Uncomment remaining to obtain 'xv's Visual Schnauzer "look and feel"
#
# $opt_thumbgeometry	= '92x72+2+2>';
# $opt_thumblabel	= '%f';
# $opt_thumblabelwidth	= 12;
# $opt_thumbgravity	= 'South';

#
# Frame related options
#
$opt_framemarginwidth	= 1;		# Pixels allocated to frame margin in horizontal direction
$opt_framemarginheight	= 1;		# Pixels allocated to frame margin in vertical direction
$opt_framebordersize	= 3 ;		# Pixels allocated to frame border
$opt_frameborder	= 'YES';	# Enable (YES) or disable (NO) decorative frame borders
$opt_framestyle		= 1;		# Frame style to use (out of those available)

#
# Meta-tag defaults
#
$opt_metaauthor = '';			# Page author
$opt_metaclassification = '';		# Page classification
$opt_metadescription = '';		# Page description
$opt_metaexpires = '';			# Date page expires (e.g "Tue, 20 Aug 1996 14:25:27 GMT")
$opt_metakeywords = 'WebMagick';	# Key words

#
# Hash table of images used -- image size read internally by webmagick
#

# $opt_icons{'background'}	= 'thumbs.jpg';		# Thumbnail frame background image
# $opt_icons{'dirbackground'}	= 'dir.jpg';		# Directory frame background image
$opt_icons{'prev'}		= 'blue_prev.gif';	# Previous
$opt_icons{'prev_gray'}		= 'gray_prev.gif';	# Previous (grayed out)
$opt_icons{'next'}		= 'blue_next.gif';	# Next
$opt_icons{'next_gray'}		= 'gray_next.gif';	# Next (grayed out)
$opt_icons{'up'}		= 'blue_up.gif';  	# Up
$opt_icons{'help'}		= 'blue_readme.gif';	# Help Readme File
# $opt_icons{'help'}		= 'blue_help.gif';	# Help Alternative (Question)
# $opt_icons{'dir'}		= 'blue_dir.gif'; 	# Directory List Icon (See below)
# $opt_icons{'ball'}		= 'blue_ball.gif';	# A ball matching other icons

#
#WebMagickRcBottom -- Don't remove this line
#

# Format Templates
#
# WARNING: This is for expert web and perl programmers only do not
# modify unless you know what you are doing.  To learn how frames work,
# read the pages under the URL
# http://home.netscape.com/assist/net_sites/frames.html
#
# Extra Images can be added to the above hash table and then used in
# the following format options. For example the 'dir' icon above can
# be uncommented then the following lines added below.  WARNING: this
# is only useful if $opt_indexname is something else.
#
# 
# <A HREF=\"./\" TARGET=\"thumbnail\">
#    <IMG SRC=\"$iconImageUrls{dir}.gif\" $iconImageSizes{dir} ALT=\"\" BORDER=0></A>
#    <A HREF=\"./\" TARGET=\"thumbnail\">Dir Listing</A><BR>
#

#
# Template for the Frame definition
# This allows adding frames, changing geometry, etc.
#
# Frame Target Names
$opt_frame_name_top="_top";		# Reload frames entirely
#$opt_frame_name_self="_self";		# Link to this (same) frame
#$opt_frame_name_parent="_parent";	# Link to parent frame
$opt_frame_name_dirview="dirview";	# Directory nav frame
$opt_frame_name_thumbview="thumbview";	# Imagemap (image selection) frame
$opt_frame_name_imageview="imageview";	# Image viewing frame (three frames)


#
# Simple two frame screen with directories listed in the left
# frame and imagemap/README displayed in the right frame.
#
#  -------------
# |  |          |
# |  |          |
# |  |          |
# |  |          |
# |  |          |
# |  |          |
#  -------------
$opt_framefmt{1}=
'<FRAMESET COLS=\"132,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
 <FRAME SRC=\"${dirframelink}\" NAME=\"${opt_frame_name_dirview}\"
   MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 <FRAME SRC=\"${pageframelink}\" NAME=\"${opt_frame_name_imageview}\"
   MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
</FRAMESET>';
$opt_framefmt_frames{1}=2;	# Number of frames expressed by this frame format

# Three frame screen with directories listed in top-left frame,
# imagemap displayed in bottom-left frame, and README/Images
# displayed in full-height right-hand frame.
#  -------------
# |  |          |
# |  |          |
# |--|          |
# |  |          |
# |  |          |
# |  |          |
#  -------------
$opt_framefmt{2}=
'<FRAMESET COLS=\"145,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
 <FRAMESET ROWS=\"20%,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
  <FRAME SRC=\"${dirframelink}\" NAME=\"${opt_frame_name_dirview}\"
    MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
  <FRAME SRC=\"${pageframelink}\" NAME=\"${opt_frame_name_thumbview}\"
    MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 </FRAMESET>
 <FRAME SRC=\"${imageFrameLink}\" NAME=\"${opt_frame_name_imageview}\"
   MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
</FRAMESET>';
$opt_framefmt_frames{2}=3;	# Number of frames expressed by this frame format

# Three frame screen with directories listed in left frame,
# imagemap displayed in top-right frame, and README/Images
# displayed in lower-right frame.
#  -------------
# |  |          |
# |  |----------|
# |  |          |
# |  |          |
# |  |          |
# |  |          |
#  -------------
$opt_framefmt{3}=
'<FRAMESET COLS=\"132,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
 <FRAME SRC=\"${dirframelink}\" NAME=\"${opt_frame_name_dirview}\"
   MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 <FRAMESET ROWS=\"150,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
   <FRAME SRC=\"${pageframelink}\" NAME=\"${opt_frame_name_thumbview}\"
     MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
   <FRAME SRC=\"${imageFrameLink}\" NAME=\"${opt_frame_name_imageview}\"
     MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 </FRAMESET>
</FRAMESET>';
$opt_framefmt_frames{3}=3;	# Number of frames expressed by this frame format

# Three frame screen with directories listed in lower-left frame,
# imagemap displayed in top frame, and README/Images displayed in
# lower-right frame.
#  -------------
# |             |
# |-- ----------|
# |  |          |
# |  |          |
# |  |          |
# |  |          |
#  -------------
$opt_framefmt{4}=
'<FRAMESET ROWS=\"172,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
 <FRAME SRC=\"${pageframelink}\" NAME=\"${opt_frame_name_thumbview}\"
   MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 <FRAMESET COLS=\"132,*\" FRAMEBORDER=${opt_frameborder} BORDER=${opt_framebordersize}>
   <FRAME SRC=\"${dirframelink}\" NAME=\"${opt_frame_name_dirview}\"
     MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
   <FRAME SRC=\"${imageFrameLink}\" NAME=\"${opt_frame_name_imageview}\"
     MARGINWIDTH=${opt_framemarginwidth} MARGINHEIGHT=${opt_framemarginheight}>
 </FRAMESET>
</FRAMESET>';
$opt_framefmt_frames{4}=3;	# Number of frames expressed by this frame format

#
# Template for the Directory Index Frame
#
$opt_frameddirfmt='
<P>
<FONT SIZE=-1>
${uphtml}
${nexthtml}
</P>
${dirhtml}
';

#
# Template for Non-Framed Top Index Page ($opt_indexname)
#
$opt_dirfmt='\n<H3>Directory Navigator ...</H3>
${uphtml}
${helphtml}
${dirhtml}
${pageindexhtml}
';


###########################################################################
#                  End of Internal Default Options
###########################################################################

select(STDERR); $| = 1;		# Make stderr unbuffered
select(STDOUT); $| = 1;		# Make stdout unbuffered

umask( 022 );			# Sets default file mode 644
$startTime = time;		# Save start time

$inChild = 0;


# Allow global options files to override defaults set above (but not
# command line options)

my $goptfile;
foreach $goptfile (@global_option_files) {
    sourceRcFile( $goptfile )
        || die("Error sourcing ${goptfile}\n");
}


# Eval per-directory rc files if they exist.  Rc files are evaluated
# for each directory starting from $opt_rootdir until the current
# directory is reached. This supports "additive" behavior for a branch
# in the tree.
$currentDirectory=cwd();	# Get current (absolute) directory
evaluateRcFiles();

# Set signal handler to gracefully abort (hah!).  Handle signal
# induced exits properly.  Only the parent prints a status message.

sub sig_handler {
    my ($sig) = @_;
    if( ! $inChild ) {
	print("\nCaught signal SIG$sig -- aborting ...\n");
    }
    exit(1);
}
$SIG{'HUP'} = \&sig_handler;
$SIG{'INT'} = \&sig_handler;
$SIG{'QUIT'} = \&sig_handler;

# Save revision & date to variables
($webmagickInfo{'revision'}, $webmagickInfo{'date'}) =
    (split( ' ', '$Id: webmagick.in,v 1.45 1998/12/19 22:03:12 bfriesen Exp $' ))[2,3];

#
# We don't really like command line options but we'll support them anyway. :-)
#
use Getopt::Long;
if ( ! GetOptions(
		'address=s'		=> \$opt_address,
		'anonymous!'		=> \$opt_anonymous,
		'cache!'		=> \$opt_cache,
		'cachedir=s'		=> \$opt_cachedir,
		'cacheformat=s'		=> \$opt_cacheformat,
		'cachegeom=s'		=> \$opt_cachegeom,
		'cachemin=i'		=> \$opt_cachemin,
		'coloralink=s'		=> \$opt_coloralink,
		'colorback=s'		=> \$opt_colorback,
		'colorfore=s'		=> \$opt_colorfore,
		'colorlink=s'		=> \$opt_colorlink,
		'colorvlink=s'		=> \$opt_colorvlink,
		'columns=i'		=> \$opt_columns,
		'debug!'		=> \$opt_debug,
		'dircoloralink=s'	=> \$opt_dircoloralink,
		'dircolorback=s'	=> \$opt_dircolorback,
		'dircolorfore=s'	=> \$opt_dircolorfore,
		'dircolorlink=s'	=> \$opt_dircolorlink,
		'dircolorvlink=s'	=> \$opt_dircolorvlink,
		'dirindexname=s'	=> \$opt_dirindexname,
		'footer=s'              => \$opt_footer,
		'forcecache!'		=> \$opt_forcecache,
		'forcegif!'		=> \$opt_forcegif,
		'forcehtml!'		=> \$opt_forcehtml,
		'forcejpeg!'            => \$opt_forcejpeg,
		'forcemontage!'		=> \$opt_forcemontage,
		'framemarginwidth=i'	=> \$opt_framemarginwidth,
		'framemarginheight=i'	=> \$opt_framemarginheight,
		'framebordersize=i'	=> \$opt_framebordersize,
		'frameborder=s'		=> \$opt_frameborder,
		'framestyle=i'		=> \$opt_framestyle,
		'header=s'		=> \$opt_header,
		'help!'			=> \$opt_help,
		'htimage=s'		=> \$opt_htimage,
		'htmlext=s'             => \$opt_htmlext,
		'iconpath=s'		=> \$opt_iconpath,
		'imgindexname=s'	=> \$opt_imgindexname,
		'indexname=s'		=> \$opt_indexname,
		'javascript!'		=> \$opt_javascript,
		'mapnetscape!'		=> \$opt_mapnetscape,
		'maptype=s'		=> \$opt_maptype,
		'maxgif=i'		=> \$opt_maxgif,
		'pageindexname=s'	=> \$opt_pageindexname,
		'pichtml!'              => \$opt_pichtml,
		'pichtmlbottom=s'       => \$opt_pichtmlbottom,
		'pichtmlext=s'          => \$opt_pichtmlext,
		'pichtmltarget=s'       => \$opt_pichtmltarget,
		'pichtmltop=s'          => \$opt_pichtmltop,
		'prefixpath=s'		=> \$opt_prefixpath,
		'readme=s'		=> \$opt_readme,
		'readmevisible!'	=> \$opt_readmevisible,
		'recurse!'		=> \$opt_recurse,
		'rootpath=s'		=> \$opt_rootpath,
		'rows=i'		=> \$opt_rows,
		'srcdir=s'		=> \$opt_srcdir,
		'thumbtexture=s'	=> \$opt_thumbtexture,
		'thumbbackground=s'	=> \$opt_thumbbackground,
		'thumbborderwidth=i'	=> \$opt_thumbborderwidth,
		'thumbframebgcolor=s'	=> \$opt_thumbframebgcolor,
		'thumbcompose=s'	=> \$opt_thumbcompose,
		'thumbfont=s'		=> \$opt_thumbfont,
		'thumbforeground=s'	=> \$opt_thumbforeground,
		'thumbframe=s'		=> \$opt_thumbframe,
		'thumbgeometry=s'	=> \$opt_thumbgeometry,
		'thumbgravity=s'	=> \$opt_thumbgravity,
		'thumblabel=s'		=> \$opt_thumblabel,
		'thumblabelwidth=s'	=> \$opt_thumblabelwidth,
		'thumbshadow=s'		=> \$opt_thumbshadow,
		'thumbtransparent=s'	=> \$opt_thumbtransparent,
		'title=s'		=> \$opt_title,
		'verbose!'		=> \$opt_verbose,
		'version!'		=> \$opt_version,
		'zoomfilter=s'		=> \$opt_zoomfilter
		)
    ) {
    help();
    exit(0);
}

#
# Print help message
#
if( $opt_help ) {
    help();
    exit(0);
}

#
# Print version message
#
if( $opt_version ) {
    version();
    exit(0);
}

#
# Check if source directory is valid
#
if ( ! -d "${opt_srcdir}" ) {
    print( STDERR "No ${opt_srcdir} directory\n" );
    exit(1);
}


#
# Open X11 RGB database
#
if ( -f $opt_rgbdb ) {
    open( RGBDB, "<$opt_rgbdb" )
	|| die("Unable to open RGB database $opt_rgbdb");
    while( <RGBDB> ) {
	m/^!/ && next;
        my ( $red, $green, $blue, $color );
        chop;
        s/^[ \t]+//; # Remove any preceding spaces
        ($red, $green, $blue, $color) = split( /[ \t]+/, $_, 4);
        $RGBDB{"\L$color"} = sprintf("#%02X%02X%02X", $red, $green, $blue);
    }
    close( RGBDB );
} else {
    print( STDERR "Warning: X11 RGB database \'$opt_rgbdb\' not found\n" );
}

#
# Minimal 16-color named set as defined by HTML 3.2
#
$RGBDB{'black'}	  = '#000000';
$RGBDB{'green'}   = '#008000';
$RGBDB{'silver'}  = '#C0C0C0';
$RGBDB{'lime'}    = '#00FF00';
$RGBDB{'gray'}    = '#808080';
$RGBDB{'olive'}   = '#808000';
$RGBDB{'white'}   = '#FFFFFF';
$RGBDB{'yellow'}  = '#FFFF00';
$RGBDB{'maroon'}  = '#800000';
$RGBDB{'navy'}    = '#000080';
$RGBDB{'red'}     = '#FF0000';
$RGBDB{'blue'}    = '#0000FF';
$RGBDB{'purple'}  = '#800080';
$RGBDB{'teal'}    = '#008080';
$RGBDB{'fuchsia'} = '#FF00FF';
$RGBDB{'aqua'}    = '#00FFFF';


#
# Set time and date related variables for general use
#
@calendarMonths=( 'January', 'February', 'March', 'April', 'May', 'June',
		  'July', 'August', 'September', 'October', 'November',
		  'December');
# Local time
# seconds=0, minutes=1, hours=2, mday=3, month=4, year=5, wday=6, yday=7, isdst=8
($dateDay, $dateMonth, $dateYear) = (localtime(time))[3,4,5];
$dateYear += 1900;

# Greenwich mean time (GMT)
#($gmt_seconds, $gmt_minutes, $gmt_hours, $gmt_mday, $gmt_month, $gmt_year,
# $gmt_wday, $gmt_yday, $gmt_isdst ) = gmtime(time);
#$gmt_year += 1900;


# Eval per-directory rc files if they exist.  Rc files are evaluated
# for each directory starting from $opt_rootdir until the current
# directory is reached. This supports "additive" behavior for a branch
# in the tree.

evaluateRcFiles();

#
# Translate paths to physical paths (avoid symlink problems)
#
$opt_srcdir	= lets_get_physical( $opt_srcdir );
print( "Physical srcdir : $opt_srcdir\n" ) if $opt_debug;
$opt_rootpath 	= lets_get_physical( $opt_rootpath );
print( "Physical rootpath : $opt_rootpath\n" ) if $opt_debug;
$icon_dir_path  = "${opt_rootpath}/${opt_iconpath}";
print( "Physical icondir : $icon_dir_path\n" ) if $opt_debug;



# html_imgsize.  Obtain image size and return HTML text (HEIGHT=foo
# WIDTH=bar) representing size.

sub html_imgsize {
    my ($file) = @_;

    use Image::Magick;

    my ( 
	$image,
	$height,
	$width,
	@ping,
	$retval,
	$status
	);

    $retval = '';
    $file =~ s?/var/www/doc/webmagick/icons?/usr/doc/webmagick/icons?g;
    if( -f $file ) {
	$image = Image::Magick->new;
	# Try PerlMagick 1.15 Ping method first
	eval qq/\@ping = split(',', \$image->Ping("$file"));/;
	if ( !$@ ) {
	    $width = $ping[0];
	    $height = $ping[1];
	} else {
	    # If Ping fails to eval, do things the hard way
	    $status = $image->Read($file);
	    if( "$status" ) {
		undef $image;
		return( $retval );
	    }
	    ($width, $height) = $image->[0]->Get("columns", "rows");
	}
        print( STDERR "Image \"$file\" has dimensions ",
	      "${width}x${height}\n") if $opt_debug;
	$retval="HEIGHT=${height} WIDTH=${width}";
	undef @$image;	# Free up space
	undef $image;	# Ditto
    } else {
        print( STDERR "html_imgsize: no such file \"$file\"\n" );
    }
    return( $retval );
}


if( $opt_recurse ) {
    # Recurse depth-first under current directory, executing &wanted
    # for each directory ignoring hidden directories
    use File::Find;
    print( "Processing directory tree $opt_srcdir ...\n" ) if $opt_debug;
    finddepth( \&wanted, $opt_srcdir );
} else {
    print( "Processing directory $opt_srcdir ...\n" ) if $opt_debug;
    $sourceDirectory = $opt_srcdir;
    dodir( $sourceDirectory );
}

#
# Print run times if running in verbose mode
#
if( $opt_verbose ) {
    my(
       $user,          # CPU time in user code for this process
       $system,        # CPU time in system code on behalf of this process
       $cuser,         # CPU time in user code of child processes
       $csystem,       # CPU time in system code on behalf of child processes
       $total_user,    # Total user time (parent + children)
       $total_system,  # Total system time (parent + children)
       $total_time     # Total elapsed time (wall clock)
       );
    my(
       $user_m,        # User time in minutes
       $system_m,      # System time in minutes
       $cuser_m,       # Child process user time in minutes
       $csystem_m,     # Child process system time in minutes
       $total_user_m,  # Total user time in minutes
       $total_system_m,# Total system time in minutes
       $total_time_m   # Total elapsed time (wall clock) in minutes
       );
    ($user, $system, $cuser, $csystem) = times;
    $user_m		= elapsedminutes( $user );
    $system_m		= elapsedminutes( $system );
    $cuser_m		= elapsedminutes( $cuser );
    $csystem_m		= elapsedminutes( $csystem );
    $total_user		= $user + $cuser;		# Total user time
    $total_user_m	= elapsedminutes( $total_user );
    $total_system	= $system + $csystem;		# Total system time
    $total_system_m	= elapsedminutes( $total_system );
    $total_time		= time - $startTime;		# Total run time
    $total_time_m	= elapsedminutes( $total_time );
    print( STDERR "Run time statistics:\n" );
    print( STDERR "Detailed times: ${user_m} user, ${system_m} system,",
	  " ${cuser_m} child_user, ${csystem_m} child_system\n" );
    print( STDERR "Summary times : ${total_time_m} total,",
	  " ${total_user_m} user, ${total_system_m} system\n" );
}
print( STDERR "Doing normal exit with code 0\n" ) if $opt_debug; 
exit(0);

#####################
#####################

# Executed for each find operation 
# Want:
# is directory
# not hidden directory
#
# Variables:
#  $File::Find::dir	current directory
#  $File::Find::name	current directory + file name
#  $File::Find::prune	set to true to prune tree
sub wanted {
    my($dev,$ino,$mode,$nlink,$uid,$gid);
    ($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_);
    if ( -d $_ && !/^\..+/ ) {
        if( $_ ne '.' && get_rc_var('.', 'opt_prune', 0) ) {
            $File::Find::prune=1;
	    # following funny logic is to avoid warnings about $prune
            print( STDERR "Pruning    $File::Find::name\n" ) if $File::Find::prune==1;
            return;
        } 
        forking_dodir($File::Find::name);
    }
}


# Execute dodir with the protection of a fork.  This ensures that
# current directory and global webmagick configuration values are
# preserved between directories.

sub forking_dodir {
    my $sourceDirectory = shift(@_);     # Directory to process
    my $inChild;		# Set to one of we are child
    my ($waitpid,            	# PID returned by wait
	$childstat,          	# Status returned from child
	$pid,			# Child process PID
	$waitpid,		# PID waited on
	$childstat		# Child return status
	);
	
FORK:
    {
	if( $pid = fork ) {
	    # parent here
	    # child process pid is available in $pid
	    $inChild=0;
	    $waitpid=wait();
	    $childstat=$?;
	    # If clean exit, then return 0
	    return 0 if ( $childstat == 0 );
	    syserror( $childstat ); # Print status from error
	    return 1;
	} elsif ( defined $pid ) {  # $pid is zero here if defined
	    # child here
	    # parent process pid is available with getppid
	    $inChild=1;
	    dodir( $sourceDirectory );
	    exit( 0 );
	} elsif ( $! =~ /No more process/ ) {
	    # EAGAIN, supposedly recoverable fork error
	    sleep 5;
	    redo FORK;
	} else {
	    # weird fork error
	    die( "Can't fork: $!\n$@\n" );
	}
    }
    return(0);			# Should never get here!
}

#
# Generate index files for directory specified by $sourceDirectory
#
sub dodir {
    $sourceDirectory = shift(@_);
    my $maxfiles = 0;		# Maximum number of index links per page
    $numPages = 0;		# Number of index pages to be generated
    my $numimages = 0;		# Number of images in directory
    my $numdirectories = 0;	# Number of subdirectories in directory
    $pageNumber = 1;		# Current index page number (1 to N)
    $haveReadme = 0;		# Is there a readme file in this directory?
    my $doIndexHtml=0;		# Set to true if HTML index files must be generated
    my $tmpstr;			# Scratch string
    my @tmplst;			# Scratch list

    #
    # Regular expression to match supported file extensions
    #
    my $includeRegex='(\.avs$)|(\.bie$)|(\.bmp$)|(\.cgm$)|(\.dcm$)|(\.dcx$)' .
        '|(\.dib$)|(\.dot$)|(\.dvi$)|(\.epdf$)|(\.epi$)|(\.eps$)' .
	'|(\.eps2$)|(\.epsf$)|(\.epsi$)|(\.ept$)|(\.fax$)|(\.fig$)' .
        '|(\.fits$)|(\.fpx$)|(\.g3$)|(\.gif$)|(\.gplt$)|(\.hdf$)' .
        '|(\.hpgl$)|(\.ico$)|(\.im1$)|(\.im24$)|(\.im8$)|(\.jbg$)' .
        '|(\.jbig$)|(\.jpeg$)|(\.jpg$)|(\.m2v$)|(\.man$)|(\.mif$)' .
        '|(\.miff$)|(\.mng$)|(\.mpeg$)|(\.mpg$)|(\.mtv$)|(\.p7$)' .
        '|(\.pbm$)|(\.pcd$)|(\.pcds$)|(\.pcx$)|(\.pdf$)|(\.pgm$)' .
        '|(\.pic$)|(\.pict$)|(\.pix$)|(\.png$)|(\.pnm$)|(\.pov$)' .
        '|(\.ppm$)|(\.ps$)|(\.psd$)|(\.rad$)|(\.rla$)|(\.rle$)' .
        '|(\.sgi$)|(\.sun$)|(\.tga$)|(\.tif$)|(\.tiff$)|(\.tim$)' .
        '|(\.ttf$)|(\.vicar$)|(\.viff$)|(\.xbm$)|(\.xpm$)|(\.xwd$)';


    #
    # Regular expression for file and directory names we ignore
    #
    my $excludeRegex="(^$opt_indexname)|(\\.html\$)|(\\.htm\$)|(^\\.)";

    #
    # Change current directory to $sourceDirectory
    #
    chdir( $sourceDirectory )
	|| die("Can't cd to $sourceDirectory\n$@\n");
    
    # Get current (absolute) directory
    $currentDirectory=cwd();

    # Eval per-directory rc files if they exist.  Rc files are
    # evaluated for each directory starting from $opt_rootdir until
    # the current directory is reached. This supports "additive"
    # behavior for a branch in the tree.

    evaluateRcFiles();


    # Decide if we want to process this directory or not based on the
    # value of $opt_ignore.  If not, then just return.

    if( $opt_ignore ) {
        # Skip this directory
        print( STDERR "Skipping   $sourceDirectory\n" );
        return( 0 );
    } else {
        print( STDERR "Processing $sourceDirectory\n" );
    }


    # Translate paths to physical paths (avoid symlink problems)
    # Note: This duplicates code executed during initialization

    $opt_srcdir		= lets_get_physical( $opt_srcdir );
    $opt_rootpath 	= lets_get_physical( $opt_rootpath );
    $icon_dir_path	= "${opt_rootpath}/${opt_iconpath}";

    #
    # Set frame targets & frame naming
    #
    if( $opt_framefmt_frames{$opt_framestyle} == 2 ) {
	# Two frame style & naming
	$frameTargets{'default_dirview'}=$opt_frame_name_top;	# Dir nav reloads entirely by default
	$frameTargets{'default_thumbview'}=$opt_frame_name_top;	# Thumbnail nav reloads entirely by default
	$frameTargets{'dirview'}=$opt_frame_name_dirview;	# Directory list displays in dirview frame
	$frameTargets{'readmeview'}=$opt_frame_name_imageview;	# Readme displays in imagemap frame
	$frameTargets{'imageview'}=$opt_frame_name_imageview;	# Images display in imagemap frame
	$frameTargets{'thumbview'}=$opt_frame_name_imageview;	# Imagemap displays in imagemap frame
    } elsif ( $opt_framefmt_frames{$opt_framestyle} == 3 ) {
	# Three frame style & naming
	$frameTargets{'default_dirview'}=$opt_frame_name_top;	# Dir nav reloads entirely by default
	$frameTargets{'default_thumbview'}=$opt_frame_name_top;	# Thumbnail nav reloads entirely by default
	$frameTargets{'dirview'}=$opt_frame_name_dirview;	# Directory list displays in dirview frame
	$frameTargets{'readmeview'}=$opt_frame_name_imageview;	# Readme displays in imageview frame
	$frameTargets{'imageview'}=$opt_frame_name_imageview;	# Images display in imageview frame
	$frameTargets{'thumbview'}=$opt_frame_name_thumbview;	# Imagemap displays in imagemap frame
    } else {
	die("Unsupported number of frames: $opt_framefmt_frames{$opt_framestyle}\n" );
    }

    #
    # Ensure that certain options have correct case
    #
    $opt_cacheformat = "\U${opt_cacheformat}";

    #
    # Default directory frame colors to page colors if not set
    #
    $opt_dircolorback 	= $opt_colorback  if ! $opt_dircolorback;
    $opt_dircolorfore 	= $opt_colorfore  if ! $opt_dircolorfore;
    $opt_dircoloralink	= $opt_coloralink if ! $opt_dircoloralink;
    $opt_dircolorlink 	= $opt_colorlink  if ! $opt_dircolorlink;
    $opt_dircolorvlink	= $opt_colorvlink if ! $opt_dircolorvlink;

    #
    # Convert all HTML colors to hex format
    #
    $opt_colorback	= lookupRGBColor( $opt_colorback );
    $opt_colorfore	= lookupRGBColor( $opt_colorfore );
    $opt_coloralink	= lookupRGBColor( $opt_coloralink );
    $opt_colorlink	= lookupRGBColor( $opt_colorlink );
    $opt_colorvlink	= lookupRGBColor( $opt_colorvlink );
    $opt_dircolorback	= lookupRGBColor( $opt_dircolorback );
    $opt_dircolorfore	= lookupRGBColor( $opt_dircolorfore );
    $opt_dircoloralink	= lookupRGBColor( $opt_dircoloralink );
    $opt_dircolorlink	= lookupRGBColor( $opt_dircolorlink );
    $opt_dircolorvlink	= lookupRGBColor( $opt_dircolorvlink );


    # Calculate the maximum number of images per index page

    $maxfiles=$opt_columns*$opt_rows;


    # Convert renamed WebMagick options to new names for backward
    # compatability

    if( defined( $opt_thumbbordercolor ) ) {
	$opt_thumbframebgcolor = $opt_thumbbordercolor;
    }

    if( defined( $opt_thumbmattecolor ) ) {
	$opt_thumbframecolor = $opt_thumbmattecolor;
    }

    #
    # Ensure that maptype is lower case
    # 
    $opt_maptype = "\L${opt_maptype}";

    #
    # Compute URL to top of icon directory
    #
    # Attempt to convert to relative URL
    $icon_base_url = relative( $currentDirectory, $icon_dir_path);
    if ( $icon_base_url =~ m|^/| ) {
        # If did not convert to relative URL then convert to absolute URL
        $icon_base_url = escapeurl( abs_path_to_url($icon_dir_path));
    }

    #
    # Source directory status file from last run
    #
    setFileNames(); 		# Set current file names
    $pageStatusTime = 0;
    if ( -f $fileNames{'pageStatus'} ) {
	sourceRcFile($fileNames{'pageStatus'}) ;
	# Obtain last modified date for status file
	$pageStatusTime=fmtime($fileNames{'pageStatus'});
    }


    # Handle a directory name to title index file.  Store alternative
    # names in %dirTitles.
    {
	my $pos = 0;
	my %tmp_dirTitles;
	undef( %tmp_dirTitles );
	if ( -f $opt_dirindexname ) {
	    open( DIRINDEX, "<$opt_dirindexname" );
	    while( <DIRINDEX> ) {
		chop;
		my($dirname, $dirtitle);
		( $dirname, $dirtitle) = split( /[ \t]+/, $_, 2);
		if(defined($dirname) && defined($dirtitle)) {
		    $tmp_dirTitles{$dirname} = escapehtml($dirtitle);
		    $dirOrder{$dirname} = $pos;
		    $pos++;
		}
	    }
	    close( DIRINDEX );
	}

	if( !defined(%dirTitles) || (  compareHash(\%dirTitles,\%tmp_dirTitles) ) ) {
	    %dirTitles = %tmp_dirTitles;
	    print( STDERR "Directory titles have changed, must re-do HTML indexes\n" )
		if $opt_debug;
	    ++$doIndexHtml;
	}	
    }

    #
    # Handle a image name to thumbnail label index file
    # Store alternative names in %imageLabels
    #
    {
	my $pos = 0;
	my %tmp_imageLabels;
	if ( -f $opt_imgindexname ) {
	    open( IMGINDEX, "<$opt_imgindexname" );
	    while( <IMGINDEX> ) {
		chop;
		my ( $imgname, $imgtitle);
		( $imgname, $imgtitle) = split( /[ \t]+/, $_, 2);
		if(defined($imgname) && defined($imgtitle)) {
		    $tmp_imageLabels{$imgname} = $imgtitle;
		    $imageOrder{$imgname} = $pos;
		    $pos++;
		}
	    }
	    close( IMGINDEX );
	}
	#
	# This code is totally BOGUS since decision should be made on a per-page basis!!
	#	
	if( !defined(%imageLabels) || (  compareHash(\%imageLabels,\%tmp_imageLabels) ) ) {
	    %imageLabels = %tmp_imageLabels;
	    print( STDERR "Image labels have changed, must re-do montages\n" )
		if $opt_debug;
	    $opt_forcemontage=1;
	}
    }

    #
    # Compute individual icon URLs.
    #
    {
	my %tmp_iconImageUrls;
	print( "Icon URLs:\n" )  if $opt_debug;
	my $icon;
	for $icon ( keys %opt_icons ) {
	    if( $opt_icons{$icon} ) { # if defined
		$tmp_iconImageUrls{$icon}  =  "$icon_base_url" . '/' . $opt_icons{$icon};
		printf( " \$tmp_iconImageUrls%-20s = \"%s\"\n", "{'$icon'}", $tmp_iconImageUrls{$icon} )
		    if $opt_debug;
	    }
	}
	if( !defined(%iconImageUrls) || (  compareHash(\%iconImageUrls,\%tmp_iconImageUrls) ) ) {
	    %iconImageUrls = %tmp_iconImageUrls;
	    print( STDERR "Icon URLs have changed, must re-do all HTML\n" )
		if $opt_debug;
	    $opt_forcehtml = 1;;
	}
    }

    #
    # Get icon image sizes
    #
    getIconImageSizes();


    #  Read source file names (if any).  Filter out any names matching
    #  the exclude list.

    opendir( SRCDIR, ".")
        || die("$0: Failed to open directory $sourceDirectory\n$@\n");
    @allFiles = grep(!/$excludeRegex/io,readdir( SRCDIR ));
    closedir( SRCDIR );

    #
    # Build list of image files
    #
    @allImageFiles = sort( sortImages grep( /$includeRegex/io, @allFiles));

    # Find subdirectory names (if any) ignoring hidden directories and
    # directories without index files. Directories should have index
    # files since our find goes from the bottom up and we should have
    # already processed the subdirectories.
    #
    # Only test files that are not in the allImageFiles list
    { 
        my %tarray;
	my @dirfiles;
	my @tmp_dirNames = ();
	
        grep($tarray{$_}++, @allImageFiles);
	foreach $_ ( grep(! $tarray{$_},@allFiles) ) {
	    #if( -f "${_}/${opt_indexname}" ) { # If directory & index file
                                                #  exists then add to list
	    if( -d "${_}" ) {			# If directory exists
		push(@dirfiles, $_); 		#  then add it to the list
		# Check which index file to use for JavaScript
		if( -f "$_/$fileNames{'jsDirIndex'}" ) {
		    $dirJsLink{"$_"} = $fileNames{'jsDirIndex'};
		} elsif ( -f "$_/$opt_indexname" ){
		    $dirJsLink{"$_"} = $opt_indexname;
		} else {
		    $dirJsLink{"$_"} = '';
		}
	    }
	}
	@tmp_dirNames = sort( sortDir @dirfiles);
	if( "@dirNames" ne "@tmp_dirNames" ) {
	    @dirNames = @tmp_dirNames;
	    print( STDERR "Subdirectories have changed, must re-do HTML indexes\n" )
		if $opt_debug;
	    ++$doIndexHtml;
	}
	# Check which parent-directory index file to use for JavaScript
	if( -f "../$fileNames{'jsDirIndex'}" ) {
	    $dirJsLink{".."} = $fileNames{'jsDirIndex'};
	} elsif ( -f "../$opt_indexname" ){
	    $dirJsLink{".."} = $opt_indexname;
	} else {
	    $dirJsLink{".."} = '';
	}
    }

    #
    # Determine the number of index pages to be generated, etc.
    #
    $numimages=scalar(@allImageFiles);		# Number of images
    $numdirectories=scalar(@dirNames); 		# Number of subdirectories
    $numPages=int($numimages/$maxfiles);
    if ( $numimages%$maxfiles != 0 ) {
        ++$numPages;
    }

    #
    # Check for README file and set haveReadme flag if exists
    #
    if( -f "${opt_readme}" ) {
    	$haveReadme = 1;
    }

    # Set haveImages flag if there are images in directory. This
    # effects the way the directory listing appears.

    $haveImages = 0;
    if( $numimages > 0 ) {
    	$haveImages = 1;
    }


    
    #
    # Determine page title
    #
    if( $opt_title ne '' ) {
        $pageTitle = $opt_title;
    } else {
        my $dirname=basename($sourceDirectory);
        $pageTitle = "Index of directory \"$dirname\"";
    }


    #
    # Put the PerlMagick Montage options together
    #
    $montageArguments =  ''; #"\n ";

    $montageArguments .= "background=>\'$opt_thumbbackground\',\n "
	if $opt_thumbbackground ne 'false';

    $montageArguments .= "borderwidth=>\'$opt_thumbborderwidth\',\n ";

    $montageArguments .= "compose=>\'$opt_thumbcompose\',\n "
	if $opt_thumbcompose ne 'false';

    $montageArguments .= "font=>\'$opt_thumbfont\',\n "
	if $opt_thumbfont ne 'false';

    $montageArguments .= "foreground=>\'$opt_thumbforeground\',\n "
	if $opt_thumbforeground ne 'false';

    $montageArguments .= "frame=>\'$opt_thumbframe\',\n "
	if $opt_thumbframe ne 'false';

    $montageArguments .= "geometry=>\'${opt_thumbgeometry}\',\n "
	if $opt_thumbgeometry ne 'false';

    $montageArguments .= "gravity=>\'$opt_thumbgravity\',\n "
	if $opt_thumbgravity ne 'false';

    $montageArguments .= "shadow=>\'$opt_thumbshadow\',\n "
	if $opt_thumbshadow ne 'false';

    $montageArguments .= "texture=>\'$opt_thumbtexture\',\n "
	if $opt_thumbtexture ne 'false';

    $montageArguments .= "tile=>\'${opt_columns}x${opt_rows}\',\n ";

    $montageArguments .= "transparent=>\'$opt_thumbtransparent\'\n "
	if $opt_thumbtransparent ne 'false';



    # Compute a conglomeration of all parameters that effect the
    # montage image to use for comparison with the parameters used in
    # the last run.
    {
	my $tmp_montageParameters = "$montageArguments";
	$tmp_montageParameters .= "bordercolor=>\'$opt_thumbframebgcolor\',\n "
	    if $opt_thumbframebgcolor ne 'false';
	$tmp_montageParameters .= "mapnetscape=>\'$opt_mapnetscape\',\n ";
	$tmp_montageParameters .= "mattecolor=>\'$opt_thumbframecolor\',\n "
	    if $opt_thumbframecolor ne 'false';
	$tmp_montageParameters .= "label=>\'$opt_thumblabel\',\n "
	    if $opt_thumblabel ne 'false';
	$tmp_montageParameters .= "labelwidth=>\'$opt_thumblabelwidth\',\n ";
	$tmp_montageParameters .= "\Lzoomfilter=>\'$opt_zoomfilter\'";
	if( !defined($montageParameters) || ($tmp_montageParameters ne $montageParameters)) {
	    $montageParameters = $tmp_montageParameters;
	    print( STDERR "Montage parameters have changed, must re-do montages\n" )
		if $opt_debug;
	    $opt_forcemontage=1;
	}
    }

    #
    # Store HTML options in associative array to make them easier to deal with
    #
    %htmlOpts =
	(
	 'address'		=> $opt_address,
	 'anonymous'		=> $opt_anonymous,
	 'backgroundimg'	=> $opt_icons{'background'},
	 'coloralink'		=> $opt_coloralink,
	 'colorback'		=> $opt_colorback,
	 'colorfore'		=> $opt_colorfore,
	 'colorlink'		=> $opt_colorlink,
	 'colorvlink'		=> $opt_colorvlink,
	 'dirbackgroundimg'	=> $opt_icons{'dirbackground'},
	 'dircoloralink'	=> $opt_dircoloralink,
	 'dircolorback'		=> $opt_dircolorback,
	 'dircolorfore'		=> $opt_dircolorfore,
	 'dircolorlink'		=> $opt_dircolorlink,
	 'dircolorvlink'	=> $opt_dircolorvlink,
	 'dirindexname'		=> $opt_dirindexname,
	 'footer'               => $opt_footer,
	 'framemarginwidth'	=> $opt_framemarginwidth,
	 'framemarginheight'	=> $opt_framemarginheight,
	 'framebordersize'	=> $opt_framebordersize,
	 'frameborder'		=> $opt_frameborder,
	 'framestyle'		=> $opt_framestyle,
	 'header'		=> $opt_header,
	 'htmlext'              => $opt_htmlext,
	 'imgindexname'		=> $opt_imgindexname,
	 'indexname'		=> $opt_indexname,
	 'jsdirindex'		=> $fileNames{'jsDirIndex'},
	 'jsfunctions'		=> $fileNames{'jsFunctions'},
	 'jspageindex'		=> $fileNames{'jsPageIndex'},
	 'jsvariables'		=> $fileNames{'jsVariables'},
	 'metaauthor'		=> $opt_metaauthor,
	 'metaclassification'	=> $opt_metaclassification,
	 'metadescription'	=> $opt_metadescription,
	 'metaexpires'		=> $opt_metaexpires,
	 'metakeywords'		=> $opt_metakeywords,
	 'numpages'		=> $numPages,
	 'pageindexname'	=> $opt_pageindexname,
	 'readme'		=> $opt_readme,
	 'readmepresent'	=> $haveReadme,
	 'readmevisible'	=> $opt_readmevisible,
	 'dateText'		=> "Page updated on $calendarMonths[$dateMonth] $dateDay, $dateYear",
	 'subdirectories'	=> join(' ',@dirNames),
	 'title'		=> $pageTitle,
	 'version'		=> $webmagickInfo{'revision'},
	 );

    # Compute a conglomeration of all parameters that effect the HTML
    # to use for comparison with the parameters used in the last run.
    {
	my $firstparam = 1;
	my $tmp_htmlParams = '';
	my $key;
	foreach $key (sort(keys(%htmlOpts))) {
	    if(defined($htmlOpts{$key})) {
		if( $firstparam ) {
		    $firstparam = 0;
		} else {
		    $tmp_htmlParams .= ",\n ";
		}
		$tmp_htmlParams .= $key . '=>\'' . $htmlOpts{$key} . '\'';
	    }
	}
	if( !defined($htmlParams) || ($tmp_htmlParams ne $htmlParams)) {
	    $htmlParams = $tmp_htmlParams;
	    print( STDERR "HTML parameters have changed, must re-do HTML\n" )
		if $opt_debug;
	    $opt_forcehtml=1;
	}
    }


    #
    # Print statistics message
    #
    print( STDERR "   $numimages Images $numdirectories Directories",
	  " $numPages Pages --- " )
	if $opt_verbose;

    my @imgfiles = @allImageFiles;	# Save full list of files for later
    
    # Loop through file list, placing a maximum of $maxfiles images on
    # each page.  Do at least one page (there might not be any
    # images).
    while (scalar(@allImageFiles) > 0 || $pageNumber == 1) {
	$doMontage=0;	# Set to true if montage must be generated
	$doPageHtml=0;	# Set to true if per-page HTML files must be generated

        
        print(STDERR " $pageNumber" ) if $opt_verbose;

	#
	# Get per-page image names
	# @imageNames is a list of lists
	{
	    my @tmp_imageNames = splice(@allImageFiles,0,$maxfiles);
	    if( !defined($imageNames[$pageNumber - 1]) ||
	       ("@tmp_imageNames" ne "@{$imageNames[$pageNumber - 1]}") ) {
		$imageNames[$pageNumber - 1] = [ @tmp_imageNames ];
		print( STDERR "Need to do both montage and page HTML because",
		      " file list differs\n") if $opt_debug;
		++$doMontage;
		++$doPageHtml;
	    }
	}
	my $numfiles = $#{$imageNames[$pageNumber - 1]} + 1;

        setFileNames(); 	# Set current file names

	#
	# Decide if we need to do HTML & montage
        #


	# Montage specific checks
	# Check for missing output files
	# Check for new input files
        if( $numfiles > 0 ) {
            if( ! -f $fileNames{'pageStatus'} ||
	       ( ! -f $fileNames{'montageGIF'} && ! -f $fileNames{'montageJPEG'} )) {
                # If key file is missing then do montage
                print(STDERR "\nMust do montage because a required output",
		      " file is missing\n")
		    if $opt_debug;
                ++$doMontage;
            } else {
                # If any file in file list is newer than status file,
                # then do montage
		my $file;
                foreach $file (@{$imageNames[$pageNumber - 1]}) {
                    if( fmtime($file) > $pageStatusTime ) {
                        print( STDERR "Need to do both montage and HTML",
			      " because file has been updated\n")
			    if $opt_debug;
                        ++$doMontage;
                        ++$doPageHtml;
                        print(STDERR "\nMust do montage and html: file",
			      " updated\n") if $opt_debug;
                    }
                }
            }
        }

	# HTML specific checks
	# Check for missing files
	if( ! -f $fileNames{'pageStatus'} || ! -f $fileNames{'htmlCurrentIndex'} || ! -f $opt_indexname) {
				# If key file is missing then do HTML
            print(STDERR "\n   Must do page and index HTML: output file",
		  " missing\n") if $opt_debug;
            ++$doPageHtml;
            ++$doIndexHtml;
	}

	# Overrides
	if( $opt_forcehtml ) {
	    ++$doPageHtml;
            ++$doIndexHtml;
	}
	if( $opt_forcemontage ) {
	    ++$doPageHtml;		# Montage effects HTML output
	    ++$doMontage;
	}

	my $errorstat = 1;	# Cleared for non-error block exit
PAGES:	{

	    #
	    # Build montage for current page
	    #
	    if( $doMontage && ( $numfiles > 0 ) ) {
		doMontage(@{$imageNames[$pageNumber - 1]}) && last PAGES;

		# Determine image name & size to use for imagemap
		{
		    my $montageImage;
		    my $montageImageSize;
		    if( -f $fileNames{'montageGIF'} ) {
			$montageImage = $fileNames{'montageGIF'};	# Use GIF
			$montageImageSize = html_imgsize($fileNames{'montageGIF'});
		    } elsif ( -f $fileNames{'montageJPEG'} ) {
			$montageImage = $fileNames{'montageJPEG'}; # Use JPEG
			$montageImageSize = html_imgsize($fileNames{'montageJPEG'});
		    }
		    if(!defined($montageImages[$pageNumber - 1]) ||
		       ( $montageImages[$pageNumber - 1] ne $montageImage )) {
			$montageImages[$pageNumber - 1] = $montageImage;
			print( STDERR "Need to re-do page HTML because montage image name ",
			      "has changed\n") if $opt_debug;
			++$doPageHtml;
		    }
		    if(!defined($montageImageSizes[$pageNumber - 1]) ||
		       ( $montageImageSizes[$pageNumber - 1] ne $montageImageSize )) {
			$montageImageSizes[$pageNumber - 1] = $montageImageSize;
			print( STDERR "Need to re-do page HTML because montage image size ",
			      "has changed\n") if $opt_debug;
			++$doPageHtml;
		    }
		}
	    }

	    #
	    # Write out page index files for current page
	    #
	    if( $doPageHtml ) {
		writeIndexFiles();
	    }
	    
	    # Write server-side imagemap file
	    if( $doPageHtml && ( $numfiles > 0 ) ) {
		writeImageMap();
	    }

            if ( $doPageHtml || $doIndexHtml || $doMontage ) {
		#
		# Save run status (source files and montage options)
		#
		writePerlIndexFiles();
		if( $opt_javascript ) {
		writeJavaScriptIndexFiles();
		}
            }

	    # Clear error flag
	    $errorstat = 0;
	}
	print( STDERR "Error encountered when creating page\n" )
                if $errorstat;
        ++$pageNumber;	# Next page
    }
   
    print( STDERR "\n" ) if $opt_verbose;
    
    #
    # Clean up old files
    #
    setFileNames();
    while(
	  -f $fileNames{'htmlCurrentIndex'} ||
	  -f $fileNames{'montageGIF'} ||
	  -f $fileNames{'montageJPEG'} ||
	  -f $fileNames{'montageServerMap'}
	  ) {
        unlink(
	       $fileNames{'htmlCurrentIndex'},
	       $fileNames{'montageGIF'},
	       $fileNames{'montageJPEG'},
	       $fileNames{'montageServerMap'}
	       );
        ++$pageNumber;	# Next page
        setFileNames();
    }

    #
    # Clean up cached thumbnails
    #
    if( $opt_cache && -d $opt_cachedir ) {
        opendir( CACHEDIR, "$opt_cachedir")
            || die("$0: Failed to open directory $opt_cachedir\n$@\n");
        @cacheFiles = grep(!/$excludeRegex/io,readdir( CACHEDIR ));
        closedir( CACHEDIR );
    }
    {
        my @extra;
        my %tarray;

        grep( $tarray{$_}++, @imgfiles );
        @extra = grep( $_ = "$opt_cachedir/$_", grep( ! $tarray{$_}, @cacheFiles ));
        print( STDERR "Removing extra cache files @extra\n") if $opt_debug;
        unlink( @extra );
    }

    #
    # Write out index files (Both main index and frames index files)
    #
    if( $doIndexHtml ) {
        writeTopIndexes();
    }
}

#
# Write out both top index and frame index files
#
sub writeTopIndexes {

    print( STDERR "Writing Index Files ${opt_indexname} & ",
                "${opt_pageindexname}dir.html ...\n" )
                if $opt_debug;

    #---- Generate the Variables for Format Options ----
    #
    # Generate HTML for up link
    #
    my $uphtml = '';
    # get indexname of parent directory
    my $indexname =
             get_rc_var('..', 'opt_indexname', $opt_indexname);
    unless ( $indexname eq 'NOLINK' ) {
       $uphtml = "<A HREF=\"../${indexname}\">
    <IMG SRC=\"$iconImageUrls{'up'}\" $iconImageSizes{'up'} ALT=\"^\" BORDER=0></A>
    <A HREF=\"../${indexname}\">Up</A><BR>";
    }

    #
    # Generate HTML for help link
    #
    my $helphtml = '';
    if( $haveReadme ) {
        $helphtml = "<A HREF=\"${opt_readme}\" TARGET=\"$frameTargets{'readmeview'}\">
    <IMG SRC=\"$iconImageUrls{'help'}\" $iconImageSizes{'help'} ALT=\"?\" BORDER=0></A>
    <A HREF=\"${opt_readme}\" TARGET=\"$frameTargets{'readmeview'}\">ReadMe</A><BR>";
    }

    #
    # Compute HTML for link to first image page
    #
    my $nexthtml = '';
    if( $haveReadme && $haveImages && $opt_framefmt_frames{$opt_framestyle}<=2 ) {
       $nexthtml .= "<A HREF=\"${opt_pageindexname}1$opt_htmlext\" TARGET=\"$frameTargets{'thumbview'}\">
    <IMG SRC=\"$iconImageUrls{'next'}\" $iconImageSizes{'next'} ALT=\"\" BORDER=0></A>
    <A HREF=\"${opt_pageindexname}1$opt_htmlext\" TARGET=\"$frameTargets{'thumbview'}\">Images</A><BR>";
    }

    #
    # Compute HTML for directory list
    #
    my $dirhtml = '';
    if( !$opt_prune && scalar(@dirNames) > 0 ) {
	$dirhtml = "<H3>Directories</H3>\n";
	my $subdir;
	foreach $subdir (@dirNames) {

	    # If an alternative name is defined, then use it
	    my $dirtitle;
	    if( defined( $dirTitles{$subdir} ) ) {
		$dirtitle=$dirTitles{$subdir};
	    } else {
		$dirtitle=$subdir;
	    }

	    # get indexname for sub-directory (default as this directory)
	    my $indexname =
		get_rc_var($subdir, 'opt_indexname', $opt_indexname);

	    unless ( $indexname eq 'NOLINK' ) {
		$dirhtml .= '<NOBR>';
		# If a bullet icon is defined, then use it
		# otherwise use plain text only
		if( defined( $iconImageUrls{'ball'} ) ) {
		    $dirhtml .= "<A HREF=\"${subdir}/${indexname}\"><IMG SRC=\"$iconImageUrls{'ball'}\" $iconImageSizes{'ball'} ALT=\"*\" BORDER=0></A>";
		}
		$dirhtml .= "<A HREF=\"${subdir}/${indexname}\">$dirtitle</A></NOBR><BR>\n";
	    } 
	}
    }

    #
    # Generate HTML for page index list
    #
    my $pageindexhtml = '';
    if( $haveImages ) {
        $pageindexhtml = "<H3>Page Navigator</H3>\n";
	my $i;
        for( $i=1; $i <= $numPages; ++$i ) {
            $pageindexhtml .= 
		"  <A HREF=\"${opt_pageindexname}${i}$opt_htmlext\">${i}</A><BR>\n";
        }
    }

    # ----- Evaluate the Format Options -----
    #
    # Evaluate the Top Index File Format Option
    #
    my $indexhtml;
    $indexhtml = eval '"' . $opt_dirfmt . '"';
    die( "Bad Eval of directory page template (\$opt_dirfmt)\n$@\n" )
       if $@;
    
    # Change header to plain bold text for framed directory file
    $dirhtml =~
        s|^<H3>Directories</H3>\n|<B>Directories</B><BR>\n|;
    $pageindexhtml =~
        s|^<H3>Page Navigator</H3>\n|<B>Page Navigator</B><BR>\n|;

    #
    # Evaluate the Framed Directory File Format Option
    #
    my ($pagedirhtml, $dirframelink, $pageframelink);
    $pagedirhtml = eval '"' . $opt_frameddirfmt . '"';
    die( "Bad Eval for directory page template (\$opt_frameddirfmt)\n$@\n" )
       if $@; 


    #
    # Pull README into thumbnail frame if it exists, and is
    # either marked always visible or there are no images.
    #
    $dirframelink = "${opt_pageindexname}dir.html";

    if( $opt_framefmt_frames{$opt_framestyle} <= 2 ) {
	if( $haveReadme && ( $opt_readmevisible || ! $haveImages ) ) {
	    # Point to README.html
	    $pageframelink = $opt_readme;
	} else {
	    # Point to first image page
	    $pageframelink = "${opt_pageindexname}1$opt_htmlext";
	}
    } else {
	if( $haveReadme && $opt_readmevisible ) {
	    # Point to README.html
	    $pageframelink = "${opt_pageindexname}1$opt_htmlext";
	    $imageFrameLink = $opt_readme;
	} else {
	    # Point to first image page
	    $pageframelink = "${opt_pageindexname}1$opt_htmlext";
	    $imageFrameLink = $fileNames{'htmlBlankPage'};
	}
    }

    #
    # Evaluate the Frame Format Option
    #
    my $framespechtml = eval '"' . $opt_framefmt{$opt_framestyle} . '"';
    die( "Bad Eval for Frame template (\$opt_framefmt{$opt_framestyle})\n$@\n" )
       if $@; 

    #
    # Evaluate the JavaScript version of the Frame Format
    #
    # Override normal frame targets
    $dirframelink = q/javascript:parent.returnDirectoryHTML();/;
    $pageframelink = q/javascript:parent.returnThumbNailsHTML();/;
    $imageFrameLink = q/javascript:parent.returnImageHTML(0);/;
    my $framespecjshtml = eval '"' . $opt_framefmt{$opt_framestyle} . '"';
    die( "Bad Eval for Frame template (\$opt_framefmt{$opt_framestyle})\n$@\n" )
       if $@; 

    # ----- Output Top Index File (usually "index.html") -------
    #
    open( INDEX, ">${opt_indexname}")
	|| die("$0: Failed to open file ${opt_indexname} for output\n$@\n");
    print( INDEX "<HTML>\n<HEAD>\n" );
    print( INDEX "  <TITLE>${pageTitle}</TITLE>\n" );

    # Meta tags
    print( INDEX "  <META NAME=\"GENERATOR\" CONTENT=\"WebMagick/$webmagickInfo{revision} [WebMagick]\">\n" );
    print( INDEX "  <META NAME=\"Author\" CONTENT=\"${opt_metaauthor}\">\n" )
	if( $opt_metaauthor );
    print( INDEX "  <META NAME=\"Description\" CONTENT=\"${opt_metadescription}\">\n" )
	if( $opt_metadescription );
    print( INDEX "  <META NAME=\"Keywords\" CONTENT=\"${opt_metakeywords}\">\n" )
	if( $opt_metakeywords );
    print( INDEX "  <META NAME=\"Classification\" CONTENT=\"${opt_metaclassification}\">\n" )
	if( $opt_metaclassification );
    # The value of $opt_metaexpires should be similar to:
    #   "Tue, 20 Aug 1996 14:25:27 GMT"
    print( INDEX "  <META HTTP-EQUIV=\"Expires\" CONTENT=\"${opt_metaexpires}\">\n" )
	if( $opt_metaexpires );

    # If in JavaScript mode, output code to switch to JavaScript pages
    # Currently knows about certain browsers.
    if( $opt_javascript ) {
	print( INDEX '<SCRIPT LANGUAGE="JavaScript1.1">' . "\n" );
	print( INDEX '<!--' . "\n" );
	print( INDEX '  var browserName = navigator.appName;', "\n" );
	print( INDEX '  var browserVersion = parseInt(navigator.appVersion);', "\n" );
	print( INDEX '  var filename = "', $fileNames{'jsDirIndex'}, '";', "\n" );
	print( INDEX '  if ( browserName == "Netscape" && browserVersion >= 3 ) {', "\n" );
	print( INDEX '    location.replace(filename);', "\n" );
	print( INDEX '  } else if ( browserName == "Microsoft Internet Explorer" && browserVersion >= 3) {', "\n" );
	print( INDEX '    location = filename;', "\n" );
	print( INDEX '  }', "\n" );
	print( INDEX "// -->\n" );
	print( INDEX "</SCRIPT>\n" );
    }

    print( INDEX "</HEAD>\n" );

    print( INDEX $framespechtml );
    print( INDEX "<NOFRAMES>\n" );
    print( INDEX "<BODY\n" );
    print( INDEX "  TEXT=\"${opt_colorfore}\"\n" );
    print( INDEX "  BGCOLOR=\"${opt_colorback}\"\n" )
	if $opt_colorback ne 'false';
    print( INDEX "  BACKGROUND=\"$iconImageUrls{background}\"\n" )
	if defined $iconImageUrls{background};
    print( INDEX "  LINK=\"${opt_colorlink}\"\n" );
    print( INDEX "  VLINK=\"${opt_colorvlink}\"\n" );
    print( INDEX "  ALINK=\"${opt_coloralink}\">\n");
    print( INDEX $indexhtml );
    print( INDEX "</BODY>\n</NOFRAMES>\n</HTML>" );
    close( INDEX );


    # ----- Output Top JavaScript Index File (usually "indexjs.html") -------
    #
    if( $opt_javascript ) {
    open( INDEX, ">$fileNames{'jsDirIndex'}")
	|| die("$0: Failed to open file $fileNames{'jsDirIndex'} for output\n$@\n");
    print( INDEX "<HTML>\n" );
    print( INDEX "<HEAD>\n" );
    print( INDEX "</HEAD>\n" );
    print( INDEX q/<SCRIPT LANGUAGE="JavaScript" SRC="/ . $fileNames{'jsVariables'} . q!"></SCRIPT>! . "\n" );
    print( INDEX q/<SCRIPT LANGUAGE="JavaScript" SRC="/ . $fileNames{'jsFunctions'}    . q!"></SCRIPT>! . "\n" );
    print( INDEX "<SCRIPT LANGUAGE=\"JavaScript\">\n" );
    print( INDEX q/document.write(returnFrameHTML());/ . "\n" );
    print( INDEX q/document.close();/ . "\n" );
    print( INDEX "</SCRIPT>\n" );
    print( INDEX "</HTML>\n" );
    close( INDEX );
    }


    # ----- Output Frame Directory File (usally ".indexdir.html") ------
    #
    open( INDEX, ">${opt_pageindexname}dir.html")
	|| die("$0: Failed to open file \"${opt_pageindexname}dir.html\"",
                " for output\n$@\n");
    print( INDEX "<HTML>\n<HEAD>\n" );
    print( INDEX "  <TITLE>${pageTitle}</TITLE>\n" );

    # Default URL target
    print( INDEX "  <BASE TARGET=\"$opt_frame_name_top\">\n" );

    # Meta tags
    print( INDEX "  <META NAME=\"GENERATOR\" CONTENT=\"WebMagick/$webmagickInfo{revision} [WebMagick]\">\n" );
    print( INDEX "  <META NAME=\"Author\" CONTENT=\"${opt_metaauthor}\">\n" )
	if( $opt_metaauthor );
    print( INDEX "  <META NAME=\"Description\" CONTENT=\"${opt_metadescription}\">\n" )
	if( $opt_metadescription );
    print( INDEX "  <META NAME=\"Keywords\" CONTENT=\"${opt_metakeywords}\">\n" )
	if( $opt_metakeywords );
    print( INDEX "  <META NAME=\"Classification\" CONTENT=\"${opt_metaclassification}\">\n" )
	if( $opt_metaclassification );
    # The value of $opt_metaexpires should be similar to:
    #   "Tue, 20 Aug 1996 14:25:27 GMT"
    print( INDEX "  <META HTTP-EQUIV=\"Expires\" CONTENT=\"${opt_metaexpires}\">\n" )
	if( $opt_metaexpires );
    
    print( INDEX "</HEAD>\n" );
    print( INDEX "<BODY\n" );
    print( INDEX "  TEXT=\"${opt_dircolorfore}\"\n" );
    print( INDEX "  BGCOLOR=\"${opt_dircolorback}\"\n" )
	if $opt_dircolorback ne 'false';
    print( INDEX "  BACKGROUND=\"$iconImageUrls{dirbackground}\"\n" )
	if defined $iconImageUrls{dirbackground};
    print( INDEX "  LINK=\"${opt_dircolorlink}\"\n" );
    print( INDEX "  VLINK=\"${opt_dircolorvlink}\"\n" );
    print( INDEX "  ALINK=\"${opt_dircoloralink}\">\n" );
    print( INDEX $pagedirhtml );
    print( INDEX "</BODY></HTML>\n" );
    close( INDEX );


    return ( 0 );
}


#
# Write out page index files
#
sub writeIndexFiles {
    my $indexbar;		# HTML text representing numeric selection bar
    my $errorstat = 0;

    print( STDERR "Writing file $fileNames{'htmlCurrentIndex'} ...\n" )
        if $opt_debug;

    my $numimages = $#{$imageNames[$pageNumber - 1]} + 1;
    
    # Calculate page index bar
    # No link for current page
    # Nothing at all when there is only one page.
    $indexbar = "<NOBR>\n";

    # --- readme link ---
    if ( $haveReadme ) {
	$indexbar .= "<A HREF=\"${opt_readme}\" TARGET=\"$frameTargets{'readmeview'}\"
    ><IMG SRC=\"$iconImageUrls{'help'}\" $iconImageSizes{'help'} ALT=\"ReadMe\" BORDER=0></A>\n";
    }
    # --- prev link ---
    if( $pageNumber == 1 ) {
        # Go to base index page if on first page
        $indexbar .= "<A HREF=\"${opt_indexname}\" TARGET=\"$opt_frame_name_top\"
     ><IMG SRC=\"$iconImageUrls{'prev'}\" $iconImageSizes{'prev'} ALT=\"Prev\" BORDER=0></A>\n";
    } else {
        # Go to preceding page
        $indexbar .= "<A HREF=\"$fileNames{'htmlPrevIndex'}\" TARGET=\"$frameTargets{'thumbview'}\"
    ><IMG SRC=\"$iconImageUrls{'prev'}\" $iconImageSizes{'prev'} ALT=\"Prev\" BORDER=0></A>\n";
    }
    # --- next link ---
    if( $numPages > 1 ) {
	if( $pageNumber < $numPages ) {
	    $indexbar .= "<A HREF=\"$fileNames{'htmlNextIndex'}\" TARGET=\"$frameTargets{'thumbview'}\"
    ><IMG SRC=\"$iconImageUrls{'next'}\" $iconImageSizes{'next'} ALT=\"Next\" BORDER=0></A>\n";
	} else {
	    # Print a grayed out arrow to maintain alignment
	    $indexbar .= "<IMG SRC=\"$iconImageUrls{'next_gray'}\" $iconImageSizes{'next_gray'} ALT=\"\" BORDER=0>\n";
        }
    # --- page links ---
	my $page;
	for ( $page = 1; $page <= $numPages; ++$page) {
	    if ( $page != $pageNumber ) {
		$indexbar .= "<A HREF=\"${opt_pageindexname}${page}$opt_htmlext\" TARGET=\"$frameTargets{'thumbview'}\">${page}</A>\n";
	    } else {
        	$indexbar .= " ${page}\n";
	    }
	}
    }
    $indexbar .= "</NOBR>\n";

    
    open( INDEX, ">$fileNames{'htmlCurrentIndex'}")
        || die("$0: Failed to open file $fileNames{'htmlCurrentIndex'} for output\n$@\n");
    print( INDEX "<HTML>\n<HEAD>\n" );
    print( INDEX "  <TITLE>${pageTitle}</TITLE>\n" );
    print( INDEX "  <BASE TARGET=\"$frameTargets{'imageview'}\">\n" );

    # Meta tags
    print( INDEX "  <META NAME=\"GENERATOR\" CONTENT=\"WebMagick/$webmagickInfo{revision} [WebMagick]\">\n" );
    print( INDEX "  <META NAME=\"Author\" CONTENT=\"${opt_metaauthor}\">\n" )
	if( $opt_metaauthor );
    print( INDEX "  <META NAME=\"Description\" CONTENT=\"${opt_metadescription}\">\n" )
	if( $opt_metadescription );
    print( INDEX "  <META NAME=\"Keywords\" CONTENT=\"${opt_metakeywords}\">\n" )
	if( $opt_metakeywords );
    print( INDEX "  <META NAME=\"Classification\" CONTENT=\"${opt_metaclassification}\">\n" )
	if( $opt_metaclassification );
    # The value of $opt_metaexpires should be similar to:
    #   "Tue, 20 Aug 1996 14:25:27 GMT"
    print( INDEX "  <META HTTP-EQUIV=\"Expires\" CONTENT=\"${opt_metaexpires}\">\n" )
	if( $opt_metaexpires );

    print( INDEX "</HEAD>\n" );
    print( INDEX "<BODY\n" );
    print( INDEX "  TEXT=\"${opt_colorfore}\"\n" );
    print( INDEX "  BGCOLOR=\"${opt_colorback}\"\n" );
    print( INDEX "  BACKGROUND=\"$iconImageUrls{background}\"\n" )
	if defined $iconImageUrls{background};
    print( INDEX "  LINK=\"${opt_colorlink}\"\n" );
    print( INDEX "  VLINK=\"${opt_colorvlink}\"\n" );
    print( INDEX "  ALINK=\"${opt_coloralink}\">\n\n" );

    print( INDEX "${opt_header}\n" ) if $opt_header;

    # Leave page blank unless there is something to show
    if( $numimages > 0 ) {
	# Total HACK!!!
	if( $opt_framestyle == 1 ) {
	    print( INDEX "<p><FONT SIZE=-1>Index of files \"$imageNames[$pageNumber - 1][0]\" through",
		  " \"$imageNames[$pageNumber - 1][$numimages-1]\"</p>\n" );
	}
	print( INDEX "\n$indexbar<BR>\n\n" );

	#
	# Add image map info to html file
	#
	my $mapname = "thumbnails";
	if ( "${opt_htimage}" ne '' ) {
	    print( INDEX
		  "<A HREF=\"${opt_htimage}$fileNames{'montageServerMap'}\"\n>" );
	} else {
	    print( INDEX
		  "<A HREF=\"" . basename($fileNames{'montageServerMap'}) . "\"\n>");
	}
	print( INDEX
	      "<IMG SRC=\"$montageImages[$pageNumber - 1]\" $montageImageSizes[$pageNumber - 1]}",
	      " USEMAP=\"#${mapname}\" BORDER=0 ISMAP>" );
	print( INDEX "</A>\n" );
	print( INDEX "<MAP NAME=\"${mapname}\">\n" );
	my $imageNum;
	for( $imageNum = 0; $imageNum <= $#{$imageNames[$pageNumber - 1]}; ++$imageNum ) {
	    my $pic = $imageNames[$pageNumber - 1][$imageNum];
	    if ( $opt_pichtml ) {
		my $pichtml;
		my $target = '';

		if( !$opt_pichtmlext ) {
			$pichtml = $pic . ".html";
		} else {
			$pichtml = $pic . $opt_pichtmlext;
		}
		open( PICHTML, ">$pichtml")
		    || die("$0: Failed to open file $pichtml for output\n$@\n");
		print( PICHTML "<HTML>\n<HEAD>\n" );
		print( PICHTML "  <TITLE>$pic</TITLE>\n" );
		print( PICHTML "</HEAD>\n" );
		print( PICHTML "<BODY\n" );
		print( PICHTML "  TEXT=\"${opt_colorfore}\"\n" );
		print( PICHTML "  BGCOLOR=\"${opt_colorback}\"\n" );
		print( PICHTML "  BACKGROUND=\"$iconImageUrls{background}\"\n" )
		    if defined $iconImageUrls{background};
		print( PICHTML "  LINK=\"${opt_colorlink}\"\n" );
		print( PICHTML "  VLINK=\"${opt_colorvlink}\"\n" );
		print( PICHTML "  ALINK=\"${opt_coloralink}\">\n\n" );
		print( PICHTML "$opt_pichtmltop") if $opt_pichtmltop;
		if ( $pic =~ /\.(jpg|jpeg?|gif|xbm)$/i ) {
		    print( PICHTML "<IMG SRC=\"$pic\">" );
		} else {
		    print( PICHTML "<A HREF=\"$pic\"><BIG><B>$pic</B></A> ", fsize($pic), "</BIG>" );
		}
		print( PICHTML "$opt_pichtmlbottom\n") if $opt_pichtmlbottom;
		print( PICHTML "</BODY>\n" );
		print( PICHTML "</HTML>\n" );
		close ( PICHTML );
		if ($opt_pichtmltarget) {
		    $target = " TARGET=\"$opt_pichtmltarget\"";
		}
		print( INDEX "  <AREA$target HREF=\"", $pichtml,
		  "\" SHAPE=RECT COORDS=", $imageThumbCoords[$pageNumber - 1][$imageNum],">\n" );
	    } else {
		print( INDEX "  <AREA HREF=\"", $pic,
		  "\" SHAPE=RECT COORDS=", $imageThumbCoords[$pageNumber - 1][$imageNum],">\n" );
	    }
	}
	print( INDEX "</MAP>\n" );
    }

    print( INDEX "${opt_footer}\n" ) if $opt_footer;

    # Print Copyright info on non-blank pages.
    if( $numimages > 0 ) {
       print( INDEX "<BR><ADDRESS>\n" );
       if( "${opt_address}" ne '' ) {
           print( INDEX "${opt_address}<BR>\n" );
       }
       print( INDEX "<FONT SIZE=-1>" );
       print( INDEX "$htmlOpts{'dateText'}\n" );
       # If anonymous, don't show copyright and address info
       if( ! $opt_anonymous ) {
	   print( INDEX "<BR><HR>\nProduced by " );
	   print( INDEX "<NOBR><A HREF=\"http://www.cyberramp.net/~bfriesen/webmagick/\"",
		 ">WebMagick</A>" );
	   print( INDEX " $webmagickInfo{revision}</NOBR>, <NOBR>Copyright &copy;</NOBR> <NOBR>Bob Friesenhahn</NOBR>\n" );
       }
       print( INDEX "</ADDRESS>\n" );
    }

    print( INDEX "</BODY>\n" );
    print( INDEX "</HTML>\n" );

    # Close current HTML index file
    close( INDEX );

    return ( $errorstat );
}

#
# Write out JavaScript index files
#
sub writeJavaScriptIndexFiles {

    print("Writing JavaScript status file: $fileNames{'jsPageIndex'}\n") if $opt_debug;

    #
    # Write JavaScript "index" page.
    # This page loads JavaScript source files and ensures that windows are drawn
    #
    open( JSINDEX, ">$fileNames{'jsPageIndex'}")
        || die("$0: Failed to open file $fileNames{'jsPageIndex'} for output\n$@\n");

    print( JSINDEX "<HTML>\n");
    print( JSINDEX "<HEAD>\n");
    print( JSINDEX "<SCRIPT LANGUAGE=\"JavaScript\" SRC=\"$fileNames{'jsVariables'}\"></SCRIPT>\n");
    print( JSINDEX "<SCRIPT LANGUAGE=\"JavaScript\" SRC=\"$fileNames{'jsFunctions'}\"></SCRIPT>\n");
    print( JSINDEX "</HEAD>\n");
    print( JSINDEX "<BODY>\n");
#    print( JSINDEX "<SCRIPT LANGUAGE=\"JavaScript\">\n");
#    print( JSINDEX "  parent.webmagick.drawWindows();\n");
#    print( JSINDEX "</SCRIPT>\n");
    print( JSINDEX "</BODY>\n");
    print( JSINDEX "</HTML>\n");
    close( JSINDEX );    


    #
    # JavaScript Variable definitions
    #
    open( JSVARS, ">$fileNames{'jsVariables'}")
        || die("$0: Failed to open file $fileNames{'jsVariables'} for output\n$@\n");

    print( JSVARS "//\n// WebMagick Run Status File -- JavaScript Format\n//\n" );

    #
    # Directory global variables
    #
    print( JSVARS "//\n// Directory-global definitions\n//\n\n" );

    # Subdirectory names
    print( JSVARS "\n// subdirectory names\n",
	  jsArray( 'dirNames', @dirNames ) );
    
    # Subdirectory titles
    print( JSVARS "\n// subdirectory titles\n",
	  jsHash( 'dirTitles', \%dirTitles ) );

    # Subdirectory links
    print( JSVARS "\n// subdirectory links\n", jsHash( 'dirLinks', \%dirJsLink ) );

    # Image labels
    print( JSVARS "\n// image titles\n", jsHash( 'imageLabels', \%imageLabels ) );

    # Montage options ($montageParameters)
#    print( JSVARS "\n// montage parameters\n",
#	  jsVariable( 'montageParameters', \$montageParameters) );
    
    # HTML options
    print( JSVARS "\n// HTML options\n",
	  jsHash( 'htmlOpts', \%htmlOpts ) );
    
    # Icon URLs
    print( JSVARS "\n// icon URLs\n",
	  jsHash( 'iconImageUrls', \%iconImageUrls ) );

    # Icon sizes
    print( JSVARS "\n// icon sizes\n", 
	  jsHash( 'iconImageSizes', \%iconImageSizes ) );

    #
    # Page specific variables
    #
    print( JSVARS "\n//\n// Page-Specific variable definitions\n//\n" );

    # Generated File names
#    print( JSVARS "\n// file names\n",
#	  jsHash( 'fileNames', \%fileNames ) );
    
    # Image names
    print( JSVARS "\n// image names (imageNames[page number][image number])\n",
	  jsDoubleArray( 'imageNames', @imageNames) );
        
    # Image thumbnail map (co-ordinate) information (@imageThumbCoords)
    print( JSVARS "\n// thumbnail coordinates (imageThumbCoords[page number])\n",
	  jsDoubleArray( 'imageThumbCoords', @imageThumbCoords ) );

    # Montage image names  (@montageImages) already in per-page array form
    print( JSVARS "\n// montage image names (montageImages[page number])\n",
	  jsArray( 'montageImages', @montageImages) );

    # Montage image sizes  (@montageImageSizes) already in per-page array form
    print( JSVARS "\n// montage image sizes (montageImageSizes[page number])\n",
	  jsArray( 'montageImageSizes', @montageImageSizes) );

    # Set flag to indicate this file completely loaded
    print( JSVARS "\nvar jsVarsLoaded = 1;\n" );

    close( JSVARS );
    print("Done writing JavaScript\n") if $opt_debug;
}

#
# Write out PERL-format run-status file
#
sub writePerlIndexFiles {
    open( PERLVARS, ">$fileNames{'pageStatus'}" )
	|| die( "Unable to open file $fileNames{'pageStatus'}!\n$@\n" );
    print(STDERR "Writing PERL status file: $fileNames{'pageStatus'}\n") if $opt_debug;

    print( PERLVARS "#\n# WebMagick Run Status File -- PERL Format\n#\n\n" );

    #
    # Directory global variables
    #
    print( PERLVARS "#\n# Directory-global definitions\n#\n" );
    
    # Subdirectory names (@dirNames)
    print( PERLVARS "\n# subdirectory names\n",
	  plArray( 'dirNames', @dirNames ) );
    
    # Subdirectory titles
    print( PERLVARS "\n# subdirectory titles\n",
	  plHash( 'dirTitles', \%dirTitles ) );

    # Image labels
    print( PERLVARS "\n# image titles\n", plHash( 'imageLabels', \%imageLabels ) );

    # Montage options ($montageParameters)
    print( PERLVARS "\n# montage parameters\n",
	  plVariable( 'montageParameters', \$montageParameters) );

    # HTML options ($htmlParams)
    print( PERLVARS "\n# HTML options\n",
	  plVariable( 'htmlParams', \$htmlParams ) );

    # Icon URLs
    print( PERLVARS "\n# icon URLs\n",
	  plHash( 'iconImageUrls', \%iconImageUrls ) );

    # Icon sizes
    print( PERLVARS "\n# icon sizes\n", 
	  plHash( 'iconImageSizes', \%iconImageSizes ) );

    #
    # Page-Specific variable definitions
    #
    print( PERLVARS "\n#\n# Page-specific variables\n#\n" );

    # Image names (@imageNames)
    print( PERLVARS "\n# image names (\$imageNames[page number][image number])\n",
	  plDoubleArray( 'imageNames', @imageNames) );

    # Image thumbnail map (co-ordinate) information (@imageThumbCoords)
    print( PERLVARS "\n# thumbnail coordinates (\$imageThumbCoords[page number][thumb number])\n",
	  plDoubleArray( 'imageThumbCoords', @imageThumbCoords ) );

    # Montage image names  (@montageImages) already in per-page array form
    print( PERLVARS "\n# montage image names (\$montageImages[page number])\n",
	  plArray( 'montageImages', @montageImages ) );

    # Montage image sizes  (@montageImageSizes) already in per-page array form
    print( PERLVARS "\n# montage image sizes (\$montageImageSizes[page number])\n",
	  plArray( 'montageImageSizes', @montageImageSizes ) );

    # Set flag to indicate this file completely loaded
    print( PERLVARS "\n\$perlVarsLoaded = 1;\n" );

    close( PERLVARS );
}

#
# Build montage using PerlMagick
#
sub doMontage {
    my $errorstat = 1;	# Started with "failed" status

    use Image::Magick;

    my (
	$imagename,		# Image name
	$image,			# An individual image
	$montage,		# Montage of images
	$newthumb,		# Set to 1 if new thumbnail
	$status,		# Return status
	$thumbs			# Thumbnail array
	);

    # If we need to, then do the expensive stuff Build index
    # files via PerlMagick's Montage operation. Go out of our
    # way to avoid problems with multi-image files. JPEG does not
    # support transparency but we fudge by setting the
    # background color in the JPEG file to the page color.
    # Hopefully browsers that support JPEG also support
    # setting the background

    unlink(
	   $fileNames{'montageGIF'},
	   $fileNames{'montageJPEG'},
	   );

    
    #
    # If caching thumbnails then ensure that directory exists
    #
    mkdir( $opt_cachedir, 0755 ) if ! -d $opt_cachedir;

    # Read images into PerlMagick object
    print( STDERR "\nReading images: ", join(' ', @{$imageNames[$pageNumber - 1]}), "\n" )
	if $opt_debug;

    # Allocate thumbnail image
    $thumbs = Image::Magick->new;
         
    # Allocate scratch image
    $image = Image::Magick->new;

    # Allocate and read Netscape map image (Netscape 216 color cube)
    # No need to do an allocation if we are not doing the mapping.
    if ($opt_mapnetscape) {
	$netscapeColormap = Image::Magick->new;
	$status = $netscapeColormap->Read('netscape:');
	handleMagickError( __FILE__, __LINE__, 'netscape:', $status) if "$status";
    }

MONTAGE:
    {     
READ:       
	foreach $imagename (@{$imageNames[$pageNumber - 1]}) {

	    my (
		$width,		# Image width
		$height,	# Image height
		$base_columns,	# Original width
		$base_rows,	# Original height
		$class,		# Image class
		$comment,	# Image comment
		$depth,		# Image color depth
		$filesize,	# Image file size
		$magick,	# Image magick
		);
	    #
	    # Handle thumbnail cache
	    #
	    my $cachename = "$opt_cachedir/$imagename";

	    $newthumb = 1;	# Start presuming that thumbnail is new
	    # If we are caching, and cache thumbnail exists and is newer then use it
	    if ( $opt_cache && ! $opt_forcecache && -f $cachename && (fmtime($cachename)
								      >= fmtime($imagename))) {
		# Read image
		print( STDERR "Reading $cachename ...\n" ) if $opt_debug;
		$status = $image->Read("$cachename");
		if("$status") {
		    undef @$image; # Only delete image data, not object
		    handleMagickError( __FILE__, __LINE__, $cachename, $status);
		    next READ; # Try to read next image
		}

		# Obtain original image parameters
		$comment = $image->Get("comment");
		if ($comment =~
		    # xv 3.00 & 3.10 format
		    /IMGINFO:(\d+)x(\d+) (\S+) file\s+\((\d+) bytes\)/ ) {
		    $width = $1;
		    $height = $2;
		    $magick = $3;
		    $filesize = $4;
		} else {
		    print( STDERR "Failed to grock image info from thumbnail ${cachename}!\n",
			  "Removing cache file ...\n" );
		    print( STDERR "Run WebMagick again to re-generate the thumbnail.\n" );
		    print( STDERR "If problem continues then your ImageMagick is out of date.\n" );
		    unlink( $cachename );
		}

		# Indicate that thumbnail came from cache
		$newthumb = 0;
	    } else {
		# Otherwise, read and scale image

		# Set desired image read size.  The JPEG library will
		# read and return a reduced image which is at least
		# the size specified (it returns a number of standard
		# scaled sizes) but not smaller.
		# This uses a feature available in PerlMagick 1.12 and beyond
		$status = $image->Set(size=>$opt_thumbgeometry);
		handleMagickError( __FILE__, __LINE__, "$opt_thumbgeometry", $status) if "$status";
		
		# Read image
		print( STDERR "Reading ${imagename}\[0\] ...\n" ) if $opt_debug;
		$status = $image->Read("${imagename}\[0\]");
		if("$status" && handleMagickError( __FILE__, __LINE__, $imagename, $status)) {
		    undef @$image; # Only delete image data, not object
		    print("Trying next image ...\n" );
		    next READ; # Try to read next image		    }
		}

		# Scale image and obtain original parameters if not from cache
		if( $newthumb ) {

		    #
		    # Apply any PerlMagick operations specified by $opt_thumbprehook
		    #
		    if( $opt_thumbprehook ) {
			print("Evaluating thumbnail pre-hook ...\n$opt_thumbprehook\n" )
			    if $opt_debug;
			eval $opt_thumbprehook;
		    }

		    # Obtain image parameters
		    ( $width, $height, $filesize, $magick, $class, $depth ) =
			$image->Get(
				    'width',
				    'height',
				    'filesize',
				    'magick',
				    'class',
				    'depth');
		    
		    if( $opt_debug ) {
		      print("Image: ${width}x${height} $class $filesize bytes $magick $depth bits\n");
		    }

		    # Obtain original image size.  This uses a feature
		    # available in PerlMagick 1.12 and beyond.  If the
		    # feature is not supported then undefined values
		    # should be returned.
		    ($base_columns, $base_rows) = $image->Get('base_columns', 'base_rows');
		    if( defined($base_columns) && defined($base_rows) ) {
			$width = $base_columns;
			$height = $base_rows;
			print("Saving original image size ${base_columns}x${base_rows}\n")
			    if $opt_debug;
		    }

		    my $geometry;
		    if( $opt_cache ) {
			$geometry = $opt_cachegeom;
		    } else {
			$geometry = $opt_thumbgeometry;
		    }

		    my $opt_sampling = 0; # Set to 1 to enable sampling
		    if( $class eq 'PseudoClass' && $opt_sampling ) {
			print( STDERR "Sampling $imagename to geometry \"${geometry}>\" ...\n")
			    if $opt_debug;
			$status = $image->Sample(geometry=>"${geometry}>");
			
		    } else {
			print( STDERR "Zooming $imagename with geometry \"${geometry}>\" ...\n")
			    if $opt_debug;
			$status = $image->Zoom(filter=>"${opt_zoomfilter}",
					       geometry=>"${geometry}>" );
		    }
		    
		    if("$status") {
			undef @$image; # Only delete image data, not object
			handleMagickError( __FILE__, __LINE__, $imagename, $status);
			next READ; # Try to read next image
		    }
		}

		#
		# Apply any PerlMagick operations specified by $opt_thumbposthook
		#
		if( $opt_thumbposthook ) {
		    print("Evaluatinog thumbnail post-hook ...\n$opt_thumbposthook\n" ) if $opt_debug;
		    eval $opt_thumbposthook;
		}

		# If we are caching, thumbnail is new, and image is
		# large enough, then write it to thumbnail cache
		if( $opt_cache && $newthumb && (($width*$height) > $opt_cachemin)) {

		    my $comment="IMGINFO:${width}x${height} ${magick} file  (${filesize} bytes)";
		    print( STDERR "Applying image comment:\n${comment}\n") if $opt_debug;

		    # Apply comment to thumbnail image
		    $status = $image->Comment( $comment );
		    handleMagickError( __FILE__, __LINE__, $cachename, $status) if "$status";
		    
		    print( STDERR "Writing ${cachename} with format ${opt_cacheformat} ...\n" )
			if $opt_debug;
                    #
                    # Give JPEG files special treatment
                    #
                    if( $opt_cacheformat eq 'JPEG' || $opt_cacheformat eq 'JPG' ) {
		        $status = $image->Write(
                                                  filename=>"${opt_cacheformat}:${cachename}",
					          interlace=>'None',
					          quality=>85
                                                );
                    } else {
		        $status = $image->Write(
                                                  filename=>"${opt_cacheformat}:${cachename}"
                                               );
                    }
		    handleMagickError( __FILE__, __LINE__, $cachename, $status) if "$status";
		}

	    }

	    #
	    # Set image label
	    #
	    my $label = '';
	    if( $opt_thumblabel ne 'false' ) {
		if( defined( $imageLabels{$imagename} ) ) {
		    # Set image specific label
		    $label = $imageLabels{$imagename};
		} else {
		    # Set default label
		    $label = $opt_thumblabel;
		}
	    }

	    if ($label ne '') {
		my $sizestr;
		my $kb = 1024;
		my $mb = $kb * $kb;
		if( $filesize <= 9999 ) {
		    # print as bytes
		    $sizestr = "${filesize}b";
		} elsif( $filesize <= 9999999 ) {
		    # print as kilobytes
		    my $size = int($filesize/$kb);
		    $sizestr = "${size}kb";	    
		} else {
		    # print as megabytes
		    my $size = int($filesize/$mb);
		    $sizestr = "${size}Mb";
		}

		#
		# Truncate label down to width $opt_thumblabelwidth
		#
		my $imagebase;
		($imagebase = $imagename) =~ s/\.[^\.]*$//g;
		# %b = file size
		# %d = directory (not implemented)
		# %e = extension (not implemented)
		# %f = full filename
		# %h = height
		# %m = magick
		# %n = filename minus extension
		# %s = scene number (not implemented)
		# %t = top of filename (not implemented)
		# %w = width
		$label =~ s/%b/$sizestr/g;
		$label =~ s/%f/$imagename/g;
		$label =~ s/%h/$height/g;
		$label =~ s/%m/$magick/g;
		$label =~ s/%n/$imagebase/g;
		$label =~ s/%w/$width/g;
		my @llines = split(/\\n/, $label);
		grep($_ = substr( $_, 0, $opt_thumblabelwidth), @llines);
		$label = join("\n", @llines);
		
		print( STDERR "Applying image label: \"${label}\"\n" )
		    if $opt_debug;
		$status = $image->Label( $label );
		handleMagickError( __FILE__, __LINE__, $imagename, $status) if "$status";
	    }

	    #
	    # Add thumbnail to thumbs array
	    #
	    push(@$thumbs, @$image);
	     
	    #print( STDERR "Freeing $imagename ...\n") if $opt_debug;
             
	    # Only delete image data, not object
	    undef @$image;
	}
# READ end block

	#
	# Set common image attributes
	#
        if( $opt_thumbframebgcolor ne 'false' ) {
	    $status = $thumbs->Set( bordercolor=>$opt_thumbframebgcolor );
	    if( "$status" ) {
		handleMagickError( __FILE__, __LINE__, "", $status);
	        last MONTAGE;
	    }
        }
        if( $opt_thumbframecolor ne 'false' ) {
	    $status = $thumbs->Set( mattecolor=>$opt_thumbframecolor );
	    if( "$status" ) {
		handleMagickError( __FILE__, __LINE__, "", $status);
	        last MONTAGE;
	    }
        }
	# New-style way to set label text foreground color
	# Somewhere along the way 'foreground' started being ignored by montage
        if( $opt_thumbforeground ne 'false' ) {
	    $status = $thumbs->Set( pen=>$opt_thumbforeground );
	    if( "$status" ) {
		handleMagickError( __FILE__, __LINE__, "", $status);
	        last MONTAGE;
	    }
        }

	#
	# Do the montage
	#
	print( STDERR "Creating montage using options:\n $montageArguments\n" )
	    if $opt_debug;

	eval "\$montage = \$thumbs->Montage( $montageArguments ) ;";
	if( $@ ) {
	    handleMagickError( __FILE__, __LINE__, "", $@);
	    last MONTAGE;
	}
	handleMagickError( __FILE__, __LINE__, "", $montage) unless ref($montage);
	
	last MONTAGE unless ref($montage);

	#
	# Obtain imagemap info (thanks to Cristy for the relevant code)
	#
	{
	    my @thumbCoords;
	    my $montageWidth = $montage->Get('width');
	    my $montageHeight = $montage->Get('height');
	    $montage->Get('montage')=~/(\d+)x(\d+)\+(\d+)\+(\d+)/;
	    my $thumbWidth=$1;
	    my $thumbHeight=$2;
	    my $x=$3;
	    my $y=$4;
	    my $directory = $montage->Get('Directory');
	    print( STDERR "Montage directory = $directory\n" ) if $opt_debug;
	    for (split(/\n/,$directory))
	    {
		# Eliminate cache dir from path HACK! HACK!
		s%$opt_cachedir/%% if $opt_cache;
		my $img = $_;
		my $x1 = $x;
		my $y1 = $y;
		my $x2 = $x+$thumbWidth-1;
		my $y2 = $y+$thumbHeight-1;

		push(@thumbCoords, "$x1,$y1,$x2,$y2");

		#print "  <area href=", $_, " shape=rect coords=$x1,$y1,", $x2,',', $y2, ">\n";
		$x+=$thumbWidth;
		if ($x >= $montageWidth)
		{
		    $x=0;
		    $y+=$thumbHeight;
		}
	    }
	    if( !defined($imageThumbCoords[$pageNumber - 1]) ||
	       ("@{$imageThumbCoords[$pageNumber - 1]}" ne "@thumbCoords") ) {
		$imageThumbCoords[$pageNumber - 1] = [ @thumbCoords ];
		print( STDERR "Thumbnail coordinates have changed, must re-do HTML page\n" )
		    if $opt_debug;
		++$doPageHtml;
	    }
	}

	#
	# Process & Write GIF file
	#

	# Copy image so we can play with it without effecting original
	print( STDERR "Copying montage to scratch ...\n" )
	    if $opt_debug;
	$image = $montage->Copy();
	handleMagickError( __FILE__, __LINE__, "", $image) unless ref($image);
	last MONTAGE unless ref($image);

	if ($opt_mapnetscape) {
	    print( STDERR "Mapping $fileNames{'montageGIF'} to Netscape 216 color cube...\n" )
		if $opt_debug;
	    $status = $image->Map(image=>$netscapeColormap, dither=>'True');
	    handleMagickError( __FILE__, __LINE__, "", $status) if "$status";
	}

	if( ! $opt_forcejpeg ) {
	print( STDERR "Writing $fileNames{'montageGIF'} ...\n" ) if $opt_debug;
	$status = $image->Write(
				colors=>256,
				colorspace=>'YUV',
				dither=>'True',
				filename=>"GIF:$fileNames{'montageGIF'}",
				interlace=>'Line'
				);
	handleMagickError( __FILE__, __LINE__, $fileNames{'montageGIF'}, $status) if "$status";
	last MONTAGE if "$status";
	undef @$image;
	}

	# If not doing GIF only, do JPEG	      
	if( ! $opt_forcegif ) {
	    # Only do JPEG if GIF is large.
	    # Most reasonable GIFs are under 30K
	    if( $opt_forcejpeg || fsize( $fileNames{'montageGIF'} ) > $opt_maxgif ) {
		# Write JPEG file
		print( STDERR "Writing $fileNames{'montageJPEG'} ...\n" )
		    if $opt_debug;
		$status = $montage->Write(
					  filename=>"JPEG:$fileNames{'montageJPEG'}",
					  interlace=>'Plane',
					  quality=>70
					  );
		handleMagickError( __FILE__, __LINE__, $fileNames{'montageJPEG'}, $status) if "$status";
		last MONTAGE if "$status";
	    } else {
		print( STDERR "Avoiding JPEG image since GIF is small enough\n" )
		    if $opt_debug;
	    }
	} else {
	    print( STDERR "Avoiding JPEG image due to forcegif option\n" )
		if $opt_debug;
	}

	# Decide to use GIF or JPEG version of output depending on size.
	# If there is only one type then no need.
	if( -f $fileNames{'montageGIF'} && -f $fileNames{'montageJPEG'} ) {
	    if( fsize($fileNames{'montageGIF'}) > fsize($fileNames{'montageJPEG'}) ) {
		print( STDERR "Choosing JPEG since it is smaller\n" )
		    if $opt_debug;
		unlink($fileNames{'montageGIF'}); # Use JPEG
	    } else {
		print( STDERR "Choosing GIF since it is smaller\n" )
		    if $opt_debug;
		unlink($fileNames{'montageJPEG'}); # Use GIF
	    }
	}
	$errorstat = 0;	# If it made it this far, then no error
    }
# MONTAGE end block

    # Delete montage image
    #print( STDERR "Freeing montage image ...\n" ) if $opt_debug;
    undef @$montage;
    undef $montage;
     
    # Delete thumbnails
    #print( STDERR "Freeing thumbnail images ...\n" ) if $opt_debug;
    undef @$thumbs;
    undef $thumbs;

    # Delete scratch image
    #print( STDERR "Freeing scratch image ...\n" ) if $opt_debug;
    undef @$image;
    undef $image;

    # Delete Netscape map image
    if ($opt_mapnetscape) {
	#print( STDERR "Freeing Netscape map image ...\n" ) if $opt_debug;
	undef @$netscapeColormap;
	undef $netscapeColormap;
    }
     
    unlink(
	   $fileNames{'montageJPEG'},
	   $fileNames{'montageGIF'}
	   ) if $errorstat;
    return( $errorstat );
}

#
# Write out server-side imagemap data
#
sub writeImageMap {
    my $errorstat = 0;
    # Write out server-side imagemap (CERN or NCSA)
    # This uses the absolute path as the URL or a relative one
    # from the referring URL
    # The server must map URLs specified with filesystem paths
    # or support relative URLs from the referrer (Apache &
    # latest NCSA do).
    print( STDERR "Writing file $fileNames{'montageServerMap'} ...\n" ) if $opt_debug;
    open( IMAGEMAP, ">$fileNames{'montageServerMap'}" )
	|| die("$0: Failed to open file $fileNames{'montageServerMap'} for output\n$@\n");
    # default URL
    if ( "${opt_htimage}" ne '' ) {
	print( IMAGEMAP "default "
	      . abs_path_to_url("${sourceDirectory}/${opt_pageindexname}${pageNumber}$opt_htmlext")
	      . "\n" );
    } else {
	print( IMAGEMAP "default ${opt_pageindexname}${pageNumber}$opt_htmlext\n" );
    }
    my $imageNum;
    for( $imageNum = 0; $imageNum <= $#{$imageNames[$pageNumber - 1]}; ++$imageNum ) {
	my $url = $imageNames[$pageNumber - 1][$imageNum];
	my($x1,$y1,$x2,$y2);
	($x1,$y1,$x2,$y2) = split(',', $imageThumbCoords[$pageNumber - 1][$imageNum]);
	if( $opt_pichtml ) {
		if( !$opt_pichtmlext ) {
			$url .= ".html";
		} else {
			$url .= $opt_pichtmlext;
		}
	}
	if( $opt_maptype eq 'ncsa' ) {
	    if ( "${opt_htimage}" ne '' ) {
		print( IMAGEMAP "rect "
		      . abs_path_to_url("${sourceDirectory}/${url}")
		      . " $x1,$y1 $x2,$y2\n" );
	    } else {
		print( IMAGEMAP "rect ${url} $x1,$y1 $x2,$y2\n" );
	    }
	} elsif ( $opt_maptype eq 'cern' ) {
	    if ( "${opt_htimage}" ne '' ) {
		print( IMAGEMAP "rect ($x1,$y1) ($x2,$y2) "
		      . abs_path_to_url("${sourceDirectory}/${url}")
		      . "\n" );
	    } else {
		print( IMAGEMAP "rect ($x1,$y1) ($x2,$y2) ${url}\n" );
	    }
	} else {
	    die( "\nError: \$opt_maptype must be \"cern\"",
		" or \"ncsa\".\n" );
	}
    }
    close( IMAGEMAP );
    $errorstat=0;
    return( $errorstat );
}

#
# Return string to represent JavaScript array
# Usage: jsArray('arrayName', @array)
#
sub jsArray {
    my($arrayName, @elements) = @_;

    my($result) = "var ${arrayName} = new Array(\n";
    my $i;
    for $i (0 .. $#elements) {
	$result .= "\t\'" . escapejs($elements[$i]) . "\'";
	$result .= ',' if $i < $#elements;
	$result .= "\n";
    }
    $result .= ");\n";
    return $result;
}
#
# Return string to represent JavaScript double-dimensioned array
# Usage: jsDoubleArray('arrayName', @array)
#                 .
sub jsDoubleArray {
    my($arrayName, @elements) = @_;

    my($result) = "var ${arrayName} = new Array(\n";
    my $i;
    for $i (0 .. $#elements) {
	$result .= "\tnew Array(\n";
	my $j;
	for $j (0 .. $#{$elements[$i]}) {
	    $result .= "\t\t\'" . escapejs($elements[$i][$j]) . "\'";
	    $result .= ',' if $j < $#{$elements[$i]};
	    $result .= "\n";
	}
	$result .= "\t)";
	$result .= ',' if $i < $#elements;
	$result .= "\n";
    }
    $result .= ");\n";
    return $result;
}

#
# Return string to represent JavaScript associative array
# Usage: jsHash('objectName', \%hashName)
#
sub jsHash {
    my( $name, $hash) = @_;

    my $result = '';
    $result .= "var ${name} = new Object();\n";
    my $key;
    foreach $key (sort(keys(%$hash))) {
	if(defined($$hash{$key})) {
	    if($$hash{$key} =~ /^\d+$/) {
		# numeric
		$result .= "${name}" . '["' . $key . '"] = ' . escapejs($$hash{$key}) . ";\n";
	    } else {
		# text string gets quoted
		$result .= "${name}" . '["' . $key . '"] = \'' . escapejs($$hash{$key}) . "\';\n";
	    }
	}
    }
    return $result;
}

#
# Return string to represent JavaScript variable
# Usage: jsVariable('variableName', \$variableName)
#
sub jsVariable {
    my( $name, $variable) = @_;
    my $result = "${name} = \'" . escapejs($$variable) . "\';\n";
    return $result;
}

#
# Return string to represent PERL list
# Usage: plArray('arrayName', @array)
#
sub plArray {
    my($arrayName, @elements) = @_;

    my($result) = "\@${arrayName} = (\n";
    my $elem;
    foreach $elem (@elements) {
      if(defined($elem)) {
	$result .= "\t\'" . escapeperl($elem) . "\',\n";
      } else {
	$result .= "\t\'\',\n";
      }
    }
    $result .= ");\n";
    return $result;
}

#
# Return string to represent PERL list of lists
# Usage: plDoubleArray('arrayName', @array)
#
sub plDoubleArray {
    my($arrayName, @elements) = @_;

    my($result) = "\@${arrayName} = (\n";
    my $slow;
    for $slow (0 .. $#elements) {
	$result .= "    [\n";
	my $fast;
	for $fast (0 .. $#{$elements[$slow]}) {
	    #print( "element $slow $fast is $elements[$slow][$fast]\n");
	    $result .= "\t\'" . escapeperl($elements[$slow][$fast]) . "\',\n";
	}
	$result .= "    ],\n";
    }
    $result .= ");\n";
    return $result;
}

#
# Return string to represent PERL associative array
# Usage: plHash('objectName', \%hashName)
#
sub plHash {
    my( $name, $hash) = @_;

    my $result = "\%${name} = (\n";
    my $key;
    foreach $key (sort(keys(%$hash))) {
	if(defined($$hash{$key})) {
	    $result .= "\t\'$key\' => \'" . escapeperl($$hash{$key}) . "\',\n";
	}
    }
    $result .= ");\n";
    return $result;
}

#
# Return string to represent PERL variable
# Usage: plVariable('variableName', \$variableName)
#
sub plVariable {
    my( $name, $variable) = @_;
    my $result = "\$${name} = \'" . escapeperl($$variable) . "\';\n";
    return $result;
}

#
# Routine used by 'sort' to sort directories
#    %dirOrder		# Order directories are listed in dirindex file
sub sortDir {
    if(defined($dirOrder{$a}) && defined($dirOrder{$b})) {
	$dirOrder{$a} <=> $dirOrder{$b}
    } else {
	lc($a) cmp lc($b);
    }
}

#
# Routine used by 'sort' to sort images
#    %imageOrder	# Order that images occur in imgindex file
sub sortImages {
    if(defined($imageOrder{$a}) && defined($imageOrder{$b})) {
	$imageOrder{$a} <=> $imageOrder{$b}
    } else {
	lc($a) cmp lc($b);
    }
}

#
# Return current directory
#
sub cwd {
    local($_);
    chop($_ = `pwd`);
    return $_;
}

#
# Return size of file in bytes (size)
#
sub fsize {
    my($name) = @_;
    return ((lstat($name))[7]);
}

#
# Return file modification time (mtime)
#
sub fmtime {
    my($name) = @_;
    return ((lstat($name))[9]);
}

#
# Return file name portion of path
#
sub basename {
   my($name) = @_;
    $name =~ s:([^\/]*/)+::;
    return($name);
}
 
#
# Return directory name portion of path
#
sub dirname {
    my($name) = @_;
    $name =~ s:(/[^\/]+$)::g;
    return($name);
}

#
# Compare two associative arrays
#
sub compareHash {
    my( $hash1, $hash2) = @_;

    if(scalar(keys(%$hash1)) != scalar(keys(%$hash2))) {
	return( 1 ); # different length
    }
    my $key;
    foreach $key (keys(%$hash1)) {
	if(( defined($$hash1{$key}) && !defined($$hash2{$key})) ||
	   ( !defined($$hash1{$key}) && defined($$hash2{$key}))) {
	    return( 1 ); # different
	}

	if( defined($$hash1{$key}) && defined($$hash2{$key}) ) {
	    if($$hash1{$key} ne $$hash2{$key}) {
		return( 1 ); # different
	    }
	}
    }
    return(0);
}

#
# Generic error handler routine to handle Magick reported errors
# Numeric error codes are currently used to aid backward compatability
# in spite of the fact that Magick.pm exports these constants
#
# Returns 0 when normal processing may continue
# Returns 1 when alternative processing (e.g. skip defective image) is recommended
# Exits process for serious problems
#
# Use similar to:
# $status = $image->Read("${imagename}\[0\]");
# handleMagickError( __FILE__, __LINE__, $imagename, $status) if "$status";
#
sub handleMagickError {
    my ($file, $line, $argument, $error) = @_;
    $error =~ /(\d+)/;
    my $errorCode = $1;

    # Benign warnings
    if (
	( $errorCode == 300 ) || # ResourceLimitWarning
	( $errorCode == 305 ) || # XServerWarning
	( $errorCode == 310 ) || # OptionWarning
	( $errorCode == 315 ) || # PluginWarning
	( $errorCode == 320 ) )  # MissingPluginWarning
    {
	warn('PerlMagick:"', $file, '", line ', $line, ', ', $error, "\n");
	return 0;
    }
    # Corrupt image problem
    elsif ( $errorCode == 325 ) { # CorruptImageWarning
	my $imagename = $argument;
	warn("Warning: Image $imagename is defective\n");
	
	# Evaluate contents of $opt_readfailhook if image fails to
	# read A typical action here would be to unlink the image file
	if( $opt_readfailhook ) {
	    print("Evaluating read-failure hook ...\n$opt_readfailhook\n" )
		if $opt_debug;
	    eval $opt_readfailhook;
	}
	return 1;
    }
    # Errors we consider fatal (until proven otherwise)
    # Presumably the user can rectify the problem
    elsif (
	   ( $errorCode == 330 ) || # FileOpenWarning
	   ( $errorCode == 400 ) || # ResourceLimitError
	   ( $errorCode == 405 ) || # XServerError
	   ( $errorCode == 410 )    # OptionError
	   )
    {
	die('PerlMagick fatal error:"', $file, '", line ', $line, ', ', $error, "\n");
    }
    # Other problems
    warn('PerlMagick:"', $file, '", line ', $line, ', ', $error, "\n");
    return 0;
}

#
# Get icon image sizes
# Sets or updates value of %iconImageSizes hash
# Sets the value of $opt_forcehtml to true if existing hash is altered
#
sub getIconImageSizes {
    my %tmp_iconImageSizes;
    my $icon;
    for $icon ( keys %opt_icons ) {
	if( $opt_icons{$icon} ) { # if defined
	    my $icon_path = $icon_dir_path .'/'.  $opt_icons{$icon};
	    if( !defined( $icon_paths{$icon} ) || ( $icon_paths{$icon} ne $icon_path )) {
		$icon_paths{$icon} = $icon_path;
		$ tmp_iconImageSizes{$icon} = html_imgsize( $icon_path );
	    }
	}
    }
    if( !defined(%iconImageSizes) || (  compareHash(\%iconImageSizes,\%tmp_iconImageSizes) ) ) {
	%iconImageSizes = %tmp_iconImageSizes;
	print( STDERR "Icon sizes have changed, must re-do all HTML\n" )
	    if $opt_debug;
	$opt_forcehtml = 1;;
    }
}

#
# Get the physical path for a specified directory/file path
#
sub lets_get_physical {
    my( $path ) = @_;
    my $physical=$path;
    if( -d $path ) {
        my( $savedir ) = cwd();
        chdir( $path );
        $physical=cwd();
        chdir( $savedir );
    }
    if( -f $path ) {
        my($dir)=dirname($path);
	my($fname)=basename($path);
        my( $savedir ) = cwd();
        chdir( $dir );
        $physical=cwd();
        chdir( $savedir );
	$physical .= "/$fname";
    }
    return( $physical );
}

#
# Attempt to build a relative path from specified directory
# to a file given the specified absolute physical path
#
# Usage:  relative($dir,$path);
#
# Example:  $relative_icon_path = relative($cwd, $absolute_path);
#
sub relative {
    my($dir, $path) = @_;
    my(@path,@dir);
    my $savepath;
    my $result;

    # Return value from cache if defined
    my $index = $dir . '|' . $path;
    if( defined($relativePathCache{$index}) ) {
	return( $relativePathCache{$index} );
    }
    
    $savepath=$path;
    $path =~ s?/var/www/doc/webmagick/icons?/usr/doc/webmagick/icons?g;
    # If not rooted then we are hosed
    if ( ( $path !~ m|^/| ) || ($dir !~ m|^/|) ) {
	print( "ERROR: The path \"${savepath}\" is not absolute.\n" );
	die( "Fix the \$opt_rootpath value and try again.\n" );
    }

    if( ! -f $path && ! -d $path ) {
	print( "ERROR: The specified path \"${savepath}\" does not exist.\n" );
	die( "Fix the \$opt_rootpath and \opt_iconpath values and try again.\n" );
    }
    
    @path=split('/', $path);	# Array form
    shift(@path);
    @dir=split('/', $dir);	# Array form
    shift(@dir);
    
    # If roots are not the same, then it is not possible to compute a relative path
    # Just return absolute path
    if ( $path[0] ne $dir[0] ) {
	$result = $savepath;
	# Cache and return result
	$relativePathCache{$index} = $result;
	return( $result );
    }
    
    # Remove common start directories
    while( scalar(@path) && scalar(@dir) ) {
	last if( $path[0] ne $dir[0] );
	shift(@path);
	shift(@dir);
    }
    
    # Prepend any ../ part
    grep($_='..',@dir);
    
    # Return results
    if( scalar(@dir) ) {
	$result = join('/',@dir,@path) ;
    } else {
	if( scalar(@path) ) {
	    $result = './' . join('/',@path);
	} else {
	    $result = '.';
	}
    }
    # Cache and return result
    $relativePathCache{$index} = $result;
    return $result;
}

#
# Build a relative path to a file given the absolute physical path
# Uses the option variables $opt_rootpath and $opt_prefixpath
#
sub abs_path_to_url {
    ($_) = @_;
    
    # Remove root prefix if absolute
    s|^${opt_rootpath}||;
    
    # Tack on prefix (if any)
    $_ = "${opt_prefixpath}${_}";
    return( $_ );
}

#
# Subroutine to print version information
#
sub version {
    print( STDOUT
qq|webmagick $webmagickInfo{revision}

Copyright Bob Friesenhahn 1996, 1997, 1998

Written by Bob Friesenhahn (bfriesen\@simple.dallas.tx.us)
| );
}

#
# Subroutine to print help message
#
sub help {
    print( STDOUT
qq|WebMagick `webmagick' recurses through directories of images and builds HTML
pages and image-maps to display those images in a web browser. Options may be
specified on the command line as --option or in .webmagickrc files as \$opt_option.
By default WebMagick processes files in the current directory.  See --srcdir for
a way to process files in a different directory.

Usage: webmagick [OPTIONS]

General:
  --debug	     Print debug messages
  --forcecache       Force cached thumbnails to be generated (default off)
  --forcehtml	     Force HTML files to be generated (default off)
  --forcemontage     Force montage (default off)
  --help	     Display usage message
  --recurse	     Recurse directory tree
  --srcdir	     Image directory to process
  --verbose	     Tell us more ...

Paths:
  --iconpath	     Relative path under rootdir to webmagick icons
  --prefixpath       Path to prepend to generated URLs (e.g. /~username)
  --rootpath	     Absolute path to server root (NCSA DocumentRoot)

Server-side imagemaps:
  --htimage	     Imagemap CGI program URL (set to '' for none)
  --maptype	     Server-side map type ("ncsa" or "cern")

Filenames:
  --dirindexname     Directory-name to title cross-reference file name
  --imgindexname     Image-name to thumbnail label cross-reference file name
  --indexname	     Name of master index files (default server index)
  --pageindexname    Base name of page-related index files
  --readme	     Name of directory info file

Caching:
  --cache            Cache thumbnails
  --cachedir         Subdirectory name to cache thumbnails in (default .cache)
  --cacheformat      Format of cached thumbnails (default JPEG)
  --cachegeom        Cache thumbnail geometry (default thumbgeom)
  --cachemin         Smallest image to cache in pixels. (default 300*200)

Montage:
  --forcegif         Force imagemap to be in GIF format
  --maxgif           Maximum size of GIF imagemap before trying JPEG
  --columns	     Montage columns
  --rows	     Montage rows (max)
  --mapnetscape      Map generated image files to Netscape 216-color cube
  --thumbbackground  Montage background color
  --thumbframebgcolor Background color inside of Frame (unused if no Frame)
  --thumbborderwidth Thumbnail border width (pixels)
  --thumbcompose     Thumbnail image composition operation (default Replace)
                     Over, In, Out, Atop, Xor, Plus, Minus, Add, Subtract,
                     Difference, Bumpmap, Replace, MatteReplace, Mask, Blend,
                     Displace
  --thumbfont	     Thumbnail title font
  --thumbforeground  Montage foreground color (effects label color)
  --thumbframe       Geometry of frame around thumbnail (default no frame)
  --thumbgeometry    Thumbnail geometry (widthxheight)
  --thumbgravity     Direction thumbnail gravitates to (default Center)
                     NorthWest, North, NorthEast, West, Center, East
                     SouthWest, South, SouthEast. North is up.
  --thumblabel       Format for default thumbnail text label
  --thumblabelwidth  Label width (in characters) to truncate to.
  --thumbframecolor  Frame color (if thumbnail frames enabled)
  --thumbshadow      Enable decorative shadow under thumbnail
  --thumbtexture     Texture to tile onto the image background
  --thumbtransparent Transparent color
  --zoomfilter       Zoom filter algorithm (Box/Triangle/Mitchell)

HTML Colors & Appearance:
  --address          Optional user address info
  --anonymous        Don't show WebMagick address and copyright info on pages.
  --coloralink	     Link (active) color
  --colorback	     Background color (also applied to JPEG montage background)
  --colorfore	     Foreground text color
  --colorlink	     Link (unvisited) color
  --colorvlink	     Link (visited) color
  --dircoloralink    Link (active) color (directory frame)
  --dircolorback     Background color (directory frame)
  --dircolorfore     Foreground color (directory frame)
  --dircolorlink     Link (unvisited) color (directory frame)
  --dircolorvlink    Link (visited) color (directory frame)

  --javascript	     Enable JavaScript output
  --header           Page header (imagemap frame)
  --title            Page title
  --pichtml          Per-image HTML file generation
  --pichtmlext       Per-image HTML file extension (default .html)
  --pichtmltarget    Per-image HTML default frame target
  --pichtmltop       Per-image HTML, extra HTML to display above image
  --pichtmlbottom    Per-image HTML, Extra HTML to display below image
  --readmevisible    Show README.html on first page rather than just linking.

Frame Options:
  --framemarginwidth Pixels allocated to frame margin in horizontal direction
  --framemarginheight Pixels allocated to frame margin in vertical direction
  --framebordersize  Pixels allocated to frame border
  --frameborder      Enable (YES) or disable (NO) decorative frame borders
  --framestyle       Frame style to use (out of those available)

Report bugs to <bfriesen\@simple.dallas.tx.us>.
| );
}

#
# Subroutine to calculate per-page file names
# This is so names can be defined in one place
#
sub setFileNames {
    my $nextPageNumber=$pageNumber + 1;
    my $previousPageNumber=$pageNumber - 1;

    # HTML file to load JavaScript code into hidden Frame
    $fileNames{'jsPageIndex'} = "${opt_pageindexname}js.html";

    # Javascript master index "indexjs.html"
    $fileNames{'jsDirIndex'} = 'indexjs.html';

    # JavaScript variable definitions
    $fileNames{'jsVariables'} = "${opt_pageindexname}.js";

    # Shared WebMagick JavaScript source file
    $fileNames{'jsFunctions'} = "$icon_base_url/webmagick.js";

    # Run status file
    $fileNames{'pageStatus'} = "${opt_pageindexname}.pl";

    # Generated GIF file
    $fileNames{'montageGIF'} = "${opt_pageindexname}${pageNumber}.gif";

    # Generated JPEG file
    $fileNames{'montageJPEG'} = "${opt_pageindexname}${pageNumber}.jpg";

    # Generated server-side imagemap file
    $fileNames{'montageServerMap'} = "${sourceDirectory}/${opt_pageindexname}${pageNumber}.map";

    # Name for current HTML index page
    $fileNames{'htmlCurrentIndex'} = "${opt_pageindexname}${pageNumber}$opt_htmlext";
    
    # Name for next HTML index page
    if($pageNumber == $numPages) {
	$fileNames{'htmlNextIndex'} = '';
    } else {
	$fileNames{'htmlNextIndex'} = "${opt_pageindexname}${nextPageNumber}$opt_htmlext";
    }
    
    # Name for previous HTML index page
    if($pageNumber == 1) {
	$fileNames{'htmlPrevIndex'} = '';
    } else {
	$fileNames{'htmlPrevIndex'} = "${opt_pageindexname}${previousPageNumber}$opt_htmlext";
    }


    # Name for next JavaScript HTML index page
    if($pageNumber == $numPages) {
	$fileNames{'htmlNextJsIndex'} = '';
    } else {
	$fileNames{'htmlNextJsIndex'} = "${opt_pageindexname}${nextPageNumber}js.html";
    }
    
    # Name for previous HTML index page
    if($pageNumber == 1) {
	$fileNames{'htmlPrevJsIndex'} = '';
    } else {
	$fileNames{'htmlPrevJsIndex'} = "${opt_pageindexname}${previousPageNumber}js.html";
    }

    # Location of blank HTML page for use in Frame target
    $fileNames{'htmlBlankPage'} = "${icon_base_url}/blank.html";
}

#
# Escape special characters in HTML text
#
sub escapehtml {
    local($_) = @_;
    s/&/&amp;/g;
    s/>/&gt;/g;
    s/</&lt;/g;
    return( $_ );
}

#
# Escape characters in strings so they may be eval'ed later in PERL
# 
sub escapeperl {
    local($_) = @_;
    s/\'/\\'/g;
    return( $_ );
}

#
# Escape characters in strings so they may be evaluated by JavaScript
# 
sub escapejs {
    local($_) = @_;
    s/\'/\\'/g;
    $_ = join(' + \'', split(/^/));
    s/\n/\\n\'\n/g;
    return( $_ );
}

#
# Escape unsafe characters in URLs
#		
sub escapeurl {
    local($_) = @_;
    s/\%/%25/g;		# % (must substitute first!)
    s/\"/%22/g;		# "
    s/\#/%23/g;		# #
    s/\</%3C/g;		# <
    s/\>/%3E/g;		# >
    s/\[/%5B/g;		# [
    s/\\/%5C/g;		# \
    s/\]/%5D/g;		# ]
    s/\^/%5E/g;		# ^
    s/\`/%60/g;		# `
    s/\{/%7B/g;		# {
    s/\|/%7C/g;		# |
    s/\}/%7D/g;		# }
    s/\~/%7E/g;		# ~
    return( $_ );
}

#
# Convert time in seconds to minutes:seconds.hundreths
#
sub elapsedminutes {
    my($seconds) = @_;
    my $min   = int($seconds/60);
    my $sec   = int($seconds%60);
    my $hund  = ($seconds - int($seconds)) * 100;
    return( "${sec}s" ) if $min == 0;
    return( "${min}:" . sprintf( "%02d", $sec ) ) if $hund == 0;
    return( "${min}:" . sprintf( "%02d.%02d", $sec, $hund ) );
}

#
# PERL-based RC file handlers
#

#
# Search for and return the contents of an rc file
# The file handle will be auto-close for next file.
#
sub get_rc {
   my ($rc) = @_;
   my $result = '';
   my $bytes = 0;
   open( RC, "<${rc}" ) || warn("Failed to open file ${rc}\n") && return '';
   $bytes = read( RC, $result, 100000 );
   #print( STDERR "Read ${bytes} bytes from file ${rc}\n" ) if $opt_debug;
   close( RC );
   return $result;
}

#
# Eval .webmagickrc files with specified path. If the file does not
# exist or is not readable, then return silently. If an error occurs,
# then print message and return zero to caller (who can die if deemed
# necessary). This allows statements like:
# $sourceRcFile( $rcfile) || die( "Failed to source $rcfile\n" );
#
sub sourceRcFile {
    my $rc;
    foreach $rc (@_) {
        next if ( ! -r $rc || ! -f $rc );
	print( "Sourcing ${rc}\n" ) if $opt_debug;
	eval ( get_rc($rc) );
	if( $@ ) {
	    print( STDERR "Bad Eval for file \"${rc}\"...\n$@\n" );
	    return( 0 );
	}
    }
    return( 1 );
}

#
# Look in the .webmagickrc file for the given directory and return
# the variable requested, or the default value given. this tries to
# be a bit more intelligent than previous eval.
#   -- added by Anthony Thyssen <anthony@cit.gu.edu.au>
#
# Use as: get_rc_var( directory, variable name, default value)
sub get_rc_var {
   my($dir, $var, $def) = @_;   
   my($rc) = "$dir/$opt_webmagickrc";
   return $def if ( ! -r $rc || ! -f $rc );
   my($val) = ';' . get_rc( $rc );
   $val =~ s/#.*//g;   # remove comments to avoid confusion
   if ( $val =~ /\$$var\b/ > 1 ) {
     print STDERR "Var \"\$$var\" is not simple in \"$rc\" -- using default.\n";
     return $def;
   }
   # find variable assignment if pressent and remove stuff before it
   unless ( $val =~ s/[\000-\177]*;\s*\$$var\s*=\s*// ) {
#     print("DB: \$$var not found in \"$rc\"\n")  if $opt_debug;
     return $def;               # variable assignment was not found
   }
   $val =~ s/;[\000-\177]*//;   # remove stuff after assignment expression

   # print("Assignment for \$$var = \"$val\"\n") if $opt_debug;

   $val = eval ( $val );
   if ( $@ ) {
     warn("Bad Eval for variable \"\$$var\" in \"$rc\"...\n$@\n");
     $val = $def;
   }

#   print("DB: \$$var found in \"$rc\" with value of \"$val\"\n")
#               if $opt_debug;
   return  $val;
}

#
# Eval PERL-format rc files in order from $opt_rootpath to
# $currentDirectory directory. Values are added to global variables
# 
sub evaluateRcFiles {
    my($dir)  = $currentDirectory;	  # current directory
    my(@top,@dir);
    my $rcpath ;
    my $top;
    my $direlem;

    # Decide how far to look for .webmagickrc files
    # Support the case where processing outside of the server
    # root directory.  In that case, use the sourceDirectory instead.
    if( $currentDirectory =~ m|^$opt_rootpath| ) {
        $top  = $opt_rootpath; # Use server root directory
    } else {
        $top  = $opt_srcdir; # Use specified source directory
    }

    @top=split('/', $top);	# Array form
    shift(@top);
    
    @dir=split('/', $dir);	# Array form
    shift(@dir);

    splice(@dir, 0, scalar(@top) ); # Leave only subdirectory part

    #
    # Build up path starting at top sourcing any .webmagickrc as we go.
    #
    my $path=$top;
    $direlem='';
    do {
	# Certain values must only be vaild in the last
	# current directory webmagickrc file.
        $opt_ignore=0;          # Ignore -- do not process this directory

        if( $direlem ) {
            $path = "$path/$direlem";
        }
        $rcpath = "$path/$opt_webmagickrc";
        sourceRcFile( $rcpath );
    } while( $direlem = shift(@dir) );

    return( 0 );
}

#
# Lookup color in RGB hash table
#
sub lookupRGBColor {
    my($color) = @_;
 
    # If already in hex format, don't translate
    if( $color =~ /^\#/ ) {
        return( "\U$color" );   # just uppercase the color hex value
    } 

    if( defined($RGBDB{"\L$color"}) ) {
        return( $RGBDB{"\L$color"} );
    } else {
        print( STDERR "No such color \"$color\" found\n" );
        return("#BEBEBE");    # Return grey as default in case of error
    }
}

#
# Print details regarding executing child process
# Takes return from system() command or $? as input
# Borrowed from example provided in the Camel book
# (PERL 5) page 230
#

sub syserror {
    my($rc) = @_;

    print("Process exited: ");

    $rc = 0xffff & $rc;
    
    if($rc == 0) {
        print("normal exit\n");
    }
    elsif ($rc == 0xff00) {
        print("command failed: $!\n");
    }
    elsif ($rc > 0x80) {
        $rc >>= 8;
	print("ran with non-zero exit status $rc\n");
    }
    else {
        print("ran with ");
	if ($rc &   0x80) {
	    $rc &= ~0x80;
	    print("coredump from ");
	}
	print("signal $rc\n");
    }
}