This file is indexed.

/usr/bin/exiftool is in libimage-exiftool-perl 8.60-2.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell
#------------------------------------------------------------------------------
# File:         exiftool
#
# Description:  Read/write meta information
#
# Revisions:    Nov. 12/03 - P. Harvey Created
#               (See html/history.html for revision history)
#
# References:   ATV - Alexander Vonk, private communication
#------------------------------------------------------------------------------
use strict;
require 5.004;

my $version = '8.60';

# add our 'lib' directory to the include list BEFORE 'use Image::ExifTool'
my $exeDir;
BEGIN {
    # get exe directory
    $exeDir = ($0 =~ /(.*)[\\\/]/) ? $1 : '.';
    # add lib directory at start of include path
    unshift @INC, "$exeDir/lib";
    # disable config file if specified
    if (@ARGV and lc($ARGV[0]) eq '-config') {
        shift;
        $Image::ExifTool::configFile = shift;
    }
}
use Image::ExifTool qw{:Public};

# function prototypes
sub SigInt();
sub Cleanup();
sub GetImageInfo($$);
sub SetImageInfo($$);
sub CleanXML($);
sub EncodeXML($);
sub FormatXML($$$);
sub EscapeJSON($;$);
sub FormatJSON($$$);
sub ConvertBinary($);
sub DoSetFromFile($$$);
sub CleanFilename($);
sub ProcessFiles($;$);
sub ScanDir($$;$);
sub PreserveTime();
sub LoadPrintFormat($);
sub FilenameSPrintf($;$);
sub NextUnusedFilename($;$);
sub CreateDirectory($);
sub SourceFile($);
sub OpenOutputFile($);
sub AcceptFile($);
sub SlurpFile($$);
sub ReadStayOpen($);
sub PrintCSV();
sub PrintTagList($@);
sub PrintErrors($$$);

# do cleanup on Ctrl-C
$SIG{INT} = 'SigInt';

END {
    Cleanup();
}

# declare all static variables
my @commonArgs;     # arguments common to all commands
my @csvFiles;       # list of files when reading with CSV option
my @csvTags;        # order of tags for first file with CSV option (lower case)
my @delFiles;       # list of files to delete
my @dynamicFiles;   # list of -tagsFromFile files with dynamic names
my @dynamicValues;  # list of -TAG<=FMT pairs for setting new values
my @exclude;        # list of excluded tags
my @fileOrder;      # tags to use for ordering of input files
my @files;          # list of files and directories to scan
my @moreArgs;       # more arguments to process after -stay_open -@
my @newValues;      # list of new tag values to set
my @tags;           # list of tags to extract
my %csvTags;        # lookup for all found tags with CSV option (lower case keys)
my %database;       # lookup for database information based on file name
my %excludeGrp;     # hash of tags excluded by group
my %filterExt;      # lookup for filtered extensions
my %ignore;         # directory names to ignore
my %preserveTime;   # preserved timestamps for files
my %printFmt;       # the contents of the print format file
my %setTags;        # hash of list references for tags to set from files
my %warnedOnce;     # lookup for once-only warnings
my $addGeotime;     # automatically added geotime argument
my $allGroup;       # show group name for all tags
my $allInGroup;     # flag to show all tags in a group
my $argFormat;      # use exiftool argument-format output
my $binaryOutput;   # flag for binary output (undef or 1, or 0 for binary XML)
my $binaryStdout;   # flag set if we output binary to stdout
my $comma;          # flag set if we need a comma in JSON output
my $condition;      # conditional processing of files
my $count;          # count of files scanned
my $countBad;       # count of files with errors
my $countBadCr;     # count files not created due to errors
my $countBadWr;     # count write errors
my $countCopyWr;    # count of files copied without being changed
my $countCreated;   # count output files created
my $countDir;       # count of directories scanned
my $countFailed;    # count files that failed condition
my $countGoodCr;    # count files created OK
my $countGoodWr;    # count files written OK
my $countNewDir;    # count of directories created
my $countSameWr;    # count files written OK but not changed
my $critical;       # flag for critical operations (disable CTRL-C)
my $csv;            # flag for CSV option (set to "CSV", or maybe "JSON" when writing)
my $csvAdd;         # flag to add CSV information to existing lists
my $deleteOrig;     # 0=restore original files, 1=delete originals, 2=delete w/o asking
my $disableOutput;  # flag to disable normal output
my $doGlob;         # flag set to do filename wildcard expansion
my $doSetFileName;  # flag set if FileName may be written
my $doUnzip;        # flag to extract info from .gz and .bz2 files
my $escapeHTML;     # flag to escape printed values for html
my $escapeXML;      # flag to escape printed values for xml
my $evalWarning;    # warning from eval
my $fileHeader;     # header to print to output file (or console, once)
my $fileTrailer;    # trailer for output file
my $filtered;       # flag indicating file was filtered by name
my $filterFlag;     # file filter flag (0x01=deny extensions, 0x02=allow extensions)
my $fixLen;         # flag to fix description lengths when writing alternate languages
my $forcePrint;     # force printing of tags whose values weren't found
my $helped;         # flag to avoid printing help if no tags specified
my $html;           # flag for html-formatted output (2=html dump)
my $interrupted;    # flag set if CTRL-C is pressed during a critical process
my $isWriting;      # flag set if we are writing tags
my $joinLists;      # flag set to join list values into a single string
my $json;           # flag for JSON-formatted output
my $listSep;        # list item separator (', ' by default)
my $mainTool;       # main ExifTool object
my $multiFile;      # non-zero if we are scanning multiple files
my $outFormat;      # -1=Canon format, 0=same-line, 1=tag names, 2=values only
my $outOpt;         # output file or directory name
my $overwriteOrig;  # flag to overwrite original file
my $pause;          # pause before returning
my $preserveTime;   # flag to preserve times of updated files
my $quiet;          # flag to disable printing of informational messages / warnings
my $recurse;        # recurse into subdirectories
my $rtnVal;         # command return value (0=success)
my $scanWritable;   # flag to process only writable file types
my $seqFileNum;     # sequential file number used for %C
my $setTagsFile;    # filename for last TagsFromFile option
my $showGroup;      # number of group to show (may be zero or '')
my $showTagID;      # non-zero to show tag ID's
my $srcFmt;         # source file name format string
my $stayOpenBuff='';# buffer for -stay_open file
my $structOpt;      # output structured XMP information (JSON and XML output only)
my $tabFormat;      # non-zero for tab output format
my $textOut;        # extension for text output file (or undef for no output)
my $textOverwrite;  # flag to overwrite existing text output file
my $tmpFile;        # temporary file to delete on exit
my $tmpText;        # temporary text file
my $useMWG;         # flag set if we are using any MWG tag
my $utf8;           # flag set if we are using UTF-8 encoding
my $validFile;      # flag indicating we processed a valid file
my $verbose;        # verbose setting
my $xml;            # flag for XML-formatted output

# flag to keep the input -@ argfile open:
# 0 = normal behaviour
# 1 = received "-stay_open true" and waiting for argfile to keep open
# 2 = currently reading from STAYOPEN argfile
# 3 = waiting for -@ to switch to a new STAYOPEN argfile
my $stayOpen = 0;

# lookup for O/S names which may use a backslash as a directory separator
# (ref File::Spec of PathTools-3.2701)
my %hasBackslash = ( MSWin32 => 1, os2 => 1, dos => 1, NetWare => 1, symbian => 1, cygwin => 1 );

# lookup for O/S names which use CR/LF newlines
my %isCRLF = ( MSWin32 => 1, os2 => 1, dos => 1 );

# lookup for JSON characters that we escape specially
my %jsonChar = ( '"'=>'"', '\\'=>'\\', "\t"=>'t', "\n"=>'n', "\r"=>'r' );

# exit routine
sub Exit {
    if ($pause) {
        if (eval 'require Term::ReadKey') {
            print STDERR "-- press any key --";
            Term::ReadKey::ReadMode('cbreak');
            Term::ReadKey::ReadKey(0);
            Term::ReadKey::ReadMode(0);
            print STDERR "\b \b" x 20;
        } else {
            print STDERR "-- press RETURN --\n";
            <STDIN>;
        }
    }
    exit shift;
}
# my warning and error routines (NEVER say "die"!)
sub Warn  { warn(@_) if $quiet < 2 or $_[0] =~ /^Error/; }
sub Error { Warn @_; $rtnVal = 1; }
sub WarnOnce($) {
    Warn(@_) and $warnedOnce{$_[0]} = 1 unless $warnedOnce{$_[0]};
}

# define signal handlers and cleanup routine
sub SigInt()  {
    $critical and $interrupted = 1, return;
    Cleanup();
    exit 1;
}
sub Cleanup() {
    unlink $tmpFile if defined $tmpFile;
    unlink $tmpText if defined $tmpText;
    undef $tmpFile;
    undef $tmpText;
    PreserveTime() if %preserveTime;
}

#------------------------------------------------------------------------------
# main script
#

# separate arguments common to all commands
if (grep /^-common_args$/i, @ARGV) {
    my (@newArgs, $common);
    foreach (@ARGV) {
        if (/^-common_args$/i) {
            $common = 1;
            next;
        } elsif ($common) {
            push @commonArgs, $_;
        }
        push @newArgs, $_;
    }
    @ARGV = @newArgs;
}

#..............................................................................
# loop over sets of command-line arguments separated by "-execute"
Command: while (@ARGV or not defined $rtnVal or $stayOpen >= 2)
{

# attempt to restore text mode for STDOUT if necessary
if ($binaryStdout) {
    binmode(STDOUT,':crlf') if $] >= 5.006 and $isCRLF{$^O};
    $binaryStdout = 0;
}

# flush console and print "{ready}" message if -stay_open is in effect
if ($stayOpen >= 2 and not $quiet) {
    eval 'require IO::Handle' and STDERR->flush();
    my $save = $|;
    $| = 1;
    print "{ready}\n";
    $| = $save;
}

$rtnVal = 0 unless defined $rtnVal;

# initialize all static variables
# (not done: @commonArgs, @moreArgs, $critical, $binaryStdout, $helped,
#  $interrupted, $mainTool, $pause, $rtnVal, $stayOpen, $stayOpenBuff)
undef @csvFiles;
undef @csvTags;
undef @delFiles;
undef @dynamicFiles;
undef @dynamicValues;
undef @exclude;
undef @fileOrder;
undef @files;
undef @newValues;
undef @tags;
undef %csvTags;
undef %database;
undef %excludeGrp;
undef %filterExt;
undef %ignore;
undef %printFmt;
undef %preserveTime;
undef %setTags;
undef %warnedOnce;
undef $addGeotime;
undef $allGroup;
undef $allInGroup;
undef $argFormat;
undef $binaryOutput;
undef $comma;
undef $condition;
undef $csv;
undef $csvAdd;
undef $deleteOrig;
undef $disableOutput;
undef $doGlob;
undef $doSetFileName;
undef $doUnzip;
undef $escapeHTML;
undef $escapeXML;
undef $evalWarning;
undef $fileHeader;
undef $fileTrailer;
undef $filtered;
undef $fixLen;
undef $forcePrint;
undef $joinLists;
undef $multiFile;
undef $outOpt;
undef $preserveTime;
undef $recurse;
undef $scanWritable;
undef $setTagsFile;
undef $showGroup;
undef $showTagID;
undef $srcFmt;
undef $structOpt;
undef $textOut;
undef $textOverwrite;
undef $tmpFile;
undef $tmpText;
undef $useMWG;
undef $validFile;
undef $verbose;

$count = 0;
$countBad = 0;
$countBadCr = 0;
$countBadWr = 0;
$countCopyWr = 0;
$countCreated = 0;
$countDir = 0;
$countFailed = 0;
$countGoodCr = 0;
$countGoodWr = 0;
$countNewDir = 0;
$countSameWr = 0;
$filterFlag = 0;
$html = 0;
$isWriting = 0;
$json = 0;
$listSep = ', ';
$outFormat = 0;
$overwriteOrig = 0;
$quiet = 0;
$seqFileNum = 0;
$tabFormat = 0;
$utf8 = 1;
$xml = 0;

# for Windows, use globbing for wildcard expansion if available - MK/20061010
if ($^O eq 'MSWin32' and eval "require File::Glob") {
    # override the core glob forcing case insensitivity
    import File::Glob qw(:globally :nocase);
    $doGlob = 1;
}

$mainTool = new Image::ExifTool;        # create ExifTool object

# don't extract duplicates by default unless set by UserDefined::Options
$mainTool->Options(Duplicates => 0) unless %Image::ExifTool::UserDefined::Options
    and defined $Image::ExifTool::UserDefined::Options{Duplicates};

# local variables
my ($doneCommonArgs, @nextPass);
my $pass = 0;

# parse command-line options in 2 passes...
# pass 1: set all of our ExifTool options
# pass 2: print all of our help and informational output (-list, -ver, etc)
for (;;) {
  if (not @ARGV) {
    if ($stayOpen >= 2) {
        ReadStayOpen(\@ARGV);   # read more arguments from -stay_open file
        next;
    }
    if ($pass == 0) {
        # require MWG module if used in any argument
        # (note: this also covers the -p option because these tags were added to @tags)
        $useMWG = 1 if not $useMWG and grep /^mwg:/i, @tags;
        require Image::ExifTool::MWG if $useMWG;
    }
    last unless @nextPass;
    # process arguments which were deferred to the next pass
    @ARGV = @nextPass;
    undef @nextPass;
    ++$pass;
  }
  $_ = shift;
  if (s/^(-|\xe2\x88\x92)//) {  # allow funny dashes (nroff dash bug for cut-n-paste from pod)
    s/^\xe2\x88\x92/-/;         # translate double-dash too
    my $a = lc $_;
    if (/^list([wfrdx]|wf|g(\d*))?$/i) {
        $pass or push(@nextPass,"-$_");
        my $type = lc($1 || '');
        if (not $type or $type eq 'w' or $type eq 'x') {
            my $group;
            if ($ARGV[0] and $ARGV[0] =~ /^(-|\xe2\x88\x92)(.+):(all|\*)$/i) {
                if ($pass == 0) {
                    $useMWG = 1 if lc($2) eq 'mwg';
                    push(@nextPass, shift);
                    next;
                }
                $group = $2;
                shift;
                $group =~ /IFD/i and Warn("Can't list tags for specific IFD\n"), next;
                $group =~ /^(all|\*)$/ and undef $group;
            } else {
                $pass or next;
            }
            $helped = 1;
            if ($type eq 'x') {
                require Image::ExifTool::TagInfoXML;
                my %opts;
                $opts{Flags} = 1 if $forcePrint;
                $opts{NoDesc} = 1 if $outFormat > 0;
                Image::ExifTool::TagInfoXML::Write(undef, $group, %opts);
                next;
            }
            my $wr = ($type eq 'w');
            my $msg = ($wr ? 'Writable' : 'Available') . ($group ? " $group" : '') . ' tags';
            PrintTagList($msg, $wr ? GetWritableTags($group) : GetAllTags($group));
            # also print shortcuts if listing all tags
            next if $group or $wr;
            my @tagList = GetShortcuts();
            PrintTagList('Command-line shortcuts', @tagList) if @tagList;
            next;
        }
        $pass or next;
        $helped = 1;
        if ($type eq 'wf') {
            my @wf;
            CanWrite($_) and push @wf, $_ foreach GetFileType();
            PrintTagList('Writable file extensions', @wf);
        } elsif ($type eq 'f') {
            PrintTagList('Supported file extensions', GetFileType());
        } elsif ($type eq 'r') {
            PrintTagList('Recognized file extensions', GetFileType(undef, 0));
        } elsif ($type eq 'd') {
            PrintTagList('Deletable groups', GetDeleteGroups());
        } else { # 'g(\d*)'
            # list all groups in specified family
            my $family = $2 || 0;
            PrintTagList("Groups in family $family", GetAllGroups($family));
        }
        next;
    }
    if ($a eq 'ver') {
        $pass or push(@nextPass,'-ver'), next;
        my $libVer = $Image::ExifTool::VERSION;
        my $str = $libVer eq $version ? '' : " [Warning: Library version is $libVer]";
        print("$version$str$Image::ExifTool::RELEASE\n");
        $helped = 1;
        next;
    }
    if (/^(all|add)?tagsfromfile(=.*)?$/i) {
        $setTagsFile = $2 ? substr($2,1) : (@ARGV ? shift : '');
        if ($setTagsFile eq '') {
            Error("File must be specified for -tagsFromFile option\n");
            next Command;
        }
        push(@newValues, "TagsFromFile=$setTagsFile");
        $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
        push @{$setTags{$setTagsFile}}, { Replace => ($1 and lc($1) eq 'add') ? 0 : 1 };
        next;
    }
    if ($a eq '@') {
        my $argFile = shift or Error("Expecting filename for -\@ option\n"), next Command;
        # switch to new ARGFILE if using chained -stay_open options
        close STAYOPEN and $stayOpen = 1 if $stayOpen == 3;
        my $fp = ($stayOpen == 1 ? \*STAYOPEN : \*ARGFILE);
        unless (open($fp, "<$argFile")) {
            unless ($argFile !~ /^\// and open($fp, "<$exeDir/$argFile")) {
                Error "Error opening arg file $argFile\n";
                next Command;
            }
        }
        if ($stayOpen == 1) {
            # defer remaining arguments until we close this argfile
            @moreArgs = @ARGV;
            undef @ARGV;
            $stayOpen = 2;
            $helped = 1;
            ReadStayOpen(\@ARGV);
            next;
        }
        my (@newArgs, $didBOM);
        foreach (<ARGFILE>) {
            # filter Byte Order Mark if it exists from start of UTF-8 text file
            unless ($didBOM) {
                s/^\xef\xbb\xbf//;
                $didBOM = 1;
            }
            s/^\s+//; s/\s+$//s; # remove leading/trailing white space
            # remove white space before, and single space after '=', '+=', '-=' or '<='
            s/^([-\w]+)\s*([-+<]?=) ?/$1$2/;
            push @newArgs, $_ unless $_ eq '' or /^#/;
        }
        close ARGFILE;
        unshift @ARGV, @newArgs;
        next;
    }
    /^(-?)(a|duplicates)$/i and $mainTool->Options(Duplicates => ($1 ? 0 : 1)), next;
    /^arg(s|format)$/i and $argFormat = 1, next;
    /^b(inary)?$/i and $mainTool->Options(Binary => 1), $binaryOutput = 1,  next;
    if (/^c(oordFormat)?$/i) {
        my $fmt = shift;
        $fmt or Error("Expecting coordinate format for -c option\n"), next Command;
        $mainTool->Options('CoordFormat', $fmt);
        next;
    }
    if ($a eq 'charset') {
        my $charset = (@ARGV and $ARGV[0] !~ /^(-|\xe2\x88\x92)/) ? shift : undef;
        if (not $charset or $charset =~ /=$/) {
            $pass or push(@nextPass, '-charset'), next;
            my %charsets;
            $charsets{$_} = 1 foreach values %Image::ExifTool::charsetName;
            PrintTagList('Available character sets', sort keys %charsets);
            $helped = 1;
        } elsif ($charset !~ s/^(\w+)=// or lc($1) eq 'exiftool') {
            $mainTool->Options(Charset => $charset);
            $utf8 = ($mainTool->Options('Charset') eq 'UTF8');
        } else {
            # set internal encoding of specified metadata type
            my $type = { id3 => 'ID3', iptc => 'IPTC', photoshop => 'Photoshop' }->{lc $1};
            $type or Warn("Unknown type for -charset option: $1\n"), next;
            $mainTool->Options("Charset$type" => $charset);
        }
        next;
    }
    /^config$/i and Warn("Ignored -config option (not first on command line)\n"), shift, next;
    if (/^csv(\+?=.*)?/i) {
        # must process on 2nd pass so -f option is available
        $pass or push(@nextPass,"-$_"), next;
        my $csvFile = $1;
        if ($csvFile) {
            $csvFile =~ s/^(\+?=)//;
            $csvAdd = 1 if $1 eq '+=';
            require Image::ExifTool::Import;
            my $msg = Image::ExifTool::Import::ReadCSV($csvFile, \%database, $forcePrint);
            $msg and Warn("$msg\n");
            $isWriting = 1;
        }
        $csv = 'CSV';
        next;
    }
    if (/^d$/ or $a eq 'dateformat') {
        my $fmt = shift;
        $fmt or Error("Expecting date format for -d option\n"), next Command;
        $mainTool->Options('DateFormat', $fmt);
        next;
    }
    (/^D$/ or $a eq 'decimal') and $showTagID = 'D', next;
    /^delete_original(!?)$/i and $deleteOrig = ($1 ? 2 : 1), next;
    (/^e$/ or $a eq '-composite') and $mainTool->Options(Composite => 0), next;
    (/^-e$/ or $a eq 'composite') and $mainTool->Options(Composite => 1), next;
    (/^E$/ or $a eq 'escapehtml') and require Image::ExifTool::HTML and $escapeHTML = 1, next;
    ($a eq 'ex' or $a eq 'escapexml') and $escapeXML = 1, next;
    if (/^echo(2)?$/i) {
        # undocumented debugging options:
        # -echo TXT   - send TXT to STDOUT
        # -echo2 TXT  - send TXT to STDERR
        next unless @ARGV;
        $pass or push(@nextPass, "-$_", shift), next;
        print {$1 ? \*STDERR : \*STDOUT} shift, "\n";
        $helped = 1;
        next;
    }
    if (/^(ee|extractembedded)$/i) {
        $mainTool->Options(ExtractEmbedded => 1);
        $mainTool->Options(Duplicates => 1);
        next;
    }
    if ($a eq 'execute') {
        # parse common arguments first if necessary
        if (@commonArgs and not $doneCommonArgs) {
            unshift @ARGV, @commonArgs, '-execute';
            $doneCommonArgs = 1;
            next;
        }
        # require MWG module before 2nd pass if used in any argument
        if ($pass == 0) {
            $useMWG = 1 if not $useMWG and grep /^mwg:/i, @tags;
            require Image::ExifTool::MWG if $useMWG;
        }
        # go back for 2nd pass of arguments if necessary
        if (@nextPass) {
            unshift @ARGV, @nextPass, '-execute';
            undef @nextPass;
            ++$pass;
            next;
        }
        $helped = 1;
        last;   # execute the command now
    }
    if (/^-?ext(ension)?$/i) {
        my $ext = shift;
        defined $ext or Error("Expecting extension for -ext option\n"), next Command;
        $ext =~ s/^\.//;    # remove leading '.' if it exists
        my $flag = /^-/ ? 0 : 1;
        $filterFlag |= (0x01 << $flag);
        $filterExt{uc($ext)} = $flag;
        next;
    }
    if (/^f$/ or $a eq 'forceprint') {
        $forcePrint = 1;
        $mainTool->Options(MissingTagValue => '-');
        next;
    }
    if (/^F([-+]?\d*)$/ or /^fixbase([-+]?\d*)$/i) {
        $mainTool->Options(FixBase => $1);
        next;
    }
    if (/^fast(\d*)$/i) {
        $mainTool->Options(FastScan => (length $1 ? $1 : 1));
        next;
    }
    if ($a eq 'fileorder') {
        push @fileOrder, shift if @ARGV;
        next;
    }
    if (/^(g)(roupHeadings|roupNames)?([\d:]*)$/i) {
        $showGroup = $3 || 0;
        $allGroup = ($2 ? lc($2) eq 'roupnames' : $1 eq 'G');
        $mainTool->Options(SavePath => 1) if $showGroup =~ /\b5\b/;
        next;
    }
    if ($a eq 'geotag') {
        my $trkfile = shift;
        $trkfile or Error("Expecting file name for -geotag option\n"), next Command;
        # allow wildcards in filename
        if ($trkfile =~ /[*?]/) {
            my @trks = $doGlob ? File::Glob::bsd_glob($trkfile) : glob($trkfile);
            @trks or Error("No matching file found for -geotag option\n"), next Command;
            push @newValues, 'geotag='.shift(@trks) while @trks > 1;
            $trkfile = pop(@trks);
        }
        $_ = "geotag=$trkfile";
        # (fall through!)
    }
    if (/^h$/ or $a eq 'htmlformat') {
        require Image::ExifTool::HTML;
        $html = $escapeHTML = 1;
        $json = $xml = 0;
        next;
    }
    (/^H$/ or $a eq 'hex') and $showTagID = 'H', next;
    if (/^htmldump([-+]?\d+)?$/i) {
        $verbose = ($verbose || 0) + 1;
        $html = 2;
        $mainTool->Options(HtmlDumpBase => $1) if defined $1;
        next;
    }
    if (/^i(gnore)?$/i) {
        my $dir = shift;
        defined $dir or Error("Expecting directory name for -i option\n"), next Command;
        $ignore{$dir} = 1;
        next;
    }
    if ($a eq 'if') {
        my $cond = shift;
        defined $cond or Error("Expecting expression for -if option\n"), next Command;
        $useMWG = 1 if $cond =~ /\$\{?mwg:/i;
        if (defined $condition) {
            $condition .= " and ($cond)";
        } else {
            $condition = "($cond)";
        }
        next;
    }
    if (/^j(son)?(\+?=.*)?$/i) {
        if ($2) {
            # must process on 2nd pass because we need -f and -charset options
            $pass or push(@nextPass,"-$_"), next;
            my $jsonFile = $2;
            $jsonFile =~ s/^(\+?=)//;
            $csvAdd = 1 if $1 eq '+=';
            my $chset = $mainTool->Options('Charset');
            require Image::ExifTool::Import;
            my $msg = Image::ExifTool::Import::ReadJSON($jsonFile, \%database, $forcePrint, $chset);
            $msg and Warn("$msg\n");
            $isWriting = 1;
            $csv = 'JSON';
        } else {
            $json = 1;
            $html = $xml = 0;
            $mainTool->Options(Duplicates => 1);
        }
        next;
    }
    /^(k|pause)$/i and $pause = 1, next;
    (/^l$/ or $a eq 'long') and --$outFormat, next;
    (/^L$/ or $a eq 'latin') and $utf8 = 0, $mainTool->Options(Charset => 'Latin'), next;
    if ($a eq 'lang') {
        my $lang = (@ARGV and $ARGV[0] !~ /^-/) ? shift : undef;
        if ($lang) {
            # make lower case and use underline as a separator (ie. 'en_ca')
            $lang =~ tr/-A-Z/_a-z/;
            $mainTool->Options(Lang => $lang);
            next if $lang eq $mainTool->Options('Lang');
        } else {
            $pass or push(@nextPass, '-lang'), next;
        }
        my $langs = "Available languages:\n";
        $langs .= "  $_ - $Image::ExifTool::langName{$_}\n" foreach @Image::ExifTool::langs;
        $langs = $mainTool->Decode($langs, 'UTF8');
        $langs = Image::ExifTool::HTML::EscapeHTML($langs) if $escapeHTML;
        $lang and Error("Invalid or unsupported language '$lang'.\n$langs"), next Command;
        print $langs;
        $helped = 1;
        next;
    }
    /^(m|ignoreminorerrors)$/i and $mainTool->Options(IgnoreMinorErrors => 1), next;
    /^(n|-printconv)$/i and $mainTool->Options(PrintConv => 0), next;
    /^(-n|printconv)$/i and $mainTool->Options(PrintConv => 1), next;
    if (/^o(ut)?$/i) {
        $outOpt = shift;
        defined $outOpt or Error("Expected output file or directory name for -o option\n"), next Command;
        CleanFilename($outOpt);
        next;
    }
    /^overwrite_original$/i and $overwriteOrig = 1, next;
    /^overwrite_original_in_place$/i and $overwriteOrig = 2, next;
    (/^p$/ or $a eq 'printformat') and LoadPrintFormat(shift), next;
    (/^P$/ or $a eq 'preserve') and $preserveTime = 1, next;
    /^password$/i and $mainTool->Options(Password => shift), next;
    /^q(uiet)?$/i and ++$quiet, next;
    /^r(ecurse)?$/i and $recurse = 1, next;
    /^restore_original$/i and $deleteOrig = 0, next;
    (/^S$/ or $a eq 'veryshort') and $outFormat+=2, next;
    /^s(hort)?(\d*)$/i and $outFormat = $2 eq '' ? $outFormat + 1 : $2, next;
    /^scanforxmp$/i and $mainTool->Options(ScanForXMP => 1), next;
    if (/^sep(arator)?$/i) {
        $listSep = shift;
        defined $listSep or Error("Expecting list item separator for -sep option\n"), next Command;
        $mainTool->Options(ListSep => $listSep);
        $joinLists = 1;
        # also split when writing values
        my $listSplit = quotemeta $listSep;
        # a space in the string matches zero or more whitespace characters
        $listSplit =~ s/(\\ )+/\\s\*/g;
        # but a single space alone matches one or more whitespace characters
        $listSplit = '\\s+' if $listSplit eq '\\s*';
        $mainTool->Options(ListSplit => $listSplit);
        next;
    }
    /^srcfile$/i and $srcFmt = shift || Warn("Expecting FMT for -srcfile option\n"), next;
    if ($a eq 'stay_open') {
        my $arg = shift;
        defined $arg or Warn("Expecting argument for -stay_open option\n"), next;
        if ($arg =~ /^(1|true)$/i) {
            if (not $stayOpen) {
                $stayOpen = 1;
            } elsif ($stayOpen == 2) {
                $stayOpen = 3;  # chained -stay_open options
            } else {
                Warn "-stay_open already active\n";
            }
        } elsif ($arg =~ /^(0|false)$/i) {
            if ($stayOpen >= 2) {
                # close STAYOPEN -@ file and process arguments up to this point
                close STAYOPEN;
                push @ARGV, $stayOpenBuff if length $stayOpenBuff;
                push @ARGV, @moreArgs;
                undef @moreArgs;
                $stayOpenBuff = '';
            } elsif (not $stayOpen) {
                Warn("-stay_open wasn't active\n");
            }
            $stayOpen = 0;
        } else {
            Warn "Invalid argument for -stay_open\n";
        }
        next;
    }
    if (/^(-)?struct$/i) {
        $structOpt = $1 ? 0 : 1;
        $mainTool->Options(Struct => $structOpt);
        # require XMPStruct in case we need to serialize a structure
        require 'Image/ExifTool/XMPStruct.pl' if $structOpt;
        next;
    }
    /^t(ab)?$/  and $tabFormat = 1, next;
    if (/^T$/ or $a eq 'table') {
        $tabFormat = 1; $outFormat+=2; ++$quiet; $forcePrint = 1;
        $mainTool->Options(MissingTagValue => '-');
        next;
    }
    if (/^(u)(nknown(2)?)?$/i) {
        my $inc = ($3 or (not $2 and $1 eq 'U')) ? 2 : 1;
        $mainTool->Options(Unknown => $mainTool->Options('Unknown') + $inc);
        next;
    }
    if ($a eq 'use') {
        my $module = shift;
        $module or Error("Expecting module name for -use option\n"), next Command;
        lc $module eq 'mwg' and $useMWG = 1, next;
        local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };
        unless (eval "require Image::ExifTool::$module" or
                eval "require $module" or
                eval "require '$module'")
        {
            delete $SIG{'__WARN__'};
            Error("Error using module $module\n");
            next Command;
        }
        next;
    }
    if (/^v(erbose)?(\d*)$/i) {
        $verbose = ($2 eq '') ? ($verbose || 0) + 1 : $2;
        next;
    }
    if (/^(w|textout)(!?)$/i) {
        $textOut = shift || Warn("Expecting output extension for -$_ option\n");
        $textOverwrite = $2;
        next;
    }
    if (/^x$/ or $a eq 'exclude') {
        my $tag = shift;
        defined $tag or Error("Expecting tag name for -x option\n"), next Command;
        $tag =~ s/\ball\b/\*/ig;    # replace 'all' with '*' in tag names
        if ($setTagsFile) {
            push @{$setTags{$setTagsFile}}, "-$tag";
        } else {
            push @exclude, $tag;
        }
        next;
    }
    (/^X$/ or $a eq 'xmlformat') and $xml = 1, $html = $json = 0, $mainTool->Options(Duplicates => 1), next;
    /^z(ip)?$/i and $doUnzip = 1, $mainTool->Options(Compress => 1), next;
    $_ eq '' and push(@files, '-'), next;   # read STDIN
    length $_ eq 1 and $_ ne '*' and Error("Unknown option -$_\n"), next Command;
    if (/^[^<]+(<?)=(.*)/s) {
        my $val = $2;
        push @newValues, $_;
        if (/^mwg:/i) {
            $useMWG = 1;
        } elsif (/^([-\w]+:)*(filename|directory)\b/i) {
            $doSetFileName = 1;
        } elsif (/^([-\w]+:)*(geotag|geotime)\b/i) {
            if (lc $2 eq 'geotag') {
                if ((not defined $addGeotime or $addGeotime) and length $val) {
                    $addGeotime = ($1 || '') . 'Geotime<DateTimeOriginal';
                }
            } else {
                $addGeotime = '';
            }
        }
    } else {
        if (not $setTagsFile and /(<|>)/) {
            # assume '-tagsFromFile @' if tags are being redirected
            # and -tagsFromFile hasn't already been specified
            $setTagsFile = '@';
            push(@newValues, "TagsFromFile=@");
            $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
        }
        if ($setTagsFile) {
            push @{$setTags{$setTagsFile}}, $_;
            if (/>/) {
                $useMWG = 1 if /^(.*>\s*)?mwg:/si;
                if (/\b(filename|directory)#?$/i) {
                    $doSetFileName = 1;
                } elsif (/\bgeotime#?$/i) {
                    $addGeotime = '';
                }
            } else {
                $useMWG = 1 if /^([^<]+<\s*(.*\$\{?)?)?mwg:/si;
                if (/^([-\w]+:)*(filename|directory)\b/i) {
                    $doSetFileName = 1;
                } elsif (/^([-\w]+:)*geotime\b/i) {
                    $addGeotime = '';
                }
            }
        } elsif (/^-(.*)/) {
            push @exclude, $1;
        } else {
            push @tags, $_;
        }
    }
  } elsif ($doGlob and /[*?]/) {
    # glob each filespec if necessary - MK/20061010
    push @files, File::Glob::bsd_glob($_);
    $doGlob = 2;
  } else {
    push @files, $_;
  }
}

# print help
unless ((@tags and not $outOpt) or @files or @newValues) {
    if ($doGlob and $doGlob == 2) {
        Warn "No matching files\n";
        $rtnVal = 1;
        next;
    }
    if ($outOpt) {
        Warn "Nothing to write\n";
        $rtnVal = 1;
        next;
    }
    unless ($helped) {
        # catch warnings if we have problems running perldoc
        local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };
        my $dummy = \*SAVEERR;  # avoid "used only once" warning
        unless ($^O eq 'os2') {
            open SAVEERR, ">&STDERR";
            open STDERR, '>/dev/null';
        }
        if (system('perldoc',$0)) {
            print "Syntax:  exiftool [OPTIONS] FILE\n\n";
            print "Consult the exiftool documentation for a full list of options.\n";
        }
        unless ($^O eq 'os2') {
            close STDERR;
            open STDERR, '>&SAVEERR';
        }
    }
    next;
}

# do sanity check on -delete_original and -restore_original
if (defined $deleteOrig and (@newValues or @tags)) {
    if (not @newValues) {
        my $verb = $deleteOrig ? 'deleting' : 'restoring from';
        Warn "Can't specify tags when $verb originals\n";
    } elsif ($deleteOrig) {
        Warn "Can't use -delete_original when writing.\n";
        Warn "Maybe you meant -overwrite_original ?\n";
    } else {
        Warn "It makes no sense to use -restore_original when writing\n";
    }
    $rtnVal = 1;
    next;
}

if ($overwriteOrig > 1 and $outOpt) {
    Warn "Can't overwrite in place when -o option is used\n";
    $rtnVal = 1;
    next;
}

if ($escapeHTML or $json) {
    # must be UTF8 for HTML conversion and JSON output
    $mainTool->Options(Charset => 'UTF8');
    # use Escape option to do our HTML escaping unless XML output
    $mainTool->Options(Escape => 'HTML') if $escapeHTML and not $xml;
} elsif ($escapeXML and not $xml) {
    $mainTool->Options(Escape => 'XML');
}

# set up for RDF/XML and JSON output formats
if ($xml) {
    require Image::ExifTool::XMP;   # for EscapeXML()
    my $charset = $mainTool->Options('Charset');
    # standard XML encoding names for supported Charset settings
    # (ref http://www.iana.org/assignments/character-set)
    my %encoding = (
        UTF8     => 'UTF-8',
        Latin    => 'windows-1252',
        Latin2   => 'windows-1250',
        Cyrillic => 'windows-1251',
        Greek    => 'windows-1253',
        Turkish  => 'windows-1254',
        Hebrew   => 'windows-1255',
        Arabic   => 'windows-1256',
        Baltic   => 'windows-1257',
        Vietnam  => 'windows-1258',
        MacRoman => 'macintosh',
    );
    # switch to UTF-8 if we don't have a standard encoding name
    unless ($encoding{$charset}) {
        $charset = 'UTF8';
        $mainTool->Options(Charset => $charset);
    }
    # set file header/trailer for XML output
    $fileHeader = "<?xml version='1.0' encoding='$encoding{$charset}'?>\n" .
                  "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n";
    $fileTrailer = "</rdf:RDF>\n";
    # extract as a list unless short output format
    $joinLists = 1 if $outFormat > 0;
    $mainTool->Options(List => 1) unless $joinLists;
    $showGroup = $allGroup = 1;         # always show group 1
    # set binaryOutput flag to 0 or undef (0 = output encoded binary in XML)
    $binaryOutput = ($outFormat > 0 ? undef : 0) if $binaryOutput;
    $showTagID = 'D' if $tabFormat and not $showTagID;
} elsif ($json) {
    $fileHeader = "[";
    $fileTrailer = "]\n";
    $mainTool->Options(List => 1) unless $joinLists;
    $mainTool->Options(Duplicates => 0) unless defined $showGroup;
    undef $binaryOutput; # can't currently use -b with -json
} elsif ($structOpt) {
    $mainTool->Options(List => 1);
} else {
    $joinLists = 1;     # join lists for all other unstructured output formats
}

if ($argFormat) {
    $outFormat = 3;
    $allGroup = 1 if defined $showGroup;
}

# change to forward slashes if necessary in all filenames (like CleanFilename)
if ($hasBackslash{$^O}) {
    tr/\\/\// foreach @files;
}

# can't do anything if no file specified
unless (@files) {
    unless ($outOpt) {
        Warn "No file specified\n";
        $rtnVal = 1;
        next;
    }
    push @files, '';    # create file from nothing
}

# set Verbose and HtmlDump options
if ($verbose) {
    $disableOutput = 1 unless @tags or @exclude;
    undef $binaryOutput;    # disable conflicting option
    if ($html) {
        $html = 2;    # flag for html dump
        $mainTool->Options(HtmlDump => $verbose);
    } else {
        $mainTool->Options(Verbose => $verbose);
    }
} elsif (defined $verbose) {
    # auto-flush output when -v0 is used
    require FileHandle;
    STDOUT->autoflush(1);
    STDERR->autoflush(1);
}

# validate all tags we're writing
if (@newValues) {
    # assume -geotime value if -geotag specified without -geotime
    if ($addGeotime) {
        unless ($setTagsFile and $setTagsFile eq '@') {
            $setTagsFile = '@';
            push(@newValues, "TagsFromFile=@");
            $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
        }
        push @{$setTags{$setTagsFile}}, $addGeotime;
        $verbose and print qq{Argument "-$addGeotime" is assumed\n};
    }
    # add/delete option lookup
    my %addDelOpt = ( '+' => 'AddValue', '-' => 'DelValue', "\xe2\x88\x92" => 'DelValue' );
    foreach (@newValues) {
        /(.*?)=(.*)/s or next;
        my ($tag, $newVal) = ($1, $2);
        $tag =~ s/\ball\b/\*/ig;    # replace 'all' with '*' in tag names
        $newVal eq '' and undef $newVal;    # undefined to delete tag
        if ($tag =~ /^(All)?TagsFromFile$/i) {
            defined $newVal or Error("Need file name for -tagsFromFile\n"), next Command;
            ++$isWriting;
            if ($newVal eq '@' or not defined FilenameSPrintf($newVal)) {
                push @dynamicFiles, $newVal unless grep /^$newVal$/, @dynamicFiles;
                next;   # set tags from dynamic file later
            }
            unless (-e $newVal) {
                Warn "File '$newVal' does not exist for -tagsFromFile option\n";
                $rtnVal = 1;
                next Command;
            }
            # set specified tags from this file
            unless (DoSetFromFile($mainTool, $newVal, $setTags{$newVal})) {
                $rtnVal = 1;
                next Command;
            }
            next;
        }
        my %opts = (
            Protected => 1, # allow writing of 'unsafe' tags
            Shift => 0,     # shift values if possible instead of adding/deleting
        );
        if ($tag =~ s/<// and defined $newVal) {
            if (defined FilenameSPrintf($newVal)) {
                SlurpFile($newVal, \$newVal) or next;
            } else {
                $tag =~ s/([-+]|\xe2\x88\x92)$// and $opts{$addDelOpt{$1}} = 1;
                # verify that this tag can be written
                my $result = Image::ExifTool::IsWritable($tag);
                if ($result) {
                    # add to list of dynamic tag values
                    push @dynamicValues, [ $tag, $newVal, \%opts ];
                    ++$isWriting;
                } elsif (defined $result) {
                    Warn "Tag '$tag' is not writable\n";
                } else {
                    Warn "Tag '$tag' does not exist\n";
                }
                next;
            }
        }
        if ($tag =~ s/([-+]|\xe2\x88\x92)$//) {
            $opts{$addDelOpt{$1}} = 1;  # set AddValue or DelValue option
            # set $newVal to '' if deleting nothing
            $newVal = '' if $1 eq '-' and not defined $newVal;
        }
        my ($rtn, $wrn) = $mainTool->SetNewValue($tag, $newVal, %opts);
        ++$isWriting if $rtn;
        $wrn and Warn "Warning: $wrn\n";
    }
    # exclude specified tags
    foreach (@exclude) {
        $mainTool->SetNewValue($_, undef, Replace => 2);
    }
    unless ($isWriting or $outOpt or @tags) {
        Warn "Nothing to do.\n";
        $rtnVal = 1;
        next;
    }
} elsif (grep /^(\*:)?\*$/, @exclude) {
    Warn "All tags excluded -- nothing to do.\n";
    $rtnVal = 1;
    next;
}
if ($isWriting and @tags and not $outOpt) {
    my ($tg, $s) = @tags > 1 ? ("$tags[0] ...", 's') : ($tags[0], '');
    Warn "Ignored superfluous tag name$s or invalid option$s: -$tg\n";
}
# save current state of new values if setting values from target file
# or if we may be translating to a different format
$mainTool->SaveNewValues() if $outOpt or @dynamicFiles or @dynamicValues or $csv;

$multiFile = 1 if @files > 1;
@exclude and $mainTool->Options(Exclude => \@exclude);

undef $binaryOutput if $html;

if ($binaryOutput) {
    $outFormat = 99;    # shortest possible output format
    $mainTool->Options(PrintConv => 0);
    unless ($textOut or $binaryStdout) {
        binmode(STDOUT);
        $binaryStdout = 1;
    }
    # disable conflicting options
    undef $showGroup;
}

# sort by groups to look nicer depending on options
if (defined $showGroup and not (@tags and $allGroup)) {
    $mainTool->Options(Sort => "Group$showGroup"),
}

if (defined $textOut) {
    CleanFilename($textOut);  # make all forward slashes
    # add '.' before output extension if necessary
    $textOut = ".$textOut" unless $textOut =~ /[.%]/;
}

# determine if we should scan for only writable files
if ($outOpt) {
    my $type = GetFileType($outOpt);
    if ($type) {
        unless (CanWrite($type)) {
            Warn "Can't write $type files\n";
            $rtnVal = 1;
            next;
        }
        $scanWritable = $type unless CanCreate($type);
    } else {
        $scanWritable = 1;
    }
    $isWriting = 1;     # set writing flag
} elsif ($isWriting) {
    $scanWritable = 1;
}

# set flag to fix description lengths if necessary
$fixLen = ($utf8 and $mainTool->Options('Lang') ne 'en' and eval 'require Encode');

# sort input files if specified
if (@fileOrder) {
    my @allFiles;
    ProcessFiles(undef, \@allFiles);
    my $sortTool = new Image::ExifTool;
    $sortTool->Options(PrintConv => $mainTool->Options('PrintConv'));
    $sortTool->Options(Duplicates => 0);
    my (%sortBy, %isFloat, @rev, $file);
    # save reverse sort flags
    push @rev, (s/^-// ? 1 : 0) foreach @fileOrder;
    foreach $file (@allFiles) {
        my @tags;
        my $info = $sortTool->ImageInfo($file, @fileOrder, \@tags);
        # get values of all tags (or '~' to sort last if not defined)
        foreach (@tags) {
            $_ = $$info{$_};
            defined $_ or $_ = '~', next;
            $isFloat{$_} = 1 if /^[+-]?(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
        }
        $sortBy{$file} = \@tags;    # save tag values for each file
    }
    # sort in specified order
    @files = sort {
        my ($i, $cmp);
        for ($i=0; $i<@rev; ++$i) {
            my $u = $sortBy{$a}[$i];
            my $v = $sortBy{$b}[$i];
            if (not $isFloat{$u} and not $isFloat{$v}) {
                $cmp = $u cmp $v;               # alphabetically
            } elsif ($isFloat{$u} and $isFloat{$v}) {
                $cmp = $u <=> $v;               # numerically
            } else {
                $cmp = $isFloat{$u} ? -1 : 1;   # numbers first
            }
            return $rev[$i] ? -$cmp : $cmp if $cmp;
        }
        return $a cmp $b;   # default to sort by name
    } @allFiles;
}

# process all specified files
ProcessFiles($mainTool);

if ($filtered and not $validFile) {
    Warn "No file with specified extension\n";
    $rtnVal = 1;
}

# print CSV information if necessary
PrintCSV() if $csv and not $isWriting;

# print file trailer if necessary
print $fileTrailer if $fileTrailer and not $textOut and not $fileHeader;

if (defined $deleteOrig) {

    # print summary and delete requested files
    unless ($quiet) {
        printf "%5d directories scanned\n", $countDir if $countDir;
        printf "%5d directories created\n", $countNewDir if $countNewDir;
        printf "%5d files failed condition\n", $countFailed if $countFailed;
        printf "%5d image files found\n", $count;
    }
    if (@delFiles) {
        # verify deletion unless "-delete_original!" was specified
        if ($deleteOrig == 1) {
            printf '%5d originals will be deleted!  Are you sure [y/n]? ', scalar(@delFiles);
            my $response = <STDIN>;
            unless ($response =~ /^(y|yes)\s*$/i) {
                Warn "Originals not deleted.\n";
                next;
            }
        }
        $countGoodWr = unlink @delFiles;
        $countBad = scalar(@delFiles) - $countGoodWr;
    }
    if ($quiet) {
        # no more messages
    } elsif ($count and not $countGoodWr and not $countBad) {
        printf "%5d original files found\n", $countGoodWr;
    } elsif ($deleteOrig) {
        printf "%5d original files deleted\n", $countGoodWr if $count;
        printf "%5d originals not deleted due to errors\n", $countBad if $countBad;
    } else {
        printf "%5d image files restored from original\n", $countGoodWr if $count;
        printf "%5d files not restored due to errors\n", $countBad if $countBad;
    }

} elsif (not $binaryStdout and not $quiet) {

    # print summary
    my $tot = $count + $countBad;
    my $totWr = $countGoodWr + $countBadWr + $countSameWr + $countCopyWr +
                $countGoodCr + $countBadCr;
    if ($countDir or $totWr or $countFailed or $tot > 1 or $textOut) {
        my $o = (($html or $json or $xml or %printFmt or $csv) and not $textOut) ? \*STDERR : \*STDOUT;
        printf($o "%5d directories scanned\n", $countDir) if $countDir;
        printf($o "%5d directories created\n", $countNewDir) if $countNewDir;
        printf($o "%5d files failed condition\n", $countFailed) if $countFailed;
        printf($o "%5d image files created\n", $countGoodCr) if $countGoodCr;
        printf($o "%5d image files updated\n", $countGoodWr) if $totWr - $countGoodCr - $countBadCr - $countCopyWr;
        printf($o "%5d image files unchanged\n", $countSameWr) if $countSameWr;
        printf($o "%5d image files copied\n", $countCopyWr) if $countCopyWr;
        printf($o "%5d files weren't updated due to errors\n", $countBadWr) if $countBadWr;
        printf($o "%5d files weren't created due to errors\n", $countBadCr) if $countBadCr;
        printf($o "%5d image files read\n", $count) if $tot>1 or ($countDir and not $totWr);
        printf($o "%5d files could not be read\n", $countBad) if $countBad;
        printf($o "%5d output files created\n", $countCreated) if $textOut;
    }
}

# set error status if we had any errors or if all files failed the "-if" condition
$rtnVal = 1 if $countBadWr or $countBadCr or $countBad or ($countFailed and not $count);

# last ditch effort to preserve filemodifydate
PreserveTime() if %preserveTime;

# clear existing new values to allow mainTool to be destroyed! (removes circ refs)
$mainTool->SetNewValue();

} # end "Command" loop ........................................................

close STAYOPEN if $stayOpen >= 2;

Exit $rtnVal;   # all done


#------------------------------------------------------------------------------
# Get image information from EXIF data in file
# Inputs: 0) ExifTool object reference, 1) file name
sub GetImageInfo($$)
{
    my ($exifTool, $orig) = @_;
    my (@foundTags, $info);
    my $file = SourceFile($orig);
    my $pipe = $file;
    my $ind;

    if ($doUnzip) {
        # pipe through gzip or bzip2 if necessary
        if ($file =~ /\.gz$/i) {
            $pipe = qq{gzip -dc "$file" |};
        } elsif ($file =~ /\.bz2$/i) {
            $pipe = qq{bzip2 -dc "$file" |};
        }
    }
    # evaluate -if expression for conditional processing
    if (defined $condition) {
        # catch run time errors as well as compile errors
        undef $evalWarning;
        local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };

        my %info;
        # extract information and build expression for evaluation
        my $opts = { Duplicates => 1, Verbose => 0, HtmlDump => 0 };
        # return all tags but explicitly mention tags on command line so
        # requested images will generate the appropriate warnings
        @foundTags = ('*', @tags) if @tags;
        $info = $exifTool->ImageInfo($pipe, \@foundTags, $opts);
        my $cond = $exifTool->InsertTagValues(\@foundTags, $condition, \%info);

        #### eval "-if" condition (%info)
        my $result = eval $cond;

        $@ and $evalWarning = $@;
        if ($evalWarning) {
            # fail condition if warning is issued
            undef $result;
            if ($verbose) {
                chomp $evalWarning;
                $evalWarning =~ s/ at \(eval .*//s;
                delete $SIG{'__WARN__'};
                Warn "Condition: $evalWarning - $file\n";
            }
        }
        unless ($result) {
            $verbose and print "-------- $file (failed condition)\n";
            ++$countFailed;
            return;
        }
        # can't make use of $info if verbose because we must reprocess
        # the file anyway to generate the verbose output
        undef $info if $verbose;
    }
    if (defined $deleteOrig) {
        print "======== $file\n" if defined $verbose;
        ++$count;
        my $original = "${file}_original";
        -e $original or return;
        if ($deleteOrig) {
            $verbose and print "Scheduled for deletion: $original\n";
            push @delFiles, $original;
        } elsif (rename $original, $file) {
            $verbose and print "Restored from $original\n";
            ++$countGoodWr;
        } else {
            Warn "Error renaming $original\n";
            ++$countBad;
        }
        return;
    }
    my $lineCount = 0;
    my ($fp, $outfile);
    if ($textOut and $verbose) {
        ($fp, $outfile) = OpenOutputFile($orig);
        $fp or ++$countBad, return;
        $tmpText = $outfile;    # deletes file if we exit prematurely
        $exifTool->Options(TextOut => $fp);
    }

    if ($isWriting) {
        print "======== $file\n" if defined $verbose;
        SetImageInfo($exifTool, $orig);
        $info = $exifTool->GetInfo('Warning', 'Error');
        PrintErrors($exifTool, $info, $file);
        # close output text file if necessary
        if ($outfile) {
            undef $tmpText;
            close($fp);
            $exifTool->Options(TextOut => \*STDOUT);
            if ($info->{Error}) {
                unlink $outfile;    # erase bad file
            } else {
                ++$countCreated;
            }
        }
        return;
    } else {
        my $tag;
        # extract EXIF information from this file
        unless ($file eq '-' or -e $file) {
            Warn "File not found: $file\n";
            $outfile and close($fp), undef($tmpText), unlink($outfile);
            ++$countBad;
            return;
        }
        unless ($binaryOutput or $textOut or %printFmt or $html > 1 or $csv) {
            if ($html) {
                require Image::ExifTool::HTML;
                my $f = Image::ExifTool::HTML::EscapeHTML($file);
                print "<!-- $f -->\n";
            } elsif (not ($json or $xml)) {
                print "======== $file\n" if $multiFile and not $quiet;
            }
        }
        if ($info) {
            # get the information we wanted
            if (@tags and not %printFmt) {
                @foundTags = @tags;
                $info = $exifTool->GetInfo(\@foundTags);
            }
        } else {
            # request specified tags unless using print format option
            my $oldDups = $exifTool->Options('Duplicates');
            if (%printFmt) {
                $exifTool->Options(Duplicates => 1);
            } else {
                @foundTags = @tags;
            }
            # extract the information
            $info = $exifTool->ImageInfo($pipe, \@foundTags);
            $exifTool->Options(Duplicates => $oldDups);
        }
        # all done now if we already wrote output text file (ie. verbose option)
        if ($fp) {
            if ($outfile) {
                $exifTool->Options(TextOut => \*STDOUT);
                undef $tmpText;
                if ($info->{Error}) {
                    close($fp);
                    unlink $outfile;    # erase bad file
                } else {
                    ++$lineCount;       # output text file (likely) is not empty
                }
            }
            if ($info->{Error}) {
                Warn "Error: $info->{Error} - $file\n";
                ++$countBad;
                return;
            }
        }
    }
    # print warnings to stderr if using binary output
    # (because we are likely ignoring them and piping stdout to file)
    # or if there is none of the requested information available
    if ($binaryOutput or not %$info) {
        my $errs = $exifTool->GetInfo('Warning', 'Error');
        PrintErrors($exifTool, $errs, $file);
    }

    # open output file (or stdout if no output file) if not done already
    unless ($fp) {
        ($fp, $outfile) = OpenOutputFile($orig);
        $fp or ++$countBad, return;
    }

    # print the results for this file
    if (%printFmt) {
        # output using print format file (-p) option
        my ($type, $doc, $grp);
        undef $fileTrailer;
        # repeat for each embedded document if necessary
        my $lastDoc = $exifTool->Options('ExtractEmbedded') ? $exifTool->{DOC_COUNT} : 0;
        foreach $type ('HEAD', 'BODY', 'TAIL') {
            my $prf = $printFmt{$type} or next;
            for ($doc=0; $doc<=$lastDoc; ++$doc) {
                if ($lastDoc) {
                    if ($doc) {
                        last unless $type eq 'BODY'; # only repeat BODY lines
                        $grp = "Doc$doc:";
                    } else {
                        $grp = 'Main:';
                    }
                    # change tag groups to print next document by adding "Main:" or "Doc#:"
                    # to all tags which don't already start with a family 3 group name
                    $prf = [ @{$printFmt{$type}} ];
                    s/((^|[^\$])(\$\$)*\$\{?)((?!(Main|Doc\d+):)[\w])/$1$grp$4/ig foreach @$prf;
                }
                my @lines;
                foreach (@$prf) {
                    my $line = $exifTool->InsertTagValues(\@foundTags, $_, 'Warn');
                    push @lines, $line if defined $line;
                }
                $lineCount += scalar @lines;
                if ($type eq 'TAIL') {
                    $fileTrailer = '' unless defined $fileTrailer;
                    $fileTrailer .= join '', @lines;
                } elsif (@lines) {
                    print $fp @lines;
                }
            }
        }
        delete $printFmt{HEAD} unless $outfile; # print header only once per output file
        my $errs = $exifTool->GetInfo('Warning', 'Error');
        PrintErrors($exifTool, $errs, $file);
    } elsif (not $disableOutput) {
        # print file header (only once)
        if ($fileHeader) {
            print $fp $fileHeader;
            undef $fileHeader unless $textOut;
        }
        my ($tag, $line, %noDups, %csvInfo);
        if ($html) {
            print $fp "<table>\n";
        } elsif ($xml) {
            my $f = $file;
            CleanXML(\$f);
            print $fp "\n<rdf:Description rdf:about='$f'";
            print $fp "\n  xmlns:et='http://ns.exiftool.ca/1.0/'";
            print $fp " et:toolkit='Image::ExifTool $Image::ExifTool::VERSION'";
            # define namespaces for all tag groups
            my %groups;
            foreach $tag (@foundTags) {
                my ($grp, $grp1) = $exifTool->GetGroup($tag);
                unless ($grp1) {
                    next unless $forcePrint;
                    $grp = $grp1 = 'Unknown';
                }
                next if $groups{$grp1};
                $groups{$grp1} = 1;
                # include family 0 and 1 groups in URI except for internal tags
                # (this will put internal tags in the "XML" group on readback)
                $grp .= "/$grp1" unless $grp eq $grp1 and
                                        $grp =~ /^(ExifTool|File|Composite|Unknown)$/;
                print $fp "\n  xmlns:$grp1='http://ns.exiftool.ca/$grp/1.0/'";
            }
            print $fp '>' if $outFormat < 1; # finish rdf:Description token unless short format
            $ind = $outFormat >= 0 ? ' ' : '   ';
        } elsif ($json) {
            print $fp ",\n" if $comma;
            print $fp qq({\n  "SourceFile": ), EscapeJSON($file, 1);
            $comma = 1;
            $ind = (defined $showGroup and not $allGroup) ? '    ' : '  ';
        } elsif ($csv) {
            $database{$file} = \%csvInfo;
            push @csvFiles, $file;
        }
        # suppress duplicates manually in JSON and short XML output
        my $noDups = ($json or ($xml and $outFormat > 0));
        my $printConv = $mainTool->Options('PrintConv');
        my $lastGroup = '';
        foreach $tag (@foundTags) {
            my $tagName = GetTagName($tag);
            my $group;
            # make sure this tag has a value
            my $val = $info->{$tag};
            if (ref $val) {
                if (defined $binaryOutput and not $binaryOutput) { # happens with -X -b
                    # avoid extracting Protected binary tags (ie. data blocks) [insider information]
                    next if $exifTool->{TAG_INFO}{$tag}{Protected};
                }
                $val = ConvertBinary($val); # convert SCALAR references
                if ($structOpt) {
                    # serialize structure if necessary
                    $val = Image::ExifTool::XMP::SerializeStruct($val) unless $xml or $json;
                } elsif (ref $val eq 'ARRAY') {
                    # join arrays of simple values (with newlines for binary output)
                    if ($binaryOutput) {
                        $val = join "\n", @$val;
                    } elsif ($joinLists) {
                        $val = join $listSep, @$val;
                    }
                }
            } elsif (not defined $val) {
                # ignore tags that weren't found unless necessary
                next if $binaryOutput;
                if ($forcePrint) {
                    $val = '-';     # forced to print all tag values
                } elsif (not $csv) {
                    next;
                }
            }
            if (defined $showGroup) {
                $group = $exifTool->GetGroup($tag, $showGroup);
                # look ahead to see if this tag may suppress a priority tag in
                # the same group, and if so suppress this tag instead
                next if $noDups and $tag =~ /^([-\w+]( #)?)\(/ and defined $$info{$1} and
                        $group eq $exifTool->GetGroup($1, $showGroup);
                $group = 'Unknown' if not $group and ($xml or $json);
                unless ($allGroup or $csv) {
                    if ($lastGroup ne $group) {
                        if ($html) {
                            my $cols = 1;
                            ++$cols if $outFormat==0 or $outFormat==1;
                            ++$cols if $showTagID;
                            print $fp "<tr><td colspan=$cols bgcolor='#dddddd'>$group</td></tr>\n";
                        } elsif ($json) {
                            print $fp "\n  }" if $lastGroup;
                            print $fp ',' if $lastGroup or $comma;
                            print $fp qq(\n  "$group": {);
                            undef $comma;
                            undef %noDups;  # allow duplicate names in different groups
                        } else {
                            print $fp "---- $group ----\n";
                        }
                        $lastGroup = $group;
                    }
                    undef $group;   # undefine so we don't print it below
                }
            }

            ++$lineCount;           # we are printing something meaningful

            # write binary output
            if ($binaryOutput) {
                print $fp $val;
                next;
            }
            # save information for CSV output
            if ($csv) {
                my $t = $group ? "$group:$tagName" : $tagName;
                $t .= '#' if $tag =~ /#/;   # add ValueConv "#" suffix if used
                # (tag-name case may be different if some tags don't exist
                # in a file, so all logic must use lower-case tag names)
                my $lcTag = lc $t;
                # override existing entry only if top priority
                next if defined $csvInfo{$lcTag} and $tag =~ /\(/;
                $csvInfo{$lcTag} = $val;
                if (defined $csvTags{$lcTag}) {
                    # overwrite with actual extracted tag name
                    $csvTags{$lcTag} = $t if defined $val;
                } else {
                    # (don't save unextracted tag name)
                    $csvTags{$lcTag} = defined($val) ? $t : '';
                    if (@csvFiles == 1) {
                        push @csvTags, $lcTag; # save order of tags for first file
                    } elsif (@csvTags) {
                        undef @csvTags;
                    }
                }
                next;
            }

            # get description if we need it (use tag name if $outFormat > 0)
            my $desc = $outFormat > 0 ? $tagName : $exifTool->GetDescription($tag);

            if ($xml) {
                # RDF/XML output format
                my $tok = "$group:$tagName";
                if ($outFormat > 0) {
                    if ($structOpt and ref $val) {
                        $val = Image::ExifTool::XMP::SerializeStruct($val);
                    }
                    if ($escapeHTML) {
                        $val =~ tr/\0-\x08\x0b\x0c\x0e-\x1f/./;
                        Image::ExifTool::XMP::FixUTF8(\$val) if $utf8;
                        $val = Image::ExifTool::HTML::EscapeHTML($val);
                    } else {
                        CleanXML(\$val);
                    }
                    unless ($noDups{$tok}) {
                        print $fp "\n $tok='$val'";
                        # XML does not allow duplicate attributes
                        $noDups{$tok} = 1;
                    }
                    next;
                }
                my ($xtra, $valNum, $descClose);
                if ($showTagID) {
                    my ($id, $lang) = $exifTool->GetTagID($tag);
                    if ($id =~ /^\d+$/) {
                        $id = sprintf("0x%.4x", $id) if $showTagID eq 'H';
                    } else {
                        $id = Image::ExifTool::XMP::FullEscapeXML($id);
                    }
                    $xtra = " et:id='$id'";
                    $xtra .= " xml:lang='$lang'" if $lang;
                } else {
                    $xtra = '';
                }
                if ($tabFormat) {
                    my $table = $exifTool->GetTableName($tag);
                    my $index = $exifTool->GetTagIndex($tag);
                    $xtra .= " et:table='$table'";
                    $xtra .= " et:index='$index'" if defined $index;
                }
                my $lastVal = $val;
                for ($valNum=0; $valNum<2; ++$valNum) {
                    $val = FormatXML($val, $ind, $group);
                    if ($outFormat >= 0) {
                        # normal output format (note: this will give
                        # non-standard RDF/XML if there are any attributes)
                        print $fp "\n <$tok$xtra$val</$tok>";
                        last;
                    } elsif ($valNum == 0) {
                        CleanXML(\$desc);
                        if ($xtra) {
                            print $fp "\n <$tok>";
                            print $fp "\n  <rdf:Description$xtra>";
                            $descClose = "\n  </rdf:Description>";
                        } else {
                            print $fp "\n <$tok rdf:parseType='Resource'>";
                            $descClose = '';
                        }
                        # print tag Description
                        print $fp "\n   <et:desc>$desc</et:desc>";
                        if ($printConv) {
                            # print PrintConv value
                            print $fp "\n   <et:prt$val</et:prt>";
                            $val = $exifTool->GetValue($tag, 'ValueConv');
                            # go back to print ValueConv value only if different
                            next if ref $val ne 'SCALAR' and $val ne $lastVal;
                            print $fp "$descClose\n </$tok>";
                            last;
                        }
                    }
                    # print ValueConv value
                    print $fp "\n   <et:val$val</et:val>";
                    print $fp "$descClose\n </$tok>";
                    last;
                }
                next;
            } elsif ($json) {
                # JSON output format
                my $tok = $allGroup ? "$group:$tagName" : $tagName;
                # (removed due to backward incompatibility)
                # $tok .= '#' if $tag =~ /#/; # add back '#' suffix if used
                next if $noDups{$tok};
                $noDups{$tok} = 1;
                print $fp ',' if $comma;
                print $fp qq(\n$ind"$tok": );
                FormatJSON($fp, $val, $ind);
                $comma = 1;
                next;
            }
            my $id;
            if ($showTagID) {
                $id = $exifTool->GetTagID($tag);
                if ($id =~ /^(\d+)(\.\d+)?$/) { # only print numeric ID's
                    $id = sprintf("0x%.4x", $1) if $showTagID eq 'H';
                } else {
                    $id = '-';
                }
            }

            # translate unprintable chars in value and remove trailing spaces
            $val =~ tr/\x01-\x1f\x7f/./;
            $val =~ s/\x00//g;
            $val =~ s/\s+$//;

            if ($html) {
                print $fp "<tr>";
                print $fp "<td>$group</td>" if defined $group;
                print $fp "<td>$id</td>" if $showTagID;
                print $fp "<td>$desc</td>" if $outFormat <= 1;
                print $fp "<td>$val</td></tr>\n";
            } else {
                my $buff = '';
                if ($tabFormat) {
                    $buff = "$group\t" if defined $group;
                    $buff .= "$id\t" if $showTagID;
                    if ($outFormat <= 1) {
                        $buff .= "$desc\t$val\n";
                    } elsif (defined $line) {
                        $line .= "\t$val";
                    } else {
                        $line = $val;
                    }
                } elsif ($outFormat < 0) {    # long format
                    $buff = "[$group] " if defined $group;
                    $buff .= "$id " if $showTagID;
                    $buff .= "$desc\n      $val\n";
                } elsif ($outFormat == 0 or $outFormat == 1) {
                    my $wid;
                    my $len = 0;
                    if (defined $group) {
                        $buff = sprintf("%-15s ", "[$group]");
                        $len = 16;
                    }
                    if ($showTagID) {
                        $wid = ($showTagID eq 'D') ? 5 : 6;
                        $len += $wid + 1;
                        ($wid = $len - length($buff) - 1) < 1 and $wid = 1;
                        $buff .= sprintf "%${wid}s ", $id;
                    }
                    $wid = 32 - (length($buff) - $len);
                    # pad description to a constant length
                    # (get actual character length when using alternate languages
                    # because these descriptions may contain UTF8-encoded characters)
                    my $padLen = $wid - length($fixLen ? Encode::decode_utf8($desc) : $desc);
                    $padLen = 0 if $padLen < 0;
                    $buff .= $desc . (' ' x $padLen) . ": $val\n";
                } elsif ($outFormat == 2) {
                    $buff = "[$group] " if defined $group;
                    $buff .= "$id " if $showTagID;
                    $buff .= "$tagName: $val\n";
                } elsif ($argFormat) {
                    $buff = '-';
                    $buff .= "$group:" if defined $group;
                    $tagName .= '#' if $tag =~ /#/; # add '#' suffix if used
                    $buff .= "$tagName=$val\n";
                } else {
                    $buff = "$group " if defined $group;
                    $buff .= "$id " if $showTagID;
                    $buff .= "$val\n";
                }
                print $fp $buff;
            }
        }
        if ($html) {
            print $fp "</table>\n";
        } elsif ($xml) {
            # close rdf:Description element
            print $fp $outFormat < 1 ? "\n</rdf:Description>\n" : "/>\n";
        } elsif ($json) {
            print $fp "\n  }" if $lastGroup;
            print $fp "\n}";
            $comma = 1;
        } elsif ($tabFormat and $outFormat > 1) {
            print $fp "$line\n" if defined $line;
        }
    }
    if ($outfile) {
        print $fp $fileTrailer if $fileTrailer; # write file trailer
        close($fp);
        undef $comma;
        if ($lineCount) {
            ++$countCreated;
        } else {
            unlink $outfile; # don't keep empty output files
        }
    }
    ++$count;
}

#------------------------------------------------------------------------------
# Set information in file
# Inputs: 0) ExifTool object reference
#         1) original source file name ('' to create from scratch)
# Returns: true on success
sub SetImageInfo($$)
{
    my ($exifTool, $orig) = @_;
    my ($outfile, $restored, $isTemporary, $isStdout);
    my $file = SourceFile($orig);
    my $infile = $file;    # save infile in case we change it again
    my $tagsFromSrc;

    undef $tmpFile; # make sure this isn't defined

    # clear any existing errors or warnings since we check these on return
    delete $exifTool->{VALUE}->{Error};
    delete $exifTool->{VALUE}->{Warning};

    # set new values from CSV information if necessary
    if ($csv) {
        $exifTool->RestoreNewValues();
        $restored = 1;
        my ($f, $found, $tag);
        # read tags for SourceFile '*' plus the specific file
        foreach $f ('*', $file) {
            my $csvInfo = $database{$f} or next;
            $found = 1;
            foreach $tag (sort keys %$csvInfo) {
                next if $tag =~ /\b(SourceFile|Directory|FileName)$/i; # don't write these
                my ($rtn, $wrn) = $mainTool->SetNewValue($tag, $$csvInfo{$tag},
                                  Protected => 1, AddValue => $csvAdd);
                $wrn and Warn "$wrn\n" if $verbose;
            }
        }
        $found or Warn("No SourceFile '$file' in imported $csv database\n"), return 0;
    }

    # first, try to determine our output file name so we can return quickly
    # if it already exists (note: this test must be delayed until after we
    # set tags from dynamic files if writing FileName or Directory)
    if (defined $outOpt) {
        if ($outOpt eq '-') {
            $isStdout = 1;
        } else {
            $outfile = FilenameSPrintf($outOpt, $orig);
            if ($outfile eq '') {
                Warn "Can't create file with zero-length name from $orig\n";
                ++$countBadCr;
                return 0;
            }
            if (-d $outfile or $outfile =~ /\/$/) {
                $outfile .= '/' unless $outfile =~ /\/$/;
                my $name = $file;
                $name =~ s/.*\///;  # remove directory name
                $outfile .= $name;
            } else {
                my $srcType = GetFileType($file) || '';
                my $outType = GetFileType($outfile);
                if ($outType and ($srcType ne $outType or $outType eq 'ICC')) {
                    unless (CanCreate($outfile)) {
                        my $what = $srcType ? 'other types' : 'scratch';
                        WarnOnce "Error: Can't create $outType files from $what\n";
                        ++$countBadCr;
                        return 0;
                    }
                    if ($file ne '') {
                        # restore previous new values unless done already
                        $exifTool->RestoreNewValues() unless $restored;
                        $restored = 1;
                        # translate to this type by setting specified tags from file
                        my @setTags = @tags;
                        foreach (@exclude) {
                            push @setTags, "-$_";
                        }
                        # force some tags to be copied for certain file types
                        my %forceCopy = (
                            ICC => 'ICC_Profile',
                            VRD => 'CanonVRD',
                        );
                        push @setTags, $forceCopy{$outType} if $forceCopy{$outType};
                        # assume "-tagsFromFile @" unless -tagsFromFile already specified
                        # (%setTags won't be empty if -tagsFromFile used)
                        if (not %setTags or (@setTags and not $setTags{'@'})) {
                            return 0 unless DoSetFromFile($exifTool, $file, \@setTags);
                        } elsif (@setTags) {
                            # add orphaned tags to existing "-tagsFromFile @" for this file only
                            push @setTags, @{$setTags{'@'}};
                            $tagsFromSrc = \@setTags;
                        }
                        # all done with source file -- create from meta information alone
                        $file = '';
                    }
                }
            }
            $outfile = NextUnusedFilename($outfile);
            if (-e $outfile and not $doSetFileName) {
                Warn "Error: '$outfile' already exists - $infile\n";
                ++$countBadWr;
                return 0;
            }
        }
    } elsif ($file eq '-') {
        $isStdout = 1;
    }
    # set new values with dynamic file names
    if (@dynamicValues) {
        # restore previous values if necessary
        $exifTool->RestoreNewValues() unless $restored;
        $restored = 1;
        my ($dyVal, $buff);
        foreach $dyVal (@dynamicValues) {
            my $dyfile = FilenameSPrintf($$dyVal[1], $orig);
            my ($rtn, $wrn);
            if (defined $dyfile and SlurpFile($dyfile, \$buff)) {
                $verbose and print "Reading $$dyVal[0] from $dyfile\n";
                ($rtn, $wrn) = $mainTool->SetNewValue($$dyVal[0], $buff, %{$$dyVal[2]});
                $wrn and Warn "$wrn\n";
            }
            # remove this tag if we couldn't set it properly
            $rtn or $mainTool->SetNewValue($$dyVal[0], undef, Replace => 2);
        }
    }
    # set tags from destination file if required
    if (@dynamicFiles) {
        # restore previous values if necessary
        $exifTool->RestoreNewValues() unless $restored;
        my $dyFile;
        foreach $dyFile (@dynamicFiles) {
            my ($fromFile, $setTags);
            if ($dyFile eq '@') {
                $fromFile = $orig;
                $setTags = $tagsFromSrc || $setTags{$dyFile};
            } else {
                $fromFile = FilenameSPrintf($dyFile, $orig);
                ++$countBadWr, return 0 unless defined $fromFile;
                $setTags = $setTags{$dyFile};
            }
            # set new values values from file
            return 0 unless DoSetFromFile($exifTool, $fromFile, $setTags);
        }
    }
    if ($isStdout) {
        # write to STDOUT
        $outfile = \*STDOUT;
        unless ($binaryStdout) {
            binmode(STDOUT);
            $binaryStdout = 1;
        }
    } else {
        # determine what our output file name should be
        my $newFileName = $exifTool->GetNewValues('FileName');
        my $newDir = $exifTool->GetNewValues('Directory');
        if ($newFileName or $newDir or ($doSetFileName and defined $outfile)) {
            if ($newFileName) {
                $newFileName = FilenameSPrintf($newFileName, $orig);
                if (defined $outfile) {
                    $outfile = Image::ExifTool::GetNewFileName($orig, $outfile) if $orig ne '';
                    $outfile = Image::ExifTool::GetNewFileName($outfile, $newFileName);
                } elsif ($orig ne '') {
                    $outfile = Image::ExifTool::GetNewFileName($orig, $newFileName);
                }
            }
            if ($newDir) {
                $newDir = FilenameSPrintf($newDir, $orig);
                $outfile = Image::ExifTool::GetNewFileName(defined $outfile ? $outfile : $orig, $newDir);
            }
            $outfile = NextUnusedFilename($outfile, $infile);
            if (-e $outfile) {
                if ($infile ne $outfile) {
                    Warn "Error: '$outfile' already exists - $infile\n";
                    ++$countBadWr;
                    return 0;
                }
                undef $outfile; # not changing the file name after all
            }
        }
        if (defined $outfile) {
            $verbose and print "'$infile' --> '$outfile'\n";
            # create output directory if necessary
            CreateDirectory($outfile);
            # set temporary file (automatically erased on abnormal exit)
            $tmpFile = $outfile if defined $outOpt;
        }
        unless (defined $tmpFile) {
            # count the number of tags and pseudo-tags we are writing
            my ($numSet, $numPseudo) = $exifTool->CountNewValues();
            if (-e $file) {
                unless ($numSet) {
                    # no need to write if no tags set
                    print "Nothing changed in $file\n" if defined $verbose;
                    ++$countSameWr;
                    return 1;
                }
            } elsif (CanCreate($file)) {
                if ($numSet == $numPseudo) {
                    # no need to write if no real tags
                    Warn("Error: Nothing to write - $file\n");
                    ++$countBadWr;
                    return 0;
                }
                unless (defined $outfile) {
                    # create file from scratch
                    $outfile = $file;
                    $file = '';
                }
            } else {
                # file doesn't exist, and we can't create it
                Warn("Error: File not found - $file\n");
                ++$countBadWr;
                return 0;
            }
            # quickly rename file and/or set file date if this is all we are doing
            if ($numSet == $numPseudo) {
                my $r1 = $exifTool->SetFileModifyDate($file);
                my $r2 = 0;
                $r2 = $exifTool->SetFileName($file, $outfile) if defined $outfile;
                if ($r1 > 0 or $r2 > 0) {
                    ++$countGoodWr;
                } elsif ($r1 < 0 or $r2 < 0) {
                    ++$countBadWr;
                    return 0;
                } else {
                    ++$countSameWr;
                }
                return 1;
            }
            unless (defined $outfile) {
                # write to a truly temporary file
                $outfile = "${file}_exiftool_tmp";
                if (-e $outfile) {
                    Warn("Error: Temporary file already exists: $outfile\n");
                    ++$countBadWr;
                    return 0;
                }
                $isTemporary = 1;
            }
            # new output file is temporary until we know it has been written properly
            $tmpFile = $outfile;
        }
    }
    # rewrite the file
    my $success = $exifTool->WriteInfo($file, $outfile);

    # get file time if preserving it
    my ($modTime, $accTime);
    if ($preserveTime and $success and -e $file) {
        $modTime = $^T - (-M $file) * (24 * 3600);
        $accTime = $^T - (-A $file) * (24 * 3600);
    }
    if ($success == 1) {
        # preserve the original file times
        if (defined $tmpFile) {
            if (-e $file) {
                if ($preserveTime and not utime($accTime, $modTime, $tmpFile)) {
                    Warn "Error setting file time - $file\n";
                }
                if ($isTemporary) {
                    # preserve original file attributes if possible
                    Image::ExifTool::CopyFileAttrs($file, $outfile);
                    # move original out of the way
                    my $original = "${file}_original";
                    if (not $overwriteOrig and not -e $original) {
                        # rename the file and check again to be sure the file doesn't exist
                        # (in case, say, the filesystem truncated the file extension)
                        if (not rename($file, $original) or -e $file) {
                            Error "Error renaming $file\n";
                            return 0;
                        }
                    }
                    if ($overwriteOrig > 1) {
                        # copy temporary file over top of original to preserve attributes
                        my ($err, $buff);
                        my $newFile = $tmpFile;
                        open(NEW_FILE, "<$newFile") or Error("Error opening $newFile\n"), return 0;
                        binmode(NEW_FILE);

                        #........................................................
                        # temporary disable CTRL-C during this critical operation
                        $critical = 1;
                        undef $tmpFile;     # handle deletion of temporary file ourself
                        if (open(ORIG_FILE, ">$file")) {
                            binmode(ORIG_FILE);
                            while (read(NEW_FILE, $buff, 65536)) {
                                print ORIG_FILE $buff or $err = 1;
                            }
                            close(NEW_FILE);
                            close(ORIG_FILE) or $err = 1;
                            if ($err) {
                                Warn "Couldn't overwrite in place - $file\n";
                                unless (rename($newFile, $file) or
                                    (unlink $file and rename($newFile, $file)))
                                {
                                    Error("Error renaming $newFile to $file\n"), return 0;
                                }
                            } else {
                                unlink $newFile;
                                if ($preserveTime) {
                                    unless (utime($accTime, $modTime, $file)) {
                                        Warn "Error setting file time - $file\n";
                                    }
                                    # save time to set it later again to patch OS X 10.6 bug
                                    $preserveTime{$file} = [ $accTime, $modTime ];
                                }
                            }
                            ++$countGoodWr;
                        } else {
                            close(NEW_FILE);
                            Warn "Error opening $file for writing\n";
                            unlink $newFile;
                            ++$countBadWr;
                        }
                        undef $critical;            # end critical section
                        SigInt() if $interrupted;   # issue delayed SIGINT if necessary
                        #........................................................

                    # simply rename temporary file to replace original
                    # (if we didn't already rename it to add "_original")
                    } elsif (rename($tmpFile, $file)) {
                        ++$countGoodWr;
                    } else {
                        my $newFile = $tmpFile;
                        undef $tmpFile; # (avoid deleting file if we get interrupted)
                        # unlink may fail if already renamed or no permission
                        if (not unlink($file)) {
                            Warn "Error renaming temporary file to $file\n";
                            unlink $newFile;
                            ++$countBadWr;
                        # try renaming again now that the target has been deleted
                        } elsif (not rename($newFile, $file)) {
                            Warn "Error renaming temporary file to $file\n";
                            # (don't delete tmp file now because it is all we have left)
                            ++$countBadWr;
                        } else {
                            ++$countGoodWr;
                        }
                    }
                } elsif ($overwriteOrig) {
                    # erase original file
                    unlink $file or Warn "Error erasing original $file\n";
                    ++$countGoodWr;
                } else {
                    ++$countGoodCr;
                }
            } else {
                # this file was created from scratch, not edited
                ++$countGoodCr;
            }
        } else {
            ++$countGoodWr;
        }
    } elsif ($success) {
        if ($isTemporary) {
            # just erase the temporary file since no changes were made
            unlink $tmpFile;
            ++$countSameWr;
        } else {
            if (defined $accTime and not utime($accTime, $modTime, $outfile)) {
                Warn "Error setting file time - $file\n";
            }
            if ($overwriteOrig) {
                unlink $file or Warn "Error erasing original $file\n";
            }
            ++$countCopyWr;
        }
        print "Nothing changed in $file\n" if defined $verbose;
    } else {
        unlink $tmpFile if defined $tmpFile;
        ++$countBadWr;
    }
    undef $tmpFile;
    return $success;
}

#------------------------------------------------------------------------------
# Clean string for XML (also removes invalid control chars and malformed UTF-8)
# Inputs: 0) string ref
# Returns: nothing, but input string is escaped
sub CleanXML($)
{
    my $strPt = shift;
    # translate control characters that are invalid in XML
    $$strPt =~ tr/\0-\x08\x0b\x0c\x0e-\x1f/./;
    # fix malformed UTF-8 characters
    Image::ExifTool::XMP::FixUTF8($strPt) if $utf8;
    # escape necessary characters for XML
    $$strPt = Image::ExifTool::XMP::EscapeXML($$strPt);
}

#------------------------------------------------------------------------------
# Encode string for XML
# Inputs: 0) string ref
# Returns: encoding used (and input string is translated)
sub EncodeXML($)
{
    my $strPt = shift;
    if ($$strPt =~ /[\0-\x08\x0b\x0c\x0e-\x1f]/ or
        ($utf8 and Image::ExifTool::XMP::IsUTF8($strPt) < 0))
    {
        # encode binary data and non-UTF8 with special characters as base64
        $$strPt = Image::ExifTool::XMP::EncodeBase64($$strPt);
        return 'http://www.w3.org/2001/XMLSchema#base64Binary'; #ATV
    } elsif ($escapeHTML) {
        $$strPt = Image::ExifTool::HTML::EscapeHTML($$strPt);
    } else {
        $$strPt = Image::ExifTool::XMP::EscapeXML($$strPt);
    }
    return '';  # not encoded
}

#------------------------------------------------------------------------------
# Format value for XML output
# Inputs: 0) value, 1) indentation, 2) group
# Returns: formatted value
sub FormatXML($$$)
{
    local $_;
    my ($val, $ind, $grp) = @_;
    my $gt = '>';
    if (ref $val eq 'ARRAY') {
        # convert ARRAY into an rdf:Bag
        my $val2 = "\n$ind <rdf:Bag>";
        foreach (@$val) {
            $val2 .= "\n$ind  <rdf:li" . FormatXML($_, "$ind  ", $grp) . "</rdf:li>";
        }
        $val = "$val2\n$ind </rdf:Bag>\n$ind";
    } elsif (ref $val eq 'HASH') {
        $gt = " rdf:parseType='Resource'>";
        my $val2 = '';
        foreach (sort keys %$val) {
            my $tok = $grp . ':' . $_;
            $val2 .= "\n$ind <$tok" . FormatXML($$val{$_}, "$ind ", $grp) . "</$tok>";
        }
        $val = "$val2\n$ind";
    } else {
        # (note: SCALAR reference should have already been converted)
        my $enc = EncodeXML(\$val);
        $gt = " rdf:datatype='$enc'>\n" if $enc; #ATV
    }
    return $gt . $val;
}

#------------------------------------------------------------------------------
# Escape string for JSON
# Inputs: 0) string, 1) flag to force numbers to be quoted too
# Returns: Escaped string (quoted if necessary)
sub EscapeJSON($;$)
{
    my ($str, $quote) = @_;
    unless ($quote) {
        # JSON boolean (true or false)
        return lc($str) if $str =~ /^(true|false)$/i;
        # JSON number (see json.org for numerical format)
        # return $str if $str =~ /^-?(\d|[1-9]\d+)(\.\d+)?(e[-+]?\d+)?$/i;
        # (these big numbers caused problems for some JSON parsers, so be more conservative)
        return $str if $str =~ /^-?(\d|[1-9]\d{1,14})(\.\d{1,16})?(e[-+]?\d{1,3})?$/i;
    }
    # escape special characters
    $str =~ s/(["\t\n\r\\])/\\$jsonChar{$1}/sg;
    # escape other control characters with \u
    $str =~ s/([\0-\x1f])/sprintf("\\u%.4X",ord $1)/sge;
    return '"' . $str . '"';    # return the quoted string
}

#------------------------------------------------------------------------------
# Print JSON value
# Inputs: 0) file reference, 1) value, 2) indentation
sub FormatJSON($$$)
{
    local $_;
    my ($fp, $val, $ind) = @_;
    my $comma;
    if (not ref $val) {
        print $fp EscapeJSON($val);
    } elsif (ref $val eq 'ARRAY') {
        if ($joinLists and not ref $$val[0]) {
            print $fp EscapeJSON(join $listSep, @$val);
        } else {
            print $fp '[';
            foreach (@$val) {
                print $fp ',' if $comma;
                FormatJSON($fp, $_, $ind);
                $comma = 1,
            }
            print $fp ']',
        }
    } elsif (ref $val eq 'HASH') {
        print $fp '{';
        foreach (sort keys %$val) {
            print $fp ',' if $comma;
            print $fp qq(\n$ind  "$_": );
            FormatJSON($fp, $$val{$_}, "$ind  ");
            $comma = 1,
        }
        print $fp "\n$ind}",
    } else {
        # (note: SCALAR reference should have already been converted)
        print $fp '"<err>"';
    }
}

#------------------------------------------------------------------------------
# Convert binary data (SCALAR references) for printing
# Inputs: 0) object reference
# Returns: converted object
sub ConvertBinary($)
{
    my $obj = shift;
    my ($key, $val);
    if (ref $obj eq 'HASH') {
        foreach $key (keys %$obj) {
            $$obj{$key} = ConvertBinary($$obj{$key}) if ref $$obj{$key};
        }
    } elsif (ref $obj eq 'ARRAY') {
        foreach $val (@$obj) {
            $val = ConvertBinary($val) if ref $val;
        }
    } elsif (ref $obj eq 'SCALAR') {
        # (binaryOutput flag is set to 0 for binary mode of XML output format)
        if (defined $binaryOutput) {
            $obj = $$obj;
        } else {
            # (-b is not valid for JSON or HTML output)
            my $bOpt = ($json or $html) ? '' : ', use -b option to extract';
            if ($$obj =~ /^Binary data/) {
                $obj = "($$obj$bOpt)";
            } else {
                $obj = '(Binary data ' . length($$obj) . " bytes$bOpt)";
            }
        }
    }
    return $obj;
}

#------------------------------------------------------------------------------
# Set new values from file
# Inputs: 0) exiftool ref, 1) filename, 2) reference to list of values to set
# Returns: 0 on error (and increments $countBadWr)
sub DoSetFromFile($$$)
{
    local $_;
    my ($exifTool, $file, $setTags) = @_;
    $verbose and print "Setting new values from $file\n";
    my $info = $exifTool->SetNewValuesFromFile($file, @$setTags);
    my $numSet = scalar(keys %$info);
    if ($$info{Error}) {
        # delete all error and warning tags
        my @warns = grep /^(Error|Warning)\b/, keys %$info;
        $numSet -= scalar(@warns);
        # issue a warning for the main error only if we were able to set some tags
        if (keys(%$info) > @warns) {
            my $err = $$info{Error};
            delete $$info{$_} foreach @warns;
            $$info{Warning} = $err;
        }
    } elsif ($$info{Warning}) {
        my $warns = 1;
        ++$warns while $$info{"Warning ($warns)"};
        $numSet -= $warns;
    }
    PrintErrors($exifTool, $info, $file);
    $$info{Error} and ++$countBadWr, return 0;
    Warn "Warning: No writable tags found - $file\n" unless $numSet;
    return 1;
}

#------------------------------------------------------------------------------
# Translate backslashes to forward slashes in filename if necessary
# Inputs: 0) Filename
# Returns: nothing, but changes filename if necessary
sub CleanFilename($)
{
    $_[0] =~ tr/\\/\// if $hasBackslash{$^O};
}

#------------------------------------------------------------------------------
# process files in our @files list
# Inputs: 0) ExifTool ref, 1) list ref to just return full file names
# Notes: arg 0 is not used if arg 1 is defined
sub ProcessFiles($;$)
{
    my ($exifTool, $list) = @_;
    my $file;
    foreach $file (@files) {
        if (-d $file) {
            $multiFile = $validFile = 1;
            ScanDir($mainTool, $file, $list);
        } elsif ($filterFlag and not AcceptFile($file)) {
            if (-e $file) {
                $filtered = 1;
                $verbose and print "-------- $file (wrong extension)\n";
            } else {
                Warn "File not found: $file\n";
                $rtnVal = 1;
            }
        } else {
            $validFile = 1;
            $list and push(@$list, $file), next;
            GetImageInfo($exifTool, $file);
        }
    }
}

#------------------------------------------------------------------------------
# Scan directory for image files
# Inputs: 0) ExifTool ref, 1) directory name, 2) list ref to return file names
sub ScanDir($$;$)
{
    my ($exifTool, $dir, $list) = @_;
    opendir(DIR_HANDLE, $dir) or Warn("Error opening directory $dir\n"), return;
    my @fileList = readdir(DIR_HANDLE);
    closedir(DIR_HANDLE);

    my $file;
    $dir =~ /\/$/ or $dir .= '/';
    foreach $file (@fileList) {
        my $path = "$dir$file";
        if (-d $path) {
            next unless $recurse and $file !~ /^\./; # ignore dirs starting with "."
            next if $ignore{$file} or ($ignore{SYMLINKS} and -l $path);
            ScanDir($exifTool, $path, $list);
            next;
        }
        # apply rules from -ext options
        my $accepted;
        if ($filterFlag) {
            $accepted = AcceptFile($file) or next;
            # must be specifically accepted to bypass selection logic
            $accepted &= 0x01;
        }
        unless ($accepted) {
            # read/write this file if it is a supported type
            if ($scanWritable) {
                if ($scanWritable eq '1') {
                    next unless CanWrite($file);
                } else {
                    my $type = GetFileType($file);
                    next unless defined $type and $type eq $scanWritable;
                }
            } elsif (not GetFileType($file)) {
                next unless $doUnzip;
                next unless $file =~ /\.(gz|bz2)$/i;
            }
        }
        $list and push(@$list, $path), next;
        GetImageInfo($exifTool, $path);
    }
    ++$countDir;
}

#------------------------------------------------------------------------------
# Add print format entry
# Inputs: 0) expression string
sub AddPrintFormat($)
{
    my $expr = shift;
    my $type;
    if ($expr =~ /^#/) {
        $expr =~ s/^#\[(HEAD|BODY|TAIL)\]// or return; # ignore comments
        $type = $1;
    } else {
        $type = 'BODY';
    }
    $printFmt{$type} or $printFmt{$type} = [ ];
    push @{$printFmt{$type}}, $expr;
    # add to list of requested tags
    push @tags, $expr =~ /\$((?:[-\w]+:)*[-\w]+#?)/g;
    # tags contained in braces too...
    push @tags, $expr =~ /\$\{((?:[-\w]+:)*[-\w]+#?)\}/g;
}

#------------------------------------------------------------------------------
# patch for OS X 10.6 to preserve file modify date
# (this probably isn't a 100% fix, but it may solve a majority of the cases)
sub PreserveTime()
{
    local $_;
    utime @{$preserveTime{$_}}, $_ foreach keys %preserveTime;
    undef %preserveTime;
}

#------------------------------------------------------------------------------
# Load print format file
# Inputs: 0) file name
# - saves lines of file to %printFmt list
# - adds tag names to @tags list
sub LoadPrintFormat($)
{
    my $arg = shift;
    if (not defined $arg) {
        Error "Must specify file or expression for -p option\n";
    } elsif (-f $arg and open(FMT_FILE, "<$arg")) {
        foreach (<FMT_FILE>) {
            AddPrintFormat($_);
        }
        close(FMT_FILE);
    } else {
        AddPrintFormat($arg . "\n");
    }
}

#------------------------------------------------------------------------------
# A sort of sprintf for filenames
# Inputs: 0) format string (%d=dir, %f=file name, %e=ext),
#         1) source filename or undef to test format string
# Returns: new filename or undef on error (or if no file and fmt contains token)
sub FilenameSPrintf($;$)
{
    my ($fmt, $file) = @_;
    # return format string straight away if no tokens
    return $fmt unless $fmt =~ /%[-+]?\d*\.?\d*[lu]?[dfe]/;
    return undef unless defined $file;
    CleanFilename($file);   # make sure we are using forward slashes
    # split filename into directory, file, extension
    my @parts = ($file =~ /^(.*?)([^\/]*?)(\.[^.\/]*)?$/);
    $parts[2] = $parts[2] ? substr($parts[2], 1) : '';
    @parts or Warn("Error: Bad pattern match for file $file\n"), return undef;
    my %part;
    foreach ('d','f','e') {
        $part{$_} = shift @parts;
    }
    my ($filename, $pos) = ('', 0);
    while ($fmt =~ /(%([-+]?)(\d*)\.?(\d*)([lu]?)([dfe]))/g) {
        $filename .= substr($fmt, $pos, pos($fmt) - $pos - length($1));
        $pos = pos($fmt);
        my ($sign, $wid, $skip, $mod, $code) = ($2, $3, $4 || 0, $5, $6);
        my $len = length $part{$code};
        next unless $skip < $len;
        $wid = $len - $skip if $wid eq '' or $wid + $skip > $len;
        $skip = $len - $wid - $skip if $sign eq '-';
        my $part = substr($part{$code}, $skip, $wid);
        $part = ($mod eq 'u') ? uc($part) : lc($part) if $mod;
        $filename .= $part;
    }
    $filename .= substr($fmt, $pos); # add rest of file name
    # remove double slashes (except at beginning to allow Windows UNC paths)
    $filename =~ s{(?!^)//}{/}g;
    return $filename;
}

#------------------------------------------------------------------------------
# Convert number to alphabetical index: a, b, c, ... z, aa, ab ...
# Inputs: 0) number
# Returns: alphabetical index string
sub Num2Alpha($)
{
    my $num = shift;
    my $alpha = chr(97 + ($num %26));
    while ($num >= 26) {
        $num = int($num / 26) - 1;
        $alpha = chr(97 + ($num % 26)) . $alpha;
    }
    return $alpha;
}

#------------------------------------------------------------------------------
# Expand '%c' and '%C' codes if filename to get next unused file name
# Inputs: 0) file name format string, 1) filename ok to use even if it exists
# Returns: new file name
sub NextUnusedFilename($;$)
{
    my ($fmt, $okfile) = @_;
    return $fmt unless $fmt =~ /%[-+]?\d*\.?\d*[lun]?[cC]/;
    my %sep = ( '-' => '-', '+' => '_' );
    my ($copy, $alpha) = (0, 'a');
    for (;;) {
        my ($filename, $pos) = ('', 0);
        while ($fmt =~ /(%([-+]?)(\d*)(\.?)(\d*)([lun]?)([cC]))/g) {
            $filename .= substr($fmt, $pos, pos($fmt) - $pos - length($1));
            $pos = pos($fmt);
            my ($sign, $wid, $dec, $wid2, $mod, $tok) = ($2, $3 || 0, $4, $5 || 0, $6, $7);
            if ($tok eq 'C') {
                $seqFileNum = $wid if $wid and not $seqFileNum;
                $wid = $wid2;
            } else {
                next unless $dec or $copy;
                $wid = $wid2 if $wid < $wid2;
            }
            # add dash or underline separator if '-' or '+' specified
            $filename .= $sep{$sign} if $sign;
            if ($mod and $mod ne 'n') {
                my $a = $tok eq 'C' ? Num2Alpha($seqFileNum++) : $alpha;
                my $str = ($wid and $wid > length $a) ? 'a' x ($wid - length($a)) : '';
                $str .= $a;
                $str = uc $str if $mod eq 'u';
                $filename .= $str;
            } else {
                my $c = $tok eq 'C' ? $seqFileNum++ : $copy;
                my $num = $c + ($mod ? 1 : 0);
                $filename .= $wid ? sprintf("%.${wid}d",$num) : $num;
            }
        }
        $filename .= substr($fmt, $pos); # add rest of file name
        # return now with filename unless file exists
        return $filename unless -e $filename;
        return $filename if defined $okfile and $filename eq $okfile;
        ++$copy;
        ++$alpha;
    }
}

#------------------------------------------------------------------------------
# Create directory for specified file
# Inputs: 0) complete file name including path
# Returns: true if a directory was created
sub CreateDirectory($)
{
    my $file = shift;
    my ($dir, $created);
    ($dir = $file) =~ s/[^\/]*$//;  # remove filename from path specification
    if ($dir and not -d $dir) {
        my @parts = split /\//, $dir;
        $dir = '';
        foreach (@parts) {
            $dir .= $_;
            if (length $dir and not -d $dir and
                # don't try to create a network drive root directory
                not ($hasBackslash{$^O} and $dir =~ m{^//[^/]*$}))
            {
                # create directory since it doesn't exist
                mkdir($dir, 0777) or Error("Error creating directory $dir\n"), return 0;
                $verbose and print "Created directory $dir\n";
                $created = 1;
            }
            $dir .= '/';
        }
    }
    ++$countNewDir if $created;
    return $created;
}

#------------------------------------------------------------------------------
# Open output text file
# Inputs: 0) file name format string
# Returns: 0) file reference (or undef on error), 1) file name if opened
sub OpenOutputFile($)
{
    my $file = shift;
    my ($fp, $outfile);
    if ($textOut) {
        $outfile = $file;
        CleanFilename($outfile);
        if ($textOut =~ /%[-+]?\d*\.?\d*[lun]?[dfecC]/) {
            # make filename from printf-like $textOut
            $outfile = FilenameSPrintf($textOut, $file);
            return () unless defined $outfile;
            $outfile = NextUnusedFilename($outfile);
            CreateDirectory($outfile);  # create directory if necessary
        } else {
            $outfile =~ s/\.[^.\/]*$//; # remove extension if it exists
            $outfile .= $textOut;
        }
        if (-e $outfile and not $textOverwrite) {
            Warn "Output file $outfile already exists for $file\n";
            return ();
        }
        open(OUTFILE, ">$outfile") or Error("Error creating $outfile\n"), return ();
        binmode(OUTFILE) if $binaryOutput;
        $fp = \*OUTFILE;
    } else {
        $fp = \*STDOUT;
    }
    return($fp, $outfile);
}

#------------------------------------------------------------------------------
# Filter files based on extension
# Inputs: 0) file name
# Returns: 0 = rejected, 1 = specifically accepted, 2 = accepted by default
# Notes: This routine should only be called if $filterFlag is set
sub AcceptFile($)
{
    my $file = shift;
    my $ext = ($file =~ /.*\.(.+)$/) ? uc($1) : '';
    return $filterExt{$ext} if defined $filterExt{$ext};
    return 0 if $filterFlag & 0x02; # reject if accepting specific extensions
    return 2;   # accept by default
}

#------------------------------------------------------------------------------
# Slurp file into buffer
# Inputs: 0) file name, 1) buffer reference
# Returns: 1 on success
sub SlurpFile($$)
{
    my ($file, $buffPt) = @_;
    open(INFILE, "<$file") or Warn("Error opening file $file\n"), return 0;
    binmode(INFILE);
    my $bsize = 1024 * 1024;
    my $num = read(INFILE, $$buffPt, $bsize);
    unless ($num) {
        close(INFILE);
        Warn("Error reading $file\n");
        return 0;
    }
    my $bmax = 64 * $bsize;
    while ($num == $bsize) {
        $bsize *= 2 if $bsize < $bmax;
        my $buff;
        $num = read(INFILE, $buff, $bsize);
        last unless $num;
        $$buffPt .= $buff;
    }
    close(INFILE);
    return 1;
}

#------------------------------------------------------------------------------
# Read arguments from -stay_open argfile
# Inputs: 0) argument list ref
# Notes: blocks until -execute, -stay_open or -@ option is available
#        (or until there was an error reading from the file)
sub ReadStayOpen($)
{
    my $args = shift;
    my (@newArgs, $processArgs, $result);
    my $lastArg = '';
    my $unparsed = length $stayOpenBuff;
    for (;;) {
        if ($unparsed) {
            # parse data already read from argfile
            $result = $unparsed;
            undef $unparsed;
        } else {
            # read more data from argfile
            # - this read may block (which is good) if reading from a tty device
            $result = sysread(STAYOPEN, $stayOpenBuff, 65536, length($stayOpenBuff));
        }
        if ($result) {
            my $pos = 0;
            while ($stayOpenBuff =~ /\n/g) {
                my $len = pos($stayOpenBuff) - $pos;
                my $arg = substr($stayOpenBuff, $pos, $len);
                $pos += $len;
                $arg =~ s/(^\s+|\s+$)//g; # remove leading/trailing white space
                # remove white space before, and single space after '=', '+=', '-=' or '<='
                $arg =~ s/^([-\w]+)\s*([-+<]?=) ?/$1$2/;
                unless ($arg eq '' or $arg =~ /^#/) {
                    push @newArgs, $arg;
                    $arg = lc $arg;
                    # process args after -execute, -stay_open or -@ option
                    # (note: we really don't know for sure if these are the options
                    #  because we aren't fully processing the arguments so these may
                    #  just be arguments for other options, but this is OK because
                    #  the main code handles all of the parsing when we exit here)
                    if ($arg eq '-execute' or $lastArg eq '-stay_open' or $lastArg eq '-@') {
                        $processArgs = 1;
                        last;   # process arguments up to this point
                    }
                    $lastArg = $arg;
                }
            }
            next unless $pos;   # nothing to do if we didn't read any arguments
            # keep unprocessed data in buffer
            $stayOpenBuff = substr($stayOpenBuff, $pos);
            if ($processArgs) {
                # process new arguments after -execute or -stay_open option
                unshift @$args, @newArgs;
                last;
            }
        } elsif ($result == 0) {
            # sysread() didn't block (ie. when reading from a file),
            # so wait for a short time (1/100 sec) then try again
            select(undef,undef,undef,0.01);
        } else {
            Warn "Error reading from ARGFILE\n";
            close STAYOPEN;
            $stayOpen = 0;
            last;
        }
    }
}

#------------------------------------------------------------------------------
# Print accumulated CSV information
sub PrintCSV()
{
    my ($file, $lcTag, @tags);

    @csvTags or @csvTags = sort keys %csvTags;
    # make a list of tags actually found
    foreach $lcTag (@csvTags) {
        push @tags, $csvTags{$lcTag} if $csvTags{$lcTag};
    }
    print join(',', 'SourceFile', @tags), "\n";
    foreach $file (@csvFiles) {
        my @vals = ($file);    # start with full file name
        my $csvInfo = $database{$file};
        foreach $lcTag (@csvTags) {
            next unless $csvTags{$lcTag};
            my $val = $$csvInfo{$lcTag};
            defined $val or push(@vals,''), next;
            if ($val =~ s/"/""/g or $val =~ /(^\s+|\s+$)/ or $val =~ /[,\n\r]/) {
                push @vals, qq{"$val"};
            } else {
                push @vals, $val;
            }
        }
        print join(',', @vals), "\n";
    }
}

#------------------------------------------------------------------------------
# Print list of tags
# Inputs: 0) message, 1-N) list of tag names
sub PrintTagList($@)
{
    my $msg = shift;
    print $msg, ":\n ";
    my $len = 1;
    my $tag;
    foreach $tag (@_) {
        my $taglen = length($tag);
        if ($len + $taglen > 78) {
            print "\n ";
            $len = 1;
        }
        print " $tag";
        $len += $taglen + 1;
    }
    @_ or print ' [empty list]';
    print "\n";
}

#------------------------------------------------------------------------------
# Get source file name for specified file
# Inputs: 0) file name
sub SourceFile($)
{
    my $file = shift;
    return $file unless $srcFmt;
    return FilenameSPrintf($srcFmt, $file);
}

#------------------------------------------------------------------------------
# Print warnings and errors from info hash
# Inputs: 0) ExifTool object ref, 1) info hash, 2) file name
sub PrintErrors($$$)
{
    my ($exifTool, $info, $file) = @_;
    my ($tag, $key);
    foreach $tag (qw(Warning Error)) {
        next unless $$info{$tag};
        my @keys = ( $tag );
        push @keys, sort(grep /^$tag /, keys %$info) if $exifTool->Options('Duplicates');
        foreach $key (@keys) {
            Warn "$tag: $info->{$key} - $file\n";
        }
    }
}

__END__

=head1 NAME

exiftool - Read and write meta information in files

=head1 SYNOPSIS

=over 4

=item B<exiftool> [I<OPTIONS>] [-I<TAG>...] [--I<TAG>...] I<FILE>...

=item B<exiftool> [I<OPTIONS>] -I<TAG>[+-E<lt>]=[I<VALUE>]... I<FILE>...

=item B<exiftool> [I<OPTIONS>] B<-tagsFromFile> I<SRCFILE>
[-I<SRCTAG>[E<gt>I<DSTTAG>]...] I<FILE>...

=item B<exiftool> [ B<-ver> |
B<-list>[B<w>|B<f>|B<wf>|B<g>[I<NUM>]|B<d>|B<x>] ]

=back

For specific examples, see the L<EXAMPLES|/READING EXAMPLES> sections below.

=head1 DESCRIPTION

A command-line interface to L<Image::ExifTool|Image::ExifTool>, used for
reading and writing meta information in image, audio and video files.
I<FILE> is one or more source file names, directory names, or C<-> for the
standard input.  Information is read from the source files and output in
readable form to the console (or written to output text files with B<-w>).

To write, copy or delete information in each I<FILE>, specify new tag values
with the -I<TAG>=[I<VALUE>] syntax or the B<-tagsFromFile> or B<-geotag>
options.  By default the original files are preserved with C<_original>
appended to their names -- be sure to verify that the new files are OK
before erasing the originals.  Once in write mode, exiftool will ignore any
read-specific options.

Note:  If I<FILE> is a directory name then only supported file types in the
directory are processed (in write mode only writable types are processed).
However, files may be specified by name, or the B<-ext> option may be used
to force processing of files with any extension.

Below is a list of file types and meta information formats currently
supported by ExifTool (r = read, w = write, c = create):

  File Types
  ------------+-------------+-------------+-------------+------------
  3FR   r     | DVB   r     | M4A/V r     | PBM   r/w   | RWL   r/w
  3G2   r     | DYLIB r     | MEF   r/w   | PDF   r/w   | RWZ   r
  3GP   r     | EIP   r     | MIE   r/w/c | PEF   r/w   | RM    r
  ACR   r     | EPS   r/w   | MIFF  r     | PFA   r     | SO    r
  AFM   r     | ERF   r/w   | MKA   r     | PFB   r     | SR2   r/w
  AI    r/w   | EXE   r     | MKS   r     | PFM   r     | SRF   r
  AIFF  r     | EXIF  r/w/c | MKV   r     | PGF   r     | SRW   r/w
  APE   r     | F4A/V r     | MNG   r/w   | PGM   r/w   | SVG   r
  ARW   r/w   | FLA   r     | MOS   r/w   | PICT  r     | SWF   r
  ASF   r     | FLAC  r     | MOV   r     | PMP   r     | THM   r/w
  AVI   r     | FLV   r     | MP3   r     | PNG   r/w   | TIFF  r/w
  BMP   r     | FPX   r     | MP4   r     | PPM   r/w   | TTC   r
  BTF   r     | GIF   r/w   | MPC   r     | PPT   r     | TTF   r
  COS   r     | GZ    r     | MPG   r     | PPTX  r     | VRD   r/w/c
  CR2   r/w   | HDP   r/w   | MPO   r/w   | PS    r/w   | VSD   r
  CRW   r/w   | HTML  r     | MQV   r     | PSB   r/w   | WAV   r
  CS1   r/w   | ICC   r/w/c | MRW   r/w   | PSD   r/w   | WDP   r/w
  DCM   r     | IIQ   r/w   | MXF   r     | PSP   r     | WEBP  r
  DCP   r/w   | IND   r/w   | NEF   r/w   | QTIF  r     | WEBM  r
  DCR   r     | ITC   r     | NRW   r/w   | RA    r     | WMA   r
  DFONT r     | JNG   r/w   | NUMBERS r   | RAF   r/w   | WMV   r
  DIVX  r     | JP2   r/w   | ODP   r     | RAM   r     | X3F   r/w
  DJVU  r     | JPEG  r/w   | ODS   r     | RAR   r     | XCF   r
  DLL   r     | K25   r     | ODT   r     | RAW   r/w   | XLS   r
  DNG   r/w   | KDC   r     | OGG   r     | RIFF  r     | XLSX  r
  DOC   r     | KEY   r     | ORF   r/w   | RSRC  r     | XMP   r/w/c
  DOCX  r     | LNK   r     | OTF   r     | RTF   r     | ZIP   r
  DV    r     | M2TS  r     | PAGES r     | RW2   r/w   |

  Meta Information
  ----------------------+----------------------+---------------------
  EXIF           r/w/c  |  CIFF           r/w  |  Ricoh RMETA    r
  GPS            r/w/c  |  AFCP           r/w  |  Picture Info   r
  IPTC           r/w/c  |  Kodak Meta     r/w  |  Adobe APP14    r
  XMP            r/w/c  |  FotoStation    r/w  |  MPF            r
  MakerNotes     r/w/c  |  PhotoMechanic  r/w  |  Stim           r
  Photoshop IRB  r/w/c  |  JPEG 2000      r    |  APE            r
  ICC Profile    r/w/c  |  DICOM          r    |  Vorbis         r
  MIE            r/w/c  |  Flash          r    |  SPIFF          r
  JFIF           r/w/c  |  FlashPix       r    |  DjVu           r
  Ducky APP12    r/w/c  |  QuickTime      r    |  M2TS           r
  PDF            r/w/c  |  Matroska       r    |  PE/COFF        r
  PNG            r/w/c  |  GeoTIFF        r    |  AVCHD          r
  Canon VRD      r/w/c  |  PrintIM        r    |  ZIP            r
  Nikon Capture  r/w/c  |  ID3            r    |  (and more)

=head1 OPTIONS

Case is not significant for any command-line option (including tag and group
names), except for single-character options when the corresponding
upper-case option exists.  Many single-character options have equivalent
long-name versions (shown in brackets), and some options have inverses which
are invoked with a leading double-dash.  Note that multiple single-character
options may NOT be combined into one argument because this would be
interpreted as a tag name.

=head2 Option Summary

L<Tag operations|/Tag operations>

  -TAG or --TAG                    Extract or exclude specified tag
  -TAG[+-]=[VALUE]                 Write new value for tag
  -TAG[+-]<=DATFILE                Write tag value from contents of file
  -TAG[+-]<SRCTAG                  Copy tag value (see -tagsFromFile)

  -tagsFromFile SRCFILE            Copy tag values from file
  -x TAG      (-exclude)           Exclude specified tag

L<Input-output text formatting|/Input-output text formatting>

  -args       (-argFormat)         Output data as exiftool arguments
  -b          (-binary)            Output data in binary format
  -c FMT      (-coordFormat)       Set format for GPS coordinates
  -charset [[TYPE=]CHARSET]        Specify encoding for special characters
  -csv[=CSVFILE]                   Export/import tags in CSV format
  -d FMT      (-dateFormat)        Set format for date/time values
  -D          (-decimal)           Show tag ID numbers in decimal
  -E, -ex     (-escape(HTML|XML))  Escape values for HTML (-E) or XML (-ex)
  -f          (-forcePrint)        Force printing of all specified tags
  -g[NUM...]  (-groupHeadings)     Organize output by tag group
  -G[NUM...]  (-groupNames)        Print group name for each tag
  -h          (-htmlFormat)        Use HMTL formatting for output
  -H          (-hex)               Show tag ID number in hexadecimal
  -htmlDump[OFFSET]                Generate HTML-format binary dump
  -j[=JSONFILE] (-json)            Export/import tags in JSON format
  -l          (-long)              Use long 2-line output format
  -L          (-latin)             Use Windows Latin1 encoding
  -lang [LANG]                     Set current language
  -n          (--printConv)        Disable print conversion
  -p FMTFILE  (-printFormat)       Print output in specified format
  -s[NUM]     (-short)             Short output format
  -S          (-veryShort)         Very short output format
  -sep STR    (-separator)         Set separator string for list items
  -struct                          Enable output of structured information
  -t          (-tab)               Output in tab-delimited list format
  -T          (-table)             Output in tabular format
  -v[NUM]     (-verbose)           Print verbose messages
  -w[!] EXT   (-textOut)           Write output text files
  -X          (-xmlFormat)         Use RDF/XML output format

L<Processing control|/Processing control>

  -a          (-duplicates)        Allow duplicate tags to be extracted
  -e          (--composite)        Do not calculate composite tags
  -ee         (-extractEmbedded)   Extract information from embedded files
  -ext EXT    (-extension)         Process files with specified extension
  -F[OFFSET]  (-fixBase)           Fix the base for maker notes offsets
  -fast[NUM]                       Increase speed for slow devices
  -fileOrder [-]TAG                Set file processing order
  -i DIR      (-ignore)            Ignore specified directory name
  -if EXPR                         Conditionally process files
  -m          (-ignoreMinorErrors) Ignore minor errors and warnings
  -o OUTFILE  (-out)               Set output file or directory name
  -overwrite_original              Overwrite original by renaming tmp file
  -overwrite_original_in_place     Overwrite original by copying tmp file
  -P          (-preserve)          Preserve date/time of original file
  -password PASSWD                 Password for processing protected files
  -q          (-quiet)             Quiet processing
  -r          (-recurse)           Recursively process subdirectories
  -scanForXMP                      Brute force XMP scan
  -u          (-unknown)           Extract unknown tags
  -U          (-unknown2)          Extract unknown binary tags too
  -z          (-zip)               Read/write compressed information

L<Special features|/Special features>

  -geotag TRKFILE                  Geotag images from specified GPS log
  -use MODULE                      Add features from plug-in module

L<Utilities|/Utilities>

  -delete_original[!]              Delete "_original" backups
  -restore_original                Restore from "_original" backups

L<Other options|/Other options>

  -@ ARGFILE                       Read command-line arguments from file
  -k          (-pause)             Pause before terminating
  -list[w|f|wf|g[NUM]|d|x]         List various exiftool attributes
  -ver                             Print exiftool version number

L<Advanced options|/Advanced options>

  -common_args                     Define common arguments
  -config CFGFILE                  Specify configuration file name
  -execute                         Execute multiple commands on one line
  -srcfile FMT                     Set different source file name
  -stay_open FLAG                  Keep reading -@ argfile even after EOF

=head2 Option Details

=head3 Tag operations

=over 5

=item B<->I<TAG>

Extract information for specified tag (ie. C<-CreateDate>).  A tag name
is the handle by which a piece of information is referenced.  See
L<Image::ExifTool::TagNames|Image::ExifTool::TagNames> for documentation on
available tag names.  A tag name may include leading group names separated
by colons (ie. C<-EXIF:CreateDate>, or C<-Doc1:XMP:Creator>), and each group
name may be prefixed by a digit to specify family number (ie.
C<-1IPTC:City>).  Use the B<-listg> option to list available group names by
family.

A special tag name of C<All> may be used to indicate all meta information.
This is particularly useful when a group name is specified to extract all
information in a group (but beware that unless the B<-a> option is also
used, some tags in the group may be suppressed by same-named tags in other
groups).  The wildcard characters C<?> and C<*> may be used in a tag name to
match any single character and zero or more characters respectively.  These
may not be used in a group name, with the exception that a group name of
C<*> (or C<All>) may be used to extract all instances of a tag (as if B<-a>
was used).  Note that arguments containing wildcards must be quoted on the
command line of most systems to prevent shell globbing, and wildcards may
not be used when writing/deleting tags.

A C<#> may be appended to the tag name to disable the print conversion on a
per-tag basis (see the B<-n> option).  This may also be used when writing or
copying tags.

If no tags are specified, all available information is extracted (as if
C<-All> had been specified).

Note:  Descriptions, not tag names, are shown by default when extracting
information.  Use the B<-s> option to see the tag names instead.

=item B<-->I<TAG>

Exclude specified tag from extracted information.  Same as the B<-x> option.
May also be used following a B<-tagsFromFile> option to exclude tags from
being copied, or to exclude groups from being deleted when deleting all
information (ie. C<-all= --exif:all> deletes all but EXIF information).  But
note that this will not exclude individual tags from a group delete.
Instead, the tags must be recovered using the B<-tagsFromFile> option (ie.
C<-all= -tagsfromfile @ -artist>).  Wildcards are permitted as described
above for B<-TAG>.

=item B<->I<TAG>[+-]B<=>[I<VALUE>]

Write a new value for the specified tag (ie. C<-comment=wow>), or delete the
tag if no I<VALUE> is given (ie. C<-comment=>). C<+=> and C<-=> are used to
add or remove existing entries from a list, or to shift date/time values
(see L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl> for details),
and C<-=> may be used to conditionally remove or replace a tag (see
L</WRITING EXAMPLES> for examples).

I<TAG> may contain a leading family 0 or 1 group name separated by a colon.
If no group name is specified, the tag is created in the preferred group,
and updated in any other location where a same-named tag already exists. 
The preferred group is the first group in the following list where I<TAG> is
valid: 1) EXIF, 2) IPTC, 3) XMP.

The special C<All> tag may be used in this syntax only if a I<VALUE> is NOT
given.  This causes all meta information to be deleted (or all information
in a group if C<-GROUP:All=> is used).  Note that not all groups are
deletable.  Use the B<-listd> option for a complete list of deletable
groups.  Also, within an image some groups may be contained within others,
and these groups are removed if the containing group is deleted:

  JPEG Image:
  - Deleting EXIF or IFD0 also deletes ExifIFD, GlobParamIFD,
    GPS, IFD1, InteropIFD, MakerNotes, PrintIM and SubIFD.
  - Deleting ExifIFD also deletes InteropIFD and MakerNotes.
  - Deleting Photoshop also deletes IPTC.

  TIFF Image:
  - Deleting EXIF only removes ExifIFD which also deletes
    InteropIFD and MakerNotes.

Note:  MakerNotes tags may be edited, but not created or deleted
individually. This avoids many potential problems including the inevitable
compatibility problems with OEM software which may be very inflexible about
the information it expects to find in the maker notes.

Special feature:  Integer values may be specified in hexadecimal with a
leading C<0x>, and simple rational values may be specified as fractions.

=item B<->I<TAG>E<lt>=I<DATFILE> or B<->I<TAG>E<lt>=I<FMT>

Set the value of a tag from the contents of file I<DATFILE>.  The file name
may also be given by a I<FMT> string where %d, %f and %e represent the
directory, file name and extension of the original I<FILE> (see the B<-w>
option for more details).  Note that quotes are required around this
argument to prevent shell redirection since it contains a C<E<lt>> symbol.
C<+E<lt>=> or C<-E<lt>=> may also be used to add or delete specific list
entries, or to shift date/time values.

=item B<-tagsFromFile> I<SRCFILE> or I<FMT>

Copy tag values from I<SRCFILE> to I<FILE>.  Tag names on the command line
after this option specify the tags to be copied, or excluded from the copy.
If no tags are specified, then all possible tags (see note 1 below) from the
source file are copied.  More than one B<-tagsFromFile> option may be used
to copy tags from multiple files.

By default, this option will commute information between same-named tags in
different groups and write each tag to the preferred group.  This allows
some information to be automatically translated when copying between images
of different formats.  However, if a group name is specified for a tag then
the information is written to the original group (unless redirected to
another group, see below).  This works even if C<All> is used as a group
name, so C<-All:All> is used to specify that all information be copied to
the same group in the destination file.

I<SRCFILE> may be the same as I<FILE> to move information around within a
file.  In this case, C<@> may be used to represent the source file (ie.
C<-tagsFromFile @>), permitting this feature to be used for batch processing
multiple files (see note 4 below).  Specified tags are then copied from each
file in turn as it is rewritten.  For advanced batch use, the source file
name may also be specified using a I<FMT> string in which %d, %f and %e
represent the directory, file name and extension of I<FILE>.  See B<-w>
option for I<FMT> string examples.

A powerful redirection feature allows a destination tag to be specified for
each extracted tag.  With this feature, information may be written to a tag
with a different name or group.  This is done using
E<quot>'-I<SRCTAG>E<gt>I<DSTTAG>'E<quot> or
E<quot>'-I<DSTTAG>E<lt>I<SRCTAG>'E<quot> on the command line after
B<-tagsFromFile>, and causes the value of I<SRCTAG> to be copied from
I<SRCFILE> and written to I<DSTTAG> in I<FILE>.  Note that this argument
must be quoted to prevent shell redirection, and there is no C<=> sign as
when assigning new values. Both source and destination tags may be prefixed
by a group name, and C<All> or C<*> may be used as a tag or group name.  If
no destination group is specified, the information is written to the
preferred group.  As a convenience, C<-tagsFromFile @> is assumed for any
redirected tags which are specified without a prior B<-tagsFromFile> option.
Copied tags may also be added or deleted from a list with arguments of the
form E<quot>'-I<SRCTAG>+E<gt>I<DSTTAG>'E<quot> or
E<quot>'-I<SRCTAG>-E<gt>I<DSTTAG>'E<quot>.

An extension of the redirection feature allows strings involving tag names
to be used on the right hand side of the C<E<lt>> symbol with the syntax
E<quot>'-I<DSTTAG>E<lt>I<STR>'E<quot>, where tag names in I<STR> are
prefixed with a C<$> symbol.  See the B<-p> option for more details about
this syntax.  Strings starting with a C<=> sign must insert a single space
after the C<E<lt>> to avoid confusion with the C<E<lt>=> syntax which would
otherwise attempt to set the tag value from the contents of a file.  A
single space at the start of the string is removed if it exists, but all
other whitespace is preserved.

See L</COPYING EXAMPLES> for examples using B<-tagsFromFile>.

Notes:

1) Some tags (generally tags which may affect the appearance of the image)
are considered "unsafe" to write, and are only copied if specified
explicitly.  See the L<tag name documentation|Image::ExifTool::TagNames> for
more details about "unsafe" tags.

2) Be aware of the difference between excluding a tag from being copied
(--I<TAG>), and deleting a tag (-I<TAG>=).  Excluding a tag prevents it from
being copied to the destination image, but deleting will remove a
pre-existing tag from the image.

3) The maker note information is copied as a block, so it isn't affected
like other information by subsequent tag assignments on the command line.
Also, since the PreviewImage referenced from the maker notes may be rather
large, it is not copied, and must be transferred separately if desired.

4) When performing complex batch processing, it is important to note that
the order of operations is different for tags copied in batch mode.  In
general, tags are copied from batch-mode files after all other command-line
arguments have been applied.  For example, the following two commands are
not equivalent:

    # (not batch mode):  Sets xmp:title to 'NEW'
    exiftool -tagsfromfile a.jpg -xmp:title -xmp:title=NEW a.jpg

    # (batch mode):  Preserves original title if it exists
    exiftool -tagsfromfile @ -xmp:title -xmp:title=NEW a.jpg

5) The normal behaviour of copied tags differs subtly from that of assigned
tags for List-type tags.  When copying to a list, each copied tag overrides
any previous operations on the list.  While this avoids duplicate list items
when copying groups of tags from a file containing redundant information, it
also prevents values of different tags from being copied into the same list
when this is the intent.  So a B<-addTagsFromFile> option is provided which
allows copying of multiple tags into the same list.  ie)

    exiftool -addtagsfromfile @ '-subject<make' '-subject<model' ...

Other than this difference, the B<-tagsFromFile> and B<-addTagsFromFile>
options are equivalent.

6) The B<-a> option (allow duplicate tags) is always in effect when reading
tags from I<SRCFILE>.

7) The B<-struct> option is in effect by default when copying tags, but this
may be disabled with B<--struct> on the command line.  See the B<-struct>
option for details.

=item B<-x> I<TAG> (B<-exclude>)

Exclude the specified tag.  There may be multiple B<-x> options.  This has
the same effect as --I<TAG> on the command line.  May also be used following
a B<-tagsFromFile> option to exclude tags from being copied.

=back

=head3 Input-output text formatting

=over 5

=item B<-args> (B<-argFormat>)

Output information in the form of exiftool arguments, suitable for use with
the B<-@> option when writing.  May be combined with the B<-G> option to
include group names.  This feature may be used to effectively copy tags
between images, but allows the metadata to be altered by editing the
intermediate file (C<out.args> in this example):

    exiftool -args -G1 --filename --directory src.jpg > out.args
    exiftool -@ out.args dst.jpg

Note:  Be careful when copying information with this technique since it is
easy to write tags which are normally considered "unsafe".  For instance,
the FileName and Directory tags are excluded in the example above to avoid
renaming and moving the destination file.  Also note that the second command
above will produce warning messages for any tags which are not writable.

=item B<-b> (B<-binary>)

Output requested data in binary format without tag names or descriptions.
This option is mainly used for extracting embedded images or other binary
data, but it may also be useful for some text strings since control
characters (such as newlines) are not replaced by '.' as they are in the
default output.  Also valid in combination with the C<-X> option.

=item B<-c> I<FMT> (B<-coordFormat>)

Set the print format for GPS coordinates.  I<FMT> uses the same syntax as
the C<printf> format string.  The specifiers correspond to degrees, minutes
and seconds in that order, but minutes and seconds are optional.  For
example, the following table gives the output for the same coordinate using
various formats:

            FMT                  Output
    -------------------    ------------------
    "%d deg %d' %.2f"\"    54 deg 59' 22.80"  (default for reading)
    "%d %d %.8f"           54 59 22.80000000  (default for copying)
    "%d deg %.4f min"      54 deg 59.3800 min
    "%.6f degrees"         54.989667 degrees

Notes:

1) To avoid loss of precision, the default coordinate format is different
when copying tags using the B<-tagsFromFile> option.

2) This print formatting may be disabled with the B<-n> option to extract
coordinates as signed decimal degrees.

=item B<-charset> [[I<TYPE>=]I<CHARSET>]

If I<TYPE> is C<ExifTool> or not specified, this option sets the ExifTool
character encoding for output tag values when reading and input values when
writing.  The default ExifTool encoding is C<UTF8>.  If no I<CHARSET> is
given, a list of available character sets is returned.  Valid I<CHARSET>
values are:

    CHARSET     Alias(es)        Description
    ----------  ---------------  ----------------------------------
    UTF8        cp65001, UTF-8   UTF-8 characters (default)
    Latin       cp1252, Latin1   Windows Latin1 (West European)
    Latin2      cp1250           Windows Latin2 (Central European)
    Cyrillic    cp1251, Russian  Windows Cyrillic
    Greek       cp1253           Windows Greek
    Turkish     cp1254           Windows Turkish
    Hebrew      cp1255           Windows Hebrew
    Arabic      cp1256           Windows Arabic
    Baltic      cp1257           Windows Baltic
    Vietnam     cp1258           Windows Vietnamese
    Thai        cp874            Windows Thai
    MacRoman    cp10000, Roman   Macintosh Roman
    MacLatin2   cp10029          Macintosh Latin2 (Central Europe)
    MacCyrillic cp10007          Macintosh Cyrillic
    MacGreek    cp10006          Macintosh Greek
    MacTurkish  cp10081          Macintosh Turkish
    MacRomanian cp10010          Macintosh Romanian
    MacIceland  cp10079          Macintosh Icelandic
    MacCroatian cp10082          Macintosh Croatian

Other values of I<TYPE> listed below are used to specify the internal
encoding of various meta information formats.

    TYPE       Description                                  Default
    ---------  -------------------------------------------  -------
    ID3        Internal encoding of ID3v1 information       Latin
    IPTC       Internal IPTC encoding to assume when        Latin
                IPTC:CodedCharacterSet is not defined
    Photoshop  Internal encoding of Photoshop IRB strings   Latin

See L<http://owl.phy.queensu.ca/~phil/exiftool/faq.html#Q10> for more
information about coded character sets.

=item B<-csv>[=I<CSVFILE>]

Export information in as a CSV file, or import information if I<CSVFILE> is
specified.  The first row of the I<CSVFILE> must be the ExifTool tag names
(with optional group names) for each column of the file.  A special
"SourceFile" column specifies the files associated with each row of
information (a SourceFile of "*" may be used to apply the information to all
target images). The following examples demonstrate basic use of this option:

    # generate CSV file with common tags from all images in a directory
    exiftool -common -csv dir > out.csv

    # update metadata for all images in a directory from CSV file
    exiftool -csv=a.csv dir

Empty values are ignored when importing.  To force a tag to be deleted, use
the B<-f> option and set the value to "-" in the CSV file.  May be combined
with the B<-g> or B<-G> option to add group names to the tags.

Special feature:  C<+=>I<CSVFILE> may be used to add items to existing
lists.  This affects only list-type tags.  Also applies to the B<-j> option.

=item B<-d> I<FMT> (B<-dateFormat>)

Set the format for date/time tag values.  The specifics of the I<FMT> syntax
are system dependent -- consult the C<strftime> man page on your system for
details.  The default format is equivalent to "%Y:%m:%d %H:%M:%S".  This
option has no effect on date-only or time-only tags and ignores timezone
information if present.  Only one B<-d> option may be used per command.  The
inverse operation (ie. un-formatting a date/time value) is currently not
applied when writing a date/time tag.

=item B<-D> (B<-decimal>)

Show tag ID number in decimal when extracting information.

=item B<-E>, B<-ex> (B<-escapeHTML>, B<-escapeXML>)

Escape characters in output values for HTML (B<-E>) or XML (B<-ex>).  For
HTML, all characters with Unicode code points above U+007F are escaped as
well as the following 5 characters: & (&amp;) E<39> (&#39;) E<quot> (&quot;)
E<gt> (&gt;) and E<lt> (&lt;).  For XML, only these 5 characters are
escaped.  The B<-E> option is implied with B<-h>, and B<-ex> is implied with
B<-X>.  The inverse conversion is applied when writing tags.

=item B<-f> (B<-forcePrint>)

Force printing of tags even if their values are not found.  This option only
applies when tag names are specified.  May also be used to add a 'flags'
attribute to the B<-listx> output, or to allow tags to be deleted with the
B<-csv> option.

=item B<-g>[I<NUM>][:I<NUM>...] (B<-groupHeadings>)

Organize output by tag group.  I<NUM> specifies a group family number, and
may be 0 (general location), 1 (specific location), 2 (category), 3
(document number) or 4 (instance number).  Multiple families may be
specified by separating them with colons.  By default the resulting group
name is simplified by removing any leading C<Main:> and collapsing adjacent
identical group names, but this can be avoided by placing a colon before the
first family number (ie. B<-g:3:1>).  If I<NUM> is not specified, B<-g0> is
assumed.  Use the B<-listg> option to list group names for a specified
family.

=item B<-G>[I<NUM>][:I<NUM>...] (B<-groupNames>)

Same as B<-g> but print group name for each tag.

=item B<-h> (B<-htmlFormat>)

Use HTML table formatting for output.  Implies the B<-E> option.  The
formatting options B<-D>, B<-H>, B<-g>, B<-G>, B<-l> and B<-s> may be used
in combination with B<-h> to influence the HTML format.

=item B<-H> (B<-hex>)

Show tag ID number in hexadecimal when extracting information.

=item B<-htmlDump>[I<OFFSET>]

Generate a dynamic web page containing a hex dump of the EXIF information.
This can be a very powerful tool for low-level analysis of EXIF information.
The B<-htmlDump> option is also invoked if the B<-v> and B<-h> options are
used together.  The verbose level controls the maximum length of the blocks
dumped.  An I<OFFSET> may be given to specify the base for displayed
offsets.  If not provided, the EXIF/TIFF base offset is used.  Use
B<-htmlDump0> for absolute offsets.  Currently only EXIF/TIFF and JPEG
information is dumped, but the -u option can be used to give a raw hex dump
of other file formats.

=item B<-j>[=I<JSONFILE>] (B<-json>)

Use JSON (JavaScript Object Notation) formatting for console output, or
import JSON file if I<JSONFILE> is specified.  This option may be combined
with B<-g> to organize the output into objects by group, or B<-G> to add
group names to each tag.  List-type tags with multiple items are output as
JSON arrays unless B<-sep> is used.  By default XMP structures are flattened
into individual tags in the JSON output, but the original structure may be
preserved with the B<-struct> option (this also causes all List-type XMP
tags to be output as JSON arrays, otherwise single-item lists would be
output as simple strings).  The B<-a> option is implied if the B<-g> or
B<-G> options are used, otherwise it is ignored and duplicate tags are
suppressed.  The B<-b>, B<-L> and B<-charset> options have no effect on the
JSON output.

If I<JSONFILE> is specified, the file is imported and the tag definitions
from the file are used to set tag values on a per-file basis.  The special
"SourceFile" entry in each JSON object associates the information with a
specific target file (see the B<-csv> option for details).  The imported
JSON file must have the same format as the exported JSON files with the
exception that the B<-g> option is not compatible with the import file
format (use B<-G> instead).  Additionally, tag names in the input JSON file
may be suffixed with a C<#> to disable print conversion.

=item B<-l> (B<-long>)

Use long 2-line Canon-style output format.  Adds a description and
unconverted value to the XML output when B<-X> is used.

=item B<-L> (B<-latin>)

Use Windows Latin1 encoding (cp1252) for output tag values instead of the
default UTF-8.  When writing, B<-L> specifies that input text values are
Latin1 instead of UTF-8.  Equivalent to C<-charset latin>.

=item B<-lang> [I<LANG>]

Set current language for tag descriptions and converted values.  I<LANG> is
C<de>, C<fr>, C<ja>, etc.  Use B<-lang> with no other arguments to get a
list of available languages.  The default language is C<en> if B<-lang> is
not specified.  Note that tag/group names are always English, independent of
the B<-lang> setting, and translation of warning/error messages has not yet
been implemented.

By default, ExifTool uses UTF-8 encoding for special characters, but the
the B<-L> or B<-charset> option may be used to invoke other encodings.

Currently, the language support is not complete, but users are welcome to
help improve this by submitting their own translations.  To submit a set of
translations, first use the B<-listx> option and redirect the output to a
file to generate an XML tag database, then add entries for other languages,
zip this file, and email it to phil at owl.phy.queensu.ca for inclusion in
ExifTool.

=item B<-n> (B<--printConv>)

Read and write values as numbers instead of words.  By default, extracted
values are converted to a more human-readable format for printing, but the
B<-n> option disables this print conversion for all tags.  For example:

    > exiftool -Orientation -S a.jpg
    Orientation: Rotate 90 CW
    > exiftool -Orientation -S -n a.jpg
    Orientation: 6

The print conversion may also be disabled on a per-tag basis by suffixing
the tag name with a C<#> character:

    > exiftool -Orientation# -Orientation -S a.jpg
    Orientation: 6
    Orientation: Rotate 90 CW

These techniques may also be used to disable the inverse print conversion
when writing.  For example, the following commands all have the same effect:

    > exiftool -Orientation='Rotate 90 CW' a.jpg
    > exiftool -Orientation=6 -n a.jpg
    > exiftool -Orientation#=6 a.jpg

=item B<-p> I<FMTFILE> or I<STR> (B<-printFormat>)

Print output in the format specified by the given file or string (and ignore
other format options).  Tag names in the format file or string begin with a
C<$> symbol and may contain a leading group name and/or a trailing C<#>. 
Case is not significant.  Braces C<{}> may be used around the tag name to
separate it from subsequent text.  Use C<$$> to represent a C<$> symbol, and
C<$/> for a newline.  Multiple B<-p> options may be used, each contributing
a line of text to the output.  Lines beginning with C<#[HEAD]> and
C<#[TAIL]> are output only for the first and last processed files
respectively.  Lines beginning with C<#[BODY]> and lines not beginning with
C<#> are output for each processed file.  Other lines beginning with C<#>
are ignored.  For example, this format file:

    # this is a comment line
    #[HEAD]# Generated by ExifTool $exifToolVersion
    File: $FileName - $DateTimeOriginal
    (f/$Aperture, ${ShutterSpeed}s, ISO $EXIF:ISO)
    #[TAIL]# end

with this command:

    exiftool -p test.fmt a.jpg b.jpg

produces output like this:

    # Generated by ExifTool 8.10
    File: a.jpg - 2003:10:31 15:44:19
    (f/5.6, 1/60s, ISO 100)
    File: b.jpg - 2006:05:23 11:57:38
    (f/8.0, 1/13s, ISO 100)
    # end

When B<-ee> (B<-extractEmbedded>) is combined with B<-p>, embedded documents
are effectively processed as separate input files.

If a specified tag does not exist, a minor warning is issued and the line
with the missing tag is not printed.  However, the B<-f> option may be used
to set the value of missing tags to '-', or the B<-m> option may be used to
ignore minor warnings and leave the missing values empty.

=item B<-s>[I<NUM>] (B<-short>)

Short output format.  Prints tag names instead of descriptions.  Add I<NUM>
or up to 3 B<-s> options for even shorter formats:

    -s1 or -s        - print tag names instead of descriptions
    -s2 or -s -s     - no extra spaces to column-align values
    -s3 or -s -s -s  - print values only

Also effective when combined with B<-t>, B<-h>, B<-X> or B<-listx> options.

=item B<-S> (B<-veryShort>)

Very short format.  The same as B<-s2> (or two B<-s> options).  Tag names
are printed instead of descriptions, and no extra spaces are added to
column-align values.

=item B<-sep> I<STR> (B<-separator>)

Specify separator string for items in List-type tags.  When reading, the
default is ", ".  When writing, this option causes values assigned to
list-type tags to be split into individual items at each substring matching
specified separator.  Space characters in the separator string match zero or
more whitespace characters.

=item B<-struct>, B<--struct>

Output structured XMP information instead of flattening to individual tags.
This option works well when combined with the XML (B<-X>) and JSON (B<-j>)
output formats.  For other output formats, the structures are serialized
into the same format as when writing structured information (see
L<http://owl.phy.queensu.ca/~phil/exiftool/struct.html> for details).  This
option is enabled by default when copying tags to allow the preservation of
complex structures, but this feature may be disabled with B<--struct>. These
options have no effect when assigning new values since both flattened tags
and structured tags may always be written.

=item B<-t> (B<-tab>)

Output a tab-delimited list of description/values (useful for database
import).  May be combined with B<-s> to print tag names instead of
descriptions, or B<-S> to print tag values only, tab-delimited on a single
line.  The B<-t> option may also be used to add tag table information to the
B<-X> option output.

=item B<-T> (B<-table>)

Output tag values in table form.  Equivalent to B<-t -S -q -f>.

=item B<-v>[I<NUM>] (B<-verbose>)

Print verbose messages.  I<NUM> specifies the level of verbosity in the
range 0-5, with higher numbers being more verbose.  If I<NUM> is not given,
then each B<-v> option increases the level of verbosity by 1.  With any
level greater than 0, most other options are ignored and normal console
output is suppressed unless specific tags are extracted.  Using B<-v0>
causes the console output buffer to be flushed after each line (which may be
useful to avoid delays when piping exiftool output), and prints the name of
each processed file when writing.

=item B<-w>[!] I<EXT> or I<FMT> (B<-textOut>)

Write console output to files with names ending in I<EXT>, one for each
source file.  The output file name is obtained by replacing the source file
extension (including the '.') with the specified extension (and a '.' is
added to the start of I<EXT> if it doesn't already contain one).
Alternatively, a I<FMT> string may be used to give more control over the
output file name and directory.  In the format string, %d, %f and %e
represent the directory, filename and extension of the source file, and %c
represents a copy number which is automatically incremented if the file
already exists.  %d includes the trailing '/' if necessary, but %e does not
include the leading '.'.  For example:

    -w %d%f.txt       # same effect as "-w txt"
    -w dir/%f_%e.out  # write files to "dir" as "FILE_EXT.out"
    -w dir2/%d%f.txt  # write to "dir2", keeping dir structure
    -w a%c.txt        # write to "a.txt" or "a1.txt" or "a2.txt"...

Existing files will not be overwritten unless an exclamation point is added
to the option name (ie. B<-w!> or B<-textOut!>).  Output directories are
created automatically if necessary.

Notes:

1) In a Windows BAT file the C<%> character is represented by C<%%>, so an
argument like C<%d%f.txt> is written as C<%%d%%f.txt>.

2) It is not possible to specify a simple filename as an argument for B<-w>.
Instead, this simple case is accomplished using shell redirection:

    exiftool FILE > out.txt

Advanced features:  A substring of the original file name, directory or
extension may be taken by specifying a field width immediately following the
'%' character.  If the width is negative, the substring is taken from the
end.  The substring position (characters to ignore at the start or end of
the string) may be given by a second optional value after a decimal point.
For example:

    Input File Name     Format Specifier    Output File Name
    ----------------    ----------------    ----------------
    Picture-123.jpg     %7f.txt             Picture.txt
    Picture-123.jpg     %-.4f.out           Picture.out
    Picture-123.jpg     %7f.%-3f            Picture.123
    Picture-123a.jpg    Meta%-3.1f.txt      Meta123.txt

For %c, these modifiers have a different effects.  If a field width is
given, the copy number is padded with zeros to the specified width.  A
leading '-' adds a dash before the copy number, and a '+' adds an underline.
By default, a copy number of zero is omitted, but this can be changed by
adding a decimal point to the modifier.  For example:

    -w A%-cZ.txt      # AZ.txt, A-1Z.txt, A-2Z.txt ...
    -w B%5c.txt       # B.txt, B00001.txt, B00002.txt ...
    -w C%.c.txt       # C0.txt, C1.txt, C2.txt ...
    -w D%-.c.txt      # D-0.txt, D-1.txt, D-2.txt ...
    -w E%-.4c.txt     # E-0000.txt, E-0001.txt, E-0002.txt ...
    -w F%-.4nc.txt    # F-0001.txt, F-0002.txt, F-0003.txt ...
    -w G%+c.txt       # G.txt, G_1.txt G_2.txt ...
    -w H%-lc.txt      # H.txt, H-b.txt, H-c.txt ...

A special feature allows the copy number to be incremented for each
processed file by using %C (upper case) instead of %c.  This allows a
sequential number to be added to output file names, even if the names are
different.  For %C, the number before the decimal place gives the starting
index, and the number after the decimal place gives the field width.  The
following examples show the output filenames when used with the command
C<exiftool rose.jpg star.jpg jet.jpg ...>:

    -w %C%f.txt       # 0rose.txt, 1star.txt, 2jet.txt
    -w %f-%10C.txt    # rose-10.txt, star-11.txt, jet-12.txt
    -w %.3C-%f.txt    # 000-rose.txt, 001-star.txt, 002-jet.txt
    -w %57.4C%f.txt   # 0057rose.txt, 0058star.txt, 0059jet.txt

All format codes may be modified by 'l' or 'u' to specify lower or upper
case respectively (ie. C<%le> for a lower case file extension).  When used
to modify %c or %C, the numbers are changed to an alphabetical base (see
example H above).  Also, %c may be modified by 'n' to count using natural
numbers starting from 1, instead of 0 (see example F).

This same I<FMT> syntax is used with the B<-o> and B<-tagsFromFile> options,
although %c is only valid for output file names.

=item B<-X> (B<-xmlFormat>)

Use RDF/XML formatting for console output.  Implies the B<-a> option, so
duplicate tags are extracted.  The formatting options B<-b>, B<-D>, B<-H>,
B<-l>, B<-s>, B<-sep>, B<-struct> and B<-t> may be used in combination with
B<-X> to affect the output, but note that the tag ID (B<-D>, B<-H> and
B<-t>), binary data (B<-b>) and structured output (B<-struct>) options are
not effective for the short output (B<-s>).  Another restriction of B<-s> is
that only one tag with a given group and name may appear in the output. 
Note that the tag ID options (B<-D>, B<-H> and B<-t>) will produce
non-standard RDF/XML unless the B<-l> option is also used.  By default,
list-type tags with multiple values are formatted as an RDF Bag, but they
are combined into a single string when B<-s> or B<-sep> is used.  Using
B<-L> changes the XML encoding from "UTF-8" to "windows-1252".  Other
B<-charset> settings change the encoding only if there is a corresponding
standard XML character set.  The B<-b> option causes binary data values to
be written, encoded in base64 if necessary.  The B<-t> option adds tag table
information to the output (table C<name>, decimal tag C<id>, and C<index>
for cases where multiple conditional tags exist with the same ID).

=back

=head3 Processing control

=over 5

=item B<-a>, B<--a> (B<-duplicates>, B<--duplicates>)

Allow (B<-a>) or suppress (B<--a>) duplicate tag names to be extracted.  By
default, duplicate tags are suppressed unless the B<-ee> or B<-X> options
are used or the Duplicates option is enabled in the configuration file.

=item B<-e> (B<--composite>)

Extract existing tags only -- don't calculate composite tags.

=item B<-ee> (B<-extractEmbedded>)

Extract information from embedded documents in EPS and PDF files, embedded
MPF images in JPEG and MPO files, streaming metadata in AVCHD videos, and
the resource fork of Mac OS files.  Implies the B<-a> option.  Use B<-g3> or
B<-G3> to identify the originating document for extracted information.
Embedded documents containing sub-documents are indicated with dashes in the
family 3 group name.  (ie. C<Doc2-3> is the 3rd sub-document of the 2nd
embedded document.)

=item B<-ext> I<EXT>, B<--ext> I<EXT> (B<-extension>)

Process only files with (B<-ext>) or without (B<--ext>) a specified
extension.  There may be multiple B<-ext> and B<--ext> options.  Extensions
may begin with a leading '.', and case is not significant.  For example:

    exiftool -ext .JPG DIR            # process only JPG files
    exiftool --ext crw --ext dng DIR  # process all but CRW and DNG
    exiftool --ext . DIR              # ignore if no extension

Using this option has two main advantages over specifying C<*.I<EXT>> on the
command line:  1) It applies to files in subdirectories when combined with
the B<-r> option.  2) The B<-ext> option is case-insensitive, which is
useful when processing files on case-sensitive filesystems.

=item B<-F>[I<OFFSET>] (B<-fixBase>)

Fix the base for maker notes offsets.  A common problem with some image
editors is that offsets in the maker notes are not adjusted properly when
the file is modified.  This may cause the wrong values to be extracted for
some maker note entries when reading the edited file.  This option allows an
integer I<OFFSET> to be specified for adjusting the maker notes base offset.
If no I<OFFSET> is given, ExifTool takes its best guess at the correct base.
Note that exiftool will automatically fix the offsets for images which store
original offset information (ie. newer Canon models).  Offsets are fixed
permanently if B<-F> is used when writing EXIF to an image. ie)

    exiftool -F -exif:resolutionunit=inches image.jpg

=item B<-fast>[I<NUM>]

Increase speed of extracting information from JPEG images.  With this
option, ExifTool will not scan to the end of a JPEG image to check for an
AFCP or PreviewImage trailer, or past the first comment in GIF images or the
audio/video data in WAV/AVI files to search for additional metadata.  These
speed benefits are small when reading images directly from disk, but can be
substantial if piping images through a network connection.  For more
substantial speed benefits, B<-fast2> also causes exiftool to avoid
extracting any EXIF MakerNote information.

=item B<-fileOrder> [-]I<TAG>

Set file processing order according to the sorted value of the specified
I<TAG>.  For example, to process files in order of date:

    exiftool -fileOrder DateTimeOriginal DIR

Additional B<-fileOrder> options may be added as secondary sort keys. 
Floating point values are sorted numerically, and all other values are
sorted alphabetically.  The sort order may be reversed by prefixing the tag
name with a C<-> (ie. C<-fileOrder -createdate>).  A C<#> may be appended to
the tag name to disable print conversion for the sorted values.  Note that
this option has a large performance impact since it involves an additional
processing pass of each file.

=item B<-i> I<DIR> (B<-ignore>)

Ignore specified directory name.  Use multiple B<-i> options to ignore more
than one directory name.  A special I<DIR> value of C<SYMLINKS> (case
sensitive) may be specified to ignore symbolic links when the B<-r> option
is used.

=item B<-if> I<EXPR>

Specify a condition to be evaluated before processing each I<FILE>.  I<EXPR>
is a Perl-like expression containing tag names prefixed by C<$> symbols.  It
is evaluated with the tags from each I<FILE> in turn, and the file is
processed only if the expression returns true.  Unlike Perl variable names,
tag names are not case sensitive and may contain a hyphen.  As well, tag
names may have a leading group name separated by a colon, and/or a trailing
C<#> character to disable print conversion.  When multiple B<-if> options
are used, all conditions must be satisfied to process the file. Returns an
exit status of 1 if all files fail the condition.  Below are a few examples:

    # extract shutterspeed from all Canon images in a directory
    exiftool -shutterspeed -if '$make eq "Canon"' dir

    # add one hour to all images created on or after Apr. 2, 2006
    exiftool -alldates+=1 -if '$CreateDate ge "2006:04:02"' dir

    # set EXIF ISO value if possible, unless it is set already
    exiftool '-exif:iso<iso' -if 'not $exif:iso' dir

    # find images containing a specific keyword (case insensitive)
    exiftool -if '$keywords =~ /harvey/i' -filename dir

=item B<-m> (B<-ignoreMinorErrors>)

Ignore minor errors and warnings.  This enables writing to files with minor
errors and disables some validation checks which could result in minor
warnings.  Generally, minor errors/warnings indicate a problem which usually
won't result in loss of metadata if ignored.  However, there are exceptions,
so ExifTool leaves it up to you to make the final decision.

=item B<-o> I<OUTFILE> or I<FMT> (B<-out>)

Set the output file or directory name when writing information.  (Without
this option, the original file is renamed to C<FILE_original> and output is
sent to I<FILE>.)  I<OUTFILE> may be C<-> to write to stdout.  The output
file name may also be specified using a I<FMT> string in which %d, %f and %e
represent the directory, file name and extension of I<FILE>.  Also, %c may
be used to add a copy number.  See the B<-w> option for I<FMT> string
examples.

The output file is taken to be a directory name if it already exists as a
directory or if the name ends with '/'.  Output directories are created if
necessary.  Existing files will not be overwritten.  Combining the
B<-overwrite_original> option with B<-o> causes the original source file to
be erased after the output file is successfully written.

A special feature of this option allows the creation of certain types of
files from scratch.  Currently, this can be done with XMP, ICC/ICM, MIE, VRD
and EXIF files by specifying the appropriate extension for I<OUTFILE>.  The
file is then created from a combination of information in I<FILE> (as if the
B<-tagsFromFile> option was used), and tag values assigned on the command
line.  If no I<FILE> is specified, the output file may be created from
scratch using only tags assigned on the command line.

=item B<-overwrite_original>

Overwrite the original I<FILE> (instead of preserving it by adding
C<_original> to the file name) when writing information to an image.
Caution: This option should only be used if you already have separate backup
copies of your image files.  The overwrite is implemented by renaming a
temporary file to replace the original.  This deletes the original file and
replaces it with the edited version in a single operation.  When combined
with B<-o>, this option causes the original file to be deleted if the output
file was successfully written.

=item B<-overwrite_original_in_place>

Similar to B<-overwrite_original> except that an extra step is added to
allow the original file attributes to be preserved.  For example, on a Mac
this causes the original file creation date, ownership, type, creator, label
color and icon to be preserved.  This is implemented by opening the original
file in update mode and replacing its data with a copy of a temporary file
before deleting the temporary.  The extra step results in slower
performance, so the B<-overwrite_original> option should be used instead
unless necessary.

=item B<-P> (B<-preserve>)

Preserve the filesystem modification date/time of the original file
(C<FileModifyDate>) when writing.  Note that some filesystems (ie. Mac and
Windows) store a creation date which is not preserved by this option.  For
these systems, the B<-overwrite_original_in_place> option may be used to
preserve the creation date.

=item B<-password> I<PASSWD>

Specify password to allow processing of password-protected PDF documents. 
If a password is required but not given, a warning is issued and the
document is not processed.  Ignored if a password is not required.

=item B<-q> (B<-quiet>)

Quiet processing.  One B<-q> suppresses normal informational messages, and a
second B<-q> suppresses warnings as well.  Error messages can not be
suppressed, although minor errors may be downgraded to warnings with the
B<-m> option.

=item B<-r> (B<-recurse>)

Recursively process files in subdirectories.  Only meaningful if I<FILE> is
a directory name.  By default, exiftool will also follow symbolic links to
directories if supported by the system, but this may be disabled with
C<-i SYMLINKS> (see the B<-i> option for details).

=item B<-scanForXMP>

Scan all files (even unsupported formats) for XMP information unless found
already.  When combined with the B<-fast> option, only unsupported file
types are scanned.  Warning: It can be time consuming to scan large files.

=item B<-u> (B<-unknown>)

Extract values of unknown tags.  Add another B<-u> to also extract unknown
information from binary data blocks.  This option applies to tags with
numerical tag ID's, and causes tag names like "Exif_0xc5d9" to be generated
for unknown information.  It has no effect on information types which have
human-readable tag ID's (such as XMP), since unknown tags are extracted
automatically from these formats.

=item B<-U> (B<-unknown2>)

Extract values of unknown tags as well as unknown information from some
binary data blocks.  This is the same as two B<-u> options.

=item B<-z> (B<-zip>)

When reading, causes information to be extracted from .gz and .bz2
compressed images.  (Only one image per archive. Requires gzip and bzip2 to
be installed on the system.)  When writing, causes compressed information to
be written if supported by the image format.  (ie. The PNG format supports
compressed text.)

=back

=head3 Special features

=over 5

=item B<-geotag> I<TRKFILE>

Geotag images from the specified GPS track log file.  Using the B<-geotag>
option is equivalent to writing a value to the C<Geotag> tag.  After the
B<-geotag> option has been specified, the value of the C<Geotime> tag is
written to define a date/time for the position interpolation.  If C<Geotime>
is not specified, the value is copied from C<DateTimeOriginal>.  For
example, the following two commands are equivalent:

    exiftool -geotag track.log image.jpg
    exiftool -geotag "-Geotime<DateTimeOriginal" image.jpg

When the C<Geotime> value is converted to UTC, the local system timezone is
assumed unless the date/time value contains a timezone.  Writing C<Geotime>
causes the following 8 EXIF tags to be created:  GPSLatitude,
GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSAltitude, GPSAltitudeRef,
GPSDateStamp and GPSTimeStamp.  Alternately C<XMP:Geotime> may be written to
create the following 5 XMP tags: GPSLatitude, GPSLongitude, GPSAltitude,
GPSAltitudeRef and GPSDateTime.

The C<Geosync> tag may be used to specify a time correction which is applied
to each C<Geotime> value for synchronization with GPS time.  For example,
the following command compensates for image times which are 1 minute and 20
seconds behind GPS:

    exiftool -geosync=+1:20 -geotag a.log DIR

C<Geosync> must be set before C<Geotime> (if specified) to be effective.
Advanced C<Geosync> features allow a linear time drift correction and
synchronization from previously geotagged images.  See "geotag.html" in the
full ExifTool distribution for more information.

Multiple B<-geotag> options may be used to concatinate GPS track log data.
Also, a single B<-geotag> option may be used to load multiple track log
files by using wildcards in the I<TRKFILE> name, but note that in this case
I<TRKFILE> must be quoted on most systems (with the notable exception of
Windows) to prevent filename expansion.  For example:

    exiftool -geotag "TRACKDIR/*.log" IMAGEDIR

Currently supported track file formats are GPX, NMEA RMC/GGA/GLL, KML, IGC,
Garmin XML and TCX, and Magellan PMGNTRK.  See L</GEOTAGGING EXAMPLES> for
examples.  Also see "geotag.html" in the full ExifTool distribution and the
L<Image::ExifTool Options|Image::ExifTool/Options> for more details and
for information about geotag configuration options.

=item B<-use> I<MODULE>

Add features from specified plug-in I<MODULE>.  Currently, the MWG module is
the only plug-in module distributed with exiftool.  This module adds
read/write support for tags as recommended by the Metadata Working Group. 
To save typing, C<-use MWG> is assumed if the C<MWG> group is specified for
any tag on the command line.  See the
L<MWG Tags documentation|Image::ExifTool::TagNames/MWG Tags> for more
details.

=back

=head3 Utilities

=over 5

=item B<-restore_original>

=item B<-delete_original>[!]

These utility options automate the maintenance of the C<_original> files
created by exiftool.  They have no effect on files without an C<_original>
copy.  The B<-restore_original> option restores the specified files from
their original copies by renaming the C<_original> files to replace the
edited versions.  For example, the following command restores the originals
of all .jpeg images in directory C<DIR>:

    exiftool -restore_original -ext jpg DIR

The B<-delete_original> option deletes the C<_original> copies of all files
specified on the command line.  Without a trailing C<!> this option prompts
for confirmation before continuing.  For example, the following command
deletes C<a.jpg_original> if it exists, after asking "Are you sure?":

    exiftool -delete_original a.jpg

These options may not be used with other options to read or write tag values
in the same command, but may be combined with options such B<-ext>, B<-if>,
B<-r>, B<-q> and B<-v>.

=back

=head3 Other options

=over 5

=item B<-@> I<ARGFILE>

Read command-line arguments from the specified file.  The file contains one
argument per line (NOT one option per line -- some options require
additional arguments which must be placed on separate lines).  Blank lines
and lines beginning with C<#> and are ignored.  Normal shell processing of
arguments is not performed, which among other things means that arguments
should not be quoted.  I<ARGFILE> may exist relative to either the current
directory or the exiftool directory unless an absolute pathname is given.

For example, the following I<ARGFILE> will set the value of Copyright to
"Copyright YYYY, Phil Harvey", where "YYYY" is the year of CreateDate:

    -d
    %Y
    -copyright<Copyright $createdate, Phil Harvey

=item B<-k> (B<-pause>)

Pause with the message C<-- press any key --> or C<-- press RETURN -->
(depending on your system) before terminating.  This option is used to
prevent the command window from closing when run as a Windows drag and drop
application.

=item B<-list>, B<-listw>, B<-listf>, B<-listr>, B<-listwf>,
B<-listg>[I<NUM>], B<-listd>, B<-listx>

Print a list of all valid tag names (B<-list>), all writable tag names
(B<-listw>), all supported file extensions (B<-listff>), all recognized file
extensions (B<-listr>), all writable file extensions (B<-listwf>), all tag
groups [in a specified family] (B<-listg>[I<NUM>]), all deletable tag groups
(B<-listd>), or an XML database of tag details (B<-listx>).  The B<-list>,
B<-listw> and B<-listx> options may be followed by an additional argument of
the form C<-GROUP:All> to list all tags in a specific group, where C<GROUP>
is one or more family 0-2 group names (excepting EXIF IFD groups) separated
by colons.  With B<-listg>, I<NUM> may be given to specify the group family,
otherwise family 0 is assumed.  When combined with B<-listx>, the B<-s>
option shortens the output by omitting the descriptions and values, and
B<-f> adds a 'flags' attribute.  Here are some examples:

    -list               # list all tag names
    -list -EXIF:All     # list all EXIF tags
    -list -xmp:time:all # list all XMP tags relating to time
    -listw -XMP-dc:All  # list all writable XMP-dc tags
    -listf              # list all supported file extensions
    -listr              # list all recognized file extensions
    -listwf             # list all writable file extensions
    -listg1             # list all groups in family 1
    -listd              # list all deletable groups
    -listx -EXIF:All    # list database of EXIF tags in XML format
    -listx -XMP:All -s  # list short XML database of XMP tags

Note that none of the B<-list> options require an input I<FILE>.

=item B<-ver>

Print exiftool version number.

=back

=head3 Advanced options

Among other things, the advanced options allow complex processing to be
performed from a single command without the need for additional scripting.
This may be particularly useful for implementations such as Windows
drag-and-drop applications.  These options may also be used to improve
performance in multi-pass processing by reducing the overhead required to
load exiftool for each invocation.

=over 5

=item B<-common_args>

Specifies that all arguments following this option are common to all
executed commands when B<-execute> is used.  This and the B<-config> option
are the only options that may not be used inside a B<-@> I<ARGFILE>.

=item B<-config> I<CFGFILE>

Load specified configuration file instead of the default ".ExifTool_config".
If used, this option must come before all other arguments on the command
line.  The I<CFGFILE> name may contain a directory specification (otherwise
the file must exist in the current directory), or may be set to an empty
string ("") to disable loading of the config file.  See the sample
configuration file and "config.html" in the full ExifTool distribution for
more information about the ExifTool configuration file.

=item B<-execute>

Execute command for all arguments up to this point on the command line.
Allows multiple commands to be executed from a single command line.

=item B<-srcfile> I<FMT>

Specify a different source file to be processed based on the name of the
original I<FILE>.  This may be useful in some special situations for
processing related preview images or sidecar files.  See the B<-w> option
for a description of the I<FMT> syntax.  Note that file name I<FMT> strings
for all options are based on the original I<FILE> specified from the command
line, not the name of the source file specified by B<-srcfile>.

=item B<-stay_open> I<FLAG>

If I<FLAG> is C<1> or C<True>, causes exiftool keep reading from the B<-@>
I<ARGFILE> even after reaching the end of file.  This feature allows calling
applications to pre-load exiftool, thus avoiding the overhead of loading
exiftool for each command.  The procedure is as follows:

1) Execute C<exiftool -stay_open True -@ I<ARGFILE>>, where I<ARGFILE> is the
name of an existing (possibly empty) argument file or C<-> to pipe arguments
from the standard input.

2) Write exiftool command-line arguments to I<ARGFILE>, one argument per
line (see the B<-@> option for details).

3) Write C<-execute\n> to I<ARGFILE>, where C<\n> represents a newline
sequence.  (Note: You may need to flush your write buffers here if using
buffered output.)  Exiftool will then execute the command with the arguments
received up to this point, send a "{ready}" message to stdout when done
(unless the B<-q> option is used), and continue trying to read arguments for
the next command from I<ARGFILE>.

4) Repeat steps 2 and 3 for each command.

5) Write C<-stay_open\nFalse\n> to I<ARGFILE> when done.  This will cause
exiftool to process any remaining arguments then exit normally.

The input I<ARGFILE> may be changed at any time before step 5 above by
writing the following lines to the currently open I<ARGFILE>:

    -stay_open
    True
    -@
    NEWARGFILE

This causes I<ARGFILE> to be closed, and I<NEWARGFILE> to be kept open.
(Without the B<-stay_open> here, exiftool would have returned to reading
arguments from I<ARGFILE> after reaching the end of I<NEWARGFILE>.)

=back

=head1 READING EXAMPLES

B<Note>: Beware when cutting and pasting these examples into your terminal!
Some characters such as single and double quotes and hyphens may have been
changed into similar-looking but functionally-different characters by the
text formatter used to display this documentation.  Also note that Windows
users must use double quotes instead of single quotes as below around
arguments containing special characters.

=over 5

=item exiftool -a -u -g1 a.jpg

Print all meta information in an image, including duplicate and unknown
tags, sorted by group (for family 1).

=item exiftool -common dir

Print common meta information for all images in C<dir>.

=item exiftool -T -createdate -aperture -shutterspeed -iso dir > out.txt

List specified meta information in tab-delimited column form for all images
in C<dir> to an output text file named "out.txt".

=item exiftool -s -ImageSize -ExposureTime b.jpg

Print ImageSize and ExposureTime tag names and values.

=item exiftool -l -canon c.jpg d.jpg

Print standard Canon information from two image files.

=item exiftool -r -w .txt -common pictures

Recursively extract common meta information from files in C<pictures>
directory, writing text output to C<.txt> files with the same names.

=item exiftool -b -ThumbnailImage image.jpg > thumbnail.jpg

Save thumbnail image from C<image.jpg> to a file called C<thumbnail.jpg>.

=item exiftool -b -JpgFromRaw -w _JFR.JPG -ext CRW -r .

Recursively extract JPG image from all Canon CRW files in the current
directory, adding C<_JFR.JPG> for the name of the output JPG files.

=item exiftool -d '%r %a, %B %e, %Y' -DateTimeOriginal -S -s *.jpg

Print formatted date/time for all JPG files in the current directory.

=item exiftool -IFD1:XResolution -IFD1:YResolution image.jpg

Extract image resolution from EXIF IFD1 information (thumbnail image IFD).

=item exiftool '-*resolution*' image.jpg

Extract all tags with names containing the word "Resolution" from an image.

=item exiftool -xmp:author:all -a image.jpg

Extract all author-related XMP information from an image.

=item exiftool -xmp -b a.jpg > out.xmp

Extract complete XMP data record intact from C<a.jpg> and write it to
C<out.xmp> using the special C<XMP> tag (see the Extra tags in
L<Image::ExifTool::TagNames|Image::ExifTool::TagNames>).

=item exiftool -p '$filename has date $dateTimeOriginal' -q -f dir

Print one line of output containing the file name and DateTimeOriginal for
each image in directory C<dir>.

=item exiftool -ee -p '$gpslatitude, $gpslongitude, $gpstimestamp' a.m2ts

Extract all GPS positions from an AVCHD video.

=item exiftool -icc_profile -b -w icc image.jpg

Save complete ICC_Profile from an image to an output file with the same name
and an extension of C<.icc>.

=item exiftool -htmldump -w tmp/%f_%e.html t/images

Generate HTML pages from a hex dump of EXIF information in all images from
the C<t/images> directory.  The output HTML files are written to the C<tmp>
directory (which is created if it didn't exist), with names of the form
'FILENAME_EXT.html'.

=back

=head1 WRITING EXAMPLES

Note that quotes are necessary around arguments which contain certain
special characters such as C<E<gt>>, C<E<lt>> or any white space.  These
quoting techniques are shell dependent, but the examples below will work for
most Unix shells.  With the Windows cmd shell however, double quotes should
be used (ie. -Comment=E<34>This is a new commentE<34>).

=over 5

=item exiftool -Comment='This is a new comment' dst.jpg

Write new comment to a JPG image (replaces any existing comment).

=item exiftool -comment= -o newdir *.jpg

Remove comment from all JPG images in the current directory, writing the
modified images to a new directory.

=item exiftool -keywords=EXIF -keywords=editor dst.jpg

Replace existing keyword list with two new keywords (C<EXIF> and C<editor>).

=item exiftool -Keywords+=word -o newfile.jpg src.jpg

Copy a source image to a new file, and add a keyword (C<word>) to the
current list of keywords.

=item exiftool -credit-=xxx dir

Delete Credit information from all files in a directory where the Credit
value was (C<xxx>).

=item exiftool -xmp:description-de='k&uuml;hl' -E dst.jpg

Write alternate language for XMP:Description, using HTML character escaping
to input special characters.

=item exiftool -all= dst.jpg

Delete all meta information from an image.  Note: You should NOT do this to
RAW images (except DNG) since proprietary RAW image formats often contain
information in the makernotes that is necessary for converting the image.

=item exiftool -all= -comment='lonely' dst.jpg

Delete all meta information from an image and add a comment back in.  (Note
that the order is important: C<-comment='lonely' -all=> would also delete
the new comment.)

=item exiftool -all= --jfif:all dst.jpg

Delete all meta information except JFIF group from an image.

=item exiftool -Photoshop:All= dst.jpg

Delete Photoshop meta information from an image (note that the Photoshop
information also includes IPTC).

=item exiftool -r -XMP-crss:all= DIR

Recursively delete all XMP-crss information from images in a directory.

=item exiftool '-ThumbnailImageE<lt>=thumb.jpg' dst.jpg

Set the thumbnail image from specified file (Note: The quotes are neccessary
to prevent shell redirection).

=item exiftool '-JpgFromRawE<lt>=%d%f_JFR.JPG' -ext CRW -r .

Recursively write JPEG images with filenames ending in C<_JFR.JPG> to the
JpgFromRaw tag of like-named files with extension C<.CRW> in the current
directory.  (This is the inverse of the C<-JpgFromRaw> command of the
L</READING EXAMPLES> section above.)

=item exiftool -DateTimeOriginal-='0:0:0 1:30:0' dir

Adjust original date/time of all images in directory C<dir> by subtracting
one hour and 30 minutes.  (This is equivalent to C<-DateTimeOriginal-=1.5>.
See L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl> for details.)

=item exiftool -createdate+=3 -modifydate+=3 a.jpg b.jpg

Add 3 hours to the CreateDate and ModifyDate timestamps of two images.

=item exiftool -AllDates+=1:30 -if '$make eq E<34>CanonE<34>' dir

Shift the values of DateTimeOriginal, CreateDate and ModifyDate forward by 1
hour and 30 minutes for all Canon images in a directory.  (The AllDates tag
is provided as a shortcut for these three tags, allowing them to be accessed
via a single tag.)

=item exiftool -xmp:city=Kingston image1.jpg image2.nef

Write a tag to the XMP group of two images.  (Without the C<xmp:> this tag
would get written to the IPTC group since C<City> exists in both, and IPTC
is preferred by default.)

=item exiftool -LightSource-='Unknown (0)' dst.tiff

Delete C<LightSource> tag only if it is unknown with a value of 0.

=item exiftool -whitebalance-=auto -WhiteBalance=tung dst.jpg

Set C<WhiteBalance> to C<Tungsten> only if it was previously C<Auto>.

=item exiftool -comment-= -comment='new comment' a.jpg

Write a new comment only if the image doesn't have one already.

=item exiftool -o %d%f.xmp dir

Create XMP meta information data files for all images in C<dir>.

=item exiftool -o test.xmp -owner=Phil -title='XMP File'

Create an XMP data file only from tags defined on the command line.

=item exiftool '-ICC_Profile<=%d%f.icc' image.jpg

Write ICC_Profile to an image from a C<.icc> file of the same name.

=item exiftool -hierarchicalkeywords='{keyword=one,children={keyword=B}}'

Write structured XMP information.

=item exiftool -trailer:all= image.jpg

Delete any trailer found after the end of image (EOI) in a JPEG file.  A
number of digital cameras store a large PreviewImage after the JPEG EOI, and
the file size may be reduced significantly by deleting this trailer.  See
the L<JPEG Tags documentation|Image::ExifTool::TagNames/JPEG Tags> for a
list of recognized JPEG trailers.

=back

=head1 COPYING EXAMPLES

These examples demonstrate the ability to copy tag values between files.

=over 5

=item exiftool -tagsFromFile src.crw dst.jpg

Copy the values of all writable tags from C<src.crw> to C<dst.jpg>, writing
the information to the preferred groups.

=item exiftool -TagsFromFile src.jpg -all:all dst.jpg

Copy the values of all writable tags from C<src.jpg> to C<dst.jpg>,
preserving the original tag groups.

=item exiftool -all= -tagsfromfile src.jpg -exif:all dst.jpg

Erase all meta information from C<dst.jpg> image, then copy EXIF tags from
C<src.jpg>.

=item exiftool -exif:all= -tagsfromfile @ -all:all -unsafe bad.jpg

Rebuild all EXIF meta information from scratch in an image.  This technique
can be used in JPEG images to repair corrupted EXIF information which
otherwise could not be written due to errors. The C<Unsafe> tag is a
shortcut for unsafe EXIF tags in JPEG images which are not normally copied. 
See the L<tag name documentation|Image::ExifTool::TagNames> for more details
about unsafe tags.

=item exiftool -Tagsfromfile a.jpg out.xmp

Copy meta information from C<a.jpg> to an XMP data file.  If the XMP data
file C<out.xmp> already exists, it will be updated with the new information.
Otherwise the XMP data file will be created.  Only XMP, ICC and MIE files
may be created like this (other file types may be edited but not created).
See L</WRITING EXAMPLES> above for another technique to generate XMP files.

=item exiftool -tagsFromFile a.jpg -XMP:All= -ThumbnailImage= -m b.jpg

Copy all meta information from C<a.jpg> to C<b.jpg>, deleting all XMP
information and the thumbnail image from the destination.

=item exiftool -TagsFromFile src.jpg -title -author=Phil dst.jpg

Copy title from one image to another and set a new author name.

=item exiftool -TagsFromFile a.jpg -ISO -TagsFromFile b.jpg -comment
dst.jpg

Copy ISO from one image and Comment from another image to a destination
image.

=item exiftool -tagsfromfile src.jpg -exif:all --subifd:all dst.jpg

Copy only the EXIF information from one image to another, excluding SubIFD
tags.

=item exiftool '-DateTimeOriginal>FileModifyDate' dir

Use the original date from the meta information to set the same file's
filesystem modification date for all images in a directory.  (Note that
C<-TagsFromFile @> is assumed if no other B<-TagsFromFile> is specified when
redirecting information as in this example.)

=item exiftool -TagsFromFile src.jpg '-all>xmp:all' dst.jpg

Copy all possible information from C<src.jpg> and write in XMP format to
C<dst.jpg>.

=item exiftool -@ iptc2xmp.args -iptc:all= a.jpg

Translate IPTC information to XMP with appropriate tag name conversions, and
delete the original IPTC information from an image.  This example uses
iptc2xmp.args, which is a file included with the ExifTool distribution that
contains the required arguments to convert IPTC information to XMP format.
Also included with the distribution are xmp2iptc.args (which performs the
inverse conversion) and a few more .args files for other conversions between
EXIF, IPTC and XMP.

=item exiftool -tagsfromfile %d%f.CRW -r -ext JPG dir

Recursively rewrite all C<JPG> images in C<dir> with information copied from
the corresponding C<CRW> images in the same directories.

=item exiftool '-make+>keywords' image.jpg

Add camera make to list of keywords.

=item exiftool '-comment<ISO=$exif:iso Exposure=${shutterspeed}' dir

Set the Comment tag of all images in C<dir> from the values of the EXIF:ISO
and ShutterSpeed tags.  The resulting comment will be in the form "ISO=100
Exposure=1/60".

=item exiftool -TagsFromFile src.jpg -icc_profile dst.jpg

Copy ICC_Profile from one image to another.

=item exiftool -TagsFromFile src.jpg -all:all dst.mie

Copy all meta information in its original form from a JPEG image to a MIE
file.  The MIE file will be created if it doesn't exist.  This technique can
be used to store the metadata of an image so it can be inserted back into
the image (with the inverse command) later in a workflow.

=item exiftool -o dst.mie -all:all src.jpg

This command performs exactly the same task as the command above, except
that the B<-o> option will not write to an output file that already exists.

=item exiftool -XMP:Flash="{mode=on,fired=true,return=not}" a.jpg

Write a structured tag.  See
L<http://owl.phy.queensu.ca/~phil/exiftool/struct.html> for more details.

=item exiftool -if '$jpgfromraw' -b -jpgfromraw -w %d%f_%ue.jpg -execute
-if '$previewimage' -b -previewimage -w %d%f_%ue.jpg -execute
-tagsfromfile @ -srcfile %d%f_%ue.jpg -overwrite_original
-common_args --ext jpg DIR

[Advanced] Extract JpgFromRaw or PreviewImage from all but JPG files in DIR,
saving them with file names like C<image_EXT.jpg>, then add all meta
information from the original files to the extracted images.  Here, the
command line is broken into three sections (separated by B<-execute>
options), and each is executed as if it were a separate command.  The
B<-common_args> option causes the C<--ext jpg DIR> arguments to be applied
to all three commands, and the B<-srcfile> option allows the extracted JPG
image to be the source file for the third command (whereas the RAW files are
the source files for the other two commands).

=back

=head1 RENAMING EXAMPLES

By writing the C<FileName> and C<Directory> tags, files are renamed and/or
moved to new directories.  This can be particularly useful and powerful for
organizing files by date when combined with the B<-d> option.  New
directories are created as necessary, but existing files will not be
overwritten.  The format codes %d, %f and %e may be used in the new file
name to represent the directory, name and extension of the original file,
and %c may be used to add a copy number if the file already exists (see the
B<-w> option for details).  Note that if used within a date format string,
an extra '%' must be added to pass these codes through the date/time parser.
(And further note that in a Windows batch file, all '%' characters must also
be escaped, so in this extreme case '%%%%f' is necessary to pass a simple
'%f' through the two levels of parsing.)  See
L<http://owl.phy.queensu.ca/~phil/exiftool/filename.html> for additional
documentation and examples.

=over 5

=item exiftool -filename=new.jpg dir/old.jpg

Rename C<old.jpg> to C<new.jpg> in directory C<dir>.

=item exiftool -directory=%e dir

Move all files from directory C<dir> into directories named by the original
file extensions.

=item exiftool '-Directory<DateTimeOriginal' -d %Y/%m/%d dir

Move all files in C<dir> into a directory hierarchy based on year, month and
day of C<DateTimeOriginal>.  ie) This command would move the file
C<dir/image.jpg> with a C<DateTimeOriginal> of C<2005:10:12 16:05:56> to
C<2005/10/12/image.jpg>.

=item exiftool -o . '-Directory<DateTimeOriginal' -d %Y/%m/%d dir

Same effect as above except files are copied instead of moved.

=item exiftool '-filename<%f_${focallength}.%e' dir

Rename all files in C<dir> by adding FocalLength to the file name.

=item exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir

Rename all images in C<dir> according to the C<CreateDate> date and time,
adding a copy number with leading '-' if the file already exists (C<%-c>),
and preserving the original file extension (C<%e>).  Note the extra '%'
necessary to escape the filename codes (C<%c> and C<%e>) in the date format
string.

=item exiftool -r '-FileName<CreateDate' -d %Y-%m-%d/%H%M_%%f.%%e dir

Both the directory and the filename may be changed together via the
C<FileName> tag if the new C<FileName> contains a '/'.  The example above
recursively renames all images in a directory by adding a C<CreateDate>
timestamp to the start of the filename, then moves them into new directories
named by date.

=item exiftool '-FileName<${CreateDate}_$filenumber.jpg' -d %Y%m%d *.jpg

Set the filename of all JPG images in the current directory from the
CreateDate and FileNumber tags, in the form "20060507_118-1861.jpg".

=back

=head1 GEOTAGGING EXAMPLES

ExifTool implements geotagging via 3 special tags: Geotag (which for
convenience is also implemented as an exiftool option), Geosync and Geotime.
The examples below highlight some geotagging features.  See
L<http://owl.phy.queensu.ca/~phil/exiftool/geotag.html> for additional
documentation.

=over 5

=item exiftool -geotag track.log a.jpg

Geotag an image (C<a.jpg>) from position information in a GPS track log
(C<track.log>).  Since the C<Geotime> tag is not specified, the value of
DateTimeOriginal is used for geotagging.  Local system time is assumed
unless DateTimeOriginal contains a timezone.

=item exiftool -geotag t.log -geotime='2009:04:02 13:41:12-05:00' a.jpg

Geotag an image with the GPS position for a specific time.  (Note that the
C<Geotag> tag must be assigned before C<Geotime> for the GPS data to be
available when C<Geotime> is set.)

=item exiftool -geotag log.gpx '-xmp:geotimeE<lt>createdate' dir

Geotag all images in directory C<dir> with XMP tags instead of EXIF tags,
based on the image CreateDate.  (In this case, the order of the arguments
doesn't matter because tags with values copied from other tags are always
set after constant values.)

=item exiftool -geotag a.log -geosync=-20 dir

Geotag images in directory C<dir>, accounting for image timestamps which
were 20 seconds ahead of GPS.

=item exiftool -geotag a.log -geosync=1.jpg -geosync=2.jpg dir

Geotag images using time synchronization from two previously geotagged images
(1.jpg and 2.jpg), synchronizing the image and GPS times using a linear time
drift correction.

=item exiftool -geotag a.log '-geotimeE<lt>${createdate}+01:00' dir

Geotag images in C<dir> using CreateDate with the specified timezone.  If
CreateDate already contained a timezone, then the timezone specified on the
command line is ignored.

=item exiftool -geotag= a.jpg

Delete GPS tags which may have been added by the geotag feature.  Note that
this does not remove all GPS tags -- to do this instead use C<-gps:all=>.

=item exiftool -xmp:geotag= a.jpg

Delete XMP GPS tags which were added by the geotag feature.

=item exiftool -xmp:geotag=track.log a.jpg

Geotag an image with XMP tags, using the time from DateTimeOriginal.

=item exiftool -geotag a.log -geotag b.log -r dir

Combine multiple track logs and geotag an entire directory tree of images.

=item exiftool -geotag 'tracks/*.log' -r dir

Read all track logs from the C<tracks> directory.

=item exiftool -p gpx.fmt -d %Y-%m-%dT%H:%M:%SZ dir > out.gpx

Generate a GPX track log from all images in directory C<dir>.  This example
uses the C<gpx.fmt> file included in the full ExifTool distribution package
and assumes that the images in C<dir> have all been previously geotagged.

=back

=head1 PIPING EXAMPLES

=over 5

=item cat a.jpg | exiftool -

Extract information from stdin.

=item exiftool image.jpg -thumbnailimage -b | exiftool -

Extract information from an embedded thumbnail image.

=item cat a.jpg | exiftool -iptc:keywords+=fantastic - > b.jpg

Add an IPTC keyword in a pipeline, saving output to a new file.

=item wget -qO - http://a.domain.com/bigfile.jpg | exiftool -fast -

Extract information from an image over the internet using the GNU wget
utility.  The B<-fast> option prevents exiftool from scanning for trailer
information, so only the meta information header is transferred.

=item exiftool a.jpg -thumbnailimage -b | exiftool -comment=wow - |
exiftool a.jpg -thumbnailimage'<=-'

Add a comment to an embedded thumbnail image.  (Why anyone would want to do
this I don't know, but I've included this as an example to illustrate the
flexibility of ExifTool.)

=back

=head1 DIAGNOSTICS

The exiftool application exits with a status of 0 on success, or 1 if an
error occured or if all files failed the B<-if> condition.

=head1 AUTHOR

Copyright 2003-2011, Phil Harvey

This 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<Image::ExifTool::TagNames(3pm)|Image::ExifTool::TagNames>,
L<Image::ExifTool::Shortcuts(3pm)|Image::ExifTool::Shortcuts>,
L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl>

=cut

#------------------------------------------------------------------------------
# end