File: llgal.in

package info (click to toggle)
llgal 0.13.19-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 664 kB
  • ctags: 160
  • sloc: perl: 2,821; makefile: 159; sh: 37; php: 15
file content (2550 lines) | stat: -rwxr-xr-x 86,753 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/perl -w

use strict ;

require Llgal::Config ;
require Llgal::Messages ;
require Llgal::Templates ;
require Llgal::Utils ;

use FileHandle ;
use Image::Size ;
use Cwd ;
use Locale::gettext ;
use POSIX qw (setlocale) ;
use URI::Escape ;
use Text::ParseWords ;
use File::Compare ;

Getopt::Long::Configure('noignorecase', 'noautoabbrev', 'bundling') ;
STDOUT->autoflush("1") ;

# constants and globals
my $self = {
    version => "@VERSION@",
    llgal_config_dir => "@SYSCONFDIR@/llgal",
    llgal_share_dir => "@DATADIR@/llgal",
    user_share_dir => $ENV{HOME}."/.llgal",
    generic_configuration_filename => "llgalrc",
    locale_dir => "@LOCALEDIR@",

    # local llgal directory, may be modified during early configuration
    local_llgal_dir => ".llgal",
    # look in current directory "."
    destination_dir => ".",
    # no section by default
    # section_dirs => (),

    # some variable may only be modified when by system
    # or user-wide configuration files only
    early_configuration => 1,

    # show version
    version_asked => 0,
    # displays brief usage message
    help_asked => 0,
    # clean up all generated files
    clean_asked => 0,
    # clean up all generated and user modified files
    cleanall_asked => 0,
    # generate (or update) captions
    generate_captions => 0,
    # give templates to the given directory
    give_templates => undef,
    # generate a config file
    generate_config => undef,

    # level of indentation, warnings, ...
    messages => Llgal::Messages::new (),
} ;

# store command-line options to write in the index <head>
my $llgal_cmdline = join (" ", @ARGV) ;

# parse early command line options
Llgal::Config::early_parse_cmdline_options ($self) ;

# gettext initialization
Llgal::Config::init_llgal_gettext ($self) ;

######################################################################
# various temporary globals
my $messages = $self->{messages} ;
my $destination_string ;
my $local_llgal_url ;
my $opts ;
my $opts_without_defaults ;

######################################################################
# --clean and --cleanall option

sub clean_files {
    my $cleanall = shift ;
    my $notdeleted = 0 ;
    if ($cleanall) {
	$messages->print ("Cleaning all in $destination_string\n") ;
    } else {
	$messages->print ("Cleaning in $destination_string\n") ;
    }

    opendir DIR, "$self->{destination_dir}$self->{local_llgal_dir}"
	or die "Can't open directory $self->{destination_dir}$self->{local_llgal_dir} ($!).\n" ;
    while ($_ = readdir DIR) {
	if (/^$opts->{thumbnail_image_filenameprefix}/ or /^$opts->{scaled_image_filenameprefix}/) {
	    unlink "$self->{destination_dir}$self->{local_llgal_dir}/$_" ;
	} elsif (/^$opts->{filmtile_filename}$/ or /^$opts->{index_link_image_filename}$/
		 or /^$opts->{prev_slide_link_image_filename}$/ or /^$opts->{next_slide_link_image_filename}$/
		 or /^$opts->{indextemplate_filename}$/ or /^$opts->{slidetemplate_filename}$/
		 or /^$opts->{css_filename}$/) {
	    my $original = (Llgal::Templates::find_generic_template_file ($self, $opts, $_, 0))."/".$_ ;
	    my $diff = 0 ;
	    # default is cleanall, which removes everything, as if file were not changed
	    if (!$cleanall) {
		$diff = compare ("$self->{destination_dir}$self->{local_llgal_dir}/$_", "$original") ;
		die "Failed to check whether $self->{destination_dir}$self->{local_llgal_dir}/$_ has been modified ($!).\n"
		    if $diff == -1 ;
	    }
	    if ($diff) {
		$messages->warning ("Preserved $self->{destination_dir}$self->{local_llgal_dir}/$_ since it seems to be modified.") ;
		$notdeleted++ ;
	    } else {
		if (!unlink "$self->{destination_dir}$self->{local_llgal_dir}/$_" and ! $!{ENOENT}) {
		    $messages->warning ("Failed to remove file $self->{destination_dir}$self->{local_llgal_dir}/$_ ($!).") ;
		}
	    }
	} elsif (/^$opts->{captions_filename}$/) {
	    my $grep = 0 ;
	    # default is cleanall, which removes everything, as if the removal line was here
	    if (!$cleanall) {
		open CAP, "$self->{destination_dir}$self->{local_llgal_dir}/$_" ;
		my @lines = <CAP> ;
		close CAP ;
		$grep = scalar (grep { $_ =~ $opts->{captions_removal_line} } @lines) ;
	    }
	    if (!$grep) {
		$messages->warning ("Preserved $self->{destination_dir}$self->{local_llgal_dir}/$_ since it seems to be modified.") ;
		$notdeleted++ ;
	    } else {
		if (!unlink "$self->{destination_dir}$self->{local_llgal_dir}/$_" and ! $!{ENOENT}) {
		    $messages->warning ("Failed to remove file $self->{destination_dir}$self->{local_llgal_dir}/$_.") ;
		}
	    }
	} else {
	    $notdeleted++ ;
	}
    }
    closedir DIR ;
    if ($notdeleted <= 2 and $cleanall) {
	if (!rmdir "$self->{destination_dir}$self->{local_llgal_dir}"  and ! $!{ENOENT}) {
	    $messages->warning ("Failed to remove directory $self->{destination_dir}$self->{local_llgal_dir} ($!).") ;
	}
    }

    opendir DIR, $self->{destination_dir} ? $self->{destination_dir} : "./" ; # destination is empty for './'
    while ($_ = readdir DIR ) {
	if (/^$opts->{index_filename}\.$opts->{www_extension}$/
	    or /^$opts->{slide_filenameprefix}.*\.$opts->{www_extension}$/) {
	    unlink "$self->{destination_dir}$_" ;
	}
    }
    closedir DIR ;
}

#####################################################################
# Main variables

# The main gallery is composed of
# - @entries (the entry list)
# - @headers and @footers

sub init_gallery {
    my $gallery = () ;
    @{$gallery->{headers}} = () ;
    @{$gallery->{footers}} = () ;
    @{$gallery->{entries}} = () ;
    %{$gallery->{user_fields}} = () ;
    $gallery->{indextemplate} = undef ;
    @{$gallery->{slidetemplate_text}} = () ;
    @{$gallery->{template_exif_tags_list}} = () ;
    return $gallery ;
}

# Entries are hashed composed of
# - type: see below
# - filename (original filename with extension)
# - url (url of the filename)
# - linktext (an associated text that may be used in a link, www-safe)
# - caption (the caption of the slide, www-safe)
# - title (title, www-safe)
# - no_thumb (1 or undef, means that the entry is listed instead of displayed as a thumbnail)
# - no_slide (1 or undef, means that the entry does not appear as any slide at all)

# - xdim, ydim, kbytes (details about the image or movie)
# - dimstring (string containing dimensions and/or size that were requested)

# - slide_filename (name of the HTML slide filename)
# - slide_url (url of the HTML slide filename)
# - counter_with_zeros (stringified counter used in slide's filename)

# - thumb_xdim, thumb_ydim (details about the thumbnail image)
# - thumb_dimstring (string containing dimensions)
# - thumb_filename (name of the thumbnail image file)
# - thumb_url (url of the thumbnail image file)

# - scaled_xdim, scaled_ydim, scaled_kbytes (details about the scaled image)
# - scaled_dimstring (string containing dimensions and/or size that were requested)
# - scaled_filename (name of the scaled image file)
# - scaled_url (url of the scaled image file)

# - gallery (the whole gallery in the subdirectory pointed by this entry)

# types
my $TYPE_TEXT = 0 ;
my $TYPE_LINK = 1 ;
my $TYPE_IMAGE = 2 ;
my $TYPE_MOVIE = 3 ;
my $TYPE_FILE = 4 ;
my $TYPE_DIR = 5 ;
my $TYPE_LINE = 6 ;
my $TYPE_BREAK = 7 ;
my $TYPE_LINKNOSLIDE = 8 ; # only used when calling create_nofile_entry, which changes it into $TYPE_LINK with no_slide set

###################################################################################
# checking files

sub check_file {
    my $filename = shift ;

    if (! -e $filename) {
	$messages->warning ("Cannot find file '$filename', skipping it.") ;
	return -1 ;
    }

    my $excluded = 0 ;
    for(my $i = 0; $i < @{$opts->{excludes}}; $i++) {
	my $entry = @{$opts->{excludes}}[$i] ;
	if ($filename =~ m@^(.*/)*$entry->{filter}$@) {
	    $excluded = $entry->{excluded}
	}
    }
    return -1
	if $excluded ;

    return 0 ;
}

###################################################################################
# returns a filename that the user provided in the llgal directory
# to be used as a thumbnail or scaled image

sub find_user_thumbnail {
    my $entry = shift ;
    my $type = $entry->{type} ;
    my $filename = $entry->{filename} ;
    my $user_thumbnail_filename = "$opts->{user_thumbnail_image_filenameprefix}$opts->{thumbnail_image_filenameprefix}$filename" ;

    if ($type == $TYPE_IMAGE) {
	if (-f "$self->{destination_dir}$self->{local_llgal_dir}/$user_thumbnail_filename") {
	    return $user_thumbnail_filename ;
	}
    } else {
	foreach my $ext (split (/\|/, $opts->{image_extensions})) {
	    if (-f "$self->{destination_dir}$self->{local_llgal_dir}/$user_thumbnail_filename.$ext") {
		return "$user_thumbnail_filename.$ext" ;
	    }
	}
    }
    return "" ;
}

sub find_user_scaled {
    my $entry = shift ;
    my $type = $entry->{type} ;
    my $filename = $entry->{filename} ;
    my $user_scaled_filename = "$opts->{user_scaled_image_filenameprefix}$opts->{scaled_image_filenameprefix}$filename" ;

    if ($type == $TYPE_IMAGE) {
	if (-f "$self->{destination_dir}$self->{local_llgal_dir}/$user_scaled_filename") {
	    return $user_scaled_filename ;
	}
    } else {
	foreach my $ext (split (/\|/, $opts->{image_extensions})) {
	    if (-f "$self->{destination_dir}$self->{local_llgal_dir}/$user_scaled_filename.$ext") {
		return "$user_scaled_filename.$ext" ;
	    }
	}
    }
    return "" ;
}

###################################################################################
# extract caption from image infos

# Image comment
sub generate_caption_from_image_comment {
    my $exif_infos = shift ;
    my @texts = () ;
    # Loop until a non-empty comment list is found
    foreach my $types (split (/,/, $opts->{make_caption_from_image_comment})) {
	# types is a + separated string of types
	foreach my $type (split (/\+/, $types)) {
	    if ($type =~ m/^std$/i) {
		# Standard comment such as JFIF or GIF
		my $comment = $exif_infos->{Comment} ;
		push (@texts, $comment)
		    if $comment ;
	    } elsif ($type =~ m/^exif$/i) {
		# Exif comment
		my $comment = $exif_infos->{UserComment} ;
		push (@texts, $comment)
		    if $comment ;
	    } elsif ($type =~ m/^exifdesc$/i) {
		# Exif image description
		my $comment = $exif_infos->{ImageDescription} ;
		push (@texts, $comment)
		    if $comment ;
	    } else {
		$messages->abort_percentage ;
		die "Unrecognized image comment type '$type'.\n" ;
	    }
	}
	return @texts
	    if @texts ;
    }
    return () ;
}

# Image timestamp
sub generate_caption_from_image_timestamp {
    my $exif_infos = shift ;
    my $imagetime = $exif_infos->{DateTimeOriginal} ;
    return $imagetime;
}

# Image infos
sub generate_caption_from_image_infos {
    my $exif_infos = shift ;
    my @texts = () ;
    if ($opts->{make_caption_from_image_comment}) {
	my @comments = generate_caption_from_image_comment $exif_infos ;
	push (@texts, @comments) ;
    }
    if ($opts->{make_caption_from_image_timestamp}) {
	my $timestamp = generate_caption_from_image_timestamp $exif_infos ;
	push (@texts, $timestamp) ;
    }
    return @texts ;
}

###################################################################################
# generating safe url

sub make_safe_url_nowarn {
    return join '/', map { uri_escape $_ } (split /\//, shift) ;
}

sub make_safe_url {
    my $file = shift ;
    my $safe = make_safe_url_nowarn ($file) ;

    $messages->warning ("Non-ascii characters were escaped in filename '$file'.")
	if $safe ne $file and $file =~ m/[\x80-\xFF]/ ;

    return $safe ;
}

###################################################################################
# Generate entries

sub create_file_entry {
    my $entry = () ;
    my $gallery = shift ;
    my $type = shift ;
    my $filename = shift ;
    my $linktext = shift ;
    my $caption = shift ;

    # cache real filename for later
    my $real_filename = "$self->{destination_dir}$filename" ;

    # check file
    return undef
	if check_file ($real_filename) < 0 ;

    # set the type
    $entry->{type} = $type ;

    # set the filename
    $entry->{filename} = $filename ;

    # make a safe url
    $entry->{url} = make_safe_url ($filename) ;

    # the link text (will be web-safe after caption file generation)
    if (not defined $linktext) {
	$linktext = "" ;
	if ($type == $TYPE_MOVIE) {
	    $linktext = $opts->{MVI_link_text}.$filename ;
	} elsif ($type == $TYPE_FILE) {
	    $linktext = $opts->{FIL_link_text}.$filename ;
	} elsif ($type == $TYPE_DIR) {
	    $linktext = $opts->{DIR_link_text}.$filename ;
	}
	$linktext =~ s/&/&amp;/g ;
	# $linktext =~ s/"/&\#34;/g ;
    }
    $entry->{linktext} = $linktext ;

    if ($type == $TYPE_DIR) {
	# subgallery specific fields

	# add index.html so that it works without a web server
	$entry->{url} = $entry->{url}."/".$opts->{index_filename}.".".$opts->{www_extension} ;

	# generate a name for links from prev/next gallery
	my @parts = split /\//, $filename ;
	$entry->{gallery_name} = pop @parts ;
    }

    # for images, we need at least the dimensions (and check their validity) and possibly some Exif info
    # if some Exif are needed, retrieve dimensions with ExifTool too
    # if not, just retrieve dimensions with imgsize
    if ($type == $TYPE_IMAGE) {
	my ($x,$y) ;

	# if showing some exif flags, or using some options that require Exif,
	# use ExifTool for both these and image dimensions validity checking
	if ($opts->{show_all_exif_tags}
	    or @{$opts->{show_exif_tags}}
	    or @{$gallery->{template_exif_tags_list}}
	    or $opts->{make_caption_from_image_timestamp}
	    or $opts->{make_caption_from_image_comment}) {

	    # only load Image::ExifTool when really required
	    if (not defined $opts->{exiftool}) {

		# Try to load the module
		if (not eval { require Image::ExifTool ; }) {
		    $messages->abort_percentage ();
		    die "Perl module Image::ExifTool not found, please install the package 'libimage-exiftool-perl' if you wish to extract tags from images.\n" ;
		}

		# ExifTool initialization
		$opts->{exiftool} = new Image::ExifTool;
		# accept unknown tags, just in case...
		$opts->{exiftool}->Options(Unknown => 1) ;
		# set the GPS coodinate format  **HACK**
		$opts->{exiftool}->Options(CoordFormat => "%.6f") ;
		# dateFormat should be initialized with whatever the user said to --ct
		$opts->{exiftool}->Options(DateFormat => $opts->{timestamp_format_in_caption}) ;

		# initialize the list of tags, empty for all
		my @exif_tags = () ;
		if (!$opts->{show_all_exif_tags}) {
		    # use the user provided Exif tags, and add ImageWidth/Height for ourself
		    @exif_tags = @{$gallery->{template_exif_tags_list}} ;
		    @exif_tags = (@exif_tags, 'ImageWidth', 'ImageHeight', @{$opts->{show_exif_tags}}) ;
		    @exif_tags = (@exif_tags, 'DateTimeOriginal')
			if $opts->{make_caption_from_image_timestamp} ;
		    @exif_tags = (@exif_tags, 'UserComment', 'Comment', 'ImageDescription')
			if $opts->{make_caption_from_image_comment} ;
		}
		@{$opts->{cached_exif_tags_list}} = @exif_tags ;
	    }

	    # do the actual exif tag retrieval
	    my $exif_infos = $opts->{exiftool}->ImageInfo ($real_filename, @{$opts->{cached_exif_tags_list}}) ;
	    $entry->{exif_infos} = $exif_infos ;

	    # get image dimensions
	    $x = $exif_infos->{ImageWidth} ;
	    $y = $exif_infos->{ImageHeight} ;

	} else {
	    # if not using Exif at all, just retrieve dimensions for ourself

	    ($x,$y) = imgsize ($real_filename) ;
	}

	# check dimensions validity
	if (not defined $x or not defined $y) {
	    $messages->warning ("Bad image file '$filename', cannot retrieve its dimensions, skipping it.") ;
	    return undef ;
	}

	$entry->{xdim} = $x ;
	$entry->{ydim} = $y ;
    }

    # the caption (will be web-safe after caption file generation)
    if (not defined $caption) {
	my @texts = () ;
	if ($opts->{make_caption_from_extension}) {
	    push (@texts, $filename) ;
	} elsif ($opts->{make_caption_from_filename}) {
	    my $basename = $filename ;
	    if ($type != $TYPE_DIR) {
		# remove the extension
		$basename =~ s/\.[^\.]+$// ;
	    }
	    push (@texts, $basename) ;
	}
	push (@texts, generate_caption_from_image_infos $entry->{exif_infos})
	    if $type == $TYPE_IMAGE ;
	$caption = join (' - ', grep {$_} @texts) ;
	$caption =~ s/&/&amp;/g ;
#	$caption =~ s/"/&\#34;/g ;
    }
    chomp $caption ;
    $entry->{caption} = $caption ;

    # title is based on the filename
    my $title = $filename ;
    $title =~ s/&/&amp;/g ;
#    $title =~ s/"/&\#34;/g ;

    # add caption to the title if asked
    $title .= ": ". $caption
	if $opts->{make_slide_title_from_caption} ;

    $entry->{title} = $title ;

    # do not generate more if we are only generating captions
    return $entry ;
}

sub fill_file_entry {
    my $entry = shift ;
    my $type = $entry->{type} ;
    my $filename = $entry->{filename} ;

    # cache real filename for later
    my $real_filename = "$self->{destination_dir}$filename" ;

    # xdim, ydim, kbytes of the image or movie
    if ($type == $TYPE_IMAGE) {
	# initialize here so that we can use it even when scaled are not used
	$entry->{scaled_xdim} = $entry->{xdim} ;
	$entry->{scaled_ydim} = $entry->{ydim} ;
    }
    if ($type == $TYPE_IMAGE or $type == $TYPE_MOVIE or $type == $TYPE_FILE) {
	my $kbytes = (-s $real_filename) >> 10 ;
	$entry->{kbytes} = $kbytes ;
	# initialize here so that we can use it even when scaled are not used
	$entry->{scaled_kbytes} = $kbytes ;
    }

    # dimstring
    if ($type == $TYPE_IMAGE) {
	if ($opts->{show_dimensions} and $opts->{show_size}) {
	    $entry->{dimstring} = "($entry->{xdim}x$entry->{ydim}, $entry->{kbytes}$opts->{show_size_unit})" ;
	} elsif ($opts->{show_size}) {
	    $entry->{dimstring} = "($entry->{kbytes}$opts->{show_size_unit})" ;
	} elsif ($opts->{show_dimensions}) {
	    $entry->{dimstring} = "($entry->{xdim}x$entry->{ydim})" ;
	} else {
	    $entry->{dimstring} = "" ;
	}
    } elsif ($type == $TYPE_MOVIE or $type == $TYPE_FILE) {
	if ($opts->{show_size}) {
	    $entry->{dimstring} = "($entry->{kbytes}$opts->{show_size_unit})" ;
	} else {
	    $entry->{dimstring} = "" ;
	}
    } else {
	$entry->{dimstring} = "" ;
    }

    ####################################
    # thumbnail, its url and dimensions
    my $thumb_filename = find_user_thumbnail ($entry) ;
    if ($thumb_filename) {
	# there's a user provided thumbnail, just use it

	# cache real thumb filename for later
	my $real_thumb_filename = "$self->{destination_dir}$self->{local_llgal_dir}/$thumb_filename" ;

	$entry->{thumb_filename} = "$self->{local_llgal_dir}/$thumb_filename" ;
	$entry->{thumb_url} = "$local_llgal_url/". make_safe_url_nowarn ($thumb_filename) ;

	# thumbnail dimensions
	my ($tx, $ty) = imgsize ($real_thumb_filename) ;

	# check thumbnail validity
	if (not defined $tx or not defined $ty) {
	    $messages->warning ("Bad user-given thumbnail file '$real_thumb_filename', cannot retrieve its dimensions, ignoring it.") ;
	    goto NO_USER_THUMB ;
	}

	# resize in the gallery if necessary
	if ($ty > $opts->{thumbnail_height_max}) {
	    $tx = $tx * ($opts->{thumbnail_height_max} / $ty) ;
	    $ty = $opts->{thumbnail_height_max} ;
	}
	if ($opts->{thumbnail_width_max} > 0 and $tx > $opts->{thumbnail_width_max}) {
	    $ty = $ty * ($opts->{thumbnail_width_max} / $tx) ;
	    $tx = $opts->{thumbnail_width_max} ;
	}

	# store values
	($entry->{thumb_xdim},$entry->{thumb_ydim}) = ($tx, $ty) ;

	# dimstring
	if ($opts->{show_dimensions}) {
	    $entry->{thumb_dimstring} = "(${tx}x${ty})" ;
	} else {
	    $entry->{thumb_dimstring} = "" ;
	}

    } elsif ($type == $TYPE_IMAGE) {
     NO_USER_THUMB:
	# no user provided thumbnail, generate one

	# filename and url
	$thumb_filename = "$opts->{thumbnail_image_filenameprefix}$filename" ;
	$thumb_filename =~ s@/@$opts->{path_separator_replacement}@g ;
	$entry->{thumb_filename} = "$self->{local_llgal_dir}/$thumb_filename" ;
	$entry->{thumb_url} = "$local_llgal_url/". make_safe_url_nowarn ($thumb_filename) ;

	# cache real thumb filename for later
	my $real_thumb_filename = "$self->{destination_dir}$entry->{thumb_filename}" ;

	# if the thumbnail does not exist, or is older than the image, or regeneration is forced
	if ((! -e $real_thumb_filename)
	    or (-M $real_thumb_filename) > (-M $real_filename)
	    or $opts->{force_image_regeneration}) {
	    my ($status, @output) ;
	    # only scale down, never up.
	    if ($entry->{ydim} <= $opts->{thumbnail_height_max}
		and ($opts->{thumbnail_width_max} <= 0 or $entry->{xdim} <= $opts->{thumbnail_width_max})) {
		# the original is not large enough, keep it
		$entry->{thumb_filename} = $entry->{filename} ;
		$entry->{thumb_url} = $entry->{url} ;
		$real_thumb_filename = $real_filename ;
	    } else {
		# scale down
		my @cmdline = map {
			s/<IN>/$real_filename/g ;
			s/<OUT>/$real_thumb_filename/g ;
			$_ ;
		} Text::ParseWords::parse_line('\s+', 0, $opts->{thumbnail_create_command}) ;
		($status, @output) = Llgal::Utils::system_with_output ( "create '$filename' thumbnail", @cmdline ) ;
		if ($status == -1) {
		    $messages->warning (@output) ;
		    $messages->abort_percentage ;
		    die "Failed to create '$real_filename' thumbnail.\n" ;
		} elsif ($status) {
		    $messages->warning ("Failed to create '$real_filename' thumbnail.") ;
		    $messages->warning (@output) ;
		    return undef ;
		}
	    }
	}

	# thumbnail dimensions
	my ($tx,$ty) = imgsize ($real_thumb_filename) ;

	# check thumbnail validity
	if (not defined $tx or not defined $ty) {
	    $messages->warning ("Bad thumbnail file '$real_thumb_filename', cannot retrieve its dimensions, skipping this entry.") ;
	    return undef ;
	}

	# store values
	($entry->{thumb_xdim},$entry->{thumb_ydim}) = ($tx,$ty) ;

	# dimstring
	if ($opts->{show_dimensions}) {
	    $entry->{thumb_dimstring} = "(${tx}x${ty})" ;
	} else {
	    $entry->{thumb_dimstring} = "" ;
	}

    } else {
	# default thumbnail dimensions
	$entry->{thumb_xdim} = $opts->{default_thumb_xdim} ;
	$entry->{thumb_ydim} = $opts->{default_thumb_ydim} ;

	# dimstring is empty
        $entry->{thumb_dimstring} = "" ;
    }

    if (!$opts->{make_no_slides}) {
	#######################################
	# scaled image, its url and dimensions

	my $scaled_filename = find_user_scaled ($entry) ;
	if ($scaled_filename) {
	    # there's a user provided scaled, just use it

	    # cache real thumb filename for later
	    my $real_scaled_filename = "$self->{destination_dir}$self->{local_llgal_dir}/$scaled_filename" ;

	    $entry->{scaled_filename} = "$self->{local_llgal_dir}/$scaled_filename" ;
	    $entry->{scaled_url} = "$local_llgal_url/". make_safe_url_nowarn ($scaled_filename) ;

	    # scaled image dimensions
	    my ($sx, $sy) = imgsize ($real_scaled_filename) ;
	    my $skbytes = (-s $real_scaled_filename) >> 10 ;

	    # check scaled validity
	    if (not defined $sx or not defined $sy) {
		$messages->warning ("Bad user-given scaled image file '$real_scaled_filename', cannot retrieve its dimensions, ignoring it.") ;
		goto NO_USER_SCALED ;
	    }

	    # resize in the gallery if necessary
	    if ($opts->{slide_height_max} > 0 and $sy > $opts->{slide_height_max}) {
		$sx = $sx * ($opts->{slide_height_max} / $sy) ;
		$sy = $opts->{slide_height_max} ;
	    }
	    if ($opts->{slide_width_max} > 0 and $sx > $opts->{slide_width_max}) {
		$sy = $sy * ($opts->{slide_width_max} / $sx) ;
		$sx = $opts->{slide_width_max} ;
	    }

	    # store values
	    ($entry->{scaled_xdim},$entry->{scaled_ydim}) = ($sx, $sy) ;
	    $entry->{scaled_kbytes} = $skbytes ;

	    # dimstring
	    if ($opts->{show_dimensions} and $opts->{show_size}) {
		$entry->{scaled_dimstring} = "(${sx}x${sy}, ${skbytes}$opts->{show_size_unit})" ;
	    } elsif ($opts->{show_size}) {
		$entry->{scaled_dimstring} = "(${skbytes}$opts->{show_size_unit})" ;
	    } elsif ($opts->{show_dimensions}) {
		$entry->{scaled_dimstring} = "(${sx}x${sy})" ;
	    } else {
		$entry->{scaled_dimstring} = "" ;
	    }

	} elsif ($type == $TYPE_IMAGE and ($opts->{slide_width_max} > 0 or $opts->{slide_height_max} > 0)) {
	 NO_USER_SCALED:
	    # no user provided scaled, generate one

	    # filename and url
	    $scaled_filename = "$opts->{scaled_image_filenameprefix}$filename" ;
	    $scaled_filename =~ s@/@$opts->{path_separator_replacement}@g ;
	    $entry->{scaled_filename} = "$self->{local_llgal_dir}/$scaled_filename" ;
	    $entry->{scaled_url} = "$local_llgal_url/". make_safe_url_nowarn ($scaled_filename) ;

	    # cache real thumb filename for later
	    my $real_scaled_filename = "$self->{destination_dir}$entry->{scaled_filename}" ;

	    # if the thumbnail does not exist, or is older than the image, or regeneration is forced
	    if ((! -e $real_scaled_filename)
		or (-M $real_scaled_filename) > (-M $real_filename)
		or $opts->{force_image_regeneration}) {
		my ($status, @output) ;
		# only scale down, never up.
		if (($opts->{slide_width_max} <= 0 or $entry->{xdim} <= $opts->{slide_width_max})
		    and ($opts->{slide_height_max} <= 0 or $entry->{ydim} <= $opts->{slide_height_max})) {
		    # the original is not large enough, keep it
		    $entry->{scaled_filename} = $entry->{filename} ;
		    $entry->{scaled_url} = $entry->{url} ;
		    $real_scaled_filename = $real_filename ;
		} else {
		    # scale down
		    my @cmdline = map {
			s/<IN>/$real_filename/g ;
			s/<OUT>/$real_scaled_filename/g ;
			$_ ;
		    } Text::ParseWords::parse_line('\s+', 0, $opts->{scaled_create_command}) ;
		    ($status, @output) = Llgal::Utils::system_with_output ( "create '$filename' scaled image", @cmdline ) ;
		    if ($status == -1) {
			$messages->warning (@output) ;
			$messages->abort_percentage ;
			die "Failed to create '$real_filename' scaled image.\n" ;
		    } elsif ($status) {
			$messages->warning ("Failed to create '$real_filename' scaled image.") ;
			$messages->warning (@output) ;
			return undef ;
		    }
		}
	    }

	    # scaled dimensions
	    my ($sx,$sy) = imgsize ($real_scaled_filename) ;
	    my $skbytes = (-s $real_scaled_filename) >> 10 ;

	    # check scaled validity
	    if (not defined $sx or not defined $sy) {
		$messages->warning ("Bad scaled image file '$real_scaled_filename', cannot retrieve its dimensions, skipping this entry.") ;
		return undef ;
	    }

	    # store values
	    ($entry->{scaled_xdim},$entry->{scaled_ydim}) = ($sx,$sy) ;
	    $entry->{scaled_kbytes} = $skbytes ;

	    # dimstring
	    if ($opts->{show_dimensions} and $opts->{show_size}) {
		$entry->{scaled_dimstring} = "(${sx}x${sy}, ${skbytes}$opts->{show_size_unit})" ;
	    } elsif ($opts->{show_size}) {
		$entry->{scaled_dimstring} = "(${skbytes}$opts->{show_size_unit})" ;
	    } elsif ($opts->{show_dimensions}) {
		$entry->{scaled_dimstring} = "(${sx}x${sy})" ;
	    } else {
		$entry->{scaled_dimstring} = "" ;
	    }

	} else {
	    $entry->{scaled_dimstring} = $entry->{dimstring} ;
	}
    } else {
	$entry->{scaled_dimstring} = $entry->{dimstring} ;
    }
    return $entry ;
}

sub create_nofile_entry {
    my $entry = () ;
    my $type = shift ;
    my $url = shift ;
    my $linktext = shift ;
    my $caption = shift ;

    # special type case
    if ($type == $TYPE_LINKNOSLIDE) {
	$entry->{no_slide} = 1 ;
	$type = $TYPE_LINK ;
    }

    # set the type
    $entry->{type} = $type ;

    # row break and horizontal lines need nothing
    if ($type == $TYPE_LINE or $type == $TYPE_BREAK) {
	$entry->{no_slide} = 1 ;
	$entry->{no_thumb} = 1 ;
	return $entry ;
    }

    # make a safe url
    if (defined $url) {
	if ($type == $TYPE_LINK) {
	    $entry->{url} = $url ;
	} else {
	    $entry->{url} = make_safe_url ($url) ;
	}
    }

    # the link text (will be web-safe after caption file generation)
    $entry->{linktext} = $linktext ;

    # the caption (will be web-safe after caption file generation)
    $caption = "" unless defined $caption ;
    $entry->{caption} = $caption ;

    # add caption to the title if asked
    my $title = "" ;
    $title = $caption
	if $opts->{make_slide_title_from_caption} ;
    $entry->{title} = $title ;

    # do not generate more if we are only generating captions
    return $entry ;
}

sub fill_nofile_entry {
    my $entry = shift ;

    # dimstring
    $entry->{dimstring} = "" ;

    # default thumbnail dimensions
    $entry->{thumb_xdim} = $opts->{default_thumb_xdim} ;
    $entry->{thumb_ydim} = $opts->{default_thumb_ydim} ;

    # dimstring is empty
    $entry->{thumb_dimstring} = "" ;

    if (!$opts->{make_no_slides}) {
	# scaled image dimensions
	$entry->{scaled_dimstring} = $entry->{dimstring} ;
    }
    return $entry ;
}

# fill entries, everything that's not required for
# captions generation, but may be done early
sub fill_entries {
    my $gallery = shift ;
    my @entries = @{$gallery->{entries}} ;
    my @final_entries = () ;

    $messages->print ("Preparing entries: ") ;
    $messages->init_percentage (scalar @entries) ;

    my $i = 0 ;
    for my $entry (@entries) {
	my $type = $entry->{type} ;
	my $final_entry ;
	if ($type == $TYPE_LINE or $type == $TYPE_BREAK) {
	    $final_entry = $entry ; # nothing to do
	} elsif ($type == $TYPE_TEXT or $type == $TYPE_LINK) {
	    $final_entry = fill_nofile_entry $entry ;
	} else {
	    $final_entry = fill_file_entry $entry ;
	}
	push @final_entries, $final_entry
	    if defined $final_entry ;
	$messages->update_percentage (($i++)+1) ;
    }
    $messages->end_percentage () ;

    @{$gallery->{entries}} = @final_entries ;
}

# generate slide number, filename and url only when the order of entries is fixed
sub finalize_entries {
    my $gallery = shift ;
    my $opts = shift ;

    my @entries = @{$gallery->{entries}} ;

    if ($opts->{list_links}) {
	map {
	    my $type = $_->{type} ;
	    if (!$_->{thumb_filename}
		and ($type == $TYPE_LINK or $type == $TYPE_DIR or $type == $TYPE_MOVIE
		     or $type == $TYPE_FILE or $type == $TYPE_TEXT)) {
		$_->{no_thumb} = 1 ;
	    }
	} @entries ;
    }

    # account slides
    my $nslides = scalar (grep { ! $_->{no_slide} } @entries) ;
    $gallery->{nslides} = $nslides ;

    # prepare numbering
    my $counter_length = length $nslides ;

    my $prev = undef ;
    my $first = undef ;
    my $indix = 0 ;
    for(my $i=0; $i < @entries; $i++) {
	my $entry = $entries[$i] ;

	# entries without a slide are not taken into account
	next if defined $entry->{no_slide} ;

	# if making no slides, only subgallery may be linked together
	next if $opts->{make_no_slides} and $entry->{type} != $TYPE_DIR and $opts->{link_subgalleries} ;

	# slide counter
	$indix++;
	$entry->{counter} = $indix ;
	my $counter_with_zeros = sprintf "%0${counter_length}d", $indix ;
	$entry->{counter_with_zeros} = $counter_with_zeros ;

	my $type = $entry->{type} ;
	my $filename = $entry->{filename} ;

	# HTML slide and its url
	if (!$opts->{make_no_slides} and $type != $TYPE_LINE and $type != $TYPE_BREAK) {
	    my $slide_filename ;
	    if ($opts->{make_slide_filename_from_filename}) {
		if ($type == $TYPE_TEXT or $type == $TYPE_LINK) {
		    $slide_filename = "$opts->{slide_filenameprefix}$counter_with_zeros.$opts->{www_extension}" ;
		} elsif ($opts->{make_slide_filename_from_extension} or $type == $TYPE_DIR) {
		    $slide_filename = "$opts->{slide_filenameprefix}$filename.$opts->{www_extension}" ;
		} else {
		    my @parts = split (/\./, $filename) ;
		    pop @parts ;
		    my $basename = join ('.', @parts) ;
		    $slide_filename = "$opts->{slide_filenameprefix}$basename.$opts->{www_extension}" ;
		}
	    } else {
		$slide_filename = "$opts->{slide_filenameprefix}$counter_with_zeros.$opts->{www_extension}" ;
	    }
	    $entry->{slide_filename} = $slide_filename ;
	    $entry->{slide_url} = make_safe_url_nowarn ($slide_filename) ;
	}

	# initialize to -1 for no link to prev/next slide
	$entry->{prev} = -1 ;
	$entry->{next} = -1 ;

	# link to previous entry
	if (defined $prev) {
	    $entry->{prev} = $prev;
	    $entries[$prev]->{next} = $i ;
	}
	$prev = $i ;

	# store first
	$first = $i unless defined $first ;
    }

    if (defined $first and $opts->{link_between_last_and_first}) {
	# link last to first
	$entries[$prev]->{next} = $first ;
	$entries[$first]->{prev} = $prev ;
    }
}

#######################################################################
# Generating entry table from files in target directory

sub sort_entries {
    my $path = shift ;

    if ($opts->{sort_criteria} eq "name") {
	return sort @_ ;
    } elsif ($opts->{sort_criteria} eq "revname") {
	return sort { $b cmp $a } @_ ;

    } elsif ($opts->{sort_criteria} eq "iname") {
	return sort { uc($a) cmp uc($b) } @_ ;
    } elsif ($opts->{sort_criteria} eq "reviname") {
	return sort { uc($b) cmp uc($a) } @_ ;

    } elsif ($opts->{sort_criteria} eq "date" or $opts->{sort_criteria} eq "time") {
	return sort { (-M "$path$a") <=> (-M "$path$b") } @_ ;
    } elsif ($opts->{sort_criteria} eq "revdate" or $opts->{sort_criteria} eq "revtime") {
	return sort { (-M "$path$b") <=> (-M "$path$a") } @_ ;

    } elsif ($opts->{sort_criteria} eq "size") {
	return sort { (-s "$path$a") <=> (-s "$path$b") } @_ ;
    } elsif ($opts->{sort_criteria} eq "revsize") {
	return sort { (-s "$path$b") <=> (-s "$path$a") } @_ ;

    } elsif ($opts->{sort_criteria} eq "none" or $opts->{sort_criteria} eq "") {
	return @_
    } else {
	die "Unknown sort criteria '$opts->{sort_criteria}'.\n" ;
    }
}

sub get_entries_from_directory {
    my $gallery = shift;
    my $dir = shift ;
    my $subdir = shift ;
    my $add_subdirs = shift ;
    my $add_others = shift ;
    my @entries = () ;

    my $destdir = "$dir$subdir" ;
    my $destdir_string = "directory $dir$subdir" ;
    if (!$destdir) {
	$destdir = "." ;
	$destdir_string = "current directory" ;
    }

    my $subdir_string = $subdir ;
    $subdir_string = "." unless $subdir_string ;

    opendir DIR, $destdir
	or die "Can't open $destdir_string ($!).\n" ;
    # get all files, except dot-starting ones and webpages
    my @filenames = map { ($subdir ? "$subdir/" : "").$_ } (grep ((!/\.$opts->{www_extension}$/i and !/^\./), readdir DIR)) ;
    closedir DIR ;

    # sort now so that slide numbering doesn't become wrong later
    @filenames = sort_entries $dir, @filenames ;

    $messages->print ("Listing entries in $subdir_string : ") ;
    $messages->init_percentage (scalar @filenames) ;

    for(my $i = 0; $i < @filenames; $i++) {
	my $filename = $filenames[$i] ;
	chomp $filename ;
	if (-d "$dir$filename") {
	    # directory
	    if ($add_subdirs) {
		my $entry = create_file_entry ($gallery, $TYPE_DIR, $filename, undef, undef) ;
		push @entries, $entry
		    if defined $entry ;
	    }

	} else {
	    # file
	    my $entry = undef ;

	    if ($filename =~ m/($opts->{image_extensions})$/i) {
		# image
		my $entry = create_file_entry ($gallery, $TYPE_IMAGE, $filename, undef, undef) ;
		goto JUST_A_FILE
		    if not defined $entry ;
		push @entries, $entry ;

	    } elsif ($filename =~ m/($opts->{movie_extensions})$/i) {
		# movie
		my $entry = create_file_entry ($gallery, $TYPE_MOVIE, $filename, undef, undef) ;
		goto JUST_A_FILE
		    if not defined $entry ;
		push @entries, $entry ;

	    } else {
	      JUST_A_FILE:
		if ($add_others) {
		    # not an image, not a movie, just a file
		    my $entry = create_file_entry ($gallery, $TYPE_FILE, $filename, undef, undef) ;
		    push @entries, $entry
			if defined $entry ;
		}
	    }
	}

	$messages->update_percentage ($i+1) ;
    }
    $messages->end_percentage () ;

    return @entries ;
}

sub get_subdir_tree {
    my @processed_dirs = () ;
    my @remaining_dirs = ("") ;

    while (@remaining_dirs) {
	my $current_dir = shift @remaining_dirs ;
	my $destdir = "$self->{destination_dir}$current_dir" ;
	my $destdir_string = "directory $destdir" ;
	if (!$destdir) {
	    $destdir = "." ;
	    $destdir_string = "current directory" ;
	}

	# enqueue subdirectories
	opendir DIR, $destdir
	    or die "Can't open $destdir_string ($!).\n" ;
	unshift @remaining_dirs, ( sort_entries
				   # base directory for sorting
				   $self->{destination_dir},
				   # add subdirectories only
				   ( grep { -d "$self->{destination_dir}$_" }
				     ( map { "$current_dir$_/" }
				       # except those starting with a dot
				       ( grep ((!/^\./),
					       ( readdir DIR ) ) ) ) ) ) ;
	closedir DIR ;

	# this directory is done
	push @processed_dirs, $current_dir ;
    }
    return @processed_dirs ;
}

sub get_entries {
    my $gallery = shift ;
    my $opts = shift ;
    my @entries = () ;

    if ($opts->{recursive_sections}
	or (defined $opts->{section_dirs} and @{$opts->{section_dirs}})) {
	my @subdirs ;
	if ($opts->{recursive_sections}) {
	    @subdirs = get_subdir_tree () ;
	} else {
	    @subdirs = @{$opts->{section_dirs}} ;
	}
	foreach my $subdir (@subdirs) {
	    # remove ending slashes
	    $subdir =~ s@/*$@@g ;
	    # separation line and title
	    push @entries, (create_nofile_entry $TYPE_LINE, undef, undef, undef)
		if $opts->{separate_sections} ;
	    if ($opts->{entitle_sections}) {
		my $text = $opts->{section_text}.($subdir ? $subdir : ".") ;
		push @entries, (create_nofile_entry $TYPE_TEXT, undef, $text, $text) ;
	    }
	    # section entries
	    push @entries, get_entries_from_directory
		$gallery,
		$self->{destination_dir},
		$subdir,
		($opts->{add_subdirs} or $opts->{recursive}),
		$opts->{add_all_files} ;
	}

    } else {
	@entries = get_entries_from_directory
	    $gallery,
	    $self->{destination_dir},
	    "",
	    ($opts->{add_subdirs} or $opts->{recursive}),
	    $opts->{add_all_files} ;

    }

    return @entries ;
}

#######################################################################
# Check acces rights and create local subdirectory to place all llgal files

sub check_destination {

    # check destination
    die "Destination $self->{destination_dir} does not exist.\n"
	if ! -e $self->{destination_dir} ;
    die "Destination $self->{destination_dir} is not a directory.\n"
	if ! -d $self->{destination_dir} ;

    # cleanup destination
    # add a final /
    $self->{destination_dir} .= "/"
	unless $self->{destination_dir} =~ m@/$@ ;
    # remove starting ./
    $self->{destination_dir} =~ s@^(\./+)+@@ ;

    # Are we in .llgal ? just check the last part of the path by concatening
    # pwd and destination_dir even if destination_dir is an absolute path
    my $path = getcwd."/".$self->{destination_dir} ;
    if ($path =~ m@/*(?:[^/]+/+)*([^/]+)/+$@) {
	if ($1 eq $self->{local_llgal_dir}) {
	    $messages->warning ("!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!") ;
	    $messages->warning ("Your working directory looks like a .llgal directory. !!") ;
	    $messages->warning ("This might not be what you really want to do.         !!") ;
	    $messages->warning ("!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!") ;
	}
    }

    # TODO: remove this one day (maybe on march 7th 2006, since it will be 6 month ?)
    # temporary check, to be removed soon
    if ($self->{local_llgal_dir} ne ".llgal.files" and -e "$self->{destination_dir}.llgal.files") {
	$messages->warning ("!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!") ;
	$messages->warning ("llgal now uses '.llgal' instead '.llgal.files'. !!") ;
	$messages->warning ("You should probably update it.                  !!") ;
	$messages->warning ("!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!") ;
    }

    # create globals to factorize later
    $local_llgal_url = make_safe_url_nowarn ($self->{local_llgal_dir}) ;
}

sub setup_destination {

    # create globals to factorize later
    $destination_string = ($self->{destination_dir} ? "directory $self->{destination_dir}" : "current directory") ;

    # Create or check the local llgal directory
    if (! -e "$self->{destination_dir}$self->{local_llgal_dir}") {
	mkdir "$self->{destination_dir}$self->{local_llgal_dir}"
	    or die "Failed to create $self->{destination_dir}$self->{local_llgal_dir} directory ($!).\n" ;
    }
    die "Local llgal $self->{destination_dir}$self->{local_llgal_dir} is not a directory.\n"
	if ! -d "$self->{destination_dir}$self->{local_llgal_dir}" ;
}

#######################################################################
# Generate captions file

sub generate_captions_entries {
    my $gallery = shift ;
    my $opts = shift ;

    my @entries = @{$gallery->{entries}} ;

    $messages->print ("Found ". (scalar @entries) ." entries in $destination_string\n") ;

    my @captions = () ;

    # store old values from the captions file, if it exists
    my $old_title ;

    my $old_parent_gallery_link = 0 ;
    my $old_parent_gallery_link_text ;

    my $old_prev_gallery_link_target ;
    my $old_prev_gallery_link_text ;

    my $old_next_gallery_link_target ;
    my $old_next_gallery_link_text ;

    if (-e "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}") {
	$messages->print ("Reading existing captions from $opts->{captions_filename}.\n") ;
	open (CAP, "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}")
	    or die "Can't open $self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename} for reading ($!).\n" ;
	@captions = <CAP> ;
	close CAP ;

	foreach my $line (@captions) {
	    if ($line =~ m/^TITLE:\s*(.*)\s*$/) {
		$old_title = $1 ;
	    } elsif ($line =~ m/^PARENT:\s*(.*)\s*$/) {
		$old_parent_gallery_link = 1 ;
		$old_parent_gallery_link_text = $1 ;
	    } elsif ($line =~ m/^PREV:\s*(.+)\s+----\s+(.+)\s*/) {
		$old_prev_gallery_link_target = $2 ;
		$old_prev_gallery_link_text = $1 ;
	    } elsif ($line =~ m/^NEXT:\s*(.+)\s+----\s+(.+)\s*/) {
		$old_next_gallery_link_target = $2 ;
		$old_next_gallery_link_text = $1 ;
	    }
	}

	open (CAP, ">>$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}")
	    or die "Can't open $self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename} file to append ($!).\n" ;
	$messages->print ("Appending new captions to $opts->{captions_filename}: ") ;

	print CAP "\n" ;
	print CAP "# Appended new captions on ". (scalar localtime) ."\n" ;
	print CAP "# invoked with $llgal_cmdline\n" ;
	print CAP "\n" ;
    } else {
	# find the captions headers
	my $headers = (Llgal::Templates::find_template_file ($self, $opts, $opts->{captions_header_filename}, 1))
	    . "/$opts->{captions_header_filename}" ;
	$messages->notice ("Using '$headers' as a header for the captions file...\n") ;

	# copy its content
	my @captions_header = () ;
	if (open CAPHEADER, $headers) {
	    @captions_header = <CAPHEADER> ;
	    close CAPHEADER ;
	} else {
	    $messages->warning ("Failed to open $headers\n") ;
	}

	# create the captions file
	open (CAP, ">$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}")
	    or die "Can't create $self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename} file ($!).\n" ;
	$messages->print ("Creating the $opts->{captions_filename} file: ") ;

	print CAP "# This is llgal's $opts->{captions_filename} file, first generated on ", scalar localtime, "\n" ;
	print CAP "# invoked with $llgal_cmdline\n" ;

	# append the header
	map { print CAP $_ ; } @captions_header ;
	# ends with a blank line

	# append the captions removal line
	print CAP "\n" ;
	print CAP "# $opts->{captions_removal_line}\n" ;
	print CAP "\n" ;
    }

    print CAP "TITLE: $opts->{index_title}\n"
	if defined $opts->{index_title}
           and (!defined $old_title or $old_title ne $opts->{index_title}) ;
    print CAP "PARENT: $gallery->{parent_gallery_link_text}\n"
	if ( defined $gallery->{parent_gallery_link_target}
	     and ( !$old_parent_gallery_link
		   or $old_parent_gallery_link_text ne $gallery->{parent_gallery_link_text} ) ) ;
    print CAP "PREV: $gallery->{prev_gallery_link_text} ---- $gallery->{prev_gallery_link_target}\n"
	if ( defined $gallery->{prev_gallery_link_target}
	     and ( !defined $old_prev_gallery_link_target
		   or $old_prev_gallery_link_target ne $gallery->{prev_gallery_link_target}
		   or !defined $old_prev_gallery_link_text
		   or $old_prev_gallery_link_text ne $gallery->{prev_gallery_link_text} ) ) ;
    print CAP "NEXT: $gallery->{next_gallery_link_text} ---- $gallery->{next_gallery_link_target}\n"
	if ( defined $gallery->{next_gallery_link_target}
	     and ( !defined $old_next_gallery_link_target
		   or $old_next_gallery_link_target ne $gallery->{next_gallery_link_target}
		   or !defined $old_next_gallery_link_text
		   or $old_next_gallery_link_text ne $gallery->{next_gallery_link_text} ) ) ;
    print CAP "\n" ;

    $messages->init_percentage (scalar @entries) ;

    for (my $i = 0; $i < @entries; $i++) {
	my $entry = $entries[$i] ;
	my $type = $entry->{type} ;
	if ($type == $TYPE_IMAGE) {
	    print CAP "IMG: ". $entry->{filename}
		." ---- ". $entry->{caption} ."\n"
		unless grep { $captions[$_] =~ m/^(\s*IMG:)?\s*\Q$entry->{filename}\E\s+----\s/ }
		    ( 0 .. $#captions ) ;

	} elsif ($type == $TYPE_MOVIE) {
	    print CAP "MVI: " . $entry->{filename}
		." ---- ". $entry->{linktext}
		." ---- ". $entry->{caption} ."\n"
		unless grep { $captions[$_] =~ m/^\s*MVI:\s*\Q$entry->{filename}\E\s+----\s/ }
		    ( 0 .. $#captions ) ;

	} elsif ($type == $TYPE_FILE) {
	    print CAP "FIL: " . $entry->{filename}
		." ---- ". $entry->{linktext}
		." ---- ". $entry->{caption} ."\n"
		unless grep { $captions[$_] =~ m/^\s*FIL:\s*\Q$entry->{filename}\E\s+----\s/ }
		    ( 0 .. $#captions ) ;

	} elsif ($type == $TYPE_DIR) {
	    print CAP "DIR: " . $entry->{filename}
		." ---- ". $entry->{linktext}
		." ---- ". $entry->{caption} ."\n"
		unless grep { $captions[$_] =~ m/^\s*DIR:\s*\Q$entry->{filename}\E\s+----\s/ }
		    ( 0 .. $#captions ) ;

	} elsif ($type == $TYPE_TEXT) {
	    # TODO: do not insert again ? (in case of --Ps)
	    print CAP "TXT: " . $entry->{linktext} ." ---- ". $entry->{caption} ."\n";

	} elsif ($type == $TYPE_LINE) {
	    print CAP "LINE\n" ;

	} elsif ($type == $TYPE_BREAK) {
	    print CAP "BREAK\n" ;

	} else {
	    $messages->abort_percentage ;
	    die "Unrecognized entry type '$type'.\n" ;
	}

	$messages->update_percentage ($i+1) ;
    }

    $messages->end_percentage () ;

    close CAP ;
}

#######################################################################
# Read entry list in the captions file

sub read_captions_file {
    my $gallery = shift ;
    my @entries = () ;
    my @headers = () ;
    my @footers = () ;
    my $user_fields = () ;

    $messages->print ("Reading entries in the $opts->{captions_filename} file: ") ;

    open(CAP,"$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}")
	or die "Can't open $self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename} file ($!).\n" ;

    my $size = (-s CAP) ;
    $messages->init_percentage ($size) ;

    my $line ;
    while (defined ($line = <CAP>)) {
	chomp $line ;
	$line =~ s/^\s*// ;
	$line =~ s/\s\(\s*\)$/$1/ ;
	# only lines that don't start with # and are not empty
	if ($line !~ m/^\#/ and $line !~ m/^$/) {
	    if ($line =~ m/^TITLE:\s*(.*)\s*/) {
		# title
		$opts->{index_title} = $1 ;

	    } elsif ($line =~ m/^INDEXHEAD:\s*(.*)\s*$/) {
		# header for the index
		push @headers, $1 ;

	    } elsif ($line =~ m/^INDEXFOOT:\s*(.*)\s*$/) {
		# footer for the index
		push @footers, $1 ;

	    } elsif ($line =~ m/^PARENT:\s*(.*)\s*$/) {
		# parent gallery link label
		$gallery->{parent_gallery_link} = 1 ;
		$gallery->{parent_gallery_link_text} = $1 ;
		$gallery->{parent_gallery_link_target} = "../$opts->{index_filename}.$opts->{www_extension}" ;

	    } elsif ($line =~ m/^PREV:\s*(.*)\s+----\s+(.*)\s*$/) {
		# prev gallery link label
		$gallery->{prev_gallery_link_text} = $1 ;
		$gallery->{prev_gallery_link_target} = $2 ;

	    } elsif ($line =~ m/^NEXT:\s*(.*)\s+----\s+(.*)\s*$/) {
		# next gallery link label
		$gallery->{next_gallery_link_text} = $1 ;
		$gallery->{next_gallery_link_target} = $2 ;

	    } elsif ($line =~ m/^REPLACE:\s*(.+)\s+----\s+(.*)\s*$/) {
		# replacing
		$user_fields->{$1} = $2 ;

	    } else {
		# that's a slide, create its entry
		my $entry ;
		# flexibility:
		# - the last \s might be omitted when there's no caption
		# - \s is facultative after TYP: at the beginning
		if ($line =~ m/^TXT:\s*(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # text slide
		    $entry = create_nofile_entry ($TYPE_TEXT, undef, $1, $2) ;

		} elsif ($line =~ m/^LNK:\s*(.+)\s+----\s+(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # link slide
		    $entry = create_nofile_entry ($TYPE_LINK, $1, $2, $3) ;

		} elsif ($line =~ m/^LNKNOSLIDE:\s*(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # direct link without slide
		    $entry = create_nofile_entry ($TYPE_LINKNOSLIDE, $1, $2, undef) ;

		} elsif ($line =~ m/^DIR:\s*(.+)\s+----\s+(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # directory slide
		    $entry = create_file_entry ($gallery, $TYPE_DIR, $1, $2, $3) ;

		} elsif ($line =~ m/^MVI:\s*(.+)\s+----\s+(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # movie slide
		    $entry = create_file_entry ($gallery, $TYPE_MOVIE, $1, $2, $3) ;

		} elsif ($line =~ m/^FIL:\s*(.+)\s+----\s+(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # movie slide
		    $entry = create_file_entry ($gallery, $TYPE_FILE, $1, $2, $3) ;

		} elsif ($line =~ m/^LINE/) {
		    # horizontal line
		    $entry = create_nofile_entry ($TYPE_LINE, undef, undef, undef) ;

		} elsif ($line =~ m/^BREAK/) {
		    # thumbnail row break
		    $entry = create_nofile_entry ($TYPE_BREAK, undef, undef, undef) ;

		} elsif ($line =~ m/^IMG:\s*(.+)\s+----\s*(?:\s(.*))?\s*$/
			 or $line =~ m/^(.+)\s+----\s*(?:\s(.*))?\s*$/) {
		    # image slide (default)
		    $entry = create_file_entry ($gallery, $TYPE_IMAGE, $1, undef, $2) ;

		} else {
		    $messages->abort_percentage ;
		    die "Unrecognized line #$. in captions file: \"$line\".\n" ;
		}

		# really add this entry
		push @entries, $entry
		    if defined $entry ;
	    }
	}
	$messages->update_percentage (tell CAP) ;
    }
    close CAP ;
    $messages->end_percentage () ;

    @{$gallery->{entries}} = @entries ;
    @{$gallery->{headers}} = @headers ;
    @{$gallery->{footers}} = @footers ;
    $gallery->{user_fields} = $user_fields ;
}

#######################################################################
# Links to add in a subgallery

# revert a path into ..
sub back_path {
    my $dir = shift ;
    $dir =~ s@([^/]+)@..@g ;
    return $dir ;
}

# store data about how a subgallery will be linked to parent/prev/next
sub create_subgallery_family {
    my $entry = shift ;
    my $opts = shift ;
    my $nentries = shift ;
    my $prev = shift ;
    my $next = shift ;

    my $dir = $entry->{filename} ;
    my $revdir = back_path $dir ;

    # contents of links in the subgallery
    my $family = () ;
    # additional opts to generate the subgallery
    my $subdir_opts = {} ;

    # link to the parent gallery
    $subdir_opts->{parent_gallery_link} = 1 ;

    if ($opts->{link_subgalleries} and $nentries > 1) {
	# link to the previous gallery
	if ($prev->{type} == $TYPE_DIR) {
	    $family->{prev_gallery_link_target} = "$revdir/$prev->{url}" ;
	    $family->{prev_gallery_link_text} = $prev->{gallery_name} ;
	}
	# link to the next gallery
	if ($next->{type} == $TYPE_DIR) {
	    $family->{next_gallery_link_target} = "$revdir/$next->{url}" ;
	    $family->{next_gallery_link_text} = $next->{gallery_name} ;
	}
    }

    return ($subdir_opts, $family) ;
}

# convert family data from parent to the current gallery
sub process_gallery_family {
    my $gallery = shift ;
    my $family = shift ;
    my $opts = shift ;

    if ($opts->{parent_gallery_link}) {
	$gallery->{parent_gallery_link_text} = $opts->{parent_gallery_link_text}
	    unless defined $gallery->{parent_gallery_link_text} ;
	$gallery->{parent_gallery_link_target} = "../$opts->{index_filename}.$opts->{www_extension}"
	    unless defined $gallery->{parent_gallery_link_target} ;
    }
    if (defined $family->{prev_gallery_link_text}) {
	$gallery->{prev_gallery_link_text} = $opts->{prev_gallery_link_text} . $family->{prev_gallery_link_text}
	    unless defined $gallery->{prev_gallery_link_text} ;
	$gallery->{prev_gallery_link_target} = $family->{prev_gallery_link_target}
	    unless defined $gallery->{prev_gallery_link_target} ;
    }
    if (defined $family->{next_gallery_link_text}) {
	$gallery->{next_gallery_link_text} = $opts->{next_gallery_link_text} . $family->{next_gallery_link_text}
	    unless defined $gallery->{next_gallery_link_text} ;
	$gallery->{next_gallery_link_target} = $family->{next_gallery_link_target}
	    unless defined $gallery->{next_gallery_link_target} ;
    }
}

#######################################################################
# Add recursion header and footer

sub add_headers_footers {
    my $gallery = shift ;
    my @headers = @{$gallery->{headers}} ;
    my @footers = @{$gallery->{footers}} ;

    my $prev_text ;
    $prev_text = "<a href=\"$gallery->{prev_gallery_link_target}\">$gallery->{prev_gallery_link_text}</a>"
	if $gallery->{prev_gallery_link_target} ;

    my $next_text ;
    $next_text = "<div style=\"text-align: right;\"><a href=\"$gallery->{next_gallery_link_target}\">$gallery->{next_gallery_link_text}</a></div>"
	if $gallery->{next_gallery_link_target} ;

    my $parent_text ;
    $parent_text = "<a href=\"$gallery->{parent_gallery_link_target}\">$gallery->{parent_gallery_link_text}</a>"
	if $opts->{parent_gallery_link} ;

    # index, prev, next in headers
    unshift @headers, $next_text
	if $next_text ;
    unshift @headers, $prev_text
	if $prev_text ;
    unshift @headers, $parent_text
	if $parent_text ;

    # prev, next, index in footers
    push @footers, $prev_text
	if $prev_text ;
    push @footers, $next_text
	if $next_text ;
    push @footers, $parent_text
	if $parent_text ;

    @{$gallery->{headers}} = @headers ;
    @{$gallery->{footers}} = @footers ;
}

#######################################################################
# Precompute common fields to be inserted in the HTML pages

sub precompute_common_html_fields
{
    my $gallery = shift ;
    my @entries = @{$gallery->{entries}} ;
    my $common_fields = () ;

    # index title
    $common_fields->{"<!--TITLE-->"} = (defined $opts->{index_title} ? $opts->{index_title} : $opts->{index_title_default}) ;

    # index link text
    $common_fields->{"<!--INDEX-LINK-TEXT-->"} = $opts->{index_link_text} ;
    if ($opts->{index_link_image}) {
	if ($opts->{index_link_image_location}) {
	    $common_fields->{"<!--INDEX-LINK-TEXT-->"} = "<img src=\"$opts->{index_link_image_location}\" "
		."alt=\"$opts->{index_link_text}\" "
		."class=\"image-link\" />" ;
	} else {
	    $common_fields->{"<!--INDEX-LINK-TEXT-->"} = "<img src=\"$self->{local_llgal_dir}/"
		. (make_safe_url $opts->{index_link_image_filename}) ."\" "
		."alt=\"$opts->{index_link_text}\" class=\"image-link\" />" ;
	}
    }

    # index file (ugly hack to also generate a title attribute right after the href)
    $common_fields->{"<!--INDEX-FILE-->"} = "$opts->{index_filename}.$opts->{www_extension}\" title=\"$opts->{over_index_link_text}" ;

    # css
    $common_fields->{"<!--CSS-->"} = "$self->{local_llgal_dir}/$opts->{css_filename}" ;
    if ($opts->{css_location}) {
	$common_fields->{"<!--CSS-->"} = $opts->{css_location} ;
    }

    # codeset
    $common_fields->{"LLGAL-CODESET"} = $opts->{codeset} ;

    # command line
    $common_fields->{"LLGAL-OPTIONS"} = $llgal_cmdline ;
    $common_fields->{"LLGAL-OPTIONS"} =~ s/\"/\'/g ;

    # credits text
    $common_fields->{"<!--CREDITS-->"} = $opts->{credits_text} ;

    # version
    $common_fields->{"<!--VERSION-->"} = $self->{version} ;

    $gallery->{common_fields} = $common_fields ;
}

#######################################################################
# Create the individual slide show files

sub generate_slides {
    my $gallery = shift ;
    my @entries = @{$gallery->{entries}} ;

    # remove old webpages
    opendir DIR, $self->{destination_dir} ? $self->{destination_dir} : "./" ; # destination is empty for './'
    while ($_ = readdir DIR ) {
	if (/^$opts->{slide_filenameprefix}.*\.$opts->{www_extension}$/) {
	    unlink "$self->{destination_dir}$_"
		or die "Failed to remove existing webpage '$_' ($!).\n" ;
	}
    }
    closedir DIR ;

    # create slides
    $messages->print ("Creating individual slides: ") ;
    $messages->init_percentage (scalar @entries) ;

    for (my $i = 0; $i < @entries; $i++) {
	my $entry = $entries[$i] ;

	next if defined $entry->{no_slide} ;

	if (not open(SW, ">$self->{destination_dir}$entry->{slide_filename}")) {
	    $messages->abort_percentage ;
	    die "Can't create slide file ($!).\n" ;
	}
	my $type = $entry->{type} ;

	##############################
	# Precompute all fields first

	# titles
	my $SLIDE_TITLE = $entry->{title} ;

	# this slide style
	my $THIS_SLIDE_STYLE = "image-slide" ;
	if (!defined $entry->{scaled_url} and $type != $TYPE_IMAGE) {
	    $THIS_SLIDE_STYLE = "text-slide" ;
	    $THIS_SLIDE_STYLE .= "\" style=\"width: $opts->{text_slide_width}px; height: $opts->{text_slide_height}px;"
		unless $opts->{slide_dimensions_from_css} ;
	}

	# slide contents
	my $THIS_SLIDE ;
	if ($type == $TYPE_IMAGE) {
	    # image slide

	    if (defined $entry->{scaled_filename}) {
		if ($opts->{slide_link_to_full_image}) {
		    # scaled image with link to the real image
		    $THIS_SLIDE = "<a href=\"$entry->{url}\" "
			."title=\"$opts->{over_scaled_text}$entry->{title} $entry->{dimstring}\">"
			."<img src=\"$entry->{scaled_url}\" " ;
		    $THIS_SLIDE .= "style=\"width: $entry->{scaled_xdim}px; height: $entry->{scaled_ydim}px;\" "
			unless $opts->{slide_dimensions_from_css} ;
		    $THIS_SLIDE .= "alt=\"$opts->{alt_scaled_text}$entry->{title} $entry->{scaled_dimstring}\" />"
			."</a>" ;

		} else {
		    # scaled image without link to the real image
		    $THIS_SLIDE = "<img src=\"$entry->{scaled_url}\" " ;
		    $THIS_SLIDE .= "style=\"width: $entry->{scaled_xdim}px; height: $entry->{scaled_ydim}px;\" "
			unless $opts->{slide_dimensions_from_css} ;
		    $THIS_SLIDE .= "alt=\"$opts->{alt_scaled_text}$entry->{title} $entry->{scaled_dimstring}\" />" ;

		}
	    } else {
		# real image
		$THIS_SLIDE = "<img src=\"$entry->{url}\" " ;
		$THIS_SLIDE .= "style=\"width: $entry->{scaled_xdim}px; height: $entry->{scaled_ydim}px;\" "
		    unless $opts->{slide_dimensions_from_css} ;
		$THIS_SLIDE .= "alt=\"$opts->{alt_full_text}$entry->{title} $entry->{dimstring}\" "
		    ."title=\"$entry->{title} $entry->{dimstring}\" />" ;

	    }
	} elsif ($entry->{scaled_url}) {
	    # another type, with a user-given scaled image
	    if ($type == $TYPE_TEXT) {
		# text with scaled image ? ok...
		$THIS_SLIDE = "<img src=\"$entry->{scaled_url}\" " ;
		$THIS_SLIDE .= "style=\"width: $entry->{scaled_xdim}px; height: $entry->{scaled_ydim}px;\" "
		    unless $opts->{slide_dimensions_from_css} ;
		$THIS_SLIDE .= "title=\"$entry->{title} $entry->{dimstring}\" "
		    ."alt=\"$entry->{linktext} $entry->{scaled_dimstring}\" />" ;

	    } else {
		# another type with scaled image linking to the target
		$THIS_SLIDE = "<a href=\"$entry->{url}\" "
		    ."title=\"$entry->{title} $entry->{dimstring}\">"
		    ."<img src=\"$entry->{scaled_url}\" " ;
		$THIS_SLIDE .= "style=\"width: $entry->{scaled_xdim}px; height: $entry->{scaled_ydim}px;\" "
		    unless $opts->{slide_dimensions_from_css} ;
		$THIS_SLIDE .= "alt=\"$entry->{linktext} $entry->{scaled_dimstring}\" />"
		    ."</a>" ;
	    }

	} elsif ($type == $TYPE_TEXT) {
	    # text slide
	    $THIS_SLIDE = $entry->{linktext} ;
	} else {
	    # link-style slide
	    $THIS_SLIDE = "<a href=\"$entry->{url}\" title=\"$entry->{title} $entry->{dimstring}\">$entry->{linktext}</a>" ;
	}

	# slide number, counter and total
	my $SLIDE_NUMBER = $entry->{counter_with_zeros} ;
	my $SLIDE_TOTAL = $gallery->{nslides} ;
	my $SLIDE_COUNTER = $opts->{slide_counter_format} ;
	$SLIDE_COUNTER =~ s/%n/$entry->{counter}/ ;
	$SLIDE_COUNTER =~ s/%0n/$SLIDE_NUMBER/ ;
	$SLIDE_COUNTER =~ s/%t/$SLIDE_TOTAL/ ;
	# caption
	my $IMAGE_CAPTION = $entry->{caption} . $SLIDE_COUNTER . "&nbsp;&nbsp;&nbsp;$entry->{dimstring}" ;

	# previous slide
	my $PREV_SLIDE_LINK_TEXT = "" ;
	my $PREV_SLIDE = "" ;
	if ($entry->{prev} != -1) {
	    my $prev = $entries[$entry->{prev}] ;
	    if ($opts->{prev_slide_link_preview} and $prev->{thumb_url}) {
		$PREV_SLIDE_LINK_TEXT = "<img src=\"$prev->{thumb_url}\" "
		    ."style=\"width: $prev->{thumb_xdim}px; height: $prev->{thumb_ydim}px;\" "
		    ."alt=\"$opts->{prev_slide_link_text}\" />" ;
	    } elsif ($opts->{prev_slide_link_image}) {
		if ($opts->{prev_slide_link_image_location}) {
		    $PREV_SLIDE_LINK_TEXT = "<img src=\"$opts->{prev_slide_link_image_location}\" "
			."alt=\"$opts->{prev_slide_link_text}\" class=\"image-link\" />" ;
		} else {
		    $PREV_SLIDE_LINK_TEXT = "<img src=\"$self->{local_llgal_dir}/". (make_safe_url $opts->{prev_slide_link_image_filename}) ."\" "
			."alt=\"$opts->{prev_slide_link_text}\" class=\"image-link\" />" ;
		}
	    } else {
		$PREV_SLIDE_LINK_TEXT = $opts->{prev_slide_link_text} ;
	    }
	    $PREV_SLIDE = "$prev->{slide_url}\" title=\"$opts->{over_prev_slide_link_text}$prev->{title}" ;
	}

	# next slide
	my $NEXT_SLIDE_LINK_TEXT = "" ;
	my $NEXT_SLIDE = "" ;
	if ($entry->{next} != -1) {
	    my $next = $entries[$entry->{next}] ;
	    if ($opts->{next_slide_link_preview} and $next->{thumb_url}) {
		$NEXT_SLIDE_LINK_TEXT = "<img src=\"$next->{thumb_url}\" "
		    ."style=\"width: $next->{thumb_xdim}px; height: $next->{thumb_ydim}px;\" "
		    ."alt=\"$opts->{next_slide_link_text}\" />" ;
	    } elsif ($opts->{next_slide_link_image}) {
		if ($opts->{next_slide_link_image_location}) {
		    $NEXT_SLIDE_LINK_TEXT = "<img src=\"". $opts->{next_slide_link_image_location} ."\" "
			."alt=\"$opts->{next_slide_link_text}\" class=\"image-link\" />" ;
		} else {
		    $NEXT_SLIDE_LINK_TEXT = "<img src=\"$self->{local_llgal_dir}/". (make_safe_url $opts->{next_slide_link_image_filename}) ."\" "
			."alt=\"$opts->{next_slide_link_text}\" class=\"image-link\" />" ;
		}
	    } else {
		$NEXT_SLIDE_LINK_TEXT = $opts->{next_slide_link_text} ;
	    }
	    $NEXT_SLIDE = "$next->{slide_url}\" title=\"$opts->{over_next_slide_link_text}$next->{title}" ;
	}

	# exif information
	my $EXIF_TABLE = "" ;
	if ($type == $TYPE_IMAGE
	    and (@{$opts->{show_exif_tags}} or $opts->{show_all_exif_tags})) {
	    my $exif_infos = $entry->{exif_infos} ;
	    foreach my $tag ($opts->{show_all_exif_tags} ? (keys %{$exif_infos}) : @{$opts->{show_exif_tags}}) {
		my $value = $exif_infos->{$tag} ;
		my $description = $opts->{exiftool}->GetDescription ($tag) ;
		$EXIF_TABLE .= "<tr><td class=\"exif-name\">$description</td>"
		    ."<td class=\"exif-value\">$value</td></tr>\n"
		    if defined $value ;
	    }
	    $EXIF_TABLE = "<table class=\"exif\">\n". $EXIF_TABLE ."</table>" ;
	}

	#################################
	# Replace fields in the template

	my @slidetemplate_text_copy = @{$gallery->{slidetemplate_text}} ; # don't touch the original template
        for my $line (@slidetemplate_text_copy) {

	    # user-defined fields
	    my $user_fields = $gallery->{user_fields} ;
	    foreach my $field (keys %{$user_fields}) {
		$line =~ s/$field/$user_fields->{$field}/g ;
	    }

	    # common fields
	    my $common_fields = $gallery->{common_fields} ;
	    foreach my $field (keys %{$common_fields}) {
		$line =~ s/$field/$common_fields->{$field}/g ;
	    }

	    # slide specific fields
	    $line =~ s/<!--SLIDE-TITLE-->/$SLIDE_TITLE/g ;
	    $line =~ s/<!--SLIDE-NUMBER-->/$SLIDE_NUMBER/g ;
	    $line =~ s/<!--SLIDE-TOTAL-->/$SLIDE_TOTAL/g ;
	    $line =~ s/<!--SLIDE-COUNTER-->/$SLIDE_COUNTER/g ;
	    $line =~ s/<!--THIS-SLIDE-STYLE-->/$THIS_SLIDE_STYLE/g ;
	    $line =~ s/<!--THIS-SLIDE-->/$THIS_SLIDE/ ;
	    $line =~ s/<!--IMAGE-CAPTION-->/$IMAGE_CAPTION/g ;
	    $line =~ s/<!--PREV-SLIDE-LINK-TEXT-->/$PREV_SLIDE_LINK_TEXT/g ;
	    $line =~ s/<!--PREV-SLIDE-->/$PREV_SLIDE/g ;
	    $line =~ s/<!--NEXT-SLIDE-LINK-TEXT-->/$NEXT_SLIDE_LINK_TEXT/g ;
	    $line =~ s/<!--NEXT-SLIDE-->/$NEXT_SLIDE/g ;
	    $line =~ s/<!--EXIF-TABLE-->/$EXIF_TABLE/ ;

	    # only one replacement per line because earlier template parsing only detected one per line
	    if ($line =~ /<!--EXIF-(.*)-->/) {
		my $name = $1;
		# EXIF-TABLE handled earlier, no need to ignore here
		my $exif_infos = $entry->{exif_infos} ;
		my $value = $exif_infos->{$name} ;
		$value = "" unless $value ;
		$line =~ s/<!--EXIF-$name-->/$value/ ;
	    }

	    # output the line
	    print SW "$line" ;
	}
	close SW ;
	$messages->update_percentage ($i+1) ;
    }
    $messages->end_percentage () ;
}


#######################################################################
# Creating the index file

sub generate_index {
    my $gallery = shift ;
    my @entries = @{$gallery->{entries}} ;
    my @headers = @{$gallery->{headers}} ;
    my @footers = @{$gallery->{footers}} ;
    my $indextemplate = $gallery->{indextemplate};

    # open the template and the destination
    $messages->print ("Creating the $opts->{index_filename}.$opts->{www_extension} file: ") ;
    open(IXR, "$indextemplate")
	or die "Can't open the index template file '$indextemplate' ($!).\n" ;
    open(IXW, ">$self->{destination_dir}$opts->{index_filename}.$opts->{www_extension}")
	or die "Can't create main $opts->{index_filename}.$opts->{www_extension} file ($!).\n" ;

    # headers
    my $line ;
    while (defined($line = <IXR>)) {

	# stop at <!-- ********** -->
	last if $line =~ m/\*{10}/ ;

	if ($line =~ m/<!--HEADERS-->/) {
	    foreach my $header (@headers) {
		print IXW "    <div class=\"header\">" . $header . "</div>\n" ;
	    }
	} else {
	    # user-defined fields
	    my $user_fields = $gallery->{user_fields} ;
	    foreach my $field (keys %{$user_fields}) {
		$line =~ s/$field/$user_fields->{$field}/g ;
	    }

	    # common fields
	    my $common_fields = $gallery->{common_fields} ;
	    foreach my $field (keys %{$common_fields}) {
		$line =~ s/$field/$common_fields->{$field}/g ;
	    }

	    print IXW "$line" ;
	}
    }
    print IXW "\n" ;

    # output thumbnails
    my $forced_width_warning = 0 ;
    my $i = 0 ;
    $messages->init_percentage (scalar @entries) ;

    while ($i < scalar @entries) {
	my $entry = $entries[$i] ;
	my $type = $entry->{type} ;

	if ($type == $TYPE_LINE or $type == $TYPE_BREAK) {
	    if ($type == $TYPE_LINE) {
		# output a horizontal line
		print IXW "<hr class=\"index\" />\n" ;
	    }
	    # next line, next entry
	    $messages->update_percentage ($i+1) ;
	    $i++ ;
	    next ;
	}

	if ($entry->{no_thumb}) {
	    # output a line with this text
	    print IXW "<div class=\"header\">" ;
	    if ($type == $TYPE_TEXT) {
		if ($opts->{make_no_slides}) {
		    print IXW $entry->{linktext} ;
		} else {
		    print IXW "<a href=\"$entry->{slide_url}\" title=\"$entry->{title} $entry->{dimstring}\">$entry->{linktext}</a>" ;
		}
	    } else {
		print IXW "<a href=\"$entry->{url}\" title=\"$entry->{title} $entry->{dimstring}\">$entry->{linktext}</a>" ;
	    }
	    print IXW "</div>\n" ;
	    # next line, next entry
	    $messages->update_percentage ($i+1) ;
	    $i++ ;
	    next ;
	}

	# output a row of thumbnail
	my $width = $entries[$i]->{thumb_xdim} + $opts->{index_cellpadding} ;
	my $num = 1 ;
	# figure out how many entries to put on this row
	while ($i + $num < @entries) {
	    # stop if this is listed instead of having a slide
	    last if defined $entries[$i+$num]->{no_thumb} ;

	    # stop if there's too much thumbnail on this row
	    last if $opts->{thumbnails_per_row}
	    and $num + 1 > $opts->{thumbnails_per_row} ;

	    # stop if these thumbnail are too large
	    my $box_width = $entries[$i+$num]->{thumb_xdim} ;
	    $box_width = $opts->{thumbnail_width_max} if $opts->{thumbnail_width_max} ;
	    last if $opts->{pixels_per_row}
		and $width + $box_width + $opts->{index_cellpadding} > $opts->{pixels_per_row} ;

	    # compute the new num and width
	    $width += $box_width + $opts->{index_cellpadding} ;
	    $num++ ;
	}
	# check whether a single thumbnail was already too large
	if ($opts->{pixels_per_row} > 0 and $width > $opts->{pixels_per_row}) {
	    $forced_width_warning++ ;
	}

	# Table header
	if ($opts->{show_film_effect}) {
	    print IXW "<table class=\"index with-tile\" style=\"border-spacing: ", $opts->{index_cellpadding}, "px 0px;\">\n" ;
	} else {
	    print IXW "<table class=\"index\" style=\"border-spacing: ", $opts->{index_cellpadding}, "px 0px;\">\n" ;
	}

	# Row header
	# include the image to force the height of the line. we could do it in the css but IE css support sucks a lot
	print IXW "  <tr><td class=\"tiled\" colspan=\"". ($num+2) ."\">"
	    ."<img src=\"$self->{local_llgal_dir}/$opts->{filmtile_filename}\" alt=\"$opts->{alt_film_tile_text}\" />"
	    ."</td></tr>\n"
	    if $opts->{show_film_effect} ;
	print IXW "  <tr>\n" ;
	print IXW "    <td class=\"thumb\">&nbsp;</td>\n"
	    if $opts->{show_film_effect} ;

	# Actual row of thumbnails
	for (my $j = 0; $j < $num; $j++) {
	    my $entry = $entries[$i+$j] ;
	    my $type = $entry->{type} ;
	    my $title ;
	    my $linktext ;
	    my $thumb_width = $entry->{thumb_xdim} ;
	    my $thumb_height = $entry->{thumb_ydim} ;
	    my $box_width = $thumb_width;
	    my $box_height = $thumb_height;

	    # if a thumbnail width max is defined, force the box to its width
	    $box_width = $opts->{thumbnail_width_max} if $opts->{thumbnail_width_max} ;

	    if ($type == $TYPE_IMAGE) {
		$linktext = "$opts->{alt_thumbnail_text}$entry->{title}" ;
		$title = "$opts->{over_thumbnail_text}$entry->{title}" ;
	    } else {
		$title = $entry->{title} ;
		$linktext = $entry->{linktext} ;
	    }

	    my $link = $entry->{url} ;
	    # if making slide and not pointing to target, the thumbnail points to the slide
	    if (!$opts->{make_no_slides} and !$entry->{no_slide}
		and (
		     ($type == $TYPE_IMAGE)
		     or ($type == $TYPE_MOVIE and !$opts->{MVI_link_to_target})
		     or ($type == $TYPE_FILE and !$opts->{FIL_link_to_target})
		     or ($type == $TYPE_LINK and !$opts->{LNK_link_to_target})
		     or ($type == $TYPE_DIR and !$opts->{DIR_link_to_target})
		     or ($type == $TYPE_TEXT)
		     )
		) {
		$link = $entry->{slide_url} ;
	    }

	    if ($entry->{thumb_url}) {
		# either IMG, or with a user-given thumbnail

		print IXW "    <td class=\"thumb\" ";
		print IXW "style=\"width: ${box_width}px; height: ${box_height}px;\" "
		    unless $opts->{thumbnails_dimensions_from_css} ;
		print IXW ">\n" ;

		if ($type == $TYPE_TEXT and $opts->{make_no_slides}) {
		    # thumbnail without any link
		    print IXW "      <img src=\"$entry->{thumb_url}\" "
			."title=\"$title $entry->{scaled_dimstring}\" ";
		    print IXW "style=\"width: ${thumb_width}px; height: ${thumb_height}px;\" "
			unless $opts->{thumbnails_dimensions_from_css} ;
		    print IXW "alt=\"$linktext $entry->{thumb_dimstring}\" />\n" ;
		} else {
		    # thumbnail linking to the slide
		    print IXW "      <a href=\"$link\" "
			."title=\"$title $entry->{scaled_dimstring}\">\n" ;
		    print IXW "	       <img src=\"$entry->{thumb_url}\" ";
		    print IXW "style=\"width: ${thumb_width}px; height: ${thumb_height}px;\" "
			unless $opts->{thumbnails_dimensions_from_css} ;
		    print IXW "alt=\"$linktext $entry->{thumb_dimstring}\" />\n" ;
		    print IXW "	     </a>" ;
		}

		print IXW "    </td>\n" ;

	    } else {
		# not IMG, without thumbnail

		print IXW "    <td class=\"text-thumb\" ";
		print IXW "style=\"width: ${box_width}px; height: ${box_height}px;\" "
		    unless $opts->{thumbnails_dimensions_from_css} ;
		print IXW ">\n";

		if ($type == $TYPE_TEXT and $opts->{make_no_slides}) {
		    # thumbnail with basic text and that's it
		    print IXW "      $entry->{linktext}\n" ;

		} else {
		    # thumbnail directly linking to the target
		    print IXW "      <a href=\"$link\" title=\"$title $entry->{dimstring}\">$entry->{linktext}</a>\n" ;
		}

		print IXW "    </td>\n" ;
	    }

	    $messages->update_percentage ($i+$j+1) ;
	}

	# Row footer
	print IXW "    <td class=\"thumb\">&nbsp;</td>\n"
	    if $opts->{show_film_effect} ;
	print IXW "  </tr>\n" ;
	print IXW "  <tr><td class=\"tiled\" colspan=\"". ($num+2) ."\">"
	    ."<img src=\"$self->{local_llgal_dir}/$opts->{filmtile_filename}\" alt=\"$opts->{alt_film_tile_text}\" />"
	    ."</td></tr>\n"
	    if $opts->{show_film_effect} ;

	# Dimensions and filesizes
	if ($opts->{show_dimensions} or $opts->{show_size}) {
	    print IXW "  <tr>\n" ;
	    print IXW "    <td>&nbsp;</td>\n"
		if $opts->{show_film_effect} ;
	    for (my $j = 0; $j < $num; $j++) {
		my $entry = $entries[$i+$j] ;
		print IXW "    <td class=\"thumb-dim\">$entry->{scaled_dimstring}</td>\n" ;
	    }
	    print IXW "    <td>&nbsp;</td>\n"
		if $opts->{show_film_effect} ;
	    print IXW "  </tr>\n" ;
	}

	# Write image captions under images if option -u is given
	if ($opts->{show_caption_under_thumbnails}) {
	    print IXW "  <tr>\n" ;
	    print IXW "<td>&nbsp;</td>\n"
		if $opts->{show_film_effect} ;
	    for (my $j = 0; $j < $num; $j++) {
		my $entry = $entries[$i+$j] ;
		print IXW "    <td class=\"thumb-caption\">$entry->{caption}</td>\n" ;
	    }
	    print IXW "  </tr>\n" ;
	}

	# Table footer
	print IXW "</table>\n" ;

	$i += $num ;
    }

    # search next <!-- ********** -->
    while (defined($line = <IXR>)) {
	last if $line =~ m/\*{10}/ ;
    }
    print IXW "\n";

    # footers
    while (defined ($line = <IXR>)) {
	if ($line =~ m/<!--FOOTERS-->/) {
	    foreach my $footer (@footers) {
		print IXW "    <div class=\"footer\">" . $footer . "</div>\n" ;
	    }
	} else {
	    # user-defined fields
	    my $user_fields = $gallery->{user_fields} ;
	    foreach my $field (keys %{$user_fields}) {
		$line =~ s/$field/$user_fields->{$field}/g ;
	    }

	    # common fields
	    my $common_fields = $gallery->{common_fields} ;
	    foreach my $field (keys %{$common_fields}) {
		$line =~ s/$field/$common_fields->{$field}/g ;
	    }

	    print IXW "$line" ;
	}
    }
    close IXW ;
    close IXR ;

    $messages->end_percentage () ;

    $messages->warning ("Row width max ($opts->{pixels_per_row}) too low for one single thumbnail. "
	. "Forced $forced_width_warning time". ($forced_width_warning>1?"s":"") .".")
	if $forced_width_warning ;
}

#######################################################################
# If --www was invoked make all files world-readable at the END

sub make_readable {
    my $file = shift ;
    my @stats = stat $file ;
    if (not scalar @stats) {
	$messages->warning ("Failed to get mode of file '$file' ($!).\n") ;
    } else {
	my $perm = $stats[2] & 07777 ;
	if (($perm & 0444) != 0444) {
	    chmod ($perm | 0444, $file)
		or $messages->warning ("Failed to set readable attributes to file '$file' ($!).\n") ;
	}
    }
}

sub make_readable_and_traversable {
    my $file = shift ;
    my @stats = stat $file ;
    if (not scalar @stats) {
	$messages->warning ("Failed to get mode of file '$file' ($!).\n") ;
    } else {
	my $perm = $stats[2] & 07777 ;
	if (($perm & 0555) != 0555) {
	    chmod ($perm | 0555, $file)
		or $messages->warning ("Failed to set readable and executable attributes to file '$file' ($!).\n") ;
	}
    }
}

sub make_www_rights {
    my $gallery = shift ;
    my $opts = shift ;
    my @entries = @{$gallery->{entries}} ;

    $messages->print ("Making all llgal files world-readable for WWW publishing.\n") ;

    # index
    make_readable "$self->{destination_dir}$opts->{index_filename}.$opts->{www_extension}" ;
    # .llgal
    make_readable_and_traversable "$self->{destination_dir}$self->{local_llgal_dir}" ;
    # css
    make_readable "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{css_filename}" ;
    # filmtile
    make_readable "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{filmtile_filename}"
	if $opts->{show_film_effect} ;
    # index link image
    make_readable "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{index_link_image_filename}"
 	if $opts->{index_link_image} ;
    # prev slide link image
    make_readable "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{prev_slide_link_image_filename}"
 	if $opts->{prev_slide_link_image} and ! $opts->{prev_slide_link_preview};
    # next slide link image
    make_readable "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{next_slide_link_image_filename}"
 	if $opts->{next_slide_link_image} and ! $opts->{next_slide_link_preview} ;

    # entries that have a slide
    foreach my $entry (@entries) {
	my $type = $entry->{type} ;

	# target
	if ($type == $TYPE_DIR) {
	    make_readable_and_traversable "$self->{destination_dir}$entry->{filename}" ;
	} elsif ($type == $TYPE_IMAGE or $type == $TYPE_MOVIE or $type == $TYPE_FILE) {
	    make_readable "$self->{destination_dir}$entry->{filename}" ;
	}

	# slide
	make_readable "$self->{destination_dir}$entry->{slide_filename}"
	    if ! $opts->{make_no_slides} and ! defined $entry->{no_slide} ;

	# thumbnail
	make_readable "$self->{destination_dir}$entry->{thumb_filename}"
	    if ($type == $TYPE_IMAGE or $entry->{thumb_url}) and !defined $entry->{no_thumb} ;

	# scaled image
	make_readable "$self->{destination_dir}$entry->{scaled_filename}"
	    if ($type == $TYPE_IMAGE or $entry->{scaled_url})
	    and ($opts->{slide_width_max} > 0 or $opts->{slide_height_max} > 0) and !$opts->{make_no_slides} ;
    }
}

#######################################################################
# Main code

# evaluate generic configuration files
my $generic_opts = {} ;
# system-wide configuration file
Llgal::Config::merge_opts ($generic_opts, Llgal::Config::parse_generic_config_file
			   ($self, "$self->{llgal_config_dir}/$self->{generic_configuration_filename}")) ;
# user-wide configuration file
Llgal::Config::merge_opts ($generic_opts, Llgal::Config::parse_generic_config_file
			   ($self, "$self->{user_share_dir}/$self->{generic_configuration_filename}")) ;

# early configuration ends here
$self->{early_configuration} = 0 ;

# parse cmdline now but DO NOT MERGE now
my $cmdline_opts = Llgal::Config::parse_cmdline_options ($self) ;

# basic special behaviors may be done here
Llgal::Config::die_usage ($self)
    if $self->{help_asked} ;
die "This is llgal version $self->{version}.\n"
    if $self->{version_asked} ;

# the local llgal directory name is now fixed
# we may check the destination directory
check_destination ;

# forward declaration
sub main_process ;

# recursive call, after saving globals
sub subdir_process {
    my $dir = shift ;
    my $subdir_opts = shift ;
    my $subdir_family = shift ;
    $messages->print ("Entering subdirectory '$dir'...\n") ;
    # save context
    my $saved_destination_dir = $self->{destination_dir};
    my $saved_destination_string = $destination_string;
    my $saved_opts = $opts ;
    my $saved_opts_without_defaults = $opts_without_defaults ;
    my $saved_messages = $messages->copy () ;
    $messages->indent () ;
    # setup new gallery context
    $self->{destination_dir} .= $dir."/" ;
    # recursive call
    my $subgallery = main_process $subdir_opts, $subdir_family ;
    # restore context
    $self->{destination_dir} = $saved_destination_dir;
    $destination_string = $saved_destination_string;
    $opts = $saved_opts ;
    $opts_without_defaults = $saved_opts_without_defaults ;
    $messages = $saved_messages ;
    $self->{messages} = $messages ;
    $messages->print ("Leaving subdirectory '$dir'.\n") ;
    print "\n" ;
    return $subgallery ;
}

sub recurse_into_gallery {
    my $gallery = shift ;
    my $opts = shift ;

    # list subdir entries
    my @entries = @{$gallery->{entries}} ;
    # process recursively
    print "\n" if @entries ;
    for (my $i = 0; $i < @entries; $i++) {
	my $entry = $entries[$i] ;
	next if $entry->{type} != $TYPE_DIR ;
	my $prev = $entries[$entry->{prev}] ;
	my $next = $entries[$entry->{next}] ;
	my ($subdir_opts, $subdir_family) = create_subgallery_family $entry, $opts, (scalar @entries), $prev, $next ;
	my $subgallery = subdir_process $entry->{filename}, $subdir_opts, $subdir_family ;
	$entry->{gallery} = $subgallery ;
    }
}

sub main_process {
    my $recursive_opts = shift ;
    my $family = shift ;

    # setup the destination directory
    setup_destination ;

    # add recursive specific opts first, so that they may be locally overridden
    $opts_without_defaults = Llgal::Config::merge_opts_into ($generic_opts, $recursive_opts) ;

    # evaluate gallery specific configuration, without modifying $generic_opts
    Llgal::Config::merge_opts ($opts_without_defaults, Llgal::Config::parse_generic_config_file
			       ($self, "$self->{destination_dir}$self->{local_llgal_dir}/$self->{generic_configuration_filename}")) ;

    # DO NOT MOVE THIS LINE BEFORE CONFIG FILE PARSING
    # parse command line options
    Llgal::Config::merge_opts ($opts_without_defaults, $cmdline_opts) ;

    # set the locale before getting the defaults
    if (defined $opts_without_defaults->{language}) {
	$messages->warning ("The LANGUAGE environment variable ($ENV{LANGUAGE}) overrides your language configuration ($opts_without_defaults->{language}).")
	    if exists $ENV{LANGUAGE} and $ENV{LANGUAGE} ;
	setlocale (LC_ALL, $opts_without_defaults->{language}) ;
    }

    # set defaults values for all uninitialized values
    $opts = Llgal::Config::add_defaults ($opts_without_defaults) ;

    # restore the current locale
    setlocale (LC_ALL, "") ;

    if ($self->{clean_asked} or $self->{cleanall_asked} or $self->{give_templates}) {
	# complex special behaviors that need full configuration, and recurse in all subdirectories

	if ($self->{clean_asked} or $self->{cleanall_asked}) {
	    # clean
	    my $cleanall = shift ;
	    $messages->delay_warnings () ;
	    clean_files $self->{cleanall_asked} ;
	    $messages->show_delayed_warnings () ;

	} elsif ($self->{give_templates}) {
	    # give templates
	    my $destdir = $self->{give_templates} ;
	    $destdir = $self->{local_llgal_dir}
		if $destdir eq "local" ;
	    $destdir = $self->{user_share_dir}
		if $destdir eq "user" ;
	    Llgal::Templates::give_templates ($self, $opts, $destdir) ;
	    $messages->print ("You may now edit templates in $destdir and generate new galleries.\n") ;
	    $messages->print ("You may also remove any template that you do not want to modify.\n") ;
	}

	# recursive in ALL subdirectories
	if ($opts->{recursive}) {
	    # list subdirs
	    opendir DIR, $self->{destination_dir} ? $self->{destination_dir} : "./" ; # destination is empty for './'
	    my @dir_entries = () ;
	    while (my $dir = readdir DIR) {
		push @dir_entries, $dir
		    if $dir =~ m/^[^.]/ and -d "$self->{destination_dir}$dir" ;
	    }
	    closedir DIR ;
	    # process recursively
	    print "\n" if @dir_entries ;
	    map { subdir_process $_, {} } @dir_entries ;
	}

    } elsif ($self->{generate_captions}) {
	# generate captions and recurse in entries only

	Llgal::Config::prepare_captions_variables ($self, $opts) ;

	my $gallery = init_gallery () ;
	my @entries = get_entries $gallery, $opts ;
	@{$gallery->{entries}} = @entries ;
	finalize_entries $gallery, $opts ;
	process_gallery_family $gallery, $family, $opts ;

	generate_captions_entries $gallery, $opts ;

	$messages->print ("Now edit the $self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename} file to your liking and run llgal!\n") ;

	recurse_into_gallery $gallery, $opts
	    if $opts->{recursive} ;

    } else {
	# main gallery creation and recurse in entries only

	Llgal::Config::prepare_gallery_variables ($self, $opts) ;

	my $gallery = init_gallery () ;

	# find the indextemplate
	$gallery->{indextemplate} = (Llgal::Templates::find_template_file ($self, $opts, $opts->{indextemplate_filename}, 1))
	    . "/$opts->{indextemplate_filename}" ;
	$messages->print ("Using '".$gallery->{indextemplate}."' as HTML index template.\n") ;

	if (!$opts->{make_no_slides}) {
	    # find the slidetemplate
	    my $slidetemplate = (Llgal::Templates::find_template_file ($self, $opts, $opts->{slidetemplate_filename}, 1))
		. "/$opts->{slidetemplate_filename}" ;
	    $messages->print ("Using '$slidetemplate' as HTML slide template.\n") ;

	    # keep the slidetemplate in memory instead of always reopening it
	    open(SR,"$slidetemplate")
		or die "Can't open the slide template file '$slidetemplate' ($!).\n" ;
	    @{$gallery->{slidetemplate_text}} = <SR> ;
	    close SR ;

	    # list Exif tags needed by the template.
	    # only one pattern per line is detected, other are ignored.
	    foreach my $line (@{$gallery->{slidetemplate_text}}) {
		if ($line =~ /<!--EXIF-(.*)-->/) {
		    if ($1 ne "TABLE") { # TABLE is llgal-reserved, unused in EXIF
			push (@{$gallery->{template_exif_tags_list}}, $1);
		    }
		}
	    }
	}

	if (-e "$self->{destination_dir}$self->{local_llgal_dir}/$opts->{captions_filename}") {
	    # generate the gallery using the caption file
	    read_captions_file $gallery ;
	    fill_entries $gallery ;
	    $messages->print ("Found ". (scalar @{$gallery->{entries}}) ." entries in the captions file.\n") ;
	} else {
	    # generate the gallery from scratch
	    @{$gallery->{entries}} = get_entries $gallery, $opts ;
	    fill_entries $gallery ;
	    $messages->print ("Found ". (scalar @{$gallery->{entries}}) ." entries in $destination_string\n") ;
	}

	finalize_entries $gallery, $opts ;

	process_gallery_family $gallery, $family, $opts ;

	add_headers_footers $gallery ;

	precompute_common_html_fields $gallery ;

	if ($opts->{make_no_slides}) {
	    $messages->print ("Linking thumbnails directly to image files...  Making no html slides.\n") ;
	} else {
	    generate_slides $gallery ;
	}

	generate_index $gallery ;

	Llgal::Templates::get_llgal_files ($self, $opts) ;

	$messages->delay_warnings () ;
	make_www_rights $gallery, $opts
	    if $opts->{www_access_rights} ;
	$messages->show_delayed_warnings () ;

	# generate a local config for this gallery
	if (defined $self->{generate_config} and $self->{generate_config} eq "local") {
	    Llgal::Config::generate_config ($self, "$self->{destination_dir}$self->{local_llgal_dir}/$self->{generic_configuration_filename}", $opts_without_defaults) ;
	}

	recurse_into_gallery $gallery, $opts
	    if $opts->{recursive} ;

	return $gallery ;
    }
}

# generate main gallery
my $root_gallery = main_process {}, {} ;

# only generate a config once
if (defined $self->{generate_config} and not $self->{generate_config} eq "local") {
    Llgal::Config::generate_config ($self, $self->{generate_config}, $opts_without_defaults) ;
}

# Indent style for emacs
# Local Variables:
# perl-indent-level: 4
# tab-width: 8
# indent-tabs-mode: t
# End: