File: example_5.c

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

#include <X11/Xos.h>
#include <X11/cursorfont.h>
#include <Xm/CascadeB.h>
#include <Xm/FileSB.h>
#include <Xm/MainW.h>
#include <Xm/Form.h>
#include <Xm/Frame.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/SeparatoG.h>
#include <Xm/RowColumn.h>
#include <Xm/LabelG.h>
#include <Xm/List.h>
#include <Xm/Text.h>
#include <Xm/ToggleBG.h>
#include <Xm/MwmUtil.h>         /* added by rlr */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>		/* isspace */
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>		/* also for getwd on non-POSIX systems */

/*****
* Change this to change the application class of the examples
*****/
#define APP_CLASS		"HTMLDemos"

/*****
* We want to have the full XmHTML instance definition available 
* when debugging this stuff, so include XmHTMLP.h
* Note:
* 	Including XmHTMLP.h normally doesn't pull in any of the internal XmHTML
*	functions. If you want to do this anyway, you need to include *both*
*	XmHTMLP.h and XmHTMLI.h (in that order).
* Note:
*	When being compiled with the provided or imake generated Makefile, the
*	symbol VERSION is defined. This is a private define which must not be used
*	when compiling applications: it sets other defines which pull in
*	other, private, header files normally not present after installation
*	of the library. Therefore we undefine this symbol *before* including
*	the XmHTMLP.h header file. This is not required when XmHTML.h is used.
*****/
#if defined(VERSION)
#undef VERSION
#endif /* VERSION */
#include <XmHTML/XmHTMLP.h>

#include "../src/debug.h"		/* we want to be able to enable debugging */

/* imagecache stuff */
#include "cache.h"

/* catch NULL strdup's for debug builds */
#if defined(DEBUG) && !defined(DMALLOC)
extern char *__rsd_strdup(const char *s1, char *file, int line);
#define strdup(PTR) __rsd_strdup(PTR, __FILE__, __LINE__)
#endif

#ifdef NEED_STRCASECMP
# include <sys/types.h>
extern int my_strcasecmp(const char *s1, const char *s2);
extern int my_strncasecmp(const char *s1, const char *s2, size_t n);
#define strcasecmp(S1,S2) my_strcasecmp(S1,S2)
#define strncasecmp(S1,S2,N) my_strncasecmp(S1,S2,N)
#endif

/*** External Function Prototype Declarations ***/
/* from visual.c */
extern int getStartupVisual(Widget shell, Visual **visual, int *depth,
	Colormap *colormap);

/* can be found in XmHTML */
extern char *my_strcasestr(const char *s1, const char *s2);

/* from misc.c */
extern int parseFilename(char *fullname, char *filename, char *pathname);
extern void XMessage(Widget widget, String msg);

#ifdef DEBUG
extern void _XmHTMLUnloadFonts(XmHTMLWidget);
extern void _XmHTMLAddDebugMenu(Widget, Widget, String);
#endif

/*** Public Variable Declarations ***/

/*** Private Datatype Declarations ****/
#define MAX_HISTORY_ITEMS	100		/* save up to this many links */
#define MAX_PATHS			25		/* size of visited path cache */
#define MAX_IMAGE_ITEMS		512		/* max. no of images per document */
#define MAX_HTML_WIDGETS	10		/* max. no of HTML widgets allowed */

#define FILE_OPEN			1
#define FILE_RELOAD			2
#define FILE_SAVEAS			3
#define FILE_RAISE			5
#define FILE_LOWER			6
#define FILE_INFO			7
#define FILE_VIEW_SOURCE	8
#define FILE_VIEW_FONTCACHE	9
#define FILE_QUIT			10

/* Link defines */
#define LINK_MADE			0
#define LINK_HOMEPAGE		1
#define LINK_TOC			2
#define LINK_INDEX			3
#define LINK_GLOSSARY		4
#define LINK_COPYRIGHT		5
#define LINK_PREVIOUS		6
#define LINK_UP				7
#define LINK_DOWN			8
#define LINK_NEXT			9
#define LINK_HELP			10
#define LINK_LAST			11

/* options menu toggle buttons defines. These may *not* be changed */
#define OPTIONS_ANCHOR_BUTTONS			0
#define OPTIONS_HIGHLIGHT_ON_ENTER		1
#define OPTIONS_ENABLE_STRICT_HTML32	2
#define OPTIONS_ENABLE_BODYCOLORS		3
#define OPTIONS_ENABLE_BODYIMAGES		4
#define OPTIONS_ENABLE_DOCUMENT_COLORS	5
#define OPTIONS_ENABLE_DOCUMENT_FONTS	6
#define OPTIONS_ENABLE_OUTLINING		7
#define OPTIONS_DISABLE_WARNINGS		8
#define OPTIONS_FREEZE_ANIMATIONS		9
#define OPTIONS_AUTO_IMAGE_LOAD			10
#define OPTIONS_FANCY_TRACKING			11
#define OPTIONS_ENABLE_IMAGES			12
#define OPTIONS_LAST					13

/* options menu pushbutton defines */
#define OPTIONS_ANCHOR		20
#define OPTIONS_FONTS		21
#define OPTIONS_BODY		22
#define OPTIONS_IMAGE		23

/* document cache */
typedef struct{
	String path;		/* path to this document */
	String file;		/* full filename of this document */
	int current_ref;	/* last activated hyperlink */
	int nrefs;			/* total no of activated hyperlinks in this document */
	String refs[MAX_HISTORY_ITEMS];	/* list of activated hyperlinks */
	String visited[MAX_HISTORY_ITEMS];	/* list of visited hyperlins */
	int nvisited;		/* total no of visited hyperlinks */
	int nimages;		/* no of images in this document */
	String images[MAX_IMAGE_ITEMS];	/* image urls for this document */
}DocumentCache;

/* List of all HTML widgets (especially for frames) */
typedef struct{
	Boolean active;		/* is this an active frame? */
	Boolean used;		/* is this frame currently being used? */
	String name;		/* name of this frame */
	String src;			/* source file for this frame */
	Widget html;		/* XmHTMLWidget id for this frame */
}HTMLWidgetList;

#define MIME_HTML			0		/* text/html */
#define MIME_HTML_PERFECT	1		/* text/html-perfect */
#define MIME_IMAGE			2		/* image/whatever */
#define MIME_PLAIN			3		/* text/plain/unknown */
#define MIME_IMG_UNSUP		4		/* unsupported image type */
#define MIME_ERR			5		/* some error occured */
  
typedef struct{
	int link_type;		/* 0 = rev, 1 = rel, which means fetch it */
	Boolean have_data;
	String href;
	String title;
}documentLinks;

typedef struct{
	Widget w;
	String name;
	Boolean value;
}optionsStruct;

/*** Private Function Prototype Declarations ****/
static DocumentCache *getDocFromCache(String file);
static void storeDocInCache(String file);
static void storeInHistory(String file, String loc);
static void storeAnchor(String href);
static void removeDocFromCache(int doc);
static void flushImages(Widget w);
static void killImages(void);

static void HelloScreen(char *use_file, Window parent);
void Done(XtPointer client_data, XtIntervalId *id);

/* XmHTMLWidget callbacks */
static void anchorCB(Widget w, XtPointer arg1, XmHTMLAnchorPtr href_data);
static void docCB(Widget w, XtPointer arg1, XmHTMLDocumentPtr cbs);
static void linkCB(Widget w, XtPointer arg1, XmHTMLLinkPtr cbs);
static void frameCB(Widget w, XtPointer arg1, XmHTMLFramePtr cbs);
static String collapseURL(String url);
static void infoCB(Widget parent, Widget popup, XButtonPressedEvent *event);

/* XmHTMLWidget functions */
static XmImageInfo *loadImage(Widget w, String url);
static int testAnchor(Widget w, String href);
static void jumpToFrame(String filename, String loc, String target,
	Boolean store);
static int getImageData(XmHTMLPLCStream *stream, XtPointer buffer);
static void endImageData(XmHTMLPLCStream *stream, XtPointer data, int type,
	Boolean ok);

/* Menu and button bar callbacks */
static void linkButtonCB(Widget w, XtPointer arg1, XtPointer arg2);
static void docInfoCB(Boolean font_only);
static void historyCB(Widget w, int button);
static void progressiveButtonCB(Widget w, int reset);
static void optionsCB(Widget w, int item);
static void showImageInfo(XmImageInfo *info);

/*** Private Variable Declarations ***/
static XtAppContext context;
static Widget back, forward, load_images, label, toplevel = NULL, reload;
static Widget link_button, link_dialog, html32, verified, info_dialog;
static Widget prg_button, image_dialog;
static documentLinks document_links[LINK_LAST];
static XmImage *preview_image;
static Widget link_buttons[LINK_LAST];
static char default_font[128], current_font[128];
static char default_charset[128], current_charset[128];
static String link_labels[LINK_LAST] = {"Mail Author", "Home", "TOC",
	"Index", "Glossary", "Copyright", "Prev", "Up", "Down", "Next",
	"Help"};
static String image_types[] = {"(error occured)", "Unknown Image type",
	"X11 Pixmap", "X11 Bitmap", "CompuServe(C) Gif87a or Gif89a",
	"Animated Gif89a", "Animated Gif89a with NETSCAPE2.0 loop extension",
	"CompuServe(C) Compatible Gzf87a or Gzf89a", "Gif89a Compatible animation",
	"Gif89a compatible animation with NETSCAPE2.0 loop extension",
	"JPEG", "PNG", "Fast Loadable Graphic"};

/*****
* global XmHTML configuration. Elements must be in the same order as the
* OPTIONS_ defines above.
*****/
static optionsStruct html_config[OPTIONS_LAST] = {
	{ NULL, XmNanchorButtons, True },
	{ NULL, XmNhighlightOnEnter, True },
	{ NULL, XmNstrictHTMLChecking, False },
	{ NULL, XmNenableBodyColors, True },
	{ NULL, XmNenableBodyImages, True },
	{ NULL, XmNenableDocumentColors, True },
	{ NULL, XmNenableDocumentFonts, True },
	{ NULL, XmNenableOutlining, True },
	{ NULL, XmNenableBadHTMLWarnings, True },
	{ NULL, XmNfreezeAnimations, False },
	{ NULL, "autoImageLoad", True },
	{ NULL, "fancyMouseTracking", False },
	{ NULL, XmNimageEnable, True },
};

/* Command line options */
static Boolean root_window, noframe, external_client;
static Boolean progressive_images, allow_exec;
static int animation_timeout = 175;
#define MAX_PROGRESSIVE_DATA_SKIP	2048

static int progressive_data_skip = MAX_PROGRESSIVE_DATA_SKIP;
static int progressive_data_inc  = 0;

#ifdef DEBUG
static Boolean debug = False;
#define Debug(MSG) do { \
	if(debug) { printf MSG ; fflush(stdout); } }while(0)
#else
#define Debug(MSG)	/* emtpy */
#endif

static String usage = {"Options:\n"
"\t-allow_exec        : honor href=\"exec:\" or href=\"xexec:\"\n"
"\t-animation_timeout : animation timeout in milliseconds. Default is 175\n"
#ifdef DEBUG
"\t-debug             : enable application debug output\n"
#endif
"\t-images_delayed    : delay image loading\n"
"\t-netscape          : fire netscape for unsupported URL's\n"
"\t-noframe           : don't put a frame around the HTML display area\n"
"\t-root              : act as root window\n"
"\t-progressive       : load images progressively (only GZF for now)\n"
"\t-prg_skip [num]    : progressive data skip. Default is 2048\n"
"\t-prg_inc [num]     : progressive data increment. Resets prg_skip to 256.\n"
"\t                     Using this option overrides any prg_skip value.\n"
"\t-h, --help         : print this help\n"};

/* document cache */
static DocumentCache doc_cache[MAX_HISTORY_ITEMS];
static int current_doc, last_doc;

/*****
* List of all html widgets. The first slot is the toplevel HTML widget and
* is never freed. All other slots are used by frames.
*****/
static HTMLWidgetList html_widgets[MAX_HTML_WIDGETS];

/* visited paths */
static String paths[MAX_PATHS][1024];
static int max_paths;

/* default settings */
static String appFallbackResources[] = {
"*fontList:               *-adobe-helvetica-bold-r-*-*-*-120-*-*-p-*-*-*",
"*useColorObj:            False",
"*usePrivateColormap:     True",
NULL};


static void readPipe( Widget w, char *cmd )
{
    FILE *fd;
    char *buf=NULL;
    int i;
    int val, offset;

    fd = popen(cmd, "r");
    fflush(fd);

    offset = 0;
    val = 0;

    buf = calloc(522, sizeof(char));
    strcpy(buf, "<html><body>\n");
    offset += strlen(buf);
    val = fread(buf+offset, 1, 512, fd);
    offset += 512;

    if (val == 512)
    {
        buf = realloc(buf, offset+512);
        while ((val = fread(buf+offset, 1,512, fd)) == 512)
        {
            offset += 512;
            buf = realloc(buf, offset+512);
        }
    }
    pclose(fd);

    buf = realloc(buf, strlen(buf)+20);
    strcat(buf, "\n</body></html>\n");

    XmHTMLTextSetString(w, buf);
    free(buf);
}


/*****
* Name: 		setBusy
* Return Type: 	void
* Description: 	changes the cursor from or to a stopwatch to indicate we are
*				busy doing something lengthy processing which can't be
*				interrupted.
* In: 
*	state:		True to display the cursor as busy, False to display the
*				normal cursor.
* Returns:
*	nothing.
*****/
static void
setBusy(Boolean state)
{
	static Boolean busy;
	static Cursor cursor;
	Display *display = XtDisplay(toplevel);

	if(!cursor)
	{
		cursor = XCreateFontCursor(display, XC_watch);
		busy = False;
	}
	if(busy != state)
	{
		busy = state;
		if(busy)
			XDefineCursor(display, XtWindow(toplevel), cursor);
		else
			XUndefineCursor(display, XtWindow(toplevel));
	}
	XFlush(display);
}

/*****
* Name: 		addPath
* Return Type: 	void
* Description: 	adds a path to the list of visited paths if it hasn't been
*				stored yet.
* In: 
*	path:		path to be stored;
* Returns:
*	nothing.
*****/
static void
addPath(String path)
{
	int i = 0;

	/* see if the path has already been added */
	for(i = 0; i < max_paths; i++)
		if(!(strcmp((char*)(paths[i]), path)))
			return;

	/* store this path */
	if(max_paths < MAX_PATHS)
	{
		strcpy((char*)(paths[max_paths]), path);
		max_paths++;
	}
}

/*****
* Follow symbolic links (if any) to translate filename into the name of the
* real file that it represents.  Returns TRUE if the call was successful,
* meaning the links were translated successfully, or the file was not 
* linked to begin with (or there was no file).  Returns false if some
* error prevented the call from determining if there were symbolic links
* to process, or there was an error in processing them.  The error
* can be read from the unix global variable errno.
*****/
Boolean
followSymLinks(String filename)
{
	/*****
	* FIXME
	*
	* readlink doesn't seem to do anything at all on Linux 2.0.27,
	* libc 5.3.12
	*****/
	int cc;
	char buf[1024];

	cc = readlink(filename, buf, 1024);
	if (cc == -1) 
	{
#ifdef __sgi
    		if (errno == EINVAL || errno == ENOENT || errno == ENXIO)
#else
    		if (errno == EINVAL || errno == ENOENT)
#endif
/* no error, just not a symbolic link, or no file */
				return(True);
    		else
				return(False);
	} 
	else
	{
		buf[cc] = '\0';
		strcpy(filename, buf);
		return(True); 
	}
}   

/*****
* Name: 		resolveFile
* Return Type: 	String
* Description: 	checks if the given file exists on the local file system
* In: 
*	filename:	file to check
* Returns:
*	a full filename when the file exists. NULL if it doesn't.
* Note:
*	This routine tries three things to check if a file exists on the local
*	file system:
*	1. if "filename" is absolute, it is assumed the file exists and is
*	   accessible;
*	2. checks whether "filename" can be found in the path of the current
*	   document;
*	3. sees if "filename" can be found in the list of stored paths.
*	When a file has been found, it is checked if this is a regular file,
*	and if so it is transformed into a fully qualified pathname (with
*	relative paths fully resolved).
*****/
static String
resolveFile(String filename)
{
	static String ret_val;
	char tmp[1024];

	/* throw out http:// stuff */
	if(!(strncasecmp(filename, "http://", 7)))
		return(NULL);

	Debug(("resolveFile, looking for %s\n", filename));

	ret_val = NULL;

	/*****
	* If this is an absolute path, check if it's really a valid file
	* (or directory). This allows us to recognize chrooted files when
	* browsing the local web directory.
	*****/
	if(filename[0] == '/')
	{
		if(!(access(filename, R_OK)))
			ret_val = strdup(filename); 
		else	/* a fake path, strip of the leading / */
			sprintf(tmp, "%s", &filename[1]);
	}
	else
	{
		strcpy(tmp, filename);
		tmp[strlen(filename)] = '\0';	/* NULL terminate */
	}

	if(ret_val == NULL)
	{
		char real_file[1024];
		int i;

		/*****
		* search the paths visited so far. Do it top to bottom as the
		* last visited path is inserted in the last slot. Quite usefull
		* when looking for images or links in the current document.
		*****/
		for(i = max_paths-1; i >= 0 ; i--)
		{
			sprintf(real_file, "%s%s", (char*)(paths[i]), tmp);

			/* check if we have access to this thing */
			if(!(access(real_file, R_OK)))
			{
				struct stat statb;
				/*****
				* We seem to have some access rights, make sure this
				* is a regular file
				*****/
				if(stat(real_file, &statb) == -1)
				{
					perror(filename);
					break;
				}
				else if(S_ISDIR(statb.st_mode))
				{
					/*****
					* It's a dir. First check for index.html then
					* for Welcome.html.
					*****/
					int len = strlen(real_file)-1;

					strcat(real_file, real_file[len] == '/' ?
						"index.html\0" : "/index.html\0");
					if(!(access(real_file, R_OK)))
					{
						ret_val = strdup(real_file);
						break;
					}
					real_file[len+1] = '\0';
					strcat(real_file, real_file[len] == '/' ?
						"Welcome.html\0" : "/Welcome.html\0");
					if(!(access(real_file, R_OK)))
					{
						ret_val = strdup(real_file);
						break;
					}
					/* no file in here, too bad */
					break;
				}
				else if(!S_ISREG(statb.st_mode))
				{
					fprintf(stderr, "%s: not a regular file\n", filename);
					break;
				}
				ret_val = strdup(real_file);
				break;
			}
		}
	}

	if(ret_val == NULL)
	{
		sprintf(tmp, "%s:\ncannot display: unable to locate file.", filename);
		XMessage(toplevel, tmp);
	}
	else
	{
		/* clean out relative path stuff and add the path to the path index. */
		char fname[1024], pname[1024];

		(void)parseFilename(ret_val, fname, pname);
		addPath(pname);

		/*
		* resolve symbolic links as well (prevents object cache from going
		* haywire by having two different objects with cross-linked
		* mappings)
		*/
#if 0
		(void)followSymLinks(pname);
#endif
		/*****
		* big chance parseFilename compressed relative paths out of ret_val,
		* do it again. We need to reallocate as the size of the fully
		* resolved path can exceed the current length.
		*****/
		ret_val = (String)realloc(ret_val, strlen(pname) + strlen(fname) + 1);
		sprintf(ret_val, "%s%s", pname, fname);
	}

	Debug(("resolveFile, found as %s\n", ret_val ? ret_val : "(not found)"));
	return(ret_val);
}

/*****
* Name: 		getMimeType
* Return Type: 	int
* Description: 	make a guess at the mime type of a document by looking at
*				the extension of the given document.
* In: 
*	file:		file for which to get a mime-type;
* Returns:
*	mime type of the given file.
*****/
static int
getMimeType(String file)
{
	String chPtr;
	unsigned char img_type;

	if((chPtr = strstr(file, ".")) != NULL)
	{
		String start;

		/* first check if this is plain HTML or not */
		for(start = &file[strlen(file)-1]; *start && *start != '.'; start--);

		if(!strcasecmp(start, ".html") || !strcasecmp(start, ".htm"))
			return(MIME_HTML);
		if(!strcasecmp(start, ".htmlp"))
			return(MIME_HTML_PERFECT);
	}

	/* something else then? */
	/* check if this is an image XmHTML knows of */
	if((img_type = XmHTMLImageGetType(file, NULL, 0)) == IMAGE_ERROR)
		return(MIME_ERR);

	/*****
	* Not an image we know of, get first line in file and see if it's
	* html anyway
	*****/
	if(img_type == IMAGE_UNKNOWN)
	{
		FILE *fp;
		char buf[128];

		/* open file */
		if((fp = fopen(file, "r")) == NULL)
			return(MIME_ERR);

		/* read first line in file */
		if((chPtr = fgets(buf, 128, fp)) == NULL)
		{
			/* close again */
			fclose(fp);
			return(MIME_ERR);
		}
		/* close again */
		fclose(fp);

		/* see if it contains any of these strings */
		if(my_strcasestr(buf, "<!doctype") || my_strcasestr(buf, "<html") ||
			my_strcasestr(buf, "<head") || my_strcasestr(buf, "<body") ||
			my_strcasestr(buf, "<!--"))
			return(MIME_HTML);
		/* we don't know it */
		return(MIME_PLAIN);
	}

	/* known imagetype, but check if support is available */
	if((img_type == IMAGE_JPEG && !XmHTMLImageJPEGSupported()) ||
		(img_type == IMAGE_PNG && !XmHTMLImagePNGSupported()) ||
		(img_type == IMAGE_GZF && !XmHTMLImageGZFSupported())) 
		return(MIME_IMG_UNSUP);

	/* we know this image type */
	return(MIME_IMAGE);
}

/*****
* Name: 		loadFile
* Return Type: 	String
* Description: 	loads the contents of the given file.
* In: 
*	filename:	name of the file to load
*	mime_type:		mimetype of file to load, updated upon return.
* Returns:
*	contents of the loaded file.
*****/
static String
loadFile(String filename, String *mime_type)
{
	FILE *file;
	int size, mime;
	static String content;
	XmString xms;
	char buf[1024];

	/* open the given file */
	if((file = fopen(filename, "r")) == NULL)
	{
		sprintf(buf, "%s:\ncannot display: %s", filename, strerror(errno));
		XMessage(toplevel, buf);
		return(NULL);
	}

	mime = getMimeType(filename);
	if(mime == MIME_ERR || mime == MIME_IMG_UNSUP)
	{
		char buf[1024];
		if(mime == MIME_ERR)
			sprintf(buf, "%s:\ncannot display, unable to load file.", filename);
		else
			sprintf(buf, "%s:\ncannot display, support for this image type "
				"not present.", filename);
		XMessage(toplevel, buf);
		return(NULL);
	}

	if(mime == MIME_HTML)
		*mime_type = "text/html";
	else if(mime == MIME_HTML_PERFECT)
		*mime_type = "text/html-perfect";
	else if(mime == MIME_IMAGE)
		*mime_type = "image/";
	else
		*mime_type = "text/plain";

	/* only load contents of file if we need to load something */
	if(mime == MIME_HTML || mime == MIME_HTML_PERFECT || mime == MIME_PLAIN)
	{
		/* see how large this file is */
		fseek(file, 0, SEEK_END);
		size = ftell(file);
		rewind(file);

		/* allocate a buffer large enough to contain the entire file */
		if((content = malloc(size+1)) == NULL)
		{
			fprintf(stderr, "malloc failed for %i bytes\n", size);
			exit(EXIT_FAILURE);
		}

		/* now read the contents of this file */
		if((fread(content, 1, size, file)) != size)
			printf("Warning: did not read entire file!\n");
		content[size] = '\0';	/* sanity */
	}
	else
		content = strdup(filename);

	fclose(file);

	/* set name of current file in the label */
	xms = XmStringCreateLocalized(filename);
	XtVaSetValues(label,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	/* return contents of this file */
	return(content);
}

/*****
* Name: 		getAndSetFile
* Return Type: 	void
* Description: 	reads the given file, sets the contents of this
*				file in the HTML widget. Also sets the title of the application
*				to the title of the document loaded.
* In: 
*	file:		name of file to load
*	loc			location file file
*	store:		history storage
* Returns:
*	True upon success, False on failure.
*****/
static int
getAndSetFile(String file, String loc, Boolean store)
{
	String buf, title, mime;
	Arg args[5];
	int argc = 0;

	setBusy(True);

	/* load the file */
	if(file == NULL || (buf = loadFile(file, &mime)) == NULL)
	{
		setBusy(False);
		return(False);
	}

	/* kill of any outstanding progressive image loading contexts */
	XmHTMLImageProgressiveKill(html_widgets[0].html);

	/* reset/unmanage progressive image load button */
	if(prg_button)
		progressiveButtonCB(prg_button, 1);

	if(html_config[OPTIONS_ENABLE_IMAGES].value)
		XtSetSensitive(load_images, True);

	/* store this document in the history */
	if(store)
		storeInHistory(file, loc);

	/* set mime type */
	XtSetArg(args[argc], XmNmimeType, mime); argc++;

	/* and set values */
	XtSetValues(html_widgets[0].html, args, argc);

	/*****
	* Now set the text directly into the widget. XmHTMLTextSetString
	* works a lot faster than using XtVaSetValues: it causes a XmHTML widget
	* to update it's display immediatly, and this is the behaviour we want
	* to have: due to the asynchronous behavior of X, the widget might not
	* have parsed and set the text when we want to set or retrieve resources
	* from the new text. Using XmHTMLTextSetString *ensures* that the new
	* text is parsed and loaded before the widget returns control to X.
	* XmUpdateDisplay *might* work also, but that has been untested.
	*****/
	XmHTMLTextSetString(html_widgets[0].html, buf);

	/* free it, XmHTML makes a copy of the text to work with. */
	free(buf);

	/*****
	* See if the current text has got a title.
	* Note that one can also get the document title by using
	* XmHTMLGetHeadAttributes() with the HeadTitle flag set.
	*****/
	if((title = XmHTMLGetTitle(html_widgets[0].html)) != NULL)
	{
		/* it has, set it */
		XtVaSetValues(toplevel,
			XtNtitle, title,
			XtNiconName, title,
			NULL);
		XtFree(title);
	}
	else
	{
		XtVaSetValues(toplevel,
			XtNtitle, "<Untitled>",
			XtNiconName, "<Untitled>",
			NULL);
	}
	XtSetSensitive(reload, True);
	setBusy(False);
	return(True);
}

/*****
* Name: 		getInfoSize
* Return Type: 	int
* Description: 	returns the size of the given XmImageInfo structure.
* In: 
*	call_data:	ptr to a XmImageInfo structure;
*	client_data: data registered when we called initCache.
* Returns:
*	size of the given XmImageInfo structure.
* Note:
*	This function is used both by us and the caching routines.
*****/
static int
getInfoSize(XtPointer call_data, XtPointer client_data)
{
	int size = 0;
	XmImageInfo *frame = (XmImageInfo*)call_data;

	while(frame != NULL)
	{
		size += sizeof(XmImageInfo);
		size += frame->width*frame->height;		/* raw image data */

		/* clipmask size. The clipmask is a bitmap of depth 1 */
		if(frame->clip)
		{
			int clipsize;
			clipsize = frame->width;
			/* make it byte-aligned */
			while((clipsize % 8))
				clipsize++;
			/* this many bytes on a row */
			clipsize /= 8;
			/* and this many rows */
			clipsize *= frame->height;
			size += clipsize;
		}
		/* reds, greens and blues */
		size += 3*frame->ncolors*sizeof(Dimension);
		frame = frame->frame;	/* next frame of this image (if any) */
	}
	return(size);
}

/*****
* Name: 		getDocFromCache
* Return Type: 	DocumentCache*
* Description: 	retrieves a document from the document cache.
* In: 
*	file:		filename of document to be retrieved.
* Returns:
*	nothing.
*****/
static DocumentCache*
getDocFromCache(String file)
{
	int i;
	for(i = 0; i < last_doc; i++)
	{
		if(!(strcmp(doc_cache[i].file, file)))
			return(&doc_cache[i]);
	}
	return(NULL);
}

/*****
* Name: 		storeDocInCache
* Return Type: 	void
* Description: 	stores the given document in the document cache.
* In: 
*	file:		filename of document to be stored;
* Returns:
*	nothing.
*****/
static void
storeDocInCache(String file)
{
	char foo[128], pname[1024];

	if(last_doc == MAX_HISTORY_ITEMS)
	{
		int i;
		/* free hrefs */
		for(i = 0; i < doc_cache[0].nrefs; i++)
		{
			if(doc_cache[0].refs[i])
				free(doc_cache[0].refs[i]);
			doc_cache[0].refs[i] = NULL;
		}

		/* free image url's */
		for(i = 0; i < doc_cache[0].nimages; i++)
		{
			free(doc_cache[0].images[i]);
			doc_cache[0].images[i] = NULL;
		}

		/* free visited anchor list */
		for(i = 0; i < doc_cache[0].nvisited; i++)
		{
			if(doc_cache[0].visited[i])
				free(doc_cache[0].visited[i]);
			doc_cache[0].visited[i] = NULL;
		}
		/* free file and path fields */
		free(doc_cache[0].file);
		free(doc_cache[0].path);

		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS-1; i++)
			doc_cache[i] = doc_cache[i+1];
		last_doc = MAX_HISTORY_ITEMS - 1;
	}

	Debug(("Storing document %s in document cache\n", file));

	current_doc = last_doc;
	doc_cache[current_doc].nrefs    = 0;
	doc_cache[current_doc].nvisited = 0;
	doc_cache[current_doc].nimages  = 0;
	doc_cache[current_doc].file = strdup(file);

	/* get path to this file */
	(void)parseFilename(file, foo, pname);
	/* and store it */
	doc_cache[current_doc].path = strdup(pname);
	last_doc++;
}

/*****
* Name: 		removeDocFromCache
* Return Type: 	void
* Description: 	removes a document from the document cache
* In: 
*	doc:		id of document to be removed;
* Returns:
*	nothing.
*****/
static void
removeDocFromCache(int doc)
{
	DocumentCache *this_doc;
	int i;

	this_doc = &doc_cache[doc];

	Debug(("Removing document %s from document cache\n", this_doc->file));

	/* remove all document url's */
	for(i = 0; i < this_doc->nrefs; i++)
	{
		if(this_doc->refs[i])
			free(this_doc->refs[i]);
		this_doc->refs[i] = NULL;
	}

	/* free visited anchor list */
	for(i = 0; i < this_doc->nvisited; i++)
	{
		if(this_doc->visited[i])
			free(this_doc->visited[i]);
		this_doc->visited[i] = NULL;
	}

	/* and remove all image url's */
	for(i = 0; i < this_doc->nimages; i++)
	{
		/* remove image cache entry for this image */
		removeURLObjectFromCache(this_doc->images[i]);
		free(this_doc->images[i]);
	}
	/*****
	* Update image cache (clears out all objects with a reference count
	* of zero).
	*****/
	pruneObjectCache();

	this_doc->nrefs    = 0;
	this_doc->nvisited = 0;
	this_doc->nimages  = 0;
	free(this_doc->file);
	free(this_doc->path);
}

/*****
* Name: 		storeInHistory
* Return Type: 	void
* Description: 	stores the given href in the history list
* In: 
*	file:		name of document
*	loc:		value of named anchor in file.
* Returns:
*	nothing.
*****/
static void
storeInHistory(String file, String loc)
{
	int i;
	DocumentCache *this_doc = NULL;

	/* sanity check */
	if(file == NULL && loc == NULL)
		return;

	/* if file is NULL we are for sure in the current document */
	if(file == NULL)
		this_doc = &doc_cache[current_doc];
	else 
	{
		/****
		* This is a new file. If we have any documents on the stack,
		* remove them.
		****/
		if(last_doc)
		{
			for(i = current_doc+1; i < last_doc; i++)
				removeDocFromCache(i);
			last_doc = current_doc+1;
		}
		/* update refs for current document */
		this_doc = &doc_cache[current_doc];
		if(this_doc->nrefs)
		{
			/* remove any existing references above the current one */
			for(i = this_doc->current_ref+1; i < this_doc->nrefs; i++)
			{
				if(this_doc->refs[i])
				{
					free(this_doc->refs[i]);
					this_doc->refs[i] = NULL;
				}
			}
			this_doc->nrefs = this_doc->current_ref + 1;
		}
		if((this_doc = getDocFromCache(file)) == NULL)
		{
			storeDocInCache(file);
			this_doc = &doc_cache[current_doc];
		}
	}

	if(this_doc->nrefs == MAX_HISTORY_ITEMS)
	{
		/* free up the first item */
		if(this_doc->refs[0])
			free(this_doc->refs[0]);
		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS - 1; i++)
			this_doc->refs[i] = this_doc->refs[i+1];
		this_doc->nrefs = MAX_HISTORY_ITEMS-1;
	}

	/* sanity check */
	if(loc)
		this_doc->refs[this_doc->nrefs] = strdup(loc);
	this_doc->current_ref = this_doc->nrefs;
	this_doc->nrefs++;

	/* set button sensitivity */
	XtSetSensitive(back, current_doc || this_doc->current_ref ? True : False);
	XtSetSensitive(forward, False);
}

/*****
* Name: 		storeAnchor
* Return Type: 	void
* Description: 	stores the given href in the visited anchor list of current
*				document.
* In: 
*	href:		value to store.
* Returns:
*	nothing.
*****/
static void
storeAnchor(String href)
{
	int i;
	DocumentCache *this_doc = NULL;

	/* sanity check */
	if(href == NULL)
		return;

	/* pick up current document */
	this_doc = &doc_cache[current_doc];

	/* check if this location is already present in the visited list */
	for(i = 0; i < this_doc->nvisited; i++)
		if(!(strcmp(this_doc->visited[i], href)))
			return;
	/* not present yet, store in visited anchor list */

	/* move everything down if list is full */
	if(this_doc->nvisited == MAX_HISTORY_ITEMS)
	{
		/* free up the first item */
		if(this_doc->visited[0])
			free(this_doc->visited[0]);
		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS - 1; i++)
			this_doc->visited[i] = this_doc->visited[i+1];
		this_doc->nvisited = MAX_HISTORY_ITEMS-1;
	}
	/* store this item */
	this_doc->visited[this_doc->nvisited] = strdup(href);
	this_doc->nvisited++;
}

/*****
* Name: 		loadOrJump
* Return Type: 	void
* Description: 	checks the given href for a file and a possible jump to
*				a named anchor in this file.
* In: 
*	file:		name of file to load
*	loc:		location in file to jump to.
*	store:		history storage
* Returns:
*	True upon success, False on failure (file load failed)
*****/
static Boolean
loadAndOrJump(String file, String loc, Boolean store)
{
	static String prev_file;

	/* only load a file if it isn't the current one */
	if(prev_file == NULL || (file && strcmp(file, prev_file)))
	{
		/* do nothing more if the load fails */
		if(!(getAndSetFile(file, loc, store)))
			return(False);
	}
	if(prev_file)
		free(prev_file);
	prev_file = strdup(file);

	/* jump to the requested anchor in this file or to top of the document */
	if(loc)
		XmHTMLAnchorScrollToName(html_widgets[0].html, loc);
	else
		XmHTMLTextScrollToLine(html_widgets[0].html, 0);
	return(True);
}

/*****
* Name: 		readFile
* Return Type: 	void
* Description: 	XmNokCallback handler for the fileSelectionDialog: retrieves
*				the entered filename and loads it.
* In: 
*	w:			widget
*	dialog:		widget id of the fileSelectionDialog
*	cbs:		callback data
* Returns:
*	nothing.
*****/
static void
readFile(Widget widget, Widget dialog, XmFileSelectionBoxCallbackStruct *cbs)
{
	String filename, file;
	int item;

	/* remove the fileSelectionDialog */
	XtPopdown(XtParent(dialog));

	/* get the entered filename */
	XmStringGetLtoR(cbs->value, XmSTRING_DEFAULT_CHARSET, &filename);

	/* sanity check */
	if(!filename || !*filename)
	{
		if(filename)
			XtFree(filename);
		return;
	}

	/* get item data */
	XtVaGetValues(dialog, XmNuserData, &item, NULL);

	if(item == FILE_OPEN)
	{
		/* find the file */
		file = resolveFile(filename);
		XtFree(filename);

		if(file == NULL)
			return;

		/* load the file, will also update the document cache */
		loadAndOrJump(file, NULL, True);

		XFlush(XtDisplay(widget));
		free(file);
	}
	else if(item == FILE_SAVEAS)
	{
		FILE *fp;
		/* get parser output */
		String buffer = XmHTMLTextGetString(html_widgets[0].html);

		if(buffer)
		{
			if((fp = fopen(filename, "w")) == NULL)
				perror(filename);
			else
			{
				fputs(buffer, fp);
				fputs("\n", fp);
				fclose(fp);
			}
			XtFree(buffer);
		}
		XtFree(filename);
	}
}


static void
callClient(URLType url_type, String url)
{
	if(external_client)
	{
		char cmd[1024];
		if(url_type == ANCHOR_MAILTO)
			sprintf(cmd, "netscape -remote 'mailto(%s)'", url);
		if(url_type == ANCHOR_NEWS)
			sprintf(cmd, "netscape -remote 'news(%s)'", url);
		else
			sprintf(cmd, "netscape -remote 'openURL(%s)'", url);
		if(!(fork()))
		{
			if(execl("/bin/sh", "/bin/sh", "-c", cmd, NULL) == -1)
			{
				fprintf(stderr, "execl failed (%s)",
					strerror(errno));
				exit(100);
			}
		}
	}
}

/*****
* Name: 		anchorCB
* Return Type: 	void
* Description: 	XmNactivateCallback handler for the XmHTML widget
* In: 
*	w:			html widget
*	arg1:		client_data, unused
*	href_data:	anchor data
* Returns:
*	nothing.
*****/
static void
anchorCB(Widget w, XtPointer arg1, XmHTMLAnchorPtr href_data)
{
	/* see if we have been called with a valid reason */
	if(href_data->reason != XmCR_ACTIVATE)
		return;

	switch(href_data->url_type)
	{
		/* a named anchor */
		case ANCHOR_JUMP:
			{
				int id;
				/* see if XmHTML knows this anchor */
				if((id = XmHTMLAnchorGetId(w, href_data->href)) != -1)
				{
					/* store href in history and visited anchor list... */
					storeInHistory(NULL, href_data->href);
					storeAnchor(href_data->href);

					/* ...and let XmHTML jump and mark as visited */
					href_data->doit = True;
					href_data->visited = True;
					return;
				}
				return;
			}
			break;

		/* a local file with a possible ID jump */
		case ANCHOR_FILE_LOCAL:
			{
				String chPtr, file = NULL, loc = NULL;

				/* store href in visited anchor list */
				storeAnchor(href_data->href);

				/* first see if this anchor contains a jump */
				if((chPtr = strstr(href_data->href, "#")) != NULL)
				{
					char tmp[1024];
					strncpy(tmp, href_data->href, chPtr - href_data->href);
					tmp[chPtr - href_data->href] = '\0';
					/* try to find the file */
					file = resolveFile(tmp);
				}
				else
					file = resolveFile(href_data->href);

				if(file == NULL)
					return;

				/*****
				* All members in the XmHTMLAnchorCallbackStruct are
				* *pointers* to the contents of the current document.
				* So, if we will be changing the document, any members of this
				* structure become INVALID (in this case, any jump address to
				* a location in a different file). Therefore we *must* save
				* the members we might need after the document has changed.
				******/
				if(chPtr)
					loc = strdup(chPtr);

				/*****
				* If we have a target, call the frame loader, else call the
				* plain document loader.
				*****/
				if(href_data->target)
					jumpToFrame(file, loc, href_data->target, True);
				else
					loadAndOrJump(file, loc, True); 
				free(file);
				if(loc)
					free(loc);
			}
			break;

		case ANCHOR_PIPE:
			if(root_window || allow_exec)
			{
				char *ptr;
				char *cmd=NULL;

				Debug(("pipe: %s\n", href_data->href));

				if((ptr = strstr(href_data->href, ":")) != NULL)
				{
					ptr++;
					cmd = strdup(ptr);
					cmd[strlen(cmd)] = '\0';
                                        readPipe(html_widgets[0].html, cmd);
					free(cmd);
				}
			}
			break;

		case ANCHOR_EXEC:
			if(root_window || allow_exec)
			{
				char *ptr;
				char *cmd=NULL;

				Debug(("execute: %s\n", href_data->href));

				if((ptr = strstr(href_data->href, ":")) != NULL)
				{
					ptr++;
					cmd = strdup(ptr);
					cmd[strlen(cmd)] = '\0';
					if(!(fork()))
					{
						if(execl("/bin/sh", "/bin/sh", "-c", cmd, NULL) == -1)
						{
							fprintf(stderr, "execl failed (%s)",
								strerror(errno));
							exit(100);
						}
					}
					free(cmd);
				}
			}
			break;

		/* all other types are unsupported */
		case ANCHOR_FILE_REMOTE:
			fprintf(stderr, "fetch remote file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_FTP:
			fprintf(stderr, "fetch ftp file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_HTTP:
			fprintf(stderr, "fetch http file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_GOPHER:
			fprintf(stderr, "gopher: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_WAIS:
			fprintf(stderr, "wais: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_NEWS:
			fprintf(stderr, "open newsgroup: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_TELNET:
			fprintf(stderr, "open telnet connection: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_MAILTO:
			fprintf(stderr, "email to: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_UNKNOWN:
		default:
			fprintf(stderr, "don't know this type of url: %s\n", 
				href_data->href);
			break;
	}
}

/*****
* Name: 		setFrameText
* Return Type: 	void
* Description: 	loads the given file in the given HTML frame;
* In: 
*	widget:		XmHTML widget id in which to load the file;
*	filename:	file to be loaded;
*	loc:		selected position in the file. If non-NULL this routine will
*				scroll to the given location.
* Returns:
*	nothing.
*****/
static void
setFrameText(Widget frame, String filename, String loc)
{
	setBusy(True);

	if(filename)
	{
		String buf, file, mime;
		file = resolveFile(filename);
		if(file == NULL || (buf = loadFile(file, &mime)) == NULL)
		{
			setBusy(False);
			return;
		}
		/* kill of any outstanding progressive image loading contexts */
		XmHTMLImageProgressiveKill(frame);

		/* set the text in the widget */
		XtVaSetValues(frame,
			XmNvalue, buf,
			XmNmimeType, mime,
			NULL);
		free(buf);
		free(file);
	}

	/* jump to the requested anchor in this file or to top of the document */
	if(loc)
		XmHTMLAnchorScrollToName(frame, loc);
	else
		XmHTMLTextScrollToLine(frame, 0);

	setBusy(False);
}

/*****
* Name: 		jumpToFrame
* Return Type: 	void
* Description:	loads the contents of the given file in a named frame
* In: 
*	filename:	name of file to load;
*	loc:		url of file;
*	target:		name of frame in which to load the file;
*	store:		flag for history storage;
* Returns:
*	nothing.
*****/
static void
jumpToFrame(String filename, String loc, String target, Boolean store)
{
	int i;

	/* html_widgets[0] is the master XmHTML Widget, never framed */
	for(i = 1; i < MAX_HTML_WIDGETS; i++)
	{
		if(html_widgets[i].active && !(strcmp(html_widgets[i].name, target)))
		{
			/*
			* Load new file into frame if it's not the same as the current 
			* src value for this frame.
			*/
			if(html_widgets[i].src && strcmp(html_widgets[i].src, filename))
			{
				free(html_widgets[i].src);
				html_widgets[i].src = strdup(filename);
				setFrameText(html_widgets[i].html, filename, loc);
			}
			else	/* same file, jump to requested location */
				setFrameText(html_widgets[i].html, NULL, loc);
			return;
		}
	}
	/* frame not found, use the toplevel HTML widget */
	if(i == MAX_HTML_WIDGETS)
		loadAndOrJump(filename, loc, store); 
}

/* external gif decoder */
#include "gif_decode.c"

/*****
* Name: 		frameCB
* Return Type: 	void
* Description: 	callback for XmHTML's XmNframeCallback
* In: 
*	w:			widget id;
*	arg1:		client_data, unused;
*	cbs:		data about the frame being created/destroyed/notified of 
*				creation.
* Returns:
*	nothing.
*****/
static void
frameCB(Widget w, XtPointer arg1, XmHTMLFramePtr cbs)
{
	int i;

	if(cbs->reason == XmCR_HTML_FRAME)
	{
		Widget html = cbs->html;

		/* find the first free slot where we can insert this frame */
		for(i = 0; i < MAX_HTML_WIDGETS;i++)
			if(!html_widgets[i].active)
				break;

		/* a frame always has a name */
		html_widgets[i].name = strdup(cbs->name);
		if(cbs->src)
			html_widgets[i].src = resolveFile(cbs->src);

		/* anchor callback */
		XtAddCallback(html, XmNactivateCallback,
			(XtCallbackProc)anchorCB, NULL);

		/* HTML document callback */
		XtAddCallback(html, XmNdocumentCallback, (XtCallbackProc)docCB, NULL);

		/* set other things we want to have */
		XtVaSetValues(html,
			XmNanchorVisitedProc, testAnchor,
			XmNimageProc, loadImage,
			XmNprogressiveReadProc, getImageData,
			XmNprogressiveEndProc, endImageData,
#ifdef HAVE_GIF_CODEC
			XmNdecodeGIFProc, decodeGIFImage,
#endif
			/* propagate current defaults */
			XmNanchorButtons,
				html_config[OPTIONS_ANCHOR_BUTTONS].value,
			XmNhighlightOnEnter,
				html_config[OPTIONS_HIGHLIGHT_ON_ENTER].value,
			XmNenableBadHTMLWarnings,
				html_config[OPTIONS_DISABLE_WARNINGS].value,
			XmNstrictHTMLChecking,
				html_config[OPTIONS_ENABLE_STRICT_HTML32].value,
			XmNenableBodyColors,
				html_config[OPTIONS_ENABLE_BODYCOLORS].value,
			XmNenableBodyImages,
				html_config[OPTIONS_ENABLE_BODYIMAGES].value,
			XmNenableDocumentColors,
				html_config[OPTIONS_ENABLE_DOCUMENT_COLORS].value,
			XmNenableDocumentFonts,
				html_config[OPTIONS_ENABLE_DOCUMENT_FONTS].value,
			XmNenableOutlining,
				html_config[OPTIONS_ENABLE_OUTLINING].value,
			XmNfreezeAnimations,
				html_config[OPTIONS_FREEZE_ANIMATIONS].value,
			XmNimageEnable,
				html_config[OPTIONS_ENABLE_IMAGES].value,
			NULL);

		/* store widget id */
		html_widgets[i].html = html;
		html_widgets[i].active = True;

		/* set source text */
		setFrameText(html_widgets[i].html, html_widgets[i].src, NULL);

		return;
	}
	if(cbs->reason == XmCR_HTML_FRAMECREATE)
	{
		/* see if we have an inactive frame in our frame cache */
		for(i = 0; i < MAX_HTML_WIDGETS;i++)
			if(!html_widgets[i].active && !html_widgets[i].used)
				break;

		/* we have an available slot */
		if(i != MAX_HTML_WIDGETS && html_widgets[i].html != NULL)
		{
			cbs->doit = False;
			cbs->html = html_widgets[i].html;
			/* this slot is being used */
			html_widgets[i].used = True;
		}
		/*
		* this is the appropriate place for doing frame reuse: set
		* the doit field in the callback structure to False and set the
		* id of a *HTML* widget in the html field.
		*/
		return;
	}
	if(cbs->reason == XmCR_HTML_FRAMEDESTROY)
	{
		int freecount = 0;
		/*
		* this is the appropriate place for keeping this widget: just set
		* the doit field to false, update the frame cache (if this frame is
		* going to be reused, it's name and src value will probably change).
		*/
		for(i = 0; i < MAX_HTML_WIDGETS; i++)
		{
			if(!html_widgets[i].active)
				freecount++;
			if(html_widgets[i].html == cbs->html)
			{
				freecount++;
				/* a frame has always got a name */
				free(html_widgets[i].name);
				if(html_widgets[i].src)
					free(html_widgets[i].src);
				html_widgets[i].name = NULL;
				html_widgets[i].src = NULL;
				/* we keep up to three frames in memory */
				if(freecount > 3)
					html_widgets[i].html = NULL;
				html_widgets[i].active = False;
				html_widgets[i].used = False;
				break;
			}
		}
		if(freecount < 4)
			cbs->doit = False;
		return;
	}
	/* do nothing */
	return;
}


/*****
* Name: 		metaListCB
* Return Type: 	void
* Description: 	callback for the list in the document information dialog.
*				Displays the data associated with the selected item in the
*				list.
* In: 
*	w:			list widget id;
*	edit:		widget id of text widget in which data will be displayed.
* Returns:
*	nothing.
*****/
static void
metaListCB(Widget w, Widget edit)
{
	int *pos_list;	/* selected list position */
	int pos_cnt, selected;	/* no of selected items */
	XmHTMLMetaDataPtr meta_data = NULL;

	if(!(XmListGetSelectedPos(w, &pos_list, &pos_cnt)))
		/* no item selected */
		return;

	selected = pos_list[0];
	/* list positions start at 1 instead of zero, so be sure to adjust */
	selected--;

	/* get meta data out of the list's userData */
	XtVaGetValues(w, XmNuserData, &meta_data, NULL);

	/* very serious error */
	if(meta_data == NULL)
	{
		fprintf(stderr, "Could not retrieve meta-data from userData field!\n");
		free(pos_list);
		return;
	}

	/* and put the selected string in the edit field */
	XmTextSetString(edit, meta_data[selected].content);
	free(pos_list);
}

static String
getCharset(String content)
{
	String ptr, start;
	int len = 0;
	static char this_set[128];

	/*
	* We possible have a charset spec in here. Check
	* for it
	*/
	if((ptr = strstr(content, "charset")) != NULL)
	{
		ptr+= 7;	/* move past "charset" */

		/* skip until we hit = */
		for(;*ptr && *ptr != '='; ptr++);
			ptr++;

		/* skip all spaces */
		for(;*ptr && isspace(*ptr); ptr++);

		/*
		* now count how many chars we have. The charset spec is terminated
		* by a a quote
		*/
		start = ptr;
		while(*ptr && *ptr != '\"')
		{
			len++;
			ptr++;
		}
		if(len)
		{
			strncpy(this_set, start, len);
			this_set[len] = '\0'; /* nullify */
			/*
			* if we don't have a - in charset, we *must* append -* to make
			* it a valid XmNcharset spec.
			*/
			if(!(strstr(this_set, "-")))
				strcat(this_set, "-*");

			return(this_set);
		}
	}
	return(NULL);
}

int
#ifdef __STDC__
	my_sprintf(String *dest, int *size, int *max_size, String fmt, ...)
#else /* ! __STDC__ */
	my_sprintf(String *dest, int *size, int *max_size, String fmt, va_list)
	String *dest;
	int *size;
	int *max_size;
    String fmt;
    va_dcl
#endif /* __STDC__ */
{
    int len;
    String s;
#ifdef __STDC__
    va_list	arg_list;
#else
	va_dcl
#endif

    if(*max_size - *size < 1024) 
    {
		*max_size += 1024;
		/* realloc(NULL, size) ain't exactly portable */
		if(*max_size == 1024)
			s = (char *)malloc(*max_size);
		else
			s = (char *)realloc(*dest, *max_size);
		*dest = s;
    }
#ifdef __STDC__
    va_start(arg_list, fmt);
#else
    va_start(arg_list);
#endif
    len = vsprintf(*dest + *size, fmt, arg_list);
    va_end(arg_list);

	/* new size of destination buffer */
    if(len != 0) 
		*size += strlen(*dest + *size);
    return(len);
}


/*****
* Name: 		docInfoCB
* Return Type: 	void
* Description: 	shows a dialog with document information. This routine gets
*				activated when the file->document info menu item is selected.
* In: 
*	font_only:	check only for a possible font spec in the meta information.
* Returns:
*	nothing.
*****/
static void
docInfoCB(Boolean font_only)
{
	static Widget title_label, author_label, base_label, doctype_label;
	static Widget list, edit;
	XmString xms;
	static XmHTMLHeadAttributes head_info;
	Boolean have_info = False;
	String tmp;
	int i, argc = 0;
	Arg args[5];

	if(font_only)
	{
		char this_font[128];
		String this_charset = NULL;

		this_font[0] = '\0';

		/* get meta info for a charset and/or font spec */
		if(XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info, HeadMeta))
		{
			if(head_info.num_meta)
			{
				for(i = 0; i < head_info.num_meta; i++)
				{
					tmp = (head_info.meta[i].http_equiv ? 
						head_info.meta[i].http_equiv : head_info.meta[i].name);

					if(!strcmp(tmp, "font"))
					{
						sprintf(this_font, "*-%s-normal-*",
							head_info.meta[i].content);
					}
					else if(!strcmp(tmp, "content-type") &&
						this_charset == NULL)
					{
						this_charset = getCharset(head_info.meta[i].content);
					}
				}
			}
		}

		/*****
		* have we been told to set a new font?
		* Please note that in a real world application it should be checked
		* if the requested font is available. XmHTML silently ignores this
		* kind of errors.
		*****/
		if(*this_font)
		{
			/* font changed */
			if(strcmp(this_font, current_font))
			{
				strcpy(current_font, this_font);
				current_font[strlen(this_font)] = '\0';

				Debug(("docInfoCB, setting XmNfontFamily to %s\n",
					current_font));
				XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
			}
			/* still the same, don't touch it */
		}
		else if(strcmp(current_font, default_font))
		{
			/* reset default font */
			strcpy(current_font, default_font);
			current_font[strlen(default_font)] = '\0';
			Debug(("docInfoCB, setting XmNfontFamily to %s\n", current_font));
			XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
		}

		/*****
		* have we been told to set a new character set?
		* Please note that a real world app *MUST* check if the requested
		* character set is available. XmHTML silently ignores any errors
		* resulting from an invalid charset, it just falls back to whatever
		* the X server provides.
		* To make these checks really consistent, it should also be verified
		* that the current font family is still valid if the charset is
		* changed. XmHTML's font allocation routines will almost *never*
		* fail on font allocations: if a font can not be found in the requested
		* character set it will use the default charset supplied by the X
		* server. If font allocation still fails after this, it will wildcard
		* the fontfamily and try again (this is done so XmHTML will always have
		* a default font available). If this also fails (which is almost
		* impossible) XmHTML will exit your application: if it can't find
		* any fonts at all, why keep on running?
		*****/
		if(this_charset)
		{
			/* charset changed */
			if(strcmp(current_charset, this_charset))
			{
				/* we currently only known koi8 and iso8859-1 */
				if(strstr(this_charset, "koi8"))
				{
					/* save charset */
					strcpy(current_charset, this_charset);
					current_charset[strlen(this_charset)] = '\0';

					/* koi8 has cronyx for its foundry */
					strcpy(current_font, "cronyx-times-*-*\0");
					argc = 0;		/* overrides a fontspec */

					Debug(("docInfoCB, setting XmNcharset to %s\n",
						current_charset));
					XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
					XtSetArg(args[argc], XmNcharset, current_charset); argc++;
				}
				else if(!strstr(this_charset, "iso8859-1"))
				{
					fprintf(stderr, "Warning: character set %s unsupported\n",
						current_charset);
				}
			}
			/* still the same, don't touch it */
		}
		else if(strcmp(current_charset, default_charset))
		{
			strcpy(current_charset, default_charset);
			current_charset[strlen(default_charset)] = '\0';
			XtSetArg(args[argc], XmNcharset, current_charset); argc++;
		}

		/* plop'em in */
		if(argc)
			XtSetValues(html_widgets[0].html, args, argc);

		/*****
		* Tell XmHTML to clear everything. This is not really required but
		* adviseable since XmHTML will only clear the fields that have
		* been requested. For example, in all subsequent calls to the above
		* XmHTMLGetHeadAttributes call, XmHTML will first clear the stored
		* meta info before filling it again.
		*****/
		XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info, HeadClear);
		return;
	}

	/*****
	* Get <head></head> information from the current document. XmHTML will
	* take care of replacing the requested members when they have been used
	* before. When no <head></head> is available this function returns false
	* Note: the value of the <!DOCTYPE> member is always returned if there
	* is one, even if GetHeadAttributes() returns False.
	*****/
	have_info = XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info,
					HeadDocType|HeadTitle|HeadBase|HeadMeta);

	if(!info_dialog)
	{
		Widget sep, rc1, rc2, fr1, fr2;
		Arg args[20];
		int argc = 0;

		info_dialog = XmCreateFormDialog(toplevel, "documentAttributes",
			NULL, 0);

		XtVaSetValues(XtParent(info_dialog),
			XtNtitle, "Document Attributes",
			NULL);
		fr1 = XtVaCreateManagedWidget("documentTitleForm",
			xmFormWidgetClass, info_dialog,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			NULL);

		sep = XtVaCreateManagedWidget("documentSeperator",
			xmSeparatorGadgetClass, info_dialog,
			XmNorientation, XmHORIZONTAL,
			XmNtopAttachment, XmATTACH_WIDGET,
			XmNtopWidget, fr1,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			XmNtopOffset, 10,
			NULL);

		fr2 = XtVaCreateManagedWidget("documentTitleForm",
			xmFormWidgetClass, info_dialog,
			XmNtopAttachment, XmATTACH_WIDGET,
			XmNtopWidget, sep,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			NULL);

		rc1 = XtVaCreateManagedWidget("documentTitleLeftRow",
			xmRowColumnWidgetClass, fr1,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			XmNtopOffset, 10,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			NULL);
		XtVaCreateManagedWidget("Document Title:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Author:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Document type:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Base Location:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);

		rc2 = XtVaCreateManagedWidget("documentTitleRightRow",
			xmRowColumnWidgetClass, fr1,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_WIDGET,
			XmNleftWidget, rc1,
			XmNrightAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			XmNtopOffset, 10,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			NULL);
		title_label = XtVaCreateManagedWidget("docTitle",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		author_label = XtVaCreateManagedWidget("docAuthor",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		doctype_label = XtVaCreateManagedWidget("docType",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		base_label = XtVaCreateManagedWidget("docBase",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtSetArg(args[argc], XmNlistSizePolicy, XmRESIZE_IF_POSSIBLE); argc++;
		XtSetArg(args[argc], XmNvisibleItemCount, 5); argc++;
		XtSetArg(args[argc], XmNleftAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNtopAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNbottomAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNleftOffset, 10); argc++;
		XtSetArg(args[argc], XmNtopOffset, 10); argc++;
		XtSetArg(args[argc], XmNbottomOffset, 10); argc++;
		list = XmCreateScrolledList(fr2, "metaList", args, argc);

		argc = 0;
		XtSetArg(args[argc], XmNscrollBarDisplayPolicy, XmAS_NEEDED); argc++;
		XtSetArg(args[argc], XmNscrollingPolicy, XmAUTOMATIC); argc++;
		XtSetArg(args[argc], XmNleftAttachment, XmATTACH_WIDGET); argc++;
		XtSetArg(args[argc], XmNleftWidget, list); argc++;
		XtSetArg(args[argc], XmNtopAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNbottomAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNrightAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNleftOffset, 10); argc++;
		XtSetArg(args[argc], XmNrightOffset, 10); argc++;
		XtSetArg(args[argc], XmNtopOffset, 10); argc++;
		XtSetArg(args[argc], XmNbottomOffset, 10); argc++;
		edit = XmCreateScrolledText(fr2, "metaEdit", args, argc);

		argc = 0;
		XtSetArg(args[argc], XmNeditable, False); argc++;
		XtSetArg(args[argc], XmNcolumns, 35); argc++;
		XtSetArg(args[argc], XmNrows, 5); argc++;
		XtSetArg(args[argc], XmNwordWrap, True); argc++;
		XtSetArg(args[argc], XmNeditMode, XmMULTI_LINE_EDIT); argc++;
		XtSetArg(args[argc], XmNscrollHorizontal, False); argc++;
		XtSetArg(args[argc], XmNscrollVertical, False); argc++;
		XtSetValues(edit, args, argc);

		/* single selection callback on the list */
		XtAddCallback(list, XmNbrowseSelectionCallback,
			(XtCallbackProc)metaListCB, edit);

		XtManageChild(list);
		XtManageChild(edit);
	}

	/* delete all list items */
	XmListDeleteAllItems(list);
	/* clear all text in the edit window */
	XmTextSetString(edit, NULL);

	if(head_info.doctype)
		xms = XmStringCreateLocalized(head_info.doctype);
	else
		xms = XmStringCreateLocalized("<Unspecified>");
	XtVaSetValues(doctype_label, XmNlabelString, xms, NULL);
	XmStringFree(xms);

	if(have_info)
	{
		if(head_info.title)
			xms = XmStringCreateLocalized(head_info.title);
		else
			xms = XmStringCreateLocalized("<Untitled>");
		XtVaSetValues(title_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		if(head_info.base)
			xms = XmStringCreateLocalized(head_info.base);
		else
			xms = XmStringCreateLocalized("<Not specified>");
		XtVaSetValues(base_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);
		xms = NULL;

		/*
		* No need to check for font or charset in meta info, that's
		* already been done from within the documentCallback.
		*/
		if(head_info.num_meta)
		{
			for(i = 0; i < head_info.num_meta; i++)
			{
				tmp = (head_info.meta[i].http_equiv ? 
					head_info.meta[i].http_equiv : head_info.meta[i].name);

				/* pick out author */
				if(!strcmp(tmp, "author"))
					xms = XmStringCreateLocalized(head_info.meta[i].content);
			}
		}
		if(xms == NULL)
			xms = XmStringCreateLocalized("<Unknown>");
		XtVaSetValues(author_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		/* string table */
		if(head_info.num_meta)
		{
			XmStringTable strs;
			strs =(XmStringTable)malloc(head_info.num_meta*sizeof(XmString*));
			
			for(i = 0; i < head_info.num_meta; i++)
			{
				if(head_info.meta[i].http_equiv)
					strs[i] =
						XmStringCreateLocalized(head_info.meta[i].http_equiv);
				else
					strs[i] =
						XmStringCreateLocalized(head_info.meta[i].name);
			}
			XtVaSetValues(list,
				XmNitemCount, head_info.num_meta,
				XmNitems, strs,
				XmNuserData, (XtPointer)head_info.meta,
				NULL);
			for(i = 0; i < head_info.num_meta; i++)
				XmStringFree(strs[i]);
			free(strs);
		}
	}
	else
	{
		xms = XmStringCreateLocalized("<Untitled>");
		XtVaSetValues(title_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		xms = XmStringCreateLocalized("<Unknown>");
		XtVaSetValues(author_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		xms = XmStringCreateLocalized("<Not specified>");
		XtVaSetValues(base_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);
	}
	/* put on screen */
	XtManageChild(info_dialog);
	XMapRaised(XtDisplay(info_dialog), XtWindow(info_dialog));
}

/*****
* Name: 		docCB
* Return Type: 	void
* Description: 	displays current document state as given by XmHTML.
* In: 
*	html:		owner of this callback
*	arg1:		client_data, unused
*	cbs:		call_data, documentcallback structure.
* Returns:
*	nothing
* Note:
*	the XmNdocumentCallback is an excellent place for setting several
*	formatting resources: XmHTML triggers this callback when the parser
*	has finished, but *before* doing any formatting. As an example, we
*	check the information contained in the document head for a font
*	specification: we call docInfoCB with the font_only arg set to True.
*****/
static void
docCB(Widget w, XtPointer arg1, XmHTMLDocumentPtr cbs)
{
	XmString xms;
	char doc_label[128];
	Pixel my_pix = (Pixel)0;
	static Pixel red, green;

	/* see if we have been called with a valid reason */
	if(cbs->reason != XmCR_HTML_DOCUMENT)
		return;

	/*
	* If we are being notified of the results of another pass on the loaded
	* document, only check whether the generated parser tree is balanced and
	* don't update the labels since the callback data is the result of a
	* modified document.
	*
	* XmHTML's document verification and repair routines are capable of
	* creating a verified, properly balanced and HTML conforming document
	* from even the most horrible non-HTML conforming documents!
	*
	* And when the XmNstrictHTMLChecking resource has been set to True, these
	* routines are also bound to make the document HTML 3.2 conformant as well.
	*/
	if(cbs->pass_level)
	{
		/*
		* Allow up to two iterations on the current document (remember that
		* the document has already been checked twice when pass_level == 1).
		* XmHTML sets the redo field to True whenever the parser tree is
		* unbalanced, so it needs to be set to False when the allowed number
		* of iterations has been reached.
		*
		* The results of displaying a document with an unbalanced parser tree
		* are undefined however and can lead to some weird markup results.
		*/
		if(!cbs->balanced && cbs->pass_level < 2)
			return;
		cbs->redo = False;

		/* done parsing, check if a font is given in the meta spec. */
		docInfoCB(True);
		return;
	}

	if(!red)
		red = XmHTMLAllocColor((Widget)html_widgets[0].html, "Red",
			BlackPixelOfScreen(XtScreen(toplevel)));

	if(!green)
		green = XmHTMLAllocColor((Widget)html_widgets[0].html, "Green",
			WhitePixelOfScreen(XtScreen(toplevel)));

	if(cbs->html32)
	{
		sprintf(doc_label, "HTML 3.2");
		my_pix = green;
	}
	else
	{
		sprintf(doc_label, "Bad HTML 3.2");
		my_pix = red;
	}
	xms = XmStringCreateLocalized(doc_label);
	XtVaSetValues(html32,
		XmNbackground, my_pix,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	if(cbs->verified)
	{
		sprintf(doc_label, "Verified");
		my_pix = green;
	}
	else
	{
		sprintf(doc_label, "Unverified");
		my_pix = red;
	}
	xms = XmStringCreateLocalized(doc_label);
	XtVaSetValues(verified,
		XmNbackground, my_pix,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	/*
	* default processing here. If the parser tree isn't balanced
	* (cbs->balanced == False) and you want to prevent XmHTML from making
	* another pass on the current document, set the redo field to false.
	*/
	if(cbs->balanced)
	{
		/* check meta info for a possible font spec */
		docInfoCB(True);
	}
}

/*****
* Name: 		linkCB
* Return Type: 	void
* Description: 	XmHTML's XmNlinkCallback handler
* In: 
*	w:			widget id;
*	arg1:		client_data, unused;
*	cbs:		link data found in current document.
* Returns:
*	nothing, but copies the link data to an internal structure which is used
*	for displaying a site-navigation bar.
*****/
static void
linkCB(Widget w, XtPointer arg1, XmHTMLLinkPtr cbs)
{
	int i, j;

	/* free previous document links */
	for(i = 0; i < LINK_LAST; i++)
	{
		if(document_links[i].have_data)
		{
			/* we always have a href */
			free(document_links[i].href);
			/* but title is optional */
			if(document_links[i].title)
				free(document_links[i].title);
			document_links[i].href= NULL;
			document_links[i].title = NULL;
		}
		document_links[i].have_data  = False;
	}

	/*****
	* Since this callback gets triggered for every document, this is also
	* the place for updating the info dialog (if it's up that is).
	*****/
	if(info_dialog && XtIsManaged(info_dialog))
		docInfoCB(False);

	/*****
	* if the current document doesn't have any links, unmanage the button
	* and dialog and return.
	*****/
	if(cbs->num_link == 0)
	{
		/* might not have been created yet */
		if(link_dialog != NULL)
			XtUnmanageChild(link_dialog);
		XtUnmanageChild(link_button);
		return;
	}

	/* store links in this document */
	for(i = 0; i < LINK_LAST; i++)
	{
		for(j = 0; j < cbs->num_link; j++)
		{
			/* kludge for the mailto */
			String tmp = (i == 0 ? "made" : link_labels[i]);

			/*****
			* url is mandatory and so is one of rel or rev. Although both
			* of them can be present, we prefer a rel over a rev.
			*****/
			if(!cbs->link[j].url || (!cbs->link[j].rel && !cbs->link[j].rev))
				continue;

			if((cbs->link[j].rel && my_strcasestr(cbs->link[j].rel, tmp)) ||
				(cbs->link[j].rev && my_strcasestr(cbs->link[j].rev, tmp)))
			{
				document_links[i].have_data = True;
				document_links[i].link_type = cbs->link[j].rel ? 1 : 0;
				/* we always have this */
				document_links[i].href = strdup(cbs->link[j].url);
				/* title is optional */
				if(cbs->link[j].title)
					document_links[i].title = strdup(cbs->link[j].title);
			}
		}
	}
	/* if the dialog is already up, update the buttons */
	if(link_dialog && XtIsManaged(link_dialog))
	{
		for(i = 0; i < LINK_LAST; i++)
		{
			if(document_links[i].have_data)
				XtSetSensitive(link_buttons[i], True);
			else
				XtSetSensitive(link_buttons[i], False);
		}
		/* and make sure everything is up and displayed */
		XmUpdateDisplay(link_dialog);
	}
	/* manage the button so user can see the site structure of this doc. */
	XtManageChild(link_button);
}

/*****
* Name: 		collapseURL
* Return Type: 
* Description:	Copies up to 50 chars from the given url and puts in three
*				dots when the given url is larger than fifty chars.
* In: 
*	url:		url to be collapsed or copied;
* Returns:
*	copied url.
*****/
static String
collapseURL(String url)
{
	static char name[51];
	int len;

	if(url == NULL)
		return("");

	len = strlen(url);

	if(len < 50)
	{
		strcpy(name, url);
		name[len] = '\0';	/* NULL terminate */
		return(name);
	}
	/* copy first 11 chars */
	strncpy(name, url, 11);
	/* put in a few dots */
	name[11] = '.';
	name[12] = '.';
	name[13] = '.';
	name[14] = '\0';
	/* copy last 36 chars */
	strcat(name, &url[len - 36]);
	name[50] = '\0';	/* NULL terminate */
	return(name);
}

/*****
* Name: 		infoCB
* Return Type: 	void
* Description: 	ButtonPressed handler for the workArea of a XmHTML widget.
*				In this case, a possible use of the XmHTMLXYToInfo resource
*				is demonstrated.
* In: 
*	w:			widget id;
*	popup:		popup menu widget id
*	event:		location of button press.
* Returns:
*	nothing.
*****/
static void
infoCB(Widget parent, Widget popup, XButtonPressedEvent *event)
{
	XmString xms;
	char tmp[84];	/* max label width */
	XmHTMLInfoPtr info;
	WidgetList children;
	Widget html_w;

	XUngrabPointer(XtDisplay(parent), CurrentTime);

	/* only button 3 */
	if(event->button != 3)
		return;

	html_w = XtParent(parent);

	if(html_w == NULL || !XmIsHTML(html_w))
	{
		fprintf(stderr, "%s parent gotten from XtParent(%s)\n",
			html_w == NULL ? "NULL" : "Invalid", XtName(parent));
		return;
	}

	/* get the info for the selected position */
	info = XmHTMLXYToInfo(html_w, event->x, event->y);

	/* no popup if no image and anchor */
	if(info == NULL || (info->image == NULL && info->anchor == NULL))
		return;

	XtVaGetValues(popup, XmNchildren, &children, NULL);

	/* unmanage all buttons */
	XtUnmanageChild(children[0]);
	XtUnmanageChild(children[1]);
	XtUnmanageChild(children[2]);
	XtUnmanageChild(children[3]);

	/*****
	* Note on how to convey the href or image url's to the popup callbacks:
	*
	* All strings provided in the anchor and/or image field of this callback
	* are internal to XmHTML and are guarenteed to exist as long as the
	* current document is up. Knowing this, we can safely store these strings
	* in the userData field of the popup menu buttons.
	****/

	/* if we have an anchor, we copy the url to the label */
	if(info->anchor)
	{
		sprintf(tmp, "Follow this link (%s)", collapseURL(info->anchor->href));
		xms = XmStringCreateLocalized(tmp);
		XtVaSetValues(children[0],
			XmNlabelString, xms,
			XmNuserData, info->anchor->href,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[0]);
	}
	if(info->image)
	{
		sprintf(tmp, "Open this image (%s)", collapseURL(info->image->url));
		xms = XmStringCreateLocalized(tmp);
		XtVaSetValues(children[1],
			XmNlabelString, xms,
			XmNuserData, info->image->url,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[1]);

		xms = XmStringCreateLocalized("View Image details");
		XtVaSetValues(children[2],
			XmNlabelString, xms,
			XmNuserData, info->image,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[2]);

		/* set proper string for fancy image tracking */
		if(html_config[OPTIONS_FANCY_TRACKING].value)
			xms = XmStringCreateLocalized("Disable Anchored Image Tracking");
		else
			xms = XmStringCreateLocalized("Enable Anchored Image Tracking");
		XtVaSetValues(children[3],
			XmNlabelString, xms,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[3]);
	}
	/* set correct menu position */
	XmMenuPosition(popup, event);
	/* and show it */
	XtManageChild(popup);
}

/*****
* Name: 		navCB
* Return Type: 	void
* Description: 	callback for the buttons in the link dialog (displayed 
*				by the linkButtonCB routine)
* In: 
*	w:			widget id of selected button;
*	item:		id of selected item;
* Returns:
*	nothing.
* Note:
*	This routine simply creates a XmHTMLAnchorCallbackStruct and calls
*	the anchorCB routine to let it handle navigation of the document
*	(which can include loading a new local or remote document, call a mail
*	application to mail something, download something, whatever).
*****/
static void
navCB(Widget w, int item)
{
	static XmHTMLAnchorCallbackStruct cbs;

	/*****
	* We just compose a XmHTMLAnchorCallbackStruct and let anchorCB do the
	* loading.
	*****/
	cbs.reason = XmCR_ACTIVATE;
	cbs.event  = NULL;
	cbs.url_type = XmHTMLGetURLType(document_links[item].href);
	cbs.href   = document_links[item].href;
	cbs.title  = document_links[item].title;
	cbs.line   = 0;
	cbs.target = NULL;
	cbs.doit   = False;
	cbs.visited= False;
	if(document_links[item].link_type == 0)
	{
		cbs.rev = link_labels[item];
		cbs.rel = NULL;
	}
	else
	{
		cbs.rel = link_labels[item];
		cbs.rev = NULL;
	}

	/* and call the activate callback */
	anchorCB(html_widgets[0].html, NULL, &cbs);
}

/*****
* Name: 		linkButtonCB
* Return Type: 	void
* Description: 	displays a dialog with buttons to allow navigation of a
*				document using the information contained in the <link></link>
*				section of a HTML document.
* In: 
*	w:			widget id, unused;
*	arg1:		client_data, unused;
*	arg2:		call_data, unused;
* Returns:
*	nothing.
*****/
static void
linkButtonCB(Widget w, XtPointer arg1, XtPointer arg2)
{
	int i;

	if(!link_dialog)
	{
		Widget rc;
		link_dialog = XmCreateFormDialog(toplevel, "Preview", NULL, 0);
		
		XtVaSetValues(XtParent(link_dialog),
			XtNtitle, "Site Structure",
			NULL);

		/* a rowcol for the buttons */
		rc = XtVaCreateManagedWidget("rowColumn",
			xmRowColumnWidgetClass, link_dialog,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNspacing, 0,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			NULL);
		/* all buttons */
		for(i = 0; i < LINK_LAST; i++)
		{
			link_buttons[i] = XtVaCreateManagedWidget(link_labels[i],
				xmPushButtonWidgetClass, rc,
				NULL);
			XtAddCallback(link_buttons[i], XmNactivateCallback,
				(XtCallbackProc)navCB, (XtPointer)i);
		}
	}
	/* Now see what buttons to activate. */
	for(i = 0; i < LINK_LAST; i++)
	{
		if(document_links[i].have_data)
			XtSetSensitive(link_buttons[i], True);
		else
			XtSetSensitive(link_buttons[i], False);
	}
	/* 
	* Keep the focus on the html widget so the navigation keys always
	* work.
	*/
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

	/* put on screen */
	XtManageChild(link_dialog);
	XMapRaised(XtDisplay(link_dialog), XtWindow(link_dialog));

	/* and make sure everything is up and displayed */
	XmUpdateDisplay(link_dialog);
}

/*****
* Name: 		historyCB
* Return Type: 	void
* Description: 	XmNactivateCallback handler for the back & forward buttons.
*				moves back or forward in the history.
* In: 
*	w:			widget
*	button:		button the triggered this callback.
* Returns:
*	nothing.
*****/
static void
historyCB(Widget w, int button)
{
	DocumentCache *this_doc = &doc_cache[current_doc];

	/* back button has been pressed */
	if(button == 0)
	{
		if(!XtIsSensitive(back))
			return;

		/* current_ref == 0 -> top of file */
		if(this_doc->current_ref)
			this_doc->current_ref--;
		/* reached bottom of current document, move to the previous one */
		else
		{
			current_doc--;
			this_doc = &doc_cache[current_doc];
		}
		if(loadAndOrJump(this_doc->file, this_doc->refs[this_doc->current_ref],
			False))
		{
			XtSetSensitive(forward, True);
			XtSetSensitive(back, 
				current_doc || this_doc->current_ref ? True : False);
		}
		else
		{
			if(current_doc)
			{
				current_doc--;
				historyCB(w, button);
			}
		}
	}
	/* forward button has been pressed */
	else
	{
		if(!XtIsSensitive(forward))
			return;

		this_doc->current_ref++;
		/* reached max of this document, move to the next doc */
		if(this_doc->current_ref == this_doc->nrefs)
		{
			this_doc->current_ref--;
			current_doc++;
			this_doc = &doc_cache[current_doc];
		}

		if(loadAndOrJump(this_doc->file, this_doc->refs[this_doc->current_ref],
			False))
		{
			XtSetSensitive(back, True);

			if(current_doc == last_doc - 1 && 
				this_doc->current_ref == this_doc->nrefs - 1)
				XtSetSensitive(forward, False);
		}
		else
		{
			if(current_doc != last_doc-1)
			{
				current_doc++;
				historyCB(w, button);
			}
		}
	}
	/* 
	* Keep the focus on the html widget so the navigation keys always
	* work.
	*/
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);
}

/*****
* Name: 		destroyCacheObject
* Return Type: 	void
* Description: 	gets called by the object caching routines when it wants to
*				destroy a cached object.
* In: 
*	call_data:	object to be destroyed;
*	client_data:data we registered ourselves when we made the initObjectCache
*				call.
* Returns:
*	nothing.
*****/
static void
destroyCacheObject(XtPointer call_data, XtPointer client_data)
{
	Debug(("destroyCacheObject, called for %s\n",
		((XmImageInfo*)call_data)->url));

	XmHTMLImageFreeImageInfo((Widget)client_data, (XmImageInfo*)call_data);
}

/*****
* Name: 		loadAnimation
* Return Type: 	XmImageInfo
* Description: 	load an animation consisting of multiple images
* In: 
*	names:		comma separated list of images
* Returns:
*	a list of XmImageInfo composing the animation
* Note:
*	this is a fairly simple example on how to add support for images
*	that are not supported by the XmHTMLImageDefaultProc convenience
*	function.
*****/
XmImageInfo*
loadAnimation(char *names)
{
	static XmImageInfo *all_frames;
	XmImageInfo *frame = NULL;
	String chPtr, name_buf, filename;
	int nframes = 0;

	name_buf = strdup(names);
	for(chPtr = strtok(name_buf, ","); chPtr != NULL; 
		chPtr = strtok(NULL, ","))
	{
		if((filename = resolveFile(chPtr)) == NULL)
		{
			free(name_buf);
			return(NULL);
		}
		if(nframes)
		{
			frame->frame = XmHTMLImageDefaultProc(html_widgets[0].html,
				filename, NULL, 0);
			frame = frame->frame;
		}
		else
		{
			all_frames = XmHTMLImageDefaultProc(html_widgets[0].html,
				filename, NULL, 0);
			frame = all_frames;
		}
		frame->timeout = animation_timeout;
		nframes++;
		free(filename);
	}
	free(name_buf);

	/* nframes is total no of frames in this animation */
	all_frames->nframes = nframes;
	all_frames->timeout = animation_timeout;
	return(all_frames);
}

/*****
* Name: 		flushImages
* Return Type: 	void
* Description: 	flushes all images (normal *and* delayed) to the currently
*				loaded document.
* In: 
*	w:			widget id, unused;
* Returns:
*	nothing.
* Note:
*	This routine simply flushes all images in the currently loaded document.
*	When it finds an image that has been delayed, it loads the real image and
*	replaces the delayed image in the current document with the real image.
*	When all images have been updated, it calls XmHTMLRedisplay to force
*	XmHTML to do a re-computation of the document layout.
*****/
static void 
flushImages(Widget w)
{
	int i;
	static XmImageInfo *image, *new_image;
	String url, filename;
	DocumentCache *this_doc;
	XmImageStatus status = XmIMAGE_OK, retval = XmIMAGE_OK;
	
	setBusy(True);

	/* get current document */
	this_doc = &doc_cache[current_doc];

	for(i = 0; i < this_doc->nimages; i++)
	{
		url = this_doc->images[i];

		/* get image to update */
		if((image = (XmImageInfo*)getURLObjectFromCache(url)) == NULL)
			continue;

		/* only do this when the image hasn't been loaded yet */
		if(image->options & XmIMAGE_DELAYED &&
			(filename = resolveFile(url)) != NULL)
		{
			if(strstr(url, ","))
				new_image = loadAnimation(url); 
			else
			{
				new_image = XmHTMLImageDefaultProc(html_widgets[0].html,
					filename, NULL, 0);
				free(filename);
			}
			if(new_image)
			{
				/* don't let XmHTML free it */
				new_image->options &= ~(XmIMAGE_DEFERRED_FREE) &
					~(XmIMAGE_DELAYED);
				/*****
				* Replace it. XmHTMLImageReplace returns a statuscode 
				* indicating success of the action. If XmIMAGE_OK is returned,
				* no call to XmHTMLRedisplay is necessary, the dimensions are
				* the same as specified in the document. It returns
				* XmIMAGE_ALMOST if a recomputation of document layout is
				* necessary, and something else if an error occured:
				* XmIMAGE_ERROR: the widget arg is not a XmHTML widget or
				*	pixmap creation failed;
				* XmIMAGE_BAD if image and/or new_image is NULL;
				* XmIMAGE_UNKNOWN if image is unbound to an internal image.
				*****/
				retval = XmHTMLImageReplace(html_widgets[0].html, image,
					new_image);

				/* update private cache */
				replaceObjectInCache((XtPointer)image, (XtPointer)new_image);

				/* and destroy previous image data */
				XmHTMLImageFreeImageInfo((Widget)html_widgets[0].html, image);
			}
		}
		else	/* same note as above applies */
			retval = XmHTMLImageUpdate(html_widgets[0].html, image);

		/* store return value of ImageReplace and/or ImageUpdate */
		if(retval == XmIMAGE_ALMOST)
			status = retval;
	}
	/* force a reformat and redisplay of the current document if required */
	if(status == XmIMAGE_ALMOST)
		XmHTMLRedisplay(html_widgets[0].html);

	/* keep focus on the html widget */
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

	setBusy(False);
}

/*****
* Name: 		killImages
* Return Type: 	void
* Description: 	kills all images (normal *and* delayed) of all documents.
*				Should be called at exit.
* In: 
*	nothing.
* Returns:
*	nothing.
*****/
static void 
killImages(void)
{
	setBusy(True);

	destroyObjectCache();

	setBusy(False);
}

static void
progressiveButtonCB(Widget w, int reset)
{
	int curr_state = 0;
	String label;
	XmString xms;

	if(reset)
	{
		if(XtIsManaged(prg_button))
			XtUnmanageChild(prg_button);

		/* set new label and global PLC state */
		xms = XmStringCreateLocalized("Suspend Image Load");
		XtVaSetValues(prg_button,
			XmNlabelString, xms,
			XmNuserData, (XtPointer)STREAM_OK,
			NULL);
		XmStringFree(xms);
		return;
	}

	/* get current progressive image loading state */
	XtVaGetValues(w, XmNuserData, &curr_state, NULL);

	switch(curr_state)
	{
		case STREAM_OK:
			XmHTMLImageProgressiveSuspend(html_widgets[0].html);
			curr_state = STREAM_SUSPEND;
			label = "Continue Image Load";
			break;
		case STREAM_SUSPEND:
			XmHTMLImageProgressiveContinue(html_widgets[0].html);
			curr_state = STREAM_OK;
			label = "Suspend Image Load";
			break;
		default:
			fprintf(stderr, "Oops, unknown button state in "
				"progressiveButtonCB\n");
			return;
	}

	/* set new label and global PLC state */
	xms = XmStringCreateLocalized(label);
	XtVaSetValues(prg_button,
		XmNlabelString, xms,
		XmNuserData, (XtPointer)curr_state,
		NULL);
	XmStringFree(xms);
}

/*****
* Name:			getImageData
* Return Type: 	int
* Description: 	XmHTMLGetDataProc method. Called when we are to
*				load images progressively.
* In: 
*	stream:		Progressive Load Context stream object
*	buffer:		destination buffer.
* Returns:
*	STREAM_END when we have run out of data, number of bytes copied into the
*	buffer otherwise.
* Note:
*	This routine is an example implementation of how to write a
*	XmHTMLGetDataProc method. As this program doesn't have networking
*	capabilities, we mimic a connection by providing the data requested in
*	small chunks (which is a command line option: prg_skip [number of bytes]).
*	The stream argument is a structure containing a minimum and maximum byte
*	count (the min_out and max_out fields), a number representing the number
*	of bytes used by XmHTML (the total_in field) and user_data registered
*	with the object that is being loaded progressively.
*
*	If this routine returns data, it must *always* be a number between
*	min_out and max_out (including min_out and max_out). Returning less is
*	not an advisable thing to do (it will cause an additional call immediatly)
*	and returning more *can* cause an error (by overflowing the buffer).
*
*	You can let XmHTML expand it's internal buffers by setting the max_out
*	field to the size you want the buffer to have and returning STREAM_RESIZE.
*	XmHTML will then try to resize its internal buffers to the requested size
*	and call this routine again immediatly. When a buffer has been resized, it
*	is very likely that XmHTML will backtrack to an appropriate starting point,
*	so be sure to check and use the total_in field of the stream arg when 
*	returning data.
*
*	If you want to abort progressive loading, you can return STREAM_ABORT.
*	This will cause XmHTML to terminate the progressive load for the given
*	object (which involves a call to any installed XmHTMLProgressiveEndData
*	method). Example use of this could be an ``Abort'' button. An alternative
*	method is to use the XmHTMLImageProgressiveKill() convenience routine as
*	shown in the getAndSetFile() routine above.
*
*	Also note that returning 0 is equivalent to returning STREAM_END (which
*	is defined as being 0).
*
*	As a final note, XmHTML will ignore any bytes copied into the buffer
*	if you return any of the STREAM_ codes.
*****/
static int
getImageData(XmHTMLPLCStream *stream, XtPointer buffer)
{
	ImageBuffer *ib = (ImageBuffer*)stream->user_data;
	int len;

	Debug(("getImageData, request made for %s\n", ib->file));
	Debug(("getImageData, XmHTML already has %i bytes\n", stream->total_in));

	/* no more data available, everything has been copied */
	if(ib->next >= ib->size)
		return(STREAM_END);

	/*
	* Maximum no of bytes we can return. ib->size contains the total size of
	* the image data, and total_in contains the number of bytes that have
	* already been used by XmHTML so far.
	* total_in may differ from ib->next due to backtracking of the calling PLC.
	*/
	len = ib->size - stream->total_in;

	/*
	* If you want to flush all data you've got to XmHTML but max_out is too
	* small, you can do something like this:
	* if(len > stream->max_out)
	* {
	*	stream->max_out = len;
	*	return(STREAM_RESIZE);
	* }
	* As noted above, XmHTML will then resize it's internal buffers to fit
	* the requested size and call this routine again. Before I forget, the
	* default size of the internal buffers is 2K.
	* And no, setting max_out to 0 will not cause XmHTML to choke. It will
	* simply ignore it (and issue a blatant warning message accusing you of
	* being a bad programmer :-).
	*/
	if(progressive_data_inc)
	{
		/* increment if not yet done for this pass */
		if(!ib->may_free)
		{
			progressive_data_skip += progressive_data_inc;

			Debug(("getImageData, incrementing buffer size to %i bytes\n",
				progressive_data_skip));

			stream->max_out = progressive_data_skip;
			ib->may_free = True;
			return(STREAM_RESIZE);
		}
		else	/* already incremented, copy data for this pass */
			ib->may_free = False;
	}

	/* provide the minimum if our skip is too small */
	if(len < stream->min_out || progressive_data_skip < stream->min_out)
		len = stream->min_out;
	else
		len = progressive_data_skip;

	/* final sanity */
	if(len + stream->total_in > ib->size)
		len = ib->size - stream->total_in;

	/* more bytes available than minimally requested, we can copy */
	if(len >= stream->min_out)
	{
		/* but don't exceed the maximum allowable amount to return */
		if(len > stream->max_out)
			len = stream->max_out;

		Debug(("getImageData, returning %i bytes (min_out = %i, "
			"max_out = %i)\n", len, stream->min_out, stream->max_out));

		memcpy((char*)buffer, ib->buffer + stream->total_in, len);
		ib->next = stream->total_in + len;
		return(len);
	}
	/*
	* some sort of error, XmHTML requested data beyond the end of the file,
	* so we just return STREAM_END here and let XmHTML decide what to do.
	*/
	return(STREAM_END);
}

static void
endImageData(XmHTMLPLCStream *stream, XtPointer data, int type, Boolean ok)
{
	XmImageInfo *image = (XmImageInfo*)data;
	ImageBuffer *ib;

	/*
	* XmHTML signals us that there are no more images being loaded
	* progressively. Remove ``Suspend Image Load'' button.
	* Beware: this is the only case in which stream is NULL.
	*/
	if(type == XmPLC_FINISHED)
	{
		XtSetSensitive(prg_button, False);
		XtUnmanageChild(prg_button);
		return;
	}

 	ib = (ImageBuffer*)stream->user_data;

	/*
	* To keep the cache size in sync, we update the cached image by replacing
	* it. As we will be replacing the same object, the only effect this call
	* will have is that the sizeObjectProc will be called.
	*/
	if(ok)
		replaceObjectInCache((XtPointer)image, (XtPointer)image);
	else
	{
		/* incomplete image, remove it from the image cache */
		removeObjectFromCache(ib->file);
		cleanObjectCache();
	}

	Debug(("endImageData, called for %s, ok = %s\n", ib->file,
		ok ? "True" : "False"));

	free(ib->file);
	free(ib->buffer);
	free(ib);
}

/*****
* Name: 		loadImage
* Return Type: 	XmImageInfo
* Description: 	XmHTMLimageProc handler
* In: 
*	w:			HTML widget id
*	url:		src value of an img element.
* Returns:
*	return value from the HTML widget imageDefaultProc
* Note:
*	this is a very simple example of how to respond to requests for images:
*	XmHTML calls this routine with the name (or location or whatever the
*	src value is) of an image to load. All you need to do is get the full
*	name of the image requested and call the imageDefaultProc and let XmHTML
*	handle the actual loading.
*	This is also the place to fetch remote images, implement an imagecache
*	or add support for images not supported by the imageDefaultProc.
*****/
static XmImageInfo*
loadImage(Widget w, String url)
{
	String filename = NULL;
	XmImageInfo *image = NULL;
	DocumentCache *this_doc;
	int i;

	/* get current document */
	this_doc = &doc_cache[current_doc];

	Debug(("Requested to load image %s\n", url));

	/*****
	* get full path for this url. The "," strstr is used to check if this
	* image is an animation consisting of a list of comma-separated images
	* (see examples/test-pages/animation?.html for an example)
	*****/
	if((filename = resolveFile(url)) == NULL)
		if(!strstr(url, ","))
			return(NULL);

	/* 
	* add this image to this document's image list.
	* First check if we haven't got it already, can only happen when the 
	* document is reloaded (XmHTML doesn't load identical images).
	* Use original URL for this.
	*/
	for(i = 0; i < this_doc->nimages; i++)
	{
		if(!(strcmp(this_doc->images[i], url)))
			break;
	}
	/* don't have it yet */
	if(i == this_doc->nimages)
	{
		/* see if it can hold any more images */
		if(this_doc->nimages != MAX_IMAGE_ITEMS)
		{
			this_doc->images[this_doc->nimages++] = strdup(url);
			i = this_doc->nimages;
		}
		else
		{
			char buf[128];
			sprintf(buf, "This document contains more than %i images,\n"
				"Only the first %i will be shown.", MAX_IMAGE_ITEMS,
  				MAX_IMAGE_ITEMS);
			XMessage(toplevel, buf);
			return(NULL);
		}
	}

	/* now check if we have this image already available */
	if((image = (XmImageInfo*)getObjectFromCache(filename, url)) != NULL)
	{
		/*
		* If i isn't equal to the current no of images for the current
		* document, the requested image has already been loaded once for this
		* document, so we do not have to store it again.
		*/
		/* call storeImage again as we might be using a different URL */
		if(i == this_doc->nimages)
			storeObjectInCache((XtPointer)image,
				filename ? filename : url, url);
		if(filename)
			free(filename);
		return(image);
	}

	if(filename || (strstr(url, ",")) != NULL)
	{
		/* test delayed image loading */
		if(html_config[OPTIONS_AUTO_IMAGE_LOAD].value)
		{
			if(strstr(url, ","))
				image = loadAnimation(url);
			else
			{
				if(!progressive_images)
					image = XmHTMLImageDefaultProc(w, filename, NULL, 0);
				else
				{
					unsigned char img_type;

					img_type = XmHTMLImageGetType(filename, NULL, 0);

					if(img_type != IMAGE_ERROR && img_type != IMAGE_UNKNOWN &&
						img_type != IMAGE_XPM && img_type != IMAGE_PNG)
					{
						FILE *file;
						static ImageBuffer *ib;

						/* open the given file */
						if((file = fopen(filename, "r")) == NULL)
						{
							perror(filename);
							return(NULL);
						}

						/*
						* We load the image data into an ImageBuffer (which
						* we will be using in the get_data() function.
						*/
						ib = (ImageBuffer*)malloc(sizeof(ImageBuffer));
						ib->file = strdup(filename);
						ib->next = 0;

						/* see how large this file is */
						fseek(file, 0, SEEK_END);
						ib->size = ftell(file);
						rewind(file);

						/* allocate a buffer to contain the entire image */
						ib->buffer = malloc(ib->size+1);

						/* now read the contents of this file */
						if((fread(ib->buffer, 1, ib->size, file)) != ib->size)
							printf("Warning: did not read entire file!\n");
						ib->buffer[ib->size] = '\0';	/* sanity */

						/* create an empty ImageInfo */
						image = (XmImageInfo*)malloc(sizeof(XmImageInfo));
						memset(image, 0, sizeof(XmImageInfo));

						/* set the Progressive bit and allow scaling */
						image->options =XmIMAGE_PROGRESSIVE|XmIMAGE_ALLOW_SCALE;
						image->url = strdup(filename);

						/* set file buffer as user data for this image */
						image->user_data = (XtPointer)ib;

						/* make the progressive image loading button visible */
						if(!XtIsManaged(prg_button))
							XtManageChild(prg_button);

						XtSetSensitive(prg_button, True);

						/* all done! */
					}
					else
						image = XmHTMLImageDefaultProc(w, filename, NULL, 0);
				}
			}
			/* failed, too bad */
			if(!image)
				return(NULL);

			/* don't let XmHTML free it */
			image->options &= ~(XmIMAGE_DEFERRED_FREE);
		}
		else
		{
			image = (XmImageInfo*)malloc(sizeof(XmImageInfo));
			memset(image, 0, sizeof(XmImageInfo));
			image->options = XmIMAGE_DELAYED|XmIMAGE_ALLOW_SCALE;
			image->url = strdup(filename ? filename : url);
		}
		/* store in the cache */
		storeObjectInCache((XtPointer)image, filename ? filename : url, url);
	}
	if(filename)
		free(filename);
	
	return(image);
}

/*****
* Name: 		testAnchor
* Return Type: 	int
* Description: 	XmNanchorVisitedProc procedure
* In: 
*	w:			widget
*	href:		href to test
* Returns:
*	True when the given href has already been visited, false otherwise.
* Note:
*	This is quite inefficient. In fact, the whole history scheme is 
*	inefficient, but then again, this is only an example and not a full 
*	featured browser ;-)
*****/
static int
testAnchor(Widget w, String href)
{
	int i, j;

	/* walk each document */
	for(i = 0 ; i < last_doc; i++)
	{
		/* and walk the history list of each document */
		for(j = 0; j < doc_cache[i].nvisited; j++)
			if(doc_cache[i].visited[j] &&
				!strcmp(doc_cache[i].visited[j], href))
				return(True);
	}
	/* we don't know it */
	return(False);
}

/*****
* Name: 		aboutCB
* Return Type: 	void
* Description: 	displays an ``About'' dialog when the help->about menu item
*				is selected.
* In: 
*	widget:		menubutton widget id
*	client_data:	unused
*	call_data:	unused
* Returns:
*	nothing
*****/
static void
aboutCB(Widget widget, XtPointer client_data, XtPointer call_data)
{
	char label[256];
  
	sprintf(label, "A Simple HTML browser using\n"
		"%s\n", XmHTMLVERSION_STRING);
  
	XMessage(toplevel, label);
}

static void
optionsCB(Widget w, int item)
{
	XmString label;
	Boolean set = False;
	int i, argc = 0;
	Arg args[4];

	switch(item)
	{
		/*
		* These are seven XmHTML On/Off resources so we can treat them
		* all in the same manner
		*/
		case OPTIONS_ANCHOR_BUTTONS:
		case OPTIONS_HIGHLIGHT_ON_ENTER:
		case OPTIONS_ENABLE_STRICT_HTML32:
		case OPTIONS_ENABLE_BODYCOLORS:
		case OPTIONS_ENABLE_BODYIMAGES:
		case OPTIONS_ENABLE_DOCUMENT_COLORS:
		case OPTIONS_ENABLE_DOCUMENT_FONTS:
		case OPTIONS_ENABLE_IMAGES:
		case OPTIONS_ENABLE_OUTLINING:
		case OPTIONS_DISABLE_WARNINGS:
		case OPTIONS_FREEZE_ANIMATIONS:

			/* get value */
			XtVaGetValues(w, XmNset, &set, NULL);

			/* check if changed */
			if(set == html_config[item].value)
				break;

			/* store new value */
			html_config[item].value = set;

			Debug(("optionsCB, setting value for resource %s to %s\n",
				html_config[item].name, set ? "True" : "False"));

			/* set new value */
			XtSetArg(args[argc], html_config[item].name,
				html_config[item].value);
			argc++;

			/*
			* if global image support has been toggled, toggle other buttons
			* as well.
			*/
			if(item == OPTIONS_ENABLE_IMAGES)
			{
				XtSetSensitive(html_config[OPTIONS_ENABLE_BODYIMAGES].w, set);
				XtSetSensitive(html_config[OPTIONS_AUTO_IMAGE_LOAD].w, set);
				XtSetSensitive(load_images, set);

				/* set corresponding resources */
				XtSetArg(args[argc],
					html_config[OPTIONS_ENABLE_BODYIMAGES].name,
					set ? html_config[OPTIONS_ENABLE_BODYIMAGES].value:False);
				argc++;
			}

			/* propagate changes down to all active HTML widgets */
			for(i = 0; i < MAX_HTML_WIDGETS; i++)
			{
				if(html_widgets[i].active)
					XtSetValues(html_widgets[i].html, args, argc);
			}
			break;

		case OPTIONS_AUTO_IMAGE_LOAD:
		case OPTIONS_FANCY_TRACKING:
			/* get value */
			XtVaGetValues(w, XmNset, &set, NULL);

			/* check if changed */
			if(set == html_config[item].value)
				break;

			/* store new value */
			html_config[item].value = set;

			Debug(("optionsCB, setting value for %s to %s\n",
				html_config[item].name, set ? "True" : "False"));

			/* change label as well */
			if(set)
				label = XmStringCreateLocalized("Reload Images");
			else
				label = XmStringCreateLocalized("Load Images");
			XtVaSetValues(load_images,
				XmNlabelString, label,
				NULL);
			XmStringFree(label);
			break;

		case OPTIONS_ANCHOR:
			fprintf(stderr, "Configure anchor appearance (not ready)\n");
			break;
		case OPTIONS_FONTS:
			fprintf(stderr, "Configure document fonts (not ready).\n");
			break;
		case OPTIONS_BODY:
			fprintf(stderr, "Configure default body settings (not ready).\n");
			break;
		case OPTIONS_IMAGE:
			fprintf(stderr, "Configure default image settings (not ready).\n");
			break;
		default:
			fprintf(stderr, "optionsCB: impossible menu selection "
				"(item = %i)\n", item);
	}
}

/*****
* Name:			Main
* Return Type:	int
* Description:	main for example 2
* In:
*	argc:		no of command line arguments
*	argv:		array of command line arguments
* Returns:
*	EXIT_FAILURE when an error occurs, EXIT_SUCCESS otherwise
*****/
int
main(int argc, char **argv)
{
    char *filename;
    Display *display;
    Widget topLevel;
    XEvent event;
    XtAppContext app_context;
    XSetWindowAttributes setAttrib;
    XClassHint *classhint;
    Atom property;
    Window parent;
    int timeout = 5;
    XtIntervalId TimeoutID;

    filename = strdup(argv[1]);

    topLevel = XtVaAppInitialize(&app_context, NULL, NULL, 0,
                0, NULL, NULL, NULL, NULL);
    display = XtDisplay(topLevel);
    XtVaSetValues(topLevel, XmNoverrideRedirect, True, XmNx,0, XmNy,0,
                  XmNwidth,1,XmNheight,1,NULL);
    XtRealizeWidget(topLevel);

    parent = XtWindow(topLevel);

    setpgrp();

    if (!fork())
    {
        HelloScreen(filename, parent);
        exit(0);
    }

    setAttrib.event_mask = SubstructureNotifyMask;
    XChangeWindowAttributes ( display,
                              XDefaultRootWindow(display),
                              CWEventMask,
                              &setAttrib);
    setAttrib.event_mask = PropertyChangeMask;
    XChangeWindowAttributes ( display,
                              parent,
                              CWEventMask,
                              &setAttrib);

    TimeoutID = XtAppAddTimeOut(app_context,
                                (unsigned long)60000,
                                Done,
                                NULL);

    property = XInternAtom (display, "_XA_CLIENT_TIMEOUT", False);

    for (;;)
    {
        XtAppNextEvent(app_context, &event);

        if ( event.type == PropertyNotify &&
             event.xproperty.window == parent &&
             event.xproperty.state == PropertyNewValue &&
             event.xproperty.atom == property)
        {
             XtRemoveTimeOut(TimeoutID);
             XtAppAddTimeOut(app_context,
                             (unsigned long)5000,
                             Done,
                             NULL);
        }
        else XtDispatchEvent(&event);
    }

}

void Done(XtPointer client_data, XtIntervalId *id)
{
    exit(0);
}



static void HelloScreen(char *use_file, Window parent)
{

    XEvent event;
    XSetWindowAttributes setAttrib;
    Display *display = NULL; /* shutup compiler */
    Visual *visual = NULL;
    int depth = 0;
    Colormap colormap = 0;

    root_window = False;
    progressive_images = False;

/* set current working directory as the first path to search */
#ifdef _POSIX_SOURCE
    getcwd((char*)(paths[0]), sizeof(paths[0]));
#else
    getwd((char*)(paths[0]));
#endif
    strcat((char*)(paths[0]), "/");
    max_paths = 1;

    toplevel = XtVaAppInitialize(&context, APP_CLASS, NULL, 0,
                                 0, NULL, appFallbackResources, NULL, NULL);
    display = XtDisplay(toplevel);

    /* check if visual, depth or colormap have been given */
    if (getStartupVisual(toplevel, &visual, &depth, &colormap))
    {
        XtVaSetValues(toplevel, XmNvisual, visual, XmNdepth, depth,
                      XmNcolormap, colormap, NULL);

        XInstallColormap(display, colormap);
    }

    XtVaSetValues(toplevel, XmNmwmDecorations, MWM_DECOR_BORDER, 
                  XmNx, 0, XmNy, 0,
                  XmNheight, DisplayHeight(display, DefaultScreen(display)),
                  XmNwidth, DisplayWidth(display, DefaultScreen(display)),
                  NULL);

    html_widgets[0].html = 
        XtVaCreateManagedWidget("html", xmHTMLWidgetClass, toplevel,
                                XmNanchorVisitedProc, testAnchor,
                                XmNimageProc, loadImage,
                                XmNimageEnable, True,
                                XmNprogressiveReadProc, getImageData,
                                XmNprogressiveEndProc, endImageData,
#ifdef HAVE_GIF_CODEC
                                XmNdecodeGIFProc, decodeGIFImage,
#endif
                                XmNheight, 
                                DisplayHeight(display, DefaultScreen(display)),
                                XmNwidth, 
                                DisplayWidth(display, DefaultScreen(display)),
                                XtVaTypedArg, XmNforeground, 
                                XmRString, "white", 6,
                                XtVaTypedArg, XmNbackground, 
                                XmRString, "black", 6,
                                NULL);



    html_widgets[0].active = True;
    html_widgets[0].used   = True;

    /* anchor activation callback */
    XtAddCallback(html_widgets[0].html, XmNactivateCallback,
                  (XtCallbackProc)anchorCB, NULL);

    /* HTML frame callback */
    XtAddCallback(html_widgets[0].html, XmNframeCallback,
                (XtCallbackProc)frameCB, NULL);

    /* set the HTML document callback */
    XtAddCallback(html_widgets[0].html, XmNdocumentCallback,
               (XtCallbackProc)docCB, NULL);

    /* link callback for site structure */
    XtAddCallback(html_widgets[0].html, XmNlinkCallback,
                (XtCallbackProc)linkCB, NULL);

    initCache(5*1024*1024, (cleanObjectProc)destroyCacheObject,
              (sizeObjectProc)getInfoSize, (XtPointer)html_widgets[0].html);

    XtRealizeWidget(toplevel);

    XRaiseWindow(XtDisplay(toplevel), XtWindow(toplevel));

    /* The HTML widget has the focus */
    XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

    /* if we have a file, load it */
    if (use_file)
    {
        String filename;

        /* get full filename */
        if ((filename = resolveFile(use_file)) != NULL)
        {
            /* load the file, will also update the document cache */
            loadAndOrJump(filename, NULL, True);
            free(filename);
        }
    }

    setAttrib.event_mask = StructureNotifyMask;
    XChangeWindowAttributes(display,
                            XtWindow(toplevel),
                            CWEventMask,
                            &setAttrib);

    XChangeProperty(display,
                    parent,
                    XInternAtom (display, "_XA_CLIENT_TIMEOUT", False),
                    XA_STRING,
                    8,
                    PropModeReplace,
                    (unsigned char *)"client",
                    7);

    XFlush(display);
    XSync(display, False);

    /* enter the event loop */
    for (;;) 
    {
        XtAppNextEvent(context, &event);
        if (event.type == ReparentNotify &&
            event.xreparent.window == XtWindow(toplevel))
        {
            XtDestroyApplicationContext(context);
            exit(0);
        }
        else XtDispatchEvent(&event);
    }

    /* never reached, but keeps compiler happy */
    exit(EXIT_SUCCESS);
}