aboutsummaryrefslogtreecommitdiff
path: root/renrot
blob: 3fa6e61516268ce6ca22e6d0cd7aaeaafa2a0780 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
#!/usr/local/bin/perl -w

#
# $Id$
#

use strict;
require 5.006;
use Time::localtime;
use Time::Local;
use Image::ExifTool;
use Getopt::Long;

our $VERSION = "0.16.1";	# the version of this script

my $noRotation;		# no rotation needed, default is to rotate
my $rotate;		# define the angle, to rotate on, 90 or 270
my $rotateThumbnail; 	# define the angle, to rotate on, 90 or 270
my $noRename;		# no rename needed, default is to rename to the YYYYmmddHHMMSS.jpg
my $noComment;		# no comment needed
my $nameTemplate;	# template for the filename taken from CLI
my $aggrTemplate;	# template for the files aggregation taken from CLI
my $extentionToProcess;	# the extention of files to work with
my $extentionToProcessLowCase; # lowercased extention of files to work with
my $usageOutput = 0;	# flag to show the usage
my $configFile;		# config file
my $comfile;		# file with commentary
my $verbose = 0;	# verbosity of output
my $dir = ".";		# we'll work ONLY in current directory
my $mtime;		# to set mtime
our $mTime;		# mtime to use to set

# information message
sub infomsg {
    print STDERR @_;
}

# warning message
sub warnmsg {
    print STDERR "Warning: ";
    print STDERR @_;
}

# error message
sub errmsg {
    print STDERR "ERROR: ";
    print STDERR @_;
}

# fatal message
sub fatalmsg {
    print STDERR "FATAL: ";
    print STDERR @_;
}

# debug message
sub dbgmsg {
    my $level = shift;
    print STDERR @_ if ($verbose >= $level);
}

# parse command line
sub getopt {
	my $ver;	# need version
	my $help;	# need help
	my $getopt = GetOptions (
		"work-directory|w=s" => \$dir,
		"ext|e=s" => \$extentionToProcess,
		"rotate|r=i" => \$rotate,
		"rotate-thumb=i" => \$rotateThumbnail,
		"no-rotate" => \$noRotation,
		"no-rename" => \$noRename,
		"comment-file=s" => \$comfile,
		"name-template=s" => \$nameTemplate,
		"aggr-template=s" => \$aggrTemplate,
		"mtime" => \$mtime,
		"config-file|c=s" => \$configFile,
		"v+" => \$verbose,
		"version" => \$ver,
		"help|?"   => \$help);

	if (defined $help && $help != 0) {
		usage();
		exit 0;
	}

	if (defined $ver && $ver != 0) {
		infomsg ("renrot version $VERSION\n");
		exit 0;
	}

	if (not defined $extentionToProcess) {
	    errmsg ("Extention of files is required!\n");
	    exit 1;
	}

	if ($getopt == 0) {
		usage();
		exit 1;
	}

	# change user's parameter '*.ext' to 'ext'
	$extentionToProcess =~ s/^\*\.//;
	dbgmsg (1, "getopt(): Process with '$extentionToProcess' extention.\n");
}

# parse command-line options
getopt();

# the default, expected to be defined in the config file
our $COMMENTARY;
our $CiAdrCity;
our $CiAdrCtry;
our $CiAdrExtadr;
our $CiAdrPcode;
our $CiAdrRegion;
our $CiEmailWork;
our $CiTelWork;
our $CiUrlWork;
our $NameTemplate = '%Y%m%d%H%M%S'; # name template

my $exiftoolVerbose = ($verbose > 4) ? ($verbose - 4) : 0;

my $etc_rc = "/etc/renrot.rc";
my $usrlocaletc_rc = "/usr/local/etc/renrot.rc";
my $homedir_rc = $ENV{"HOME"} . "/.renrotrc";;

if ( defined ( $configFile ) and -f $configFile ) { do $configFile; }
else {
	if ( -f $etc_rc ) { do $etc_rc; }
	if ( -f $usrlocaletc_rc ) { do $usrlocaletc_rc; }
	if ( -f $homedir_rc ) { do $homedir_rc; }
}

if ( defined $nameTemplate ) {
	$NameTemplate = $nameTemplate;
}

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

my $file;		# file in the directory
my @files;		# array of the sorted filenames to process
my @filenames;		# array of the filenames to process
our $info;		# ImageInfo object
my $newfilename;	# the name file to be renamed to
my %filenameshash;	# hash for old file names
my $filenameshashkey;
my $orientation = '';	# Orientation tag value
my @filenameSplited;	# array to hold filename splitted to the parts
my $comment;		# where to put the commentary to write
my @commentar;		# array to put the content of the file with commentary
our $filecounter = 1;	# counter to cat and increment when DateTimeOriginal is absent
my $counterprefix;	# 4 digit file number counter
my $now;		# now timestamp to use to name the files without DateTimeOriginal tag
my $rotas;		# how to rotate

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

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

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

my $errorMessage;
my $warningMessage;

chdir ($dir) || ( fatalmsg ("Can't enter to $dir!\n"), die );
opendir (DIR, $dir) || ( fatalmsg ("Can't open $dir!\n"), die );

while ( defined ( $file = readdir DIR )) {
	next if $file =~ /^\.\.?$/;	# skip the current directory entry
	next if ( -d $file );		# is this a directory?

	$extentionToProcessLowCase = $extentionToProcess;
	$extentionToProcessLowCase =~ tr/A-Z/a-z/;

	@filenameSplited = split (/\./,$file);
	# if we have defined extention files here
	if ( $filenameSplited[$#filenameSplited] && ( $filenameSplited[$#filenameSplited] eq $extentionToProcess ) ) {
		push @filenames, $file;
	}
}

@files = sort @filenames;

our $anglesuffix;	# the suffix to add to the end of the rotated files 90cw or 270cw

foreach $file ( @files ) {
	print "Processing file: $file ...\n";

	# Setup defaults
	$info = $exifTool->ImageInfo($file);
	$newfilename = "";
	$anglesuffix = "0cw";
	$mTime = "";

	################################################################################################
	#
	## analyzing whether to rotate
	#
	if ( defined $noRotation ) { infomsg ("No rotation asked, file orientation is left untouched.\n"); }
	elsif ( defined $rotate ) {
		dbgmsg (2, "main(): We'll deal with: $file and $rotangles{$rotate}.\n");
		rotateFile($file, $rotangles{$rotate});
		rotateThumbnail($file, $rotangles{$rotate});
		$anglesuffix = $rotate . "cw";
	}
	elsif ( defined $rotateThumbnail ) {
		rotateThumbnail($file, $rotangles{$rotateThumbnail});
	}
	else {
		if ( defined( $orientation = $exifTool->GetValue("Orientation", 'ValueConv') ) ) {
			if ( $orientation > 1 ) {
				$rotas = $rotparms[$orientation - 1];
				rotateFile($file, $rotas);
				rotateThumbnail($file, $rotas);
				$anglesuffix = $angles[$orientation - 1];
			}
			elsif ( $orientation == 1 ) {
				infomsg ("No need to rotate, orientation is: Horisontal (normal).\n");
			}
			else {
				errmsg ("Something wrong, orientation is < 1: $orientation.\n");
			}
		}
		else {
			warnmsg ("Orientation tag is absent!\n");
		}
	}

	#################################################################################
	#
	## analyzing whether and how to rename file
	#
	if ( defined $noRename ) {
		infomsg ("No renaming asked, filename is left untouched.\n");
		if ( ($newfilename) = ( $file =~ /^(.*)\.jpg/ ) ) {
			$filenameshash{$newfilename} = 1;
		}
	}
	else {
		$newfilename = template2name($NameTemplate);
		if ( $filenameshash{$newfilename} ) {
			$newfilename = sprintf("%s.%.4d",$newfilename,$filecounter);
		}
		$filenameshash{$newfilename} = 1;
		
		$newfilename = sprintf("%s.%s", $newfilename, $extentionToProcessLowCase);

		if ( $file ne $newfilename ) {
			if ( -f $newfilename ) {
				fatalmsg ("File $newfilename already exists!\n"), die;
			}
			rename ( $file, $newfilename )
				|| ( fatalmsg ("Unable to rename $file -> $newfilename.\n"), die );
			print "Renamed: $file -> $newfilename\n";
		}
		else { warnmsg ("No renaming needed for $newfilename, it looks as needed!\n"); }
	}

	###############################
	#
	## analyzing whether to comment
	#
	my $comentedfilename = $newfilename . "_comment";
	if ( $comfile ) {
		if ( open ( COMMENT, "<$comfile" ) ) {
			@commentar = <COMMENT>;
			unless ( close ( COMMENT ) ) { errmsg ("$comfile wasn't closed!\n"); }
			$comment = join ( '', @commentar );
			# preparing to write the commentary
			$exifTool->SetNewValue(Comment => $comment);
		}
	}
	else { infomsg ("No commenting, file commentary is left untouched.\n"); }

	######################################
	#
	## preparing to write the UserComment and some additional tags
	#
	if ( defined ( $COMMENTARY ) ) { $exifTool->SetNewValue(UserComment => $COMMENTARY); }

	if ( defined ( $CiAdrCity ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiAdrCity', $CiAdrCity, Group=>'XMP');
	}
	if ( defined ( $CiAdrCtry ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiAdrCtry', $CiAdrCtry, Group=>'XMP');
	}
	if ( defined ( $CiAdrExtadr ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiAdrExtadr', $CiAdrExtadr, Group=>'XMP');
	}
	if ( defined ( $CiAdrPcode ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiAdrPcode', $CiAdrPcode, Group=>'XMP');
	}
	if ( defined ( $CiAdrRegion ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiAdrRegion', $CiAdrRegion, Group=>'XMP');
	}
	if ( defined ( $CiEmailWork ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiEmailWork', $CiEmailWork, Group=>'XMP');
	}
	if ( defined ( $CiTelWork ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiTelWork', $CiTelWork, Group=>'XMP');
	}
	if ( defined ( $CiUrlWork ) ) {
		$exifTool->SetNewValue('CreatorContactInfoCiUrlWork', $CiUrlWork, Group=>'XMP');
	}

	# writing the changes to the EXIFs
	my $res = $exifTool->WriteInfo( $newfilename, $comentedfilename);
	if ( $res == 1 ) {
		dbgmsg (2, "main(): Writing to $comentedfilename ok.\n");
		rename ( $comentedfilename, $newfilename  )
			|| ( fatalmsg ("$comentedfilename -> $newfilename\n"), die );
	}
	elsif ( $res == 2 ) {
		warnmsg ("No changes between $newfilename and $comentedfilename. No EXIF was written.\n");
		unlink $comentedfilename;
	}
	else {
		my $errorMessage   = $exifTool->GetValue('Error');
		my $warningMessage = $exifTool->GetValue('Warning');
		if ( defined $errorMessage ) { errmsg ("ExifTool: $errorMessage\n"); }
		if ( defined $warningMessage ) { warnmsg ("ExifTool: $warningMessage\n"); }
	}

	# seting mtime for the file if been asked for
	if ( defined $mtime ) {
		my $timestamp = getTimestamp();
		$mTime = getUnixTime($timestamp);
		utime $mTime,$mTime,$newfilename;
		dbgmsg (2, "main(): Changing mtime for $newfilename ok.\n");
	}

	print "\n";
	$filecounter++;
}

closedir(DIR);

########################################################################################
#
# file aggregation if requested
#
if ( defined $aggrTemplate ) {
	infomsg ("NOW IS FILE AGGREGATION\n=======================\n\n");
	$filecounter=1;
	foreach $file ( sort ( keys %filenameshash ) ) {
		$file .= ".jpg";
		$info = $exifTool->ImageInfo($file);
		$newfilename = template2name($aggrTemplate);
		if ( not -d $newfilename ) {
			unless ( mkdir $newfilename ) { errmsg ("$newfilename wasn't created!\n"); }
		}
		infomsg ( "$file has been aggregated to the directory $newfilename\n" );
		$newfilename .= "/" . $file;
		rename ( $file, $newfilename  ) || ( fatalmsg ("$file -> $newfilename\n"), die );
		$filecounter++;
	}
}

exit 0;

########################################################################################
#
# timeNow() returns timestamp in form YYYYmmddHHMMSS
#
sub timeNow {
	my $date = localtime();
	my $timeNow = sprintf("%04d%02d%02d%02d%02d%02d",
		$$date[5] + 1900, $$date[4] + 1, $$date[3],
		$$date[2], $$date[1], $$date[0]);
	return $timeNow;
}

########################################################################################
#
# timeValidator() returns correctness of timestamp in form YYYYmmddHHMMSS
#
sub timeValidator {
	my $timestamp = shift;

	# check length (14)
	return 1 if (length($timestamp) != 14);

	my @tm = ($timestamp =~ m/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/);
	return 1 unless @tm == 6;
	dbgmsg (4, "timeValidator(): @tm\n");

	if (
		# check year
		($tm[0] < 1900) or
		# check month
		(($tm[1] > 12) or ($tm[1] < 1)) or
		# check day
		(($tm[2] > 31) or ($tm[2] < 1)) or
		# check hour, minute, second
		($tm[3] > 23) or ($tm[4] > 59) or ($tm[5] > 59)
	   ) {
		return 1;
	}

	return 0;
}

########################################################################################
#
# getTimestamp() returns EXIF timestamp in form YYYYmmddHHMMSS if exists, otherwise
# it returns timeNow()
#
sub getTimestamp {
	my $timestamp;

	if ( defined $info->{"DateTimeOriginal"} and not timeValidator($info->{"DateTimeOriginal"}) ) {
		$timestamp = $info->{"DateTimeOriginal"};
	}
	elsif ( defined $info->{"FileModifyDate"} and not timeValidator($info->{"FileModifyDate"}) ) {
		$timestamp = $info->{"FileModifyDate"};
	}
	else {
		$timestamp = timeNow();
		warnmsg ("EXIF timestamp isn't correct, using timeNow()!\n");
	}
	
	return $timestamp;
}

########################################################################################
#
# getUnixTime() converts timestamp to unix time form
#
sub getUnixTime {
	my $timestamp = shift;
	my @tm = ($timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/);
	$tm[0] -= 1900;     # convert year
	$tm[1] -= 1;        # convert month
	@tm = reverse @tm;  # change to order required by timelocal()
	return Time::Local::timelocal(@tm);
}

########################################################################################
#
# rotating the image and it's thumbnail, rewriting Orientation tag and the commentary
# to the result file
#
sub rotateFile {
	# $_[0] - file name to transform with jpegtran
	# $_[1] - the switches for jpegtran to transform the image

	my $oldfile =  $_[0];			# original name
	my $origfile = $_[0] . "_orig";	# backup original name
	my $newfile =  $_[0] . "_rotated";	# temporay name to store rotated file

	# jpegtran the image
	my $cmd = "jpegtran -copy all " . $_[1] . " -outfile " . $newfile . " " . $oldfile;
	dbgmsg (3, "rotateFile(): $cmd\n");
	system $cmd || ( fatalmsg ("System $cmd failed: $?\n"), die );

	rename ( $oldfile, $origfile ) || ( fatalmsg ("$oldfile -> $origfile\n"), die );
	rename ( $newfile, $oldfile )  || ( fatalmsg ("$newfile -> $oldfile\n"), die );

	# preparing to write Orientation tag to the just rotated file
	my $exifAfterRot = new Image::ExifTool;
	$exifAfterRot->Options(Binary => 1);
	my $exifedfile = $oldfile . "_exifed";	# the file name, exifed file to be put to

	$exifAfterRot->SetNewValue("Orientation", 1, Type => 'ValueConv');

	# writing the changes to the EXIFs
	my $res = $exifAfterRot->WriteInfo($oldfile, $exifedfile);
	if ( $res == 1 ) {
		dbgmsg (2, "rotateFile(): Writing to $exifedfile ok.\n");
		rename ( $exifedfile, $oldfile )
			|| ( fatalmsg ("$exifedfile -> $oldfile\n"), die );
	}
	elsif ( $res == 2 ) { infomsg ("No changes for $exifedfile.\n"); }
	else {
		my $errorMessage   = $exifAfterRot->GetValue('Error');
		my $warningMessage = $exifAfterRot->GetValue('Warning');
		if ( defined $errorMessage ) { errmsg ("ExifTool: $errorMessage\n"); }
		if ( defined $warningMessage ) { warnmsg ("ExifTool: $warningMessage\n"); }
	}
	$oldfile = $origfile = $newfile = "";
}

########################################################################################
#
# rotate thubnail only, where the file was rotated but thumbnail was left untouched
#
sub rotateThumbnail {
	# $_[0] - file, which thumbnale to transform with jpegtran
	# $_[1] - the switch for jpegtran to rotate the thumbnail

	if ( defined ${$$info{ThumbnailImage}} ) {
		my $fileToThumbnail =  $_[0];			# original name

		# extracting the thumbnail image
		my $ThumbnailOriginal = $fileToThumbnail . "_thumborig";
		unless ( open ( OLDTHUMBNAIL, ">$ThumbnailOriginal" ) ) {
			errmsg ("$ThumbnailOriginal wasn't opened!\n");
		}
		print OLDTHUMBNAIL ${$$info{ThumbnailImage}};
		unless ( close ( OLDTHUMBNAIL ) ) { warnmsg ("$ThumbnailOriginal wasn't closed!\n"); }

		# rotating the thumbnail
		my $ThumbnailOriginalRotated = $ThumbnailOriginal . "_rotated";
		my $cmd = "jpegtran -copy all " . $_[1] . " -outfile " . $ThumbnailOriginalRotated . " " . $ThumbnailOriginal;
		dbgmsg (3, "rotateThumbnail(): $cmd\n");
		system $cmd || ( fatalmsg ("System $cmd failed: $?\n"), die );

		# preparing to write the just rotated thumbnail, back to the file
		unless ( open ( THUMBNAILROTATED, "<$ThumbnailOriginalRotated" ) ) {
			errmsg ("$ThumbnailOriginalRotated wasn't opened!\n");
		}
		binmode THUMBNAILROTATED;
		my ( @rthumb ) = <THUMBNAILROTATED>;
		my $thethumb = join ('',@rthumb);
		unless ( close ( THUMBNAILROTATED ) ) { errmsg ("$ThumbnailOriginalRotated wasn't closed!\n"); }

 	 	# preparing to write thumbnale to the just rotated file
		my $exifThumbnailed = new Image::ExifTool;
		$exifThumbnailed->Options(Binary => 1);

		my $fileThumbnailed = $fileToThumbnail . "_thumb";  # the file name, thumbnailed file to be put to

		$exifThumbnailed->SetNewValue("ThumbnailImage", $thethumb, Type => 'ValueConv');

		# writing the changes to the EXIFs
		my $res = $exifThumbnailed->WriteInfo($fileToThumbnail, $fileThumbnailed);
		if ( $res == 1 ) {
			dbgmsg (2, "rotateThumbnail(): Writing to $fileThumbnailed ok.\n");
			rename ( $fileThumbnailed, $fileToThumbnail )
				|| ( fatalmsg ("$fileThumbnailed -> $fileToThumbnail\n"), die );
		}
		elsif ( $res == 2 ) { infomsg ("No changes for $fileThumbnailed.\n"); }
		else {
			my $errorMessage   = $exifThumbnailed->GetValue('Error');
			my $warningMessage = $exifThumbnailed->GetValue('Warning');
			if ( defined $errorMessage ) { errmsg ("ExifTool: $errorMessage\n"); }
			if ( defined $warningMessage ) { warnmsg ("ExifTool: $warningMessage\n"); }
		}

		unlink ($ThumbnailOriginalRotated) || ( fatalmsg ("While killing $ThumbnailOriginalRotated.\n"), die );
		unlink ($ThumbnailOriginal) || ( fatalmsg ("While killing $ThumbnailOriginal.\n"), die );
	}
	else {
		warnmsg ("No thumbnail found.\n");
	}
}

########################################################################################
#
# usage() - the instruction how to use the script
#
sub usage {
infomsg (
"Usage:	renrot 	[-h|--help] [--no-rotate] [--no-rename] [--comment-file FILE]
		[--version] [--name-prefix PREFIX] [--work-directory DIR] <--ext EXTENTION>

		-h | --help		this very page
		-c | --config-file	use this configuration file (see manual for details)
		-v [-v -v ... ]		verbose, debug level
		--work-directory <DIR>	specify working directory
		--ext <EXTENTION>	extention of files to be processed, JPG, jpg, JPEG e.t.c.
		--no-rotate		no rotation needed, default is to rotate
		--rotate <90|270>	define the angle, to rotate file and the thumbnail on,
					90 or 270. it's for the files where no Orientation tag
					is present and set right way
		--rotate-thumb <90|270>	rotate thumbnail ONLY. 90 or 270 degree
					it's for the files which were rotated, but thumbnail wasn't
		--no-rename		no rename needed, default is to rename to the YYYYmmddHHMMSS.jpg
		--name-template <TPL>	filename template (see manual for details)
		--aggr-template <TPL>	aggregation template (see manual for details)
		--mtime			to set file mtime according DateTimeOriginal tag value
		--comment-file <FILE>	file with commentary
		--version		the version of this script
");
}

########################################################################################
#
# template2name() - file name builder, according the template
#
sub template2name {
	if ( not defined $_[0] ) {
		fatalmsg ("NameTemplate isn't given!\n"), die;
	}

	my $template = $_[0];	# $_[0] the template to be used

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

	my $ExposureTime = "";
	my $FileNumber = 'NA';
	my $FNumber = "";
	my $ISO = "";
	my $WhiteBalance = "";

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

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

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

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

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

	my @templatearea = split (//, $template);
	my %templatehash = (
		'%' => "%",
		'a' => $anglesuffix,
		'c' => sprintf('%.4d', $filecounter),
		'd' => $tm[3],
		'E' => "E" . $ExposureTime,
		'F' => "F" . $FNumber,
		'H' => $tm[4],
		'I' => "I" . $ISO,
		'i' => $FileNumber,
		'M' => $tm[5],
		'm' => $tm[2],
		'S' => $tm[6],
		'W' => "W" . $WhiteBalance,
		'Y' => $tm[0],
		'y' => $tm[1],
			   );
	my $thename = "";

	my $substroffset = 0;
	my $substrchar;

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

	return $thename;
}

__END__

=head1 NAME

renrot - rename and rotate images according EXIF data

=head1 SYNOPSIS

renrot [OPTIONS]

=head1 DESCRIPTION

B<RenRot> is intended to work ONLY in current directory. You can change the
behaviour by specifying B<--work-directory> option.

Renrot renames files according the DateTimeOriginal and FileModifyDate EXIF
tags, if they exist. Otherwise, the name will be set according to the current
time stamp and will look as YYYYmmddHHMMSS.XXXX.jpg, where XXXX is whether file
ID, if exists in EXIF (as for Canon) or incremental suffix to the name
YYYYmmddHHMMSS.

Additionally, it rotates files and their thumbnails, accordingly Orientation
EXIF tag. When the tag is absent or miss set the program allows to rotate the
file as well as it's thumbnail.

The script can also put commentary into:

=over

- Commentary tag, if commentary file provided with B<--comment-file> option

- UserComment tag, if $COMMENTARY variable set in configuration file

=back

Personal details can be specified via XMP tags defined in a configuration
file, look L<CONFIG> section.

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

=head1 OPTIONS

=over

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

the help

=item B<-c> or B<--config-file> I<Configuration FILE>

location of the configuration file

=item B<-v>

one or more I<-v> sets debug level. from 1 to 4 - internal levels, 
5 till 9 - equal to 1-5 levels for ExifTool plus maximum verbosity for renrot

=item B<--work-directory> I<DIR>

define the working directory

=item B<--ext> I<EXTENTION>

extension of files to be processed, JPG, jpg, JPEG, CRW, crw e.t.c.

=item B<--rotate> I<90> or I<270>

define the angle, to rotate file and the thumbnail on, 90 or 270 it's for the
files where no Orientation tag is set right way

=item B<--rotate-thumb> I<90> or I<270>

rotate thumbnail ONLY. 90 or 270 degree. it's for the files which were
rotated, but thumbnail wasn't

=item B<--no-rotate>

no rotation needed, default is to rotate

=item B<--no-rename>

no rename needed, default is to rename to the YYYYmmddHHMMSS.jpg

=item B<--comment-file> I<Comment FILE>

file with commentary

=item B<--version>

the version of this script

=item B<--mtime>

defines, whether to set mtime of the file, using DateTimeOriginal tag value

=item B<--name-template> I<Name TEMPLATE>

template, which is used for file name building while renaming. It could be
defined in configuration file (the variable NameTemplate). The default is
I<%Y%m%d%H%M%S>. For practical results look L<EXAMPLES> section.

Interpreted sequences are:

=over

B<%%>	a literal %

B<%c>	file order number in the processed file set

B<%d>	day of the month (01-31)

B<%E>	ExposureTime tag value if defined, otherwise E

B<%F>	FNumber tag value if defined, otherwise F

B<%H>	hour (00-23)

B<%I>	ISO tag value if defined, otherwise I

B<%i>	FileNumber tag if exists (otherwise, it'll be replaced by string
C<NA>)

B<%M>	minute (00-59)

B<%m>	month (01-12)

B<%S>	second (00-59)

B<%W>	WhiteBalance tag value if defined, otherwise W

B<%Y>	year (1900, 1901, and so on)

B<%y>	last two digits of year (00..99)

=back

=item B<--aggr-template> I<Aggregation TEMPLATE>

template, which is used for file aggregation. Aggragation fulfils according date/time patterns.

=over

B<%d>	day of the month (01-31)

B<%H>	hour (00-23)

B<%M>	minute (00-59)

B<%m>	month (01-12)

B<%S>	second (00-59)

B<%Y>	year (1900, 1901, and so on)

B<%y>	last two digits of year (00..99)

=back

=back

=head1 B<EXAMPLES>

The template C<01.%c.%Y%m%d%H%M%S.%i.%E%F%W%I> may produces following names:

=over

01.0021.20030414103656.NA.E1by40F2.8WAutoI160.jpg

01.0024.20040131230857.100-0078.E1by320F2.8WAutoI50.jpg

01.0022.20000820222108.NA.EFWI.jpg

=back

where I<F> stays for FNumber, I<E> for ExposureTime, I<I> for ISO and
I<W> for WhiteBalance.

=head1 CONFIG

Config file could be used to set some variables. Config file is just perl
code. B<Renrot> looks for B<--config-file> option firstly, than it looks for
file named renrot.rc in system directories such as /etc and /usr/local/etc.
And finally it looks for file named .renrotrc in home directory of the user.
User defined configuration file can be given via B<--config-file> option.

These tags could be set via configuration file:

=over

=item B<NameTemplate>

Name template, which defines the file name look (see B<--name-template>).

=item B<UserComment>

anything you'd wanna put as commentary

=item B<CiAdrCity>

City

=item B<CiAdrCtry>

Country

=item B<CiAdrExtadr>

extended address (usually street and apartments)

=item B<CiAdrPcode>

zip code

=item B<CiAdrRegion>

region

=item B<CiEmailWork>

email

=item B<CiTelWork>

phone

=item B<CiUrlWork>

URL

=back

=head1 FILES

configuration file placement (with high priority first)

=over

=item B<~/.renrotrc>

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

=item B</etc/renrot.rc>

=back

=head1 AUTHOR

Copyright 2005-2006, Zeus Panchenko

This library 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<jpegtran(1)>

=cut

Return to:

Send suggestions and report system problems to the System administrator.