summaryrefslogtreecommitdiffabout
path: root/renrot
blob: ad7ea13ac8e3cc7a16df39c61ecd62c10e82f171 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
#!/usr/bin/env perl

#
# vim: ts=2 sw=2 et :
#

# Analyze crash in third-party modules
# (Recipe has been borrowed from http://ilya-dogolazky.livejournal.com/15061.html)
BEGIN { $| = 1; $SIG{__DIE__} = sub { use Carp; confess $_[0] . 'Aborted' } }

use strict;
use warnings;
use diagnostics;
require 5.006;
use Pod::Usage;
use Image::ExifTool;
use Getopt::Long;
use File::Spec;
use File::Basename;

# add our 'lib' directory to the include list
my $exeDir;
BEGIN {
  $exeDir = ($0 =~ /(.*)[\\\/]/) ? $1 : '.';  # get exe directory
  unshift @INC, "$exeDir/lib";                # add lib directory at start of include path
}

use Image::RenRot::Util;
use Image::RenRot::Logging;
use Image::RenRot::Config;
use Image::RenRot::TimeUtil;
use Image::RenRot::FileUtil;

# perl 5.8.x memory overflow workaround (perl5.8.1-8 which uses it's own malloc)
my $mem_trouble_stub = " "x4_000_000; undef $mem_trouble_stub;

# Versioning
my @svnrevision = split(/ /, '$Revision$');
our $VERSION = '1.1.0';
our $REVISION = defined $svnrevision[1] ? $svnrevision[1] : '0';

my $maxVerbosity = 4;                                         # our max verbosity level (internal)
my $homeURL = 'http://puszcza.gnu.org.ua/projects/renrot/';   # homepage of the project

########################################################################################
#
# The global definition for a new XMP namespace. The
# %Image::ExifTool::UserDefined::RenRot defines XMP-RenRot tags which could be
# added to mark the file as processed with RenRot.
#
if (%Image::ExifTool::UserDefined::RenRot) {
  die_renrot("Won't redefine Image::ExifTool::UserDefined::RenRot.\n");
}

%Image::ExifTool::UserDefined::RenRot = (
    GROUPS => { 0 => 'XMP', 1 => 'RenRot', 2 => 'Image' },
    NAMESPACE => [ 'RenRot' => $homeURL ],
    WRITABLE => 'string',
    RenRotFileNameOriginal => { },
    RenRotProcessingTimestamp => { },
    RenRotVersion => { },
    RenRotURL => { },
);

# The %Image::ExifTool::UserDefined hash defines new tags to be added to
# existing tables.
%Image::ExifTool::UserDefined = (
  # new XMP namespaces must be added to the Main XMP table
  'Image::ExifTool::XMP::Main' => {
    RenRot => {
      SubDirectory => {
        TagTable => 'Image::ExifTool::UserDefined::RenRot',
      },
    },
  },
);

########################################################################################
#
# Parsed configuration file in hash
# Note: unfortunately we still need manual adaptation in getOptions()
#
my $co_aggr = {
  # aggregation time delta in seconds (file with delta > $delta is placed in new DIR)
  'delta'     => { type => 'i', default => 900 },
  # counterless directory name for "delta" type aggregation
  'directory' => { type => 's', default => 'Images' },
  # aggregation framework
  'enabled'   => { type => '!', default => 0},
  # define aggregation mode, possible values are: none, delta or template
  'mode'      => { type => 's', default => 'none' },
  # template for the files aggregation taken from CLI
  'template'  => { type => 's', default => '%Y%m%d' },
  # flag to do links instead real file moving while aggregation
  'virtual'   => { type => '!', default => 0 },
};

my $co_cs = {
  # background, look ImageMagick documentation for montage options
  'background'  => { type => 's', default => 'FFF' },
  # bordercolor, look ImageMagick documentation for montage options
  'bordercolor' => { type => 's', default => 'DDD' },
  # tmp directory for the montage operations
  'dir'         => { type => 's', default => 'Contact.Sheet' },
  # contact sheet generation
  'enabled'     => { type => '!', default => 0 },
  # file name for the montage
  'file'        => { type => 's', default => 'cs-%c.jpg' },
  # fill, look ImageMagick documentation for montage options
  'fill'        => { type => 's', default => '000' },
  # font, look ImageMagick documentation for montage options
  'font'        => { type => 's', default => 'Helvetica' },
  # frame, look ImageMagick documentation for montage options
  'frame'       => { type => 's', default => '3' },
  # label, look ImageMagick documentation for montage options
  'label'       => { type => 's', default => '%t' },
  # mattecolor, look ImageMagick documentation for montage options
  'mattecolor'  => { type => 's', default => 'CCC' },
  # pointsize, look ImageMagick documentation for montage options
  'pointsize'   => { type => 's', default => '11' },
  # ranking
  'rank'        => { type => '!', default => 0 },
  # file with images ranks
  'rank file'   => { type => 's', default => '.rank' },
  # shadow, look ImageMagick documentation for montage options
  'shadow'      => { type => '!', default => 1 },
  # is $extToProcess files are the thumbnails?
  'thm'         => { type => '!', default => 0 },
  # font, look ImageMagick documentation for montage options
  'thm font'    => { type => 's', default => 'Helvetica' },
  # fill, look ImageMagick documentation for montage options
  'thm fill'    => { type => 's', default => 'gray34' },
  # thumbnail background gradient from
  'thm grad fr' => { type => 's', default => 'FFFFFF' },
  # thumbnail background gradient to
  'thm grad to' => { type => 's', default => '909090' },
  # thumbnail text
  'thm text'    => { type => 's', default => "thumbnail\n\nNA" },
  # tile in the montage
  'tile'        => { type => 's', default => '7x5' },
  # title for the montage
  'title'       => { type => 's', default => 'Default Contact Sheet Title' },
};

my $co_g = {
  'generate thumbnail size' => { type => 's', default => '160x120' },
  # mtime taken from CLI
  'mtime'                   => { type => '!', default => 1 },
  # template for the filename taken from CLI
  'name template'           => { type => 's', default => '%Y%m%d%H%M%S' },
  # jpegtran -trim
  'trim'                    => { type => '!', default => 1 },
  # colorized output
  'use color'               => { type => '!', default => 0 },
  # rotate thumbnail via pipe
  'use ipc'                 => { type => '!', default => 0 },
};

my $co_kw = {
  # whether or not to fill Keywords tag
  'enabled' => { type => '!', default => 0 },
  # file with keyword set
  'file'    => { type => 's', default => '.keywords' },
  # whether to add keywords to the existent ones or replace them
  'replace' => { type => '!', default => 0 },
};

my $config_opts = {
  'aggregation'     => $co_aggr,
  'contact sheet'   => $co_cs,
  'general'         => $co_g,
  'keywords'        => $co_kw,
};

########################################################################################
#
# Command line options
#
my $backup = 1;		# make or not a backup of the original files
my $comfile;		# file with commentary
my $configFile;		# configuration file

my $countFF = 1;	# use fixed field for counter
my $countStart = 1;	# Start value for counter
my $countStep = 1;	# Step for counter
my $dryRun = 0;		# show what would have been happened
my @excludeList = ();	# files that will be excluded from list
my $extToProcess = '';	# the extension of files to work with
my $gen_thm = 0;	# to not to generate ThumbnailImage if empty

my $noRename = 0;	# no rename needed, default is to rename to the YYYYmmddHHMMSS.ext
my $noRotation = 0;	# no rotation needed, default is to rotate
my $noTags = 0;		# no tags writing needed
my $noRenRoTagMtm = 0;	# no rename, no rotate, no tag and no mtime have to be done
my $orientTag = 0;	# rotate by changing Orientation tag (no real rotation)
my $quiet = 0;		# suppressing messages
my $rotateAngle;	# define the angle to rotate on 90, 180 or 270
my $rotateThumbnail;	# define the angle to rotate on 90, 180 or 270
my $subFileSet = '';	# subset of files to process, given in file rather than in commandline
my %tagsFromCli = ();	# tags are got from CLI
my @tag_to_name = ();	# tags for name building, theirs values to be used (in theory any EXIF)
my $userComment;	# text to put into UserComment tag
my $verbose = 0;	# verbosity of output
my $workDir = './';	# we'll work ONLY in current directory
my $isThereIM = 0;	# is there Image::Magick package?

########################################################################################
#
# Tags hash for injecting to EXIFs when renaming
#
my %tags = (
  'RenRotProcessingTimestamp' => {
    value => now(),
    group => 'RenRot',
  },
  'RenRotVersion' => {
    value => $VERSION . " (r" . $REVISION . ")",
    group => 'RenRot',
  },
  'RenRotURL' => {
    value => $homeURL,
    group => 'RenRot',
  },
); # define tags for filling

########################################################################################
#
# Global variables (internal)
#
my @rotparms = (
  '',
  '-flip horizontal',
  '-rotate 180',
  '-flip vertical',
  '-transpose',
  '-rotate 90',
  '-transverse',
  '-rotate 270',
); # jpegtran options array to rotate the file

my @angles = (
  '',
  'fh',
  '180cw',
  'fv',
  'tp',
  '90cw',
  'tv',
  '270cw',
); # the array of suffixes to add to the newfilename after rotating

my %rotangles = (
  '90' => '-rotate 90',
  '180' => '-rotate 180',
  '270' => '-rotate 270'
); # array of options to rotate file "by hands"

my %rotorient = (
  1 => 0,
  6 => 90,
  3 => 180,
  8 => 270,
);

my %rotorientrev = reverse %rotorient;

my @multOpts = (
  'color',
  'include',
  'tag',
  'tagfile',
);

my @files = ();		# array of the sorted filenames to process
my %filenameshash = ();	# hash for old file names

########################################################################################
###                         GETTINNG OPTIONS FROM CLI                                ###
########################################################################################

########################################################################################
# Usage      : getOptions(...)
# Purpose    : parses command line arguments
# Returns    : nothing
# Parameters : many of them, look bellow
# Throws     : no exceptions
# Comments   : none
# See Also   : Getopt::Long GetOptions()
sub getOptions {
  my @tmpTags = ();

  # For 'aggregation'
  my $s_aggr_opts;
  my %h_aggr_opts;

  # For 'contact sheet'
  my $s_cs_opts;
  my %h_cs_opts;

  # For 'general'
  my %h_g_opts;

  # For 'keywords'
  my $s_kw_opts;
  my %h_kw_opts;

  my $ll_opts = {
    'aggregation'   => { 's' => \$s_aggr_opts, 'h' => \%h_aggr_opts },
    'contact sheet' => { 's' => \$s_cs_opts,   'h' => \%h_cs_opts },
    'keywords'      => { 's' => \$s_kw_opts,   'h' => \%h_kw_opts },
  };

  GetOptions (
      # AGGREGATION
      "aggr-opts=s"       => \$s_aggr_opts,
      "aggr-delta=i"      => \$h_aggr_opts{'delta'},
      "aggr-directory=s"  => \$h_aggr_opts{'directory'},
      "aggr-mode=s"       => \$h_aggr_opts{'mode'},
      "aggr-template|a=s" => \$h_aggr_opts{'template'},
      "aggr-virtual!"     => \$h_aggr_opts{'virtual'},

      # CONTACT SHEET
      "contact-sheet-opts|cs-opts=s"           => \$s_cs_opts,
      "contact-sheet-bg|cs-bg=s"               => \$h_cs_opts{'background'},
      "contact-sheet-bd|cs-bd=s"               => \$h_cs_opts{'bordercolor'},
      "contact-sheet-dir|cs-dir=s"             => \$h_cs_opts{'dir'},
      "contact-sheet|cs!"                      => \$h_cs_opts{'enabled'},
      "contact-sheet-file|cs-file=s"           => \$h_cs_opts{'file'},
      "contact-sheet-fl|cs-fl=s"               => \$h_cs_opts{'fill'},
      "contact-sheet-fn|cs-fn=s"               => \$h_cs_opts{'font'},
      "contact-sheet-fr|cs-fr=s"               => \$h_cs_opts{'frame'},
      "contact-sheet-lb|cs-lb=s"               => \$h_cs_opts{'label'},
      "contact-sheet-mt|cs-mt=s"               => \$h_cs_opts{'mattecolor'},
      "contact-sheet-pntsz|cs-pntsz=i"         => \$h_cs_opts{'pointsize'},
      "contact-sheet-rank|cs-rank!"            => \$h_cs_opts{'rank'},
      "contact-sheet-rank-file|cs-rank-file=s" => \$h_cs_opts{'rank file'},
      "contact-sheet-shadow|cs-shadow"         => \$h_cs_opts{'shadow'},
      "contact-sheet-thm|cs-thm"               => \$h_cs_opts{'thm'},
      "contact-sheet-thm-fl|cs-thm-fl=s"       => \$h_cs_opts{'thm fill'},
      "contact-sheet-thm-fn|cs-thm-fn=s"       => \$h_cs_opts{'thm font'},
      "contact-sheet-thm-grfr|cs-thm-grfr=s"   => \$h_cs_opts{'thm grad fr'},
      "contact-sheet-thm-grto|cs-thm-grto=s"   => \$h_cs_opts{'thm grad to'},
      "contact-sheet-thm-text|cs-thm-text=s"   => \$h_cs_opts{'thm text'},
      "contact-sheet-tile|cs-tile=s"           => \$h_cs_opts{'tile'},
      "contact-sheet-title|cs-title=s"         => \$h_cs_opts{'title'},

      # GENERAL
      "mtime!"               => \$h_g_opts{'mtime'},
      "name-template|n=s"    => \$h_g_opts{'name template'},
      "trim!"                => \$h_g_opts{'trim'},
      "use-color!"           => \$h_g_opts{'use color'},
      "use-ipc!"             => \$h_g_opts{'use ipc'},

      # KEYWORDIZER
      "kw-opts=s"         => \$s_kw_opts,
      "keywords!"         => \$h_kw_opts{'enabled'},
      "keywords-file|k=s" => \$h_kw_opts{'file'},
      "keywords-replace!" => \$h_kw_opts{'replace'},

      # RENAMIMG
      "counter-fixed-field!" => \$countFF,
      "counter-start=i"      => \$countStart,
      "counter-step=i"       => \$countStep,
      "no-rename|norename"   => \$noRename,

      # ROTATIMG
      "no-rotate|norotate"   => \$noRotation,
      "only-orientation"     => \$orientTag,
      "rotate-angle|r=i"     => \$rotateAngle,
      "rotate-thumb=i"       => \$rotateThumbnail,

      # TAG WRITER
      "comment-file=s"       => \$comfile,
      "no-tags|notags"       => \$noTags,
      "tag|t=s"              => \@tmpTags,
      "user-comment=s"       => \$userComment,

      # OTHERS
      "backup!"              => \$backup,
      "config-file|c=s"      => \$configFile,
      "dry-run"              => \$dryRun,
      "exclude=s"            => \@excludeList,
      "extension|e=s"        => \$extToProcess,
      "generate-thumb|g"     => \$gen_thm,
      "help|?"               => sub { usage(0, 2) },
      "no-renrot|nochg"      => \$noRenRoTagMtm,
      "quiet|q"              => \$quiet,
      "sub-fileset=s"        => \$subFileSet,
      "v+"                   => \$verbose,
      "version"              => sub { usage(0, 0) },
      "work-directory|d=s"   => \$workDir,
  ) or usage(1, 1);

  # Set the verbosity first
  Image::RenRot::Logging->set(Verbose => $quiet ? -1 : $verbose);

  my $fileCount = scalar(@ARGV);

  foreach my $key (keys %$ll_opts) {
    # Parse long list option
    if (defined ${$ll_opts->{$key}{'s'}}) {
      update_cfg_value($config_opts->{$key}{'enabled'}, 1);
      parse2hash(${$ll_opts->{$key}{'s'}}, $config_opts, $key);
    }
    # Override long list option by set of standalone ones before any other action
    assign2hash($config_opts, $key, $ll_opts->{$key}{'h'});
    # Debug result
    ldbg3opts($config_opts, $key);
  }

  # For 'general' section
  assign2hash($config_opts, 'general', \%h_g_opts);
  ldbg3opts($config_opts, 'general');

  ldbg3("--backup: ", bool2str($backup));
  ldbg3("--comment-file: $comfile") if (defined $comfile);
  ldbg3("--config-file: $configFile") if (defined $configFile);

  ldbg3("--counter-start: $countStart",
    "   --counter-step: $countStep",
    "   --counter-fixed-field: ", bool2str($countFF));
  ldbg3("--dry-run: ", bool2str($dryRun)) if (defined $dryRun);
  ldbg3("--exclude:\n", join("\n", @excludeList)) if (scalar(@excludeList) > 0);
  ldbg3("--extension: '$extToProcess'");
  ldbg3("--generate-thumb: ", bool2str($gen_thm));

  ldbg3("--no-rename: ", bool2str($noRename),
    "   --no-rotate: ", bool2str($noRotation),
    "   --no-tags: ", bool2str($noTags),
    "   --no-renrot: ", bool2str($noRenRoTagMtm));
  ldbg3("--only-orientation: ", bool2str($orientTag));
  ldbg3("--rotate-angle: $rotateAngle") if (defined $rotateAngle);
  ldbg3("--rotate-thumb: $rotateThumbnail") if (defined $rotateThumbnail);
  ldbg3("--sub-fileset: $subFileSet") if ($subFileSet ne "");
  ldbg3("--tag:\n", join("\n", @tmpTags)) if (scalar(@tmpTags) > 0);
  ldbg3("--work-directory: $workDir");
  ldbg3("ARGV:\n", join("\n", @ARGV)) if ($fileCount > 0);

  if ($extToProcess eq "" and ($fileCount == 0) and $subFileSet eq "") {
    fatalmsg ("Extension of files is required!\n");
    exit 1;
  }

  if ($extToProcess ne "" and ($fileCount != 0)) {
    warnmsg ("Extension of files will be ignored!\n");
  }

  if ($noRenRoTagMtm != 0) {
    $noRename = $noRotation = $noTags = 1;
    update_cfg_value($config_opts->{'general'}{'mtime'}, 0);
  }

  # is there ImageMagick?
  if ($isThereIM == 1) {
    dbgmsg (1, "We have Image::Magick package and could proceed with --contact-sheet related functionality.\n");
  } elsif (get_cfg_value($co_cs, 'enabled') == 1) {
    errmsg ("To use --contact-sheet related functionality you need Image::Magick package!\n",
            "Contact Sheet generation disabled.\n");
  } elsif ($gen_thm != 0) {
    errmsg ("To use --generate-thumb functionality you need Image::Magick package!\n",
            "ThumbnailImage generation is disabled.\n");
  }

  # preparing Software tag according the usage or not of ImageMagick
  if ($isThereIM == 1) {
    my ($imName, $imVersion) = (split(/ /, Image::Magick->new()->Get('version')))[0,1];
    $tags{'Software'}{'value'} = sprintf("RenRot v%s (r%s), ExifTool v%s, %s v%s", $VERSION, $REVISION, $Image::ExifTool::VERSION, $imName, $imVersion);
  } else {
    $tags{'Software'}{'value'} = sprintf("ExifTool v%s, RenRot v%s (r%s)", $Image::ExifTool::VERSION, $VERSION, $REVISION);
  }
  $tags{'Software'}{'group'} = 'EXIF';

  # Change user's parameter '*.ext' or 'ext' to '.ext'
  $extToProcess =~ s/^\*?\.?/\./ if ($fileCount == 0);
  dbgmsg (1, "Process with '$extToProcess' extension.\n");

  # Convert multiple tag parameters to tags hash
  foreach my $tagStr (@tmpTags) {
    my %tag = str2hash($tagStr);
    map { $tagsFromCli{$_} = $tag{$_} } keys %tag;
  }
}

########################################################################################
#
# parseConfig() parses user's or standart configuration files to hash
#
sub parseConfig {
  my $file = shift;
  my $hash = shift;

  my @sections = keys %$hash;
  Image::RenRot::Config->init(Sections => \@sections, MultiOptions => \@multOpts);

  return Image::RenRot::Config->parsefile($file, $hash) if (defined $file);

  my $home = $ENV{"HOME"};
  my @homeRC = ();
  $home = $ENV{"USERPROFILE"} if (not defined $home);

  if (defined $home and $home ne "") {
    push (@homeRC, File::Spec->catfile($home, ".renrotrc"));
    push (@homeRC, File::Spec->catfile($home, ".renrot", ".renrotrc"));
    push (@homeRC, File::Spec->catfile($home, ".renrot", "renrot.conf"));
  } else {
    warnmsg ("User's home environment variable isn't defined or empty!\n");
  }

  my @rcFiles = (
      "/etc/renrot.rc",
      "/etc/renrot/renrot.rc",
      "/etc/renrot/renrot.conf",
      "/usr/local/etc/renrot.rc",
      "/usr/local/etc/renrot/renrot.rc",
      "/usr/local/etc/renrot/renrot.conf",
      @homeRC,
  );

  map { Image::RenRot::Config->parsefile($_, $hash) } @rcFiles;
}

########################################################################################
#
# switchColor() switches to user defined color scheme
#
sub switchColor {
  my $colors = ();

  # Parse configuration file color set
  while (my ($cKey, $v) = each %$config_opts) {
    next if ($cKey !~ m/^color#\d+#\d+$/);	# skip not a color
    my ($ck, $ch) = str2hash($v, 'reset');
    $colors->{$ck} = $ch;
  }
  Image::RenRot::Logging->set(Color => $colors,
                              UseColor => get_cfg_value($co_g, 'use color'));
  dbgmsg (1, "Switch to user defined color scheme.\n");
}

########################################################################################
# Usage      : keywordizer($keywords_file)
# Purpose    : validates keywords
# Returns    : [array of strings] @results with CR and LF symbols removed
# Parameters : [string] $keywords_file
# Throws     : no exceptions
# Comments   : none
# See Also   : N/A
sub keywordizer {
  my $file = shift;			# keywords file
  return if (not (-R $file and -f $file and -T $file));
  dbgmsg (2, "Reading keywords from file: $file\n");
  my @result = ();
  my @keywordArr = Image::RenRot::FileUtil->getFileDataLines($file);
  for (my $i = 0; $i < scalar(@keywordArr); $i++) {
    $keywordArr[$i] =~ s/\r?\n$//;	# remove CR and LF symbols
    push (@result, trim($keywordArr[$i])) if ($keywordArr[$i] !~ m/^\s*$/);
  }
  return @result;
}

########################################################################################
# Usage      : renRotProcess($exif_tool_obj, $counter_size)
# Purpose    : renames and rotates given file set
# Returns    : nothing
# Parameters : $exif_tool_obj [ref]
#            : $counter_size  [num] file name counter digit capacity (number of digits in
#            :                      counter. for tens it is 2, for thousands - 4, e.t.c.)
# Throws     : no exceptions
# Comments   : none
# See Also   : N/A
sub renRotProcess {
  my $exifToolObj = shift;
  my $counterSize = shift;
  my $fileCounter = $countStart;# file counter
  my $newFileName;		# the name file to be renamed to
  my $info;			# ImageInfo object
  my @keywordArr = ();		# array for keywords

  if (get_cfg_value($co_kw, 'enabled') != 0) {
    @keywordArr = keywordizer (get_cfg_value($co_kw, 'file'));
    errmsg ("Keywords file doesn't exist!\n") if (not -e get_cfg_value($co_kw, 'file'));
  }

  if (scalar(@keywordArr) > 0) {
    dbgmsg (2, "Keywords count: ", scalar(@keywordArr), "\n");
    if (get_cfg_value($co_kw, 'replace') != 0) {
      $exifToolObj->SetNewValue(Keywords => \@keywordArr);
    } else {
      $exifToolObj->SetNewValue(Keywords => \@keywordArr, AddValue => 1);
    }
  }

  # Convert trim boolean value to string
  my $trimStr = get_cfg_value($co_g, 'trim') ? '-trim' : '';
  dbgmsg (1, "Trim string: '$trimStr'\n");

  dbgmsg (1, "Initializing tags...\n");
  foreach my $key (sort (keys %tags)) {
    $exifToolObj->SetNewValue($key, $tags{$key}{value}, Group => $tags{$key}{group});
  }

  procmsg ("RENAMING / ROTATING\n");
  procmsg ("===================\n");

  my $file_num = scalar(@files);
  my $file_rem = 0;
  foreach my $file (@files) {
    $file_rem++;
    procmsg ("Processing file: ($file_rem of $file_num) $file...\n");

    # Setup defaults
    $info = $exifToolObj->ImageInfo($file);

    # analyzing whether to rotate
    my $angleSuffix = rotateFile($exifToolObj, $info, $file, $trimStr);

    # generating absent ThumbnailImage tag from the original image
    if (($isThereIM == 1) and ($gen_thm != 0) and not defined ${$$info{ThumbnailImage}}) {
      thm_gen_orig($file, 1);
    }

    # analyzing whether and how to rename file
    $newFileName = renameFile($exifToolObj, $info, $file, $fileCounter, $counterSize, $angleSuffix);

    # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file
    saveOurHdrs($exifToolObj, $info, $file);

    # Writing tags.
    tagWriter($exifToolObj, $newFileName) if ($noTags == 0);

    # seting mtime for the file if been asked for
    mtimeSet($exifToolObj, $info, $newFileName);

    procmsg ("\n");

    $fileCounter += $countStep;
  }
}

########################################################################################
# Usage      : saveOurHdrs($exif_tool_obj, $info_obj, $file)
# Purpose    : saves native RenRot defined tags to file EXIF
# Returns    : nothing
# Parameters : $exif_tool_obj [ref]
#            : $info_obj      [ref]
#            : $file          [str]
# Throws     : no exceptions
# Comments   : none
# See Also   : N/A
sub saveOurHdrs {
  my $exifToolObj = shift;
  my $infoObj = shift;
  my $file = shift;

  my $fileNameOriginal = $exifToolObj->GetValue("RenRotFileNameOriginal");

  if (not defined $fileNameOriginal) {
    $tags{'RenRotFileNameOriginal'} = {value => $file, group => 'RenRot'};
    dbgmsg (2, "Set RenRotFileNameOriginal to $file.\n");
  } else {
    $tags{'RenRotFileNameOriginal'} = {
              value => $infoObj->{"RenRotFileNameOriginal"},
              group => 'RenRot'
    };
    dbgmsg (2, "RenRotFileNameOriginal: $fileNameOriginal.\n");
  }

  $exifToolObj->SetNewValue("RenRotFileNameOriginal", $tags{'RenRotFileNameOriginal'}{value}, Group => $tags{'RenRotFileNameOriginal'}{group});
}

########################################################################################
#
# rotateFile() rotates file and its thumbnail if needed, changes Orientation tag
#
sub rotateFile {
  my $exifToolObj = shift;
  my $infoObj = shift;
  my $file = shift;
  my $trimStr = shift;
  my $orientation = $exifToolObj->GetValue("Orientation", 'ValueConv');
  my $angleSuffix = "0cw";

  if ($noRotation != 0) { dbgmsg (2, "No rotation asked, file orientation is left untouched.\n"); }
  elsif (defined $rotateAngle) {
    dbgmsg (2, "We'll deal with: $file and $rotangles{$rotateAngle}.\n");
    if ($orientTag != 0) {
      rotateOrient($exifToolObj, $file, $orientation);
    } else {
      rotateImg($file, $rotangles{$rotateAngle}, $trimStr);
      rotateThumbnail($infoObj, $file, $rotangles{$rotateAngle}, $trimStr);
    }
    $angleSuffix = $rotateAngle . "cw";
  } elsif (defined $rotateThumbnail) {
    rotateThumbnail($infoObj, $file, $rotangles{$rotateThumbnail}, $trimStr);
  } else {
    if (defined $orientation) {
      if ($orientation > 1) {
        rotateImg($file, $rotparms[$orientation - 1], $trimStr);
        rotateThumbnail($infoObj, $file, $rotparms[$orientation - 1], $trimStr);
        $angleSuffix = $angles[$orientation - 1];
      } elsif ($orientation == 1) {
        dbgmsg (2, "No need to rotate, orientation is: Horizontal (normal).\n");
      }
      else {
        errmsg ("Something wrong, orientation low than 1: $orientation.\n");
      }
    } else {
      warnmsg ("Orientation tag is absent!\n");
    }
  }
  return $angleSuffix;
}

########################################################################################
#
# renameFile() renames file according to user request and EXIF data
#
sub renameFile {
  my $exifToolObj = shift;
  my $infoObj = shift;
  my $file = shift;
  my $fileCounter = shift;
  my $counterSize = shift;
  my $angleSuffix = shift;
  my $newFileName;
  my $unixTime = get_unix_time(getTimestamp($exifToolObj, $infoObj));

  if ($noRename != 0) {
    dbgmsg (2, "No renaming asked, filename is left untouched.\n");
    $newFileName = $file;
    $filenameshash{$newFileName} = $unixTime;
  } else {
    $newFileName = template2name (
        $exifToolObj,
        $infoObj,
        get_cfg_value($co_g, 'name template'),
        $fileCounter,
        $file,
        $counterSize,
        $angleSuffix
    );

    my $ext = "." . (splitext($file))[1];

    $newFileName .= "." . sprintf($counterSize, $fileCounter) if ($filenameshash{$newFileName . $ext});

    $newFileName .= $ext;

    $filenameshash{$newFileName} = $unixTime;

    if ($file ne $newFileName) {
      if (-f $newFileName) {
        die_renrot("File $newFileName already exists!\n");
      }
      if ($dryRun == 0) {
        rename ($file, $newFileName) || die_renrot("Unable to rename $file -> $newFileName.\n");
      }
      procmsg ("Renamed: $file -> $newFileName\n");
    } else { warnmsg ("No renaming needed for $newFileName, it looks as needed!\n"); }
  }
  return $newFileName;
}

########################################################################################
#
# mtimeSet() sets mtime for the given file
#
sub mtimeSet {
  my $exifToolObj = shift;
  my $infoObj = shift;
  my $file = shift;
  if (get_cfg_value($co_g, 'mtime') != 0) {
    my $mTime = get_unix_time(getTimestamp($exifToolObj, $infoObj));
    if ($dryRun == 0) { utime $mTime, $mTime, $file; }
    else { procmsg ("Setting mtime.\n"); }
    dbgmsg (2, "Changing mtime for $file OK.\n");
  }
}

########################################################################################
#
# tagWriter() writes couple of tags defined via configuration file and command line
#
sub tagWriter {
  my $exifToolObj = shift;
  my $file = shift;

  # writing the changes to the EXIFs
  if ($dryRun == 0) { exifWriter($exifToolObj, $file); }
  else { procmsg ("Writing user defined EXIF tags to $file.\n"); }
}

########################################################################################
#
# exifWriter() applies EXIF info, set by SetNewValue, to the image taken from
# the file, and writes the result to the same file.
#
sub exifWriter {
  my $exifToolObject = shift;
  my $fileRes = shift;		# the file the *image* taken from

  my $result = $exifToolObject->WriteInfo($fileRes);
  if ($result == 1) {
    dbgmsg (2, "Writing to $fileRes seems to be OK.\n");
  } elsif ($result == 2) {
    warnmsg ("No EXIF difference. No EXIF was written.\n");
  } else {
    my $errorMessage   = $exifToolObject->GetValue('Error');
    my $warningMessage = $exifToolObject->GetValue('Warning');
    if (defined $errorMessage) { errmsg ("ExifTool: $errorMessage\n"); }
    if (defined $warningMessage) { warnmsg ("ExifTool: $warningMessage\n"); }
  }
  return $result;
}

########################################################################################
###                           AGGREGATION FRAMEWORK                                  ###
########################################################################################

########################################################################################
#
# aggregationProcess() aggregates files to separate directories by request
#
sub aggregationProcess {
  return if (get_cfg_value($co_aggr, 'mode') eq "none");

  my $exifToolObj = shift;
  my $counterSize = shift;
  my $file;
  my $info;
  my $BaseDir = get_cfg_value($co_aggr, 'directory');
  my $NewDir;
  my $file_num = scalar(keys(%filenameshash));
  my $file_rem = 0;

  procmsg ("AGGREGATION\n");
  procmsg ("===========\n");

  makedir($BaseDir) if ($dryRun == 0);

  if (get_cfg_value($co_aggr, 'mode') eq "template") {
    dbgmsg (1, "Template: ", get_cfg_value($co_aggr, 'template'), "\n");
    my $fileCounter = $countStart;

    foreach $file (sort (keys %filenameshash)) {
      $file_rem++;
      $info = $exifToolObj->ImageInfo($file);
      $NewDir = template2name (
          $exifToolObj,
          $info,
          get_cfg_value($co_aggr, 'template'),
          $fileCounter,
          $file,
          $counterSize,
          "0cw"
      );
      $NewDir = File::Spec->catdir($BaseDir, $NewDir);
      aggregateFile($file, $NewDir) if ($dryRun == 0);
      procmsg ("Aggregate: ($file_rem of $file_num) $file -> $NewDir\n", "\n");
      $fileCounter += $countStep;
    }
  } elsif (get_cfg_value($co_aggr, 'mode') eq "delta") {
    my $DirCounter = 1;
    my $timestampPrev;
    my $filePrev;
    my $filetmp;

    foreach $file (sort (keys %filenameshash)) {
      $filetmp = $file;
      $file_rem++;

      if ($DirCounter == 1) {
        $timestampPrev = $filenameshash{$filetmp};
        $filePrev = $filetmp;
        $NewDir = $BaseDir . "." . sprintf($counterSize, $DirCounter);
        $DirCounter++;
        aggregateFile($file, $NewDir) if ($dryRun == 0);
      } else {
        # Check for new direcroty creation
        if (($filenameshash{$filetmp} - $timestampPrev) > get_cfg_value($co_aggr, 'delta')) {
          $NewDir = $BaseDir . "." . sprintf($counterSize, $DirCounter);
          $DirCounter++;
        }
        aggregateFile($file, $NewDir) if ($dryRun == 0);
        $timestampPrev = $filenameshash{$filetmp};
      }
      procmsg ("Aggregate: ($file_rem of $file_num) $file -> $NewDir\n", "\n");
    }
  } else {
    errmsg ("Aggregation mode ", get_cfg_value($co_aggr, 'mode'), " isn't implemented!\n");
  }
}

########################################################################################
# Usage      : contactSheetGenerator();
# Purpose    : builds contact sheet(s)
# Returns    : none
# Parameters : $exifTool ref    -
# Throws     : no exceptions
# Comments   : requires --ext; --counter-start is valid
# See Also   : template2name()
sub contactSheetGenerator {
  return if (not get_cfg_value($co_cs, 'enabled'));

  use File::Copy;

  my $exifToolObj = shift;
  my $workdir = get_cfg_value($co_cs, 'dir');
  my $file;
  my $info;
  my $infothm;
  my $ThumbnailOriginal;
  my $width;
  my $height;
  my $size = 0;
  my @thumbnailes = ();
  my @thumbnailes_sorted = ();
  my $orientation;
  my $filefull;
  my $ranks;              # reference to the hash of files ranks

  # ranks file processing
  if (get_cfg_value($co_cs, 'rank') == 1 and -f get_cfg_value($co_cs, 'rank file')) {
    $ranks = Image::RenRot::FileUtil->getFileDatLns(get_cfg_value($co_cs, 'rank file'));
    if ($ranks != 0) {
      dbgmsg (3, "Ranks successfully processed.\n");
    } else {
      errmsg ("Ranks processing failed.\n");
    }
  }

  makedir($workdir) if ($dryRun == 0);

  procmsg ("CONTACT SHEET GENERATION\n");
  procmsg ("========================\n");

  # no sort since it'll be sorted below
  foreach $file (keys %filenameshash) {
    $info = $exifToolObj->ImageInfo($file);
    $orientation = $exifToolObj->GetValue("Orientation", 'ValueConv');

    $filefull = $file;

    if (get_cfg_value($co_cs, 'thm') != 0 and defined $orientation) {
      if ($orientation > 1) {
        $filefull = rot_thm_cs ($file, $rotorient{$orientation}, $workdir);
      } elsif ($orientation == 1) {
        # We need this since rotated imgage will be at $workdir, but others are
        # in current
        $ThumbnailOriginal = File::Spec->catfile($workdir, $file);
        if ($dryRun == 0) {
          copy ($file, $ThumbnailOriginal) || die_renrot("copy failed: $!");
        }
        $filefull = $ThumbnailOriginal;
      }
    } elsif (get_cfg_value($co_cs, 'thm') == 0) {
      if (defined ${$$info{ThumbnailImage}}) {
        $ThumbnailOriginal = File::Spec->catfile($workdir, $file);
        if ($dryRun == 0) {
          open (OLDTHUMBNAIL, ">$ThumbnailOriginal") || die_renrot("$ThumbnailOriginal wasn't opened!\n");
          binmode OLDTHUMBNAIL;
          print OLDTHUMBNAIL ${$$info{ThumbnailImage}};
          unless (close (OLDTHUMBNAIL)) { warnmsg ("$ThumbnailOriginal wasn't closed!\n"); }
        }

        if (not defined $orientation) {
          $orientation = $exifToolObj->GetValue("Rotation", 'ValueConv');
        }

        if (defined $orientation and $orientation > 1) {
          $filefull = rot_thm_cs ($ThumbnailOriginal, $orientation, File::Spec->curdir());
        } else {
          $filefull = $ThumbnailOriginal;
        }
      } else {
        my $ffwf = File::Spec->catfile($workdir, $file);
        if ($gen_thm == 0) {
          warnmsg ("$filefull has no ThumbnailImage tag. Stub thumbnail image will be used.\n");
          my $thmbstubjpg = File::Spec->catfile($workdir, "thmbstub.jpg");
          thm_gen_stub($thmbstubjpg) if (not -f $thmbstubjpg);
          copy ($thmbstubjpg, $ffwf) if ($dryRun == 0);
        } else {
          warnmsg ("$filefull has no ThumbnailImage tag. Thumbnail image will be generated.\n");
          move (thm_gen_orig($file, 0), $ffwf) if ($dryRun == 0);
        }
        $filefull = $ffwf;
      }
    }

    if ($dryRun == 0) {
      $infothm = $exifToolObj->ImageInfo($filefull);

      $width = $exifToolObj->GetValue("ImageWidth");
      if ($width > $size) { $size = $width; }

      $height = $exifToolObj->GetValue("ImageHeight");
      if ($height > $size) { $size = $height; }
    }

    push (@thumbnailes, $filefull);
  }
  @thumbnailes_sorted = sort {$a cmp $b} @thumbnailes;

  # here it's iteration by tile
  my ($tileX, $tileY) = split ("x", get_cfg_value($co_cs, 'tile'));
  my $tileMul = $tileX * $tileY;
  my $csIterationNumber = scalar @thumbnailes_sorted;
  my $csFullIterations = int($csIterationNumber/$tileMul);
  my $csRest = $csIterationNumber % $tileMul;
  my $fileCounter = $countStart;
  my $csIteration = 0;
  my $csIterator = 0;
  my $csIter = 0;
  my $readres;
  my $image;
  my $writeres;
  my $montage;
  my $montagename;
  my $infoMontage;
  my @left_up_row = ("RenRot v$VERSION (r$REVISION)", $homeURL);
  my $substrFile;
  my $readIndex;
  my $counter_size;

  if ($csFullIterations != 0) {
    $counter_size = "%." . length($csFullIterations * $countStep + $countStart) . "d";
    dbgmsg (1, "Counter size: $size (CS files num: $csFullIterations)\n");
  } else {
    $counter_size = "%d";
  }

  if ($csFullIterations > 0) {
    # we need this for the case when $csRest == 0 and $csIterationNumber > $tileMul
    if (not $csRest) {
      --$csFullIterations;
    }
    for (; $csIterator < $csFullIterations; $csIterator++, $fileCounter += $countStep) {
      $image = Image::Magick->new;

      $montagename = template2name (
          $exifToolObj,
          $info,
          get_cfg_value($co_cs, 'file'),
          $fileCounter,
          "stub",
          $counter_size,
          "none"
      );
      for ($readIndex = 0, $csIter = $csIterator * $tileMul; $csIter < ($csIterator * $tileMul + $tileMul); $csIter++, $readIndex++) {
        $readres = $image->Read($thumbnailes_sorted[$csIter]);
        if (not $readres) {
          dbgmsg (4, "$thumbnailes_sorted[$csIter] was successfully read.\n");
        } else { errmsg ("Image::Magick error: $readres\n"); }

        # ranking
        $substrFile = substr($thumbnailes_sorted[$csIter], length(get_cfg_value($co_cs, 'dir')) + 1);
        if (defined $ranks->{$substrFile}->[1]) {
          dbgmsg (4, "$substrFile mattecolor is \"$ranks->{$substrFile}->[1]\"\n");
          $image->[$readIndex]->Set(mattecolor => $ranks->{$substrFile}->[1]);
        } else {
          dbgmsg (4, "$substrFile mattecolor is undefined, using \"", get_cfg_value($co_cs, 'mattecolor'), "\" from config\n");
          $image->[$readIndex]->Set(mattecolor => normalize_color(get_cfg_value($co_cs, 'mattecolor')));
        }
      }
      dbgmsg (1, "$csIterator montage is started, wait a bit please...\n");
      $montage = $image->Montage(background => normalize_color(get_cfg_value($co_cs, 'background')),
          bordercolor => normalize_color(get_cfg_value($co_cs, 'bordercolor')),
          font => get_cfg_value($co_cs, 'font'),
          fill => normalize_color(get_cfg_value($co_cs, 'fill')),
          label => get_cfg_value($co_cs, 'label'),
          frame => get_cfg_value($co_cs, 'frame'),
          geometry => $size . "x" . $size . "+4+4",
          pointsize => get_cfg_value($co_cs, 'pointsize'),
          shadow => get_cfg_value($co_cs, 'shadow'),
          title => get_cfg_value($co_cs, 'title'),
          tile => get_cfg_value($co_cs, 'tile'),
          stroke => 'none',
      );

      if (not ref($montage)) { errmsg ("Image::Magick error: $montage\n"); }
      else { dbgmsg (1, "$csIterator montage've finished successfully.\n"); }

      $montage->Set (
          filename => 'jpg:' . $montagename,
          quality => 95,
          interlace => 'Partition',
          gravity => 'Center',
          stroke => 'none',
      );
      $montage->Annotate (
          font => get_cfg_value($co_cs, 'font'),
          pointsize => 9,
          x => 5,
          y => 13,
          fill => 'lightgray',
          text => $left_up_row[0],
      );
      $montage->Annotate (
          font => get_cfg_value($co_cs, 'font'),
          pointsize => 9,
          x => 5,
          y => 23,
          fill => 'lightgray',
          text => $left_up_row[1],
      );
      $writeres = $montage->Write();
      if (not $writeres) { dbgmsg (1, "Successfully written $montagename file.\n"); }
      else { errmsg ("Image::Magick error: $writeres\n"); }

      $infoMontage = $exifToolObj->ImageInfo($montagename);

      # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file
      saveOurHdrs($exifToolObj, $infoMontage, $montagename);

      # Writing tags.
      tagWriter($exifToolObj, $montagename);

      # Writing ThumbnailImage tag with generated thumbnail
      thm_gen_orig($montagename, 1);

      undef $image;
    }
  }

  $image = Image::Magick->new;

  $montagename = template2name (
      $exifToolObj,
      $info,
      get_cfg_value($co_cs, 'file'),
      $fileCounter,
      "stub",
      $counter_size,
      "none"
  );

  for ($readIndex = 0, $csIteration = $csIterator * $tileMul; $csIteration < $csIterationNumber; $csIteration++, $readIndex++) {
    $readres = $image->Read($thumbnailes_sorted[$csIteration]);
    if (not $readres) { dbgmsg (4, "$thumbnailes_sorted[$csIteration] was successfully red.\n"); }
    else { errmsg ("Image::Magick error: $readres\n"); }

    # ranking
    $substrFile = substr($thumbnailes_sorted[$csIteration], length(get_cfg_value($co_cs, 'dir')) + 1);
    if (defined $ranks->{$substrFile}->[1] and length($ranks->{$substrFile}->[1]) > 1) {
      dbgmsg (4, "[last] $substrFile mattecolor is \"$ranks->{$substrFile}->[1]\"\n");
      $image->[$readIndex]->Set(mattecolor => $ranks->{$substrFile}->[1]) if ($dryRun == 0);
    } else {
      dbgmsg (4, "[last] $substrFile mattecolor is undefined, using \"", get_cfg_value($co_cs, 'mattecolor'), "\" from config.\n");
      $image->[$readIndex]->Set(mattecolor => normalize_color(get_cfg_value($co_cs, 'mattecolor'))) if ($dryRun == 0);
    }
  }
  dbgmsg (1, "Final, $csIterator montage is started, wait a bit please...\n");

  # the final invocation of ->Montage() method for the the rest of files didn't fit
  # previous loop	->Montage() calls when  $csIterationNumber < $tileX * $tileY
  $montage = $image->Montage (
      background => normalize_color(get_cfg_value($co_cs, 'background')),
      bordercolor => normalize_color(get_cfg_value($co_cs, 'bordercolor')),
      font => get_cfg_value($co_cs, 'font'),
      fill => normalize_color(get_cfg_value($co_cs, 'fill')),
      label => get_cfg_value($co_cs, 'label'),
      frame => get_cfg_value($co_cs, 'frame'),
      geometry => $size . "x" . $size . "+4+4",
      pointsize => get_cfg_value($co_cs, 'pointsize'),
      shadow => get_cfg_value($co_cs, 'shadow'),
      title => get_cfg_value($co_cs, 'title'),
      tile => get_cfg_value($co_cs, 'tile'),
      stroke => 'none',
  );

  if (not ref($montage)) { errmsg ("Image::Magick error: $montage\n"); }
  else { dbgmsg (1, "Montage've finished successfully.\n"); }

  if ($dryRun == 0) {
    $montage->Set (
        filename => 'jpg:' . $montagename,
        quality => 95,
        interlace => 'Partition',
        gravity => 'Center',
        stroke => 'none',
    );
    $montage->Annotate (
        font => get_cfg_value($co_cs, 'font'),
        pointsize => 9,
        x => 5,
        y => 13,
        fill => 'lightgray',
        text => $left_up_row[0],
    );
    $montage->Annotate (
        font => get_cfg_value($co_cs, 'font'),
        pointsize => 9,
        x => 5,
        y => 23,
        fill => 'lightgray',
        text => $left_up_row[1],
    );
    $writeres = $montage->Write();
  }
  if (not $writeres) { dbgmsg (1, "Successfully written $montagename file.\n"); }
  else { errmsg ("Image::Magick error: $writeres\n"); }
  undef $image;

  $infoMontage = $exifToolObj->ImageInfo($montagename);

  # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file
  saveOurHdrs($exifToolObj, $infoMontage, $montagename);

  # Writing tags.
  tagWriter($exifToolObj, $montagename);

  # Writing ThumbnailImage tag with generated thumbnail
  thm_gen_orig($montagename, 1);

  if (-d $workdir) {
    chdir $workdir;
    unlink <*>;
    chdir "..";
  }
  rmdir $workdir;

  procmsg ("\n");
}

########################################################################################
# Usage      : thm_gen_stub($thm_name);
# Purpose    : thumbnail stub generator
# Returns    : none
# Parameters : $thm_name str - thumbnail image pathname
# Throws     : no exceptions
# Comments   : none
# See Also   : contactSheetGenerator();
sub thm_gen_stub {
  my $thm_name = shift;
  my $size = get_cfg_value($co_g, 'generate thumbnail size');
  my $thmb = Image::Magick->new;

  $thmb->Set(size => $size, filename => $thm_name, quality => 95, interlace => 'Partition');

  my $gf = normalize_color(get_cfg_value($co_cs, 'thm grad fr'));
  my $gt = normalize_color(get_cfg_value($co_cs, 'thm grad to'));
  $thmb->ReadImage("gradient:$gf-$gt");
  $thmb->Annotate(
	   pointsize => 25,
	   fill => normalize_color(get_cfg_value($co_cs, 'thm fill')),
	   font => get_cfg_value($co_cs, 'thm font'),
	   text => get_cfg_value($co_cs, 'thm text'),
	   gravity => 'Center',
  );

  if ($dryRun == 0) {
    my $thmbnum = $thmb->Write();
    if ($thmbnum) {
      errmsg ("$thmbnum\n");
      undef $thmb;
      return;
    }
  }

  undef $thmb;

  procmsg ("Stub thumbnail image has been created.\n");
}

########################################################################################
# Usage      : thm_gen_orig($file, $unlink);
# Purpose    : generate thumbnail image from the original file and write it
#            : to the ThumbnailImage tag
# Returns    : thumbnail file name if unlink not asked
# Parameters : $file str - original image name
#            : $unlink bin - 0 not to kill generated thumbnail
#            :               1 to kill generated thumbnail
# Throws     : no exceptions
# Comments   : none
# See Also   : n/a
sub thm_gen_orig {
  my $file = shift;
  my $unlink = shift;
  my $thm_name = "thm_" . $file;
  my $size = get_cfg_value($co_g, 'generate thumbnail size');
  my $thmb = Image::Magick->new;

  $thmb->Set(size => $size, filename => $thm_name, quality => 95, interlace => 'Partition');

  $thmb->ReadImage($file);
  $thmb->Thumbnail(geometry => $size);

  if ($dryRun == 0) {
    my $thmbnum = $thmb->Write();
    if ($thmbnum) {
      errmsg ("$thmbnum\n");
      undef $thmb;
      return;
    }
  }

  undef $thmb;

  procmsg ("ThumbnailImage was generated for $file\n");

  if ($unlink) {
    dbgmsg (3, "Attempt to write ThumbnailImage tag to $file\n");
    thumbWriter($file, Image::RenRot::FileUtil->getFileData($thm_name));
    unlink $thm_name;
    return;
  } else {
    return $thm_name;
  }
}

########################################################################################
# Usage      : rot_thm_cs($base_orig, $angle, $workdir);
# Purpose    : rotates thumbnails for contact sheet and put it to the workdir
# Returns    : none
# Parameters : $base_orig str - pathless filename of the rotated file
#            : $angle     num - rotation angle
#            : $workdir   str - the work directory thumbnails kept in
# Throws     : no exceptions
# Comments   : works only with JPEGs
# See Also   : contactSheetGenerator();
sub rot_thm_cs {
  my $base_orig = shift;
  my $angle = shift;
  my $workdir = shift;
  my $image_to_rotate = Image::Magick->new;
  my $result = File::Spec->catfile($workdir, $base_orig);

  $image_to_rotate->Read("JPEG:" . $base_orig);
  $image_to_rotate->Rotate(degrees => $angle);
  $image_to_rotate->Write(filename => "JPEG:" . $result, quality => 95, compression => 'JPEG2000');
  undef $image_to_rotate;
  return $result;
}

########################################################################################
# Usage      : normalize_color($color);
# Purpose    : validates given string as color suitable for ImageMagick
# Returns    : none
# Parameters : $color str - color
# Throws     : no exceptions
# Comments   : none
# See Also   : convert -list color
sub normalize_color {
  my $color = shift;
  if ($color =~ /^#?([[:xdigit:]]{3})$/ or $color =~ /^#?([[:xdigit:]]{6})$/) {
    return "#" . $1;
  }
  return $color;
}

########################################################################################
# Usage      : aggregateFile($file, $NewDir);
# Purpose    : moves or links file to the aggregation directory
# Returns    : none
# Parameters : $file [str] - name of file to be moved
#            : $new_dir [str] - name of dir the file to be moved to
# Throws     : no exceptions
# Comments   : none
# See Also   : N/A
sub aggregateFile {
  my $file = shift;
  my $new_dir = shift;
  my $base_name = basename($file);

  makedir($new_dir);

  if (get_cfg_value($co_aggr, 'virtual') == 0) {
    my $newname = File::Spec->catfile($new_dir, $base_name);
    rename ($file, $newname) || die_renrot("While moving $file -> $newname, perhaps a different file system is using\n");
    dbgmsg (3, "$file moved to $newname\n");
  } else {
    my $newfile = File::Spec->catfile(File::Spec->abs2rel($new_dir), $base_name);
    if (not -l $newfile) {
      # Make relative path to original file from new directory
      my $oldfile = File::Spec->catfile(File::Spec->abs2rel(File::Spec->curdir(), $new_dir), $file);
      symlink ($oldfile, $newfile) || die_renrot("While linking $oldfile -> $newfile\n");
      dbgmsg (3, "Following link was created $newfile -> $oldfile\n");
    } else {
      warnmsg ("Link $newfile already exists.\n");
    }
  }
}

########################################################################################
#
# getTimestamp() returns EXIF timestamp in form YYYYmmddHHMMSS if exists, otherwise
# it returns Image::RenRot::TimeUtil->now()
#
sub getTimestamp {
  my $exifToolObj = shift;
  my $infoObj = shift;

  my $timestamp;

  if (defined $infoObj->{"DateTimeOriginal"} and not time_validator($infoObj->{"DateTimeOriginal"})) {
    $timestamp = $infoObj->{"DateTimeOriginal"};
  }
  elsif (defined $infoObj->{"FileModifyDate"} and not time_validator($infoObj->{"FileModifyDate"})) {
    $timestamp = $infoObj->{"FileModifyDate"};
  } else {
    $timestamp = now();
    $exifToolObj->SetNewValue('FileModifyDate', $timestamp, Group => 'File');
    warnmsg ("EXIF timestamp isn't correct, using current time!\n");
  }
  return $timestamp;
}

########################################################################################
#
# rotateOrient() rotates image by changing Orientation tag. No real rotation
# will be made.
#
sub rotateOrient {
  my $exifToolObj = shift;
  my $fileOrient = shift;
  my $orientation = shift;

  dbgmsg (4, "Original Orientation: $orientation\n");
  my $angleTmp = $rotorient{$orientation};
  if (not defined $angleTmp) {
    errmsg ("Operation not permited for mirror type orientation.\n");
    return;
  }

  $angleTmp += $rotateAngle;
  $angleTmp -= 360 if ($angleTmp >= 360);

  $orientation = $rotorientrev{$angleTmp};
  dbgmsg (4, "New Orientation: $orientation\n");

  $exifToolObj->SetNewValue("Orientation", $orientation, Type => 'ValueConv');
  if ($dryRun == 0) { exifWriter($exifToolObj, $fileOrient); }
  else { procmsg ("Rotating Orientation tag value.\n"); }
}

########################################################################################
#
# rotateImg() rotates the image file by given angle
#
sub rotateImg {
  my $oldfile = shift;			# original name to transform with jpegtran
  my $origfile = $oldfile . "_orig";	# backup original name
  my $newfile = $oldfile . "_rotated";	# temporay name to store rotated file
  my @addon = @_;			# the switches for jpegtran to transform the image

  # jpegtran the image
  my $cmd = "jpegtran -copy none @addon -outfile \"$newfile\" \"$oldfile\"";
  dbgmsg (3, "$cmd\n");

  if ($dryRun == 0) {
    system $cmd || die_renrot("System $cmd failed: $?\n");
  }

  # preparing to write tags to the just rotated file
  my $exifAfterRot = new Image::ExifTool;
  $exifAfterRot->Options(Binary => 1);
  $exifAfterRot->SetNewValuesFromFile($oldfile, '*:*');
  $exifAfterRot->SetNewValue("Orientation", 1, Type => 'ValueConv');

  if ($dryRun == 0) {
    if ($backup != 0) {
      rename ($oldfile, $origfile) || die_renrot("$oldfile -> $origfile\n");
    }
    rename ($newfile, $oldfile) || die_renrot("$newfile -> $oldfile\n");
  }

  procmsg ("$oldfile was rotated\n");

  # writing the changes to the EXIFs
  exifWriter($exifAfterRot, $oldfile) if ($dryRun == 0);
}

########################################################################################
#
# thumbWriter() writes binary data as thumbnail to given file
#
sub thumbWriter {
  my $file = shift;
  my $thethumb = shift;

  # preparing to write thumbnale to the just rotated file
  my $exifThumbnailed = new Image::ExifTool;
  $exifThumbnailed->Options(Binary => 1);
  $exifThumbnailed->SetNewValue("ThumbnailImage", $thethumb, Type => 'ValueConv');

  # writing the changes to the EXIFs
  procmsg ("Writing thumbnail to $file...\n");
  exifWriter($exifThumbnailed, $file) if ($dryRun == 0);
}

########################################################################################
#
# rotateThumbnail() rotates thumbnail only, where the file was rotated but
# thumbnail was left untouched
#
sub rotateThumbnail {
  my $infoObj = shift;
  my $file = shift;	# file, which thumbnale to transform with jpegtran
  my @addon = @_;		# the switches for jpegtran to rotate the thumbnail

  if (not defined ${$$infoObj{ThumbnailImage}}) {
    warnmsg ("No thumbnail found.\n");
    return;
  }

  my $origThumb = ${$$infoObj{ThumbnailImage}};

  if (get_cfg_value($co_g, 'use ipc') == 0) {
    # extracting the thumbnail image
    my $ThumbnailOriginal = $file . "_thumborig";
    unless (open (OLDTHUMBNAIL, ">$ThumbnailOriginal")) {
      errmsg ("$ThumbnailOriginal wasn't opened!\n");
      return;
    }
    binmode OLDTHUMBNAIL;
    print OLDTHUMBNAIL $origThumb;
    unless (close (OLDTHUMBNAIL)) { warnmsg ("$ThumbnailOriginal wasn't closed!\n"); }

    # rotating the thumbnail
    my $ThumbnailOriginalRotated = $ThumbnailOriginal . "_rotated";
    my $cmd = "jpegtran -copy none @addon -outfile \"$ThumbnailOriginalRotated\" \"$ThumbnailOriginal\"";
    dbgmsg (3, "$cmd\n");

    if ($dryRun == 0) {
      system $cmd || die_renrot("System $cmd failed: $?\n");
    }

    # write the just rotated thumbnail back to file
    thumbWriter($file, Image::RenRot::FileUtil->getFileData($ThumbnailOriginalRotated));

    if ($dryRun == 0) {
      unlink ($ThumbnailOriginalRotated) || die_renrot("While killing $ThumbnailOriginalRotated.\n");
    }
    unlink ($ThumbnailOriginal) || die_renrot("While killing $ThumbnailOriginal.\n");
  } else {
    my $cmd = "jpegtran -copy none @addon";
    dbgmsg (3, "$cmd\n");

    # write the just rotated thumbnail back to file
    thumbWriter($file, Image::RenRot::FileUtil->piper($origThumb, $cmd));
  }
}

########################################################################################
#
# usage() prints the instructions how to use the script
#
sub usage {
  my $exitcode = shift;
  my $v = shift;

  if ($v == 0) {
    infomsg ("RenRot version $VERSION (r$REVISION)\n");
  } elsif ($v == 1) {
    infomsg (
"Usage: renrot <--extension EXTENSION> [--quiet] [--no-rotate] [--no-rename]
          [--name-template TPL] [--comment-file FILE] [--work-directory DIR]
          [[--] FILE1 FILE2 ...]

Options:
  -c, --config-file <FILE>      configuration file to use
  -d, --work-directory <DIR>    set working directory
  -e, --extension <EXTENSION>   extension of files to process: JPG, jpeg, ...

Renaming options:
  -n, --name-template <TPL>     filename template (see manual for details)

Rotating options:
  -r, --rotate-angle <ANGLE>    angle to rotate files and thumbnails by 90,
                                180, 270
      --rotate-thumb <ANGLE>    rotate only thumbnails by 90, 180, 270
      --mtime (*)               set file mtime according to DateTimeOriginal
                                tag

Misc options:
      --dry-run                 do nothing, only print would have been done
      --use-ipc (*)             rotate thumbnail via pipe, rather than via file
  -v                            increment debugging level by 1
  -h, --help                    display this help and exit
      --version                 output version and exit

(*) The options marked with this sign do not take arguments and can be negated,
i.e. prefixed by 'no'. E.g. '--mtime' sets file mtime value, while '--nomtime'
or '--no-mtime' disables setting it.

Consult the documentation for a full list of options.

");
  } elsif ($v == 2) {
    pod2usage(-verbose => 2);
  }
  exit $exitcode;
}

########################################################################################
# Usage      : $name = template2name(...);
# Purpose    : builds file name according to the template
# Returns    : name as string
# Parameters : $exifToolObj [ref] -
#            : $infoObj     [ref] -
#            : $template    [str] - the template to be used
#            : $fileNo      [num] - counter for %c
#            : $fileName    [str] - file name for %n and %e
#            : $counterSize [num] - the size of the counter for format (like "01", "0012")
#            : $angleSuffix [str] - suffix to add to the end of the rotated files
# Throws     : no exceptions
# Comments   : none
# See Also   : n/a
sub template2name {
  my $exifToolObj = shift;
  my $infoObj = shift;
  my $template = shift;
  my $fileNo = shift;
  my $fileName = shift;
  my $counterSize = shift;
  my $angleSuffix = shift;

  if (not defined $template) {
    die_renrot("Template isn't given!\n");
  }

  my $timestamp = getTimestamp($exifToolObj, $infoObj);
  my @tm = ($timestamp =~ m/(\d\d(\d\d))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/);
  dbgmsg (4, "tm: @tm\n");

  my $ExposureTime = "";
  my $FileNumber = 'NA';
  my $FNumber = "";
  my $ISO = "";
  my $WhiteBalance = "";
  my $fileNameOriginal = "";
  my $fileNameOriginalCounter = "";		# we can not use 0 as default value

  if (defined $infoObj->{"FileNumber"}) {
    $FileNumber = $infoObj->{"FileNumber"};
  }

  if (defined $infoObj->{"ExposureTime"}) {
    $ExposureTime = $infoObj->{"ExposureTime"};
    $ExposureTime =~ s/\//by/g;
  }

  if (defined $infoObj->{"FNumber"}) {
    $FNumber = $infoObj->{"FNumber"};
  }

  if (defined $infoObj->{"ISO"}) {
    $ISO = $infoObj->{"ISO"};
  }

  if (defined $infoObj->{"WhiteBalance"}) {
    $WhiteBalance = $infoObj->{"WhiteBalance"};
    $WhiteBalance =~ s/[\s()]//g;
  }

  if (defined $infoObj->{"RenRotFileNameOriginal"}) {
    $fileNameOriginal = $infoObj->{"RenRotFileNameOriginal"};
  } else {
    # Temporary stub to make renrot remember original file name for the formats
    # ExifTool writing to doesn't support.
    # Reported by Neil Hooey <nhooey@gmail.com>
    $fileNameOriginal = $infoObj->{"FileName"};
  }

  # file name starts with letters and ends with digits
  if ($fileNameOriginal =~ m/^[[:alpha:]\-_]*(\d+)(\.[^\.]+)?$/) {
    $fileNameOriginalCounter = $1;
  }

  my ($base, $ext) = splitext($fileName); # file name %n and extension %e

  my @templatearea = split (//, $template);
  my %templatehash = (
      '%' => "%",
      '#' => "#",
      'a' => $angleSuffix,
      'C' => $fileNameOriginalCounter,
      'c' => sprintf($counterSize, $fileNo),
      'd' => $tm[3],
      'E' => $ExposureTime,
      'e' => $ext,
      'F' => $FNumber,
      'H' => $tm[4],
      'I' => $ISO,
      'i' => $FileNumber,
      'M' => $tm[5],
      'm' => $tm[2],
      'n' => $base,
      'O' => (splitext($fileNameOriginal))[0],
      'o' => $fileNameOriginal,
      'S' => $tm[6],
      'W' => $WhiteBalance,
      'Y' => $tm[0],
      'y' => $tm[1],
  );
  my $thename = "";

  my $substroffset = 0;
  my $substrchar;
  my $tag_to_name_val = "";
  my $tag_to_name = "";

  dbgmsg (4, "'$template' (length: ", scalar(@templatearea), ")\n");
  while ($substroffset < scalar(@templatearea)) {
    $substrchar = $templatearea[$substroffset++];
    if ($substrchar eq "%" and $substroffset < scalar(@templatearea)) {
      $substrchar = $templatearea[$substroffset++];
      if (defined $templatehash{$substrchar}) {
        $thename .= $templatehash{$substrchar};
      }
    } elsif ($substrchar eq "#" and $substroffset < scalar(@templatearea)) {
      $substrchar = $templatearea[$substroffset++];

      until ($substrchar eq "#") {
        $tag_to_name .= $substrchar;
        $substrchar = $templatearea[$substroffset++];
      }
      if (defined $infoObj->{$tag_to_name}) {
        $tag_to_name_val = $infoObj->{$tag_to_name};
        dbgmsg (2, "Tag '$tag_to_name' = $tag_to_name_val\n");
        $tag_to_name_val =~ s/[\s()]//g;
        $tag_to_name_val =~ s/[\/\\:;\'\"]/_/g;
        $thename .= $tag_to_name_val;
      }
      $tag_to_name_val = $tag_to_name = "";
    } else { $thename .= $substrchar; }
  }
  return $thename;
}

########################################################################################
#
# MAIN() renames and rotates given files
#

# Check for modules
$isThereIM = 1 if (defined loadpkg("Image::Magick"));

getOptions();
parseConfig($configFile, $config_opts);
switchColor();

# redefining options set in configuration file with set via CLI ones
Image::RenRot::Config->apply($config_opts);

dbgmsg (1, "Show what would have been happened (no real actions).\n") if ($dryRun != 0);

# Validate aggregation mode possible values
my $aggr_mode = get_cfg_value($co_aggr, 'mode');
if (not grep (/^$aggr_mode$/, ('none', 'delta', 'template'))) {
  warnmsg ("Aggregation mode isn't correct!\n");
}

# Calculate ExifTool's verbosity
my $exiftoolVerbose = ($verbose > $maxVerbosity) ? ($verbose - $maxVerbosity) : 0;

# ExifTool object configuration
my $exifTool = new Image::ExifTool;
$exifTool->Options(Binary => 1, Unknown => 1, DateFormat => '%Y%m%d%H%M%S', Verbose => $exiftoolVerbose);

chdir ($workDir) || die_renrot("Can't enter to $workDir!\n");

if ($subFileSet eq "") {
  # All things in ARGV will be treated as file names to process
  @files = @ARGV;
} else {
  dbgmsg (2, "Reading file names for processing from file: $subFileSet\n");
  @files = Image::RenRot::FileUtil->getFileDataLines($subFileSet);
  chomp(@files);
}

# if no file is given
if (scalar(@files) == 0) {
  my $fileMask = "*" . $extToProcess;
  @files = grep { -f } glob ($fileMask);
}

# independently of @files initialization doing this
my @filenames = ();

foreach my $file (@files) {
  next if (not -f $file);			# skip absent file or not a file
  next if (grep {/^$file$/} @excludeList);	# skip excluded file
  push (@filenames, $file);
}

# No file to process?
if (scalar(@filenames) == 0) {
  fatalmsg ("No files to process!\n");
  exit 1;
}

# Parse configuration file tag set
foreach my $cKey (keys %$config_opts) {
  next if ($cKey !~ m/^tag(file)?#\d+#\d+$/);	# skip not a tag or tagfile
  my %tag = str2hash($config_opts->{$cKey});
  foreach my $key (keys %tag) {
    $tags{$key} = $tag{$key};
    if ($cKey =~ m/^tagfile/) {
      dbgmsg (4, "Read data from '$tags{$key}{value}' for '$key'\n");
      $tags{$key}{value} = Image::RenRot::FileUtil->getFileData($tags{$key}{value});
    }
  }
}

# Put command line arguments to appropriate tags
$tags{'Comment'} = {value => Image::RenRot::FileUtil->getFileData($comfile)} if (defined $comfile);
$tags{'UserComment'} = {value => $userComment} if (defined $userComment);

# Merge tags from configuration file with command line arguments
map { $tags{$_} = $tagsFromCli{$_} } keys %tagsFromCli;

# Print parsed tags at debug level
my @dbgTags = ();
foreach my $key (sort (keys %tags)) {
  my $group = defined $tags{$key}{group} ? $tags{$key}{group} : "";
  my $value = defined $tags{$key}{value} ? $tags{$key}{value} : "";
  push (@dbgTags, "$key [$group] = $value");
}
dbgmsg (4, "Tags:\n", join("\n", @dbgTags), "\n") if (scalar(@dbgTags) > 0);

# Validate angle value
if ((defined $rotateAngle and not grep(/^$rotateAngle$/, keys %rotangles)) or
    (defined $rotateThumbnail and not grep(/^$rotateThumbnail$/, keys %rotangles))) {
  fatalmsg ("Angle should be 90, 180 or 270!\n");
  exit 1;
}

@files = sort @filenames;
dbgmsg (4, "Pushed files(", scalar(@files), "):\n", join("\n", @files), "\n");

# Preparing the variable, which contains the format of the counter output
my $counterSize;

if ($countFF != 0) {
  my $size = length((scalar(@filenames) - 1) * $countStep + $countStart);
  $counterSize = "%." . $size . "d";
  dbgmsg (1, "Counter size: $size (amount files in cache: ", scalar(@filenames), ")\n");
} else {
  $counterSize = "%d";
}

renRotProcess($exifTool, $counterSize);

contactSheetGenerator($exifTool) if ($isThereIM);

aggregationProcess($exifTool, $counterSize);

__END__

=head1 NAME

renrot - rename and rotate images according EXIF data

=head1 SYNOPSIS

renrot [OPTIONS] [[B<-->] FILE1 FILE2 ...]

=head1 DESCRIPTION

B<Renrot> is intended to work with a set of files containing EXIF data and
can do two things to them -- rename and rotate. A set of files can be given
either explicitly or using the B<--extension> option, which select the files
with the given suffix. B<Renrot> operates on files in current working
directory, unless given the B<--work-directory> option, which changes this
default.

B<Renrot> renames input files using a flexible name template (which,
among others, uses DateTimeOriginal and FileModifyDate EXIF tags, if they
exist, otherwise names the file according to the current timestamp). Further,
B<renrot> can aggregate files according to the shooting time period or to a
given template.

Additionally, it rotates files and their thumbnails, as per Orientation EXIF
tag. If that tag is absent, the program allows to set rotation parameters
using B<--rotate-angle> and B<--rotate-thumb> command line options. This is
currently implemented only for JPEG format.

The program can also place commentaries into the following locations:

=over

- Commentary tag from file (see B<--comment-file> option)

- UserComment tag from configuration variable (see L</TAGS> section)

=back

Personal details may be specified via XMP tags defined in a configuration
file, see L</TAGS> section.

In addition, B<renrot> can aggregate all files in different directories,
according to a given date/time pattern template, set with B<--aggr-template>.

=head1 OPTIONS

=over

=item B<-c> or B<--config-file> F<FILE>

Path to the configuration file.

=item B<-d> or B<--work-directory> F<DIR>

Define the working directory.

=item B<--exclude> F<FILE>

Specify files to exclude. Wildcards are not allowed. If a set of files is
given, there must be as many occurrences of this option as there are files in
the set.

=item B<--sub-fileset> F<FILE>

Get names of files to operate upon from F<FILE>. The file must contain a
file name per line. This option is useful when you need to process only a
set of X from Y files in the directory. If specified, the rest of files
given in the command line is ignored.

=item B<-e> or B<--extension> I<EXTENSION>

Process the files with given I<EXTENSION> (JPG, jpeg, CRW, crw, etc).
Depending on the operating system, the extension search might or might not be
case-sensitive.

=item B<--mtime>, B<--no-mtime>

Defines whether to set the file's mtime, using DateTimeOriginal tag value.
Use B<--no-mtime> to set it to current time stamp after processing.

=item B<--no-renrot> or B<--nochg>

Do not rename, rotate, tag and mtime images. It saves files from any changes
while allows to do aggregation, contact sheet generation e.t.c.

=item B<--use-color>, B<--no-use-color>

Colorize output. This does NOT work under Windows.

=item B<--dry-run>

Do not do anything, only print would have been done.

=item B<-g> or B<--generate-thumb>

Generation and writing ThumbnailImage tag. The original value of the ThumbnailImage
tag remains intact. To rewrite it you need to delete it first (look exiftool examples).

=item B<--use-ipc>, B<--no-use-ipc>

Rotate thumbnails using pipe, rather than files. This does NOT work under
Windows.

=item B<-v>

Increase debugging level by 1. Debugging levels from 1 to 4 are internal
levels, the levels from 5 till 9 are equivalent to levels 1-5 levels ExifTool
with the maximum verbosity for B<renrot>.

=item B<-?> or B<--help>

Display short usage summary and exit.

=item B<--version>

Output version information and exit.

=back

=head1 B<AGGREGATION>

=over

=item B<--aggr-mode> I<MODE>

Run aggregation process in given I<MODE>. Possible values are: none, delta or
template.

=item B<--aggr-delta> I<NUMBER>

Aggregation time delta, in seconds. Files with DateTimeOriginal and ones of
the previous file delta, greater than B<--aggr-delta> are placed in the
directories, with the names are constructed by concatenating the value of the
B<--aggr-directory> option and the directory name counter.

=item B<--aggr-directory> F<DIR>

Aggregation directory name prefix (default is I<Images>), have to be on the
same file system (or on the file system which supports symbolic links in case
of virtual aggregation), relative to the current working directory or an
absolute path.

=item B<-a> or B<--aggr-template> I<TEMPLATE>

File name template to use for file aggregation. Images are aggregated by
date/time patterns. You may use combination of B<%d>, B<%H>, B<%M>, B<%m>,
B<%S>, B<%Y>, and B<%y> meta-characters. The template can also be defined
in the configuration file (see Aggregation Template variable). The default
is I<%Y%m%d>. For the detailed description, refer to B<--name-template>
option. For practical uses, see L</TEMPLATE EXAMPLES> section.

=item B<--aggr-virtual>, B<--no-aggr-virtual>

Defines virtualization for existent aggregation modes. The main effect of
B<--aggr-virtual> is that any files to be aggregated remain untouched in their
places, and relative symbolic links pointing to them are stored in the
directory tree created. Use B<--no-aggr-virtual> to prevent virtualization.

=back

=head1 B<CONTACT SHEET GENERATOR>

=over

=item B<--contact-sheet>, B<--no-contact-sheet> or B<--cs>, B<--no-cs>

Create the contact sheet. Currently it works with ThumbnailImage EXIFs and the
files defined as thumbnails (see the option B<--contact-sheet-thm>, below)

=item B<--contact-sheet-file> or B<--cs-file> F<FILE>

Base file name for montage files.

=item B<--contact-sheet-dir> or B<--cs-dir> F<DIR>

Temporary directory for montage (created in the begining and deleted at the
end of the process)

=item B<--contact-sheet-thm> or B<--cs-thm>

Files for the montage are already thumbnails

=back

Options bellow are native ImageMagic montage options look ImageMagick
documentation for montage options: I<montage --help> and
I<http://www.imagemagick.org/>

Note please, for I<COLOR> use RGB triplets only like I<000> for the I<black>
or I<F00> for the I<red>.

=over

=item B<--contact-sheet-tile> or B<--cs-tile> I<GEOMETRY>

Tile MxN (IM: -tile)

=item B<--contact-sheet-title> or B<--cs-title> I<STRING>

Set the title of the contact sheet (IM: -title).

=item B<--contact-sheet-bg> or B<--cs-bg> I<COLOR>

Background color (IM: -background).

=item B<--contact-sheet-bd> or B<--cs-bd> I<COLOR>

Border color (IM: -bordercolor).

=item B<--contact-sheet-mt> or B<--cs-mt> I<COLOR>

Frame color (IM: -mattecolor).

=item B<--contact-sheet-fn> or B<--cs-fn> I<STRING>

Render text with this font (IM: -font).

=item B<--contact-sheet-fl> or B<--cs-fl> I<COLOR>

Color to fill the text (IM: -fill).

=item B<--contact-sheet-lb> or B<--cs-lb> I<STRING>

Assign a label to an image (IM: -label).

=item B<--contact-sheet-fr> or B<--cs-fr> I<GEOMETRY>

Surround image with an ornamental border in N pixels (IM: -frame).

=item B<--contact-sheet-pntsz> or B<--cs-pntsz> I<NUMBER>

Font point size (IM: -pointsize).

=item B<--contact-sheet-shadow> or B<--cs-shadow>

Set the shadow beneath a tile to simulate depth (IM: -shadow).

=item B<--contact-sheet-thm-fl> or B<--cs-thm-fl> I<COLOR>

Color to fill the text in generated thumbnail.

=item B<--contact-sheet-thm-fn> or B<--cs-thm-fn> I<STRING>

Render the generated thumbnail text with this font (IM: -font).

=item B<--contact-sheet-thm-grfr> or B<--cs-thm-grfr> I<COLOR>

Generated thumbnail background gradient COLOR-from

=item B<--contact-sheet-thm-grto> or B<--cs-thm-grto> I<COLOR>

Generated thumbnail background gradient COLOR-to

=item B<--contact-sheet-thm-text> or B<--cs-thm-text> I<STRING>

Generated thumbnail text

=item B<--contact-sheet-rank> or B<--cs-rank>

Run ranking process according to the ranks defined with
B<--contact-sheet-rank-file> The result is the colored frames of the
thumbnails of contact sheets.

=item B<--contact-sheet-rank-file> or B<--cs-rank-file>

Path to the file with ranks. Its format is a "file rankcolor" per line.
Filename separated from the color by space or tabulation.

=over

01.file.jpg        red

02.JPG             CornflowerBlue

03.jpg             aquamarine

04.file.JPG        green

=back

Only the files found in the file will be ranked.

=back

=head1 B<KEYWORDIZER>

=over

=item B<--keywords>, B<--no-keywords>

Whether to fill Keywords tag. Default is to not. Be careful, since with this option
enabled, the existing keywords are rewriten. The keywords are taken from
F<.keywords> file or file specified with option B<--keywords-file>.

=item B<-k> or B<--keywords-file> F<FILE>

Path to the file with keywords. Its format is a keyword per line. The CR and
LF symbols are removed. Empty (only whitespace) lines are ignored. Any leading
and trailing whitespace is removed. For example, the line C<  _Test_  CRLF> is
read as C<_Test_>.

=item B<--keywords-replace>, B<--no-keywords-replace>

Replace existing Keywords tag list rather than add new values to it. Default
is not to replace.

=back

=head1 B<RENAMING>

=over

=item B<-n> or B<--name-template> I<TEMPLATE>

A template to use for creating new file names while renaming. It can also be
defined in the configuration file (variable Name Template). The default is
I<%Y%m%d%H%M%S>. For practical uses, see L</TEMPLATE EXAMPLES> section.

Interpreted sequences are:

=over

B<%%>	a literal %

B<%#>	a literal #

B<%C>	Numeric part of the original file name. Implemented for the sake
of cameras, that do not supply FileNumber EXIF tag (currently all makes,
except I<Canon>). Such cameras generate file names starting with letters
and ended with digits. No other symbols are allowed in file names, except
C<->, C<.> and C<_>.

B<%c>	Ordinal number of file in the processed file set (see also
B<--counter-fixed-field> option).

B<%d>	Day of month (01-31).

B<%E>	The value of ExposureTime tag, if defined.

B<%e>	Old file extension

B<%F>	The value of FNumber tag, if defined.

B<%H>	Hour (00-23).

B<%I>	The value of ISO tag, if defined.

B<%i>	FileNumber tag if exists (otherwise, it is replaced by string
C<NA>).

B<%M>	Minute (00-59).

B<%m>	Month (01-12).

B<%n>	Previous filename (the one before B<renrot> started processing).

B<%O>	Base part of the original filename (see B<%o>). In other words, the
first part from the beginning to the last dot character.

B<%o>	The name file had before it was processed by B<renrot> for the first
time. If the file was processed only once, the tag RenRotFileNameOriginal is
set to the original file name.

B<%S>	Second (00-59)

B<%W>	The value of WhiteBalance tag, if defined.

B<%Y>	Year with the century (1900, 1901, and so on)

B<%y>	Year without a century (00..99)

You can use value of any EXIF tag to be included as name part. To do that you
need to embrace tag name with sign B<"#">, while building name template
(see L</TEMPLATE EXAMPLES>).

Be careful, since any binary EXIF (like ThumbnaiImage) can produce totally
unexpected results.

=back

=item B<--no-rename>

Do not rename files (default is to rename them to YYYYmmddHHMMSS.ext)

=item B<--counter-fixed-field>, B<--no-counter-fixed-field>

Set fixed length for file counter, used in file name templates (see B<%c>).
It is enabled by default. Use B<--no-counter-fixed-field> to undo its effect.

=item B<--counter-start> I<NUMBER>

Initial value for the file counter (default is I<1>)

=item B<--counter-step> I<NUMBER>

Step to increment file counter with (default is I<1>)

=back

=head1 B<ROTATING>

=over

=item B<-r> or B<--rotate-angle> I<ANGLE>

Define the angle to rotate files and thumbnails. Allowed values for I<ANGLE>
are 90, 180 or 270. It is useful for files not having Orientation tag.

=item B<--rotate-thumb> I<ANGLE>

Rotate only thumbnails. Allowed values for I<ANGLE> are 90, 180 or 270 degrees.
Use if the files which were already rotated, but their thumbnails were not.

=item B<--only-orientation>

Rotate by changing the value of Orientation tag, no real rotation will be
made. The sequence of values to rotate an image from normal (0 degrees) by
90 degrees clockwise is: 0 -> 90 -> 180 -> 270 -> 0. It means. set Orientation
tag to 90cw after the first rotation, and increase that value by 90 each time
the rotation is applied. For 270cw the rotation algorithm uses the reverted
sequence. Rotation by 180cw triggers values in two pairs: 0 <-> 180
and 90 <-> 270. This option cannot be applied to mirror values of Orientation
tag.

=item B<--trim>, B<--no-trim>

Pass the C<-trim> option to L<jpegtran(1)>, to trim if needed. By default,
trimming is enabled. Use B<--no-trim> to disable it.

=item B<--no-rotate>

Do not rotate images (default is to rotate according to EXIF data).

=back

=head1 B<TAG WRITER>

=over

=item B<--comment-file> F<FILE>

File with commentaries. It is a low priority alias to I<TagFile = Comment: FILE>.

=item B<--user-comment> I<STRING>

A low priority alias to I<--tag UserComment: STRING>

=item B<-t> or B<--tag> I<TAG>

See the section L</TAGS>, for the detailed description

=item B<--no-tags>

No user's defined tags will be written.

=back

=head1 B<TEMPLATE EXAMPLES>

The name template C<01.%c.%Y%m%d%H%M%S.%i.shtr-%E.f-%F.wb-%W.iso-%I> (where
I<F> stays for FNumber, I<E> for ExposureTime, I<I> for ISO and I<W> for
WhiteBalance) can produce the following names:

=over

01.0021.20030414103656.NA.shtr-1by40.f-2.8.wb-Auto.iso-160.jpg

01.0024.20040131230857.100-0078.shtr-1by320.f-2.8.wb-Auto.iso-50.jpg

01.0022.20000820222108.NA.jpg

=back

The name template
C<01.%c.%Y%m%d%H%M%S.%i.shtr-#ExposureTime#.f-#FNumber#.wb-#WhiteBalance#.iso-#ISO#>
can produce the following names:

=over

01.0021.20030414103656.NA.shtr-1_40.f-2.8.wb-Auto.iso-160.jpg

01.0024.20040131230857.100-0078.shtr-1_320.f-2.8.wb-Auto.iso-50.jpg

01.0022.20000820222108.NA.jpg

=back

The aggregation template C<%Y%m%d> produces the following aggregation:

these three files

=over

01.11.20030414103656.NA.jpg

01.12.20030414103813.NA.jpg

01.13.20030414103959.NA.jpg

=back

will be stored in the directory I<20030414>, and

=over

01.14.20040131130857.100-0078.jpg

01.15.20040131131857.100-0079.jpg

01.16.20040131133019.100-0080.jpg

=back

will be stored in the directory F<20040131>.

=head1 CONFIG

A configuration file can be used to set some variables. B<Renrot> looks for
its configuration file, named F<renrot.conf>, in system configuration
directories F</etc/renrot> and F</usr/local/etc/renrot>, and in subdirectory
F<.renrot>. of the current user home directory. An alternate configuration
file can also be explicitly given using the B<--config-file> option.

The configuration file consists of a set of case-insensive keywords and their
values separated by equal sign. Each such keyword/value pair occupies a
separate line. Boolean variables can have one of the following values: 0, No,
False, Off, Disable for false, and 1, Yes, True, On, Enable for true.

The variables defined for use in the configuration file are, for example:

=over

=item B<mtime>

Set to C<Yes> for synchronize mtime with tags, otherwise set it to C<No>.

=item B<name template>

File name template (see B<--name-template>, for the description).

=item B<trim>

Set to C<Yes> to trim rotated images when using L<jpegtran(1)>.

=item B<aggregation mode>

Aggregation mode, possible values are: none, delta or template.

=item B<aggregation template>

Aggregation template, which defines the file aggregation (see
B<--aggr-template>, for the description).

=item B<aggregation virtual>

Defines virtualization for the existing aggregation modes (see the
B<--aggr-virtual> option).

=item B<Tag>, B<TagFile>

Refer to the section L</TAGS>, for the detailed description

=item B<include>

Include the named file.

=back

=head1 TAGS

A I<TAG> is defined by the following combination: I<TagName [Group]: 'value'>.
The defined tags are selected to be set and writen to the EXIF tree using
the command line option B<--tag> and/or configuration file options B<Tag>.

The syntax of the command line option B<--tag> is:

=over

B<--tag> I<TagName [Group]: 'value'>

=back

The syntax of the configuration file option B<Tag>:

=over

B<Tag> = I<TagName [Group]: 'value'>

=back

The parameters I<TagName> and I<Group> are passed to ExifTool as is. The
name of the group must be enclosed in square brackets. Its I<value> (after
the semicolon) can be enclosed in single quotes.

The TagFile keyword allows to set multi-line tags from a file. Its syntax is:

=over

B<TagFile> = I<TagName [Group]:> F<FILE>

=back

The following table summarizes the tags that can be used with the B<--tag>
option and B<Tag> keyword:

=over

=item B<Copyright>

Copyright notes.

=item B<Comment>

General comment.

=item B<UserComment>

Anything you would like to put as a comment.

=item B<CreatorContactInfoCiAdrCity>

A city tag.

=item B<CreatorContactInfoCiAdrCtry>

A country tag.

=item B<CreatorContactInfoCiAdrExtadr>

Extended address (usually includes street and apartment number).

=item B<CreatorContactInfoCiAdrPcode>

Zip code.

=item B<CreatorContactInfoCiAdrRegion>

Region.

=item B<CreatorContactInfoCiEmailWork>

Email.

=item B<CreatorContactInfoCiTelWork>

Phone number.

=item B<CreatorContactInfoCiUrlWork>

URL.

=back

Additionally, you can add any known tag here, using B<Tag> or B<TagFile>
options as described above.

=head1 FILES

=over

=item

The main configuration file B<renrot.conf> is searched in the following
locations (in the order of their appearance):

=over

=item B<~/.renrot/>

directory under user's home place

=item B</usr/local/etc/renrot/>

system directory

=item B</etc/renrot/>

system directory

=back

Take into consideration, the files which are found will be loaded and
parsed in the order when user's configuration has maximal priority.

=item

Other configuration files with additional options could be included into
main file:

=over

=item B<colors.conf>

colors setup for different output facilities

=item B<tags.conf>

different tags setup

=back

=item

The following files could be placed locally in the working directory:

=over

=item B<.keywords>

file with keywords (see B<--keywords-file>)

=item B<.rank>

file with ranks (see B<--contact-sheet-rank-file>)

=back

=back

=head1 BUGS

If you found some bug or have some nice propositions, you are welcome.
Additionally, please, read the section RESTRICTIONS in file README.

=over

=item 1.

It seems that on FreeBSD 6, Perl versions 5.8.x exhibits a bug that causes
B<renrot> to crash. The overal amount of memory for the perl process
increasing up to the user datasize limit (in FreeBSD default is 512M).

It seems to be a bug in perl's own malloc implementation. The bug should not
occur in any perl which uses the system malloc (unless the system malloc has
the same bug).

B<renrot> aborts with the error message:

=over

Out of memory during "large" request for XXXX bytes ...

=back

This, however, does not happen with Perl v.5.6.x

=item 2.

Some versions of ImageMagick render contact sheets incorrectly. it seems
it is the question to ImageMagick.

=back

=head1 AUTHORS

Copyright 2005-2012, Zeus Panchenko, Andy Shevchenko.

This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

=head1 SEE ALSO

L<Image::ExifTool(3pm)|Image::ExifTool>,
L<exiftool(1)>,
L<jpegtran(1)>,
L<Image::Magick(3pm)|Image::Magick>

=cut

Return to:

Send suggestions and report system problems to the System administrator.