#!/usr/bin/env perl

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

my %rotorientrev = reverse %rotorient;

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

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

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

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

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

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

  # For 'general'
  my %h_g_opts;

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

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

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

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

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

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

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

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

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

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

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

  my $fileCount = scalar(@ARGV);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    procmsg ("\n");

    $fileCounter += $countStep;
  }
}

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

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

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

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

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

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

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

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

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

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

    $newFileName .= $ext;

    $filenameshash{$newFileName} = $unixTime;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  use File::Copy;

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

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

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

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

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

    $filefull = $file;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      undef $image;
    }
  }

  $image = Image::Magick->new;

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

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

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

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

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

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

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

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

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

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

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

  procmsg ("\n");
}

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

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

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

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

  undef $thmb;

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

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

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

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

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

  undef $thmb;

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

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

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

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

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

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

  makedir($new_dir);

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

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

  my $timestamp;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Consult the documentation for a full list of options.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

renRotProcess($exifTool, $counterSize);

contactSheetGenerator($exifTool) if ($isThereIM);

aggregationProcess($exifTool, $counterSize);

__END__

=head1 NAME

renrot - rename and rotate images according EXIF data

=head1 SYNOPSIS

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

=head1 DESCRIPTION

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

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

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

The program can also place commentaries into the following locations:

=over

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

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

=back

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

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

=head1 OPTIONS

=over

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

Path to the configuration file.

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

Define the working directory.

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

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

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

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

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

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

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

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

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

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

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

Colorize output. This does NOT work under Windows.

=item B<--dry-run>

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

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

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

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

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

=item B<-v>

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

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

Display short usage summary and exit.

=item B<--version>

Output version information and exit.

=back

=head1 B<AGGREGATION>

=over

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

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

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

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

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

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

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

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

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

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

=back

=head1 B<CONTACT SHEET GENERATOR>

=over

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

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

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

Base file name for montage files.

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

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

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

Files for the montage are already thumbnails

=back

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

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

=over

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

Tile MxN (IM: -tile)

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

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

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

Background color (IM: -background).

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

Border color (IM: -bordercolor).

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

Frame color (IM: -mattecolor).

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

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

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

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

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

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

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

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

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

Font point size (IM: -pointsize).

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

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

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

Color to fill the text in generated thumbnail.

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

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

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

Generated thumbnail background gradient COLOR-from

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

Generated thumbnail background gradient COLOR-to

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

Generated thumbnail text

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

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

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

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

=over

01.file.jpg        red

02.JPG             CornflowerBlue

03.jpg             aquamarine

04.file.JPG        green

=back

Only the files found in the file will be ranked.

=back

=head1 B<KEYWORDIZER>

=over

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

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

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

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

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

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

=back

=head1 B<RENAMING>

=over

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

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

Interpreted sequences are:

=over

B<%%>	a literal %

B<%#>	a literal #

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

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

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

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

B<%e>	Old file extension

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

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

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

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

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

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

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

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

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

B<%S>	Second (00-59)

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

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

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

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

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

=back

=item B<--no-rename>

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

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

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

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

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

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

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

=back

=head1 B<ROTATING>

=over

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

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

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

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

=item B<--only-orientation>

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

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

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

=item B<--no-rotate>

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

=back

=head1 B<TAG WRITER>

=over

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

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

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

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

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

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

=item B<--no-tags>

No user's defined tags will be written.

=back

=head1 B<TEMPLATE EXAMPLES>

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

=over

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

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

01.0022.20000820222108.NA.jpg

=back

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

=over

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

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

01.0022.20000820222108.NA.jpg

=back

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

these three files

=over

01.11.20030414103656.NA.jpg

01.12.20030414103813.NA.jpg

01.13.20030414103959.NA.jpg

=back

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

=over

01.14.20040131130857.100-0078.jpg

01.15.20040131131857.100-0079.jpg

01.16.20040131133019.100-0080.jpg

=back

will be stored in the directory F<20040131>.

=head1 CONFIG

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

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

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

=over

=item B<mtime>

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

=item B<name template>

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

=item B<trim>

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

=item B<aggregation mode>

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

=item B<aggregation template>

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

=item B<aggregation virtual>

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

=item B<Tag>, B<TagFile>

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

=item B<include>

Include the named file.

=back

=head1 TAGS

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

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

=over

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

=back

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

=over

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

=back

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

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

=over

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

=back

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

=over

=item B<Copyright>

Copyright notes.

=item B<Comment>

General comment.

=item B<UserComment>

Anything you would like to put as a comment.

=item B<CreatorContactInfoCiAdrCity>

A city tag.

=item B<CreatorContactInfoCiAdrCtry>

A country tag.

=item B<CreatorContactInfoCiAdrExtadr>

Extended address (usually includes street and apartment number).

=item B<CreatorContactInfoCiAdrPcode>

Zip code.

=item B<CreatorContactInfoCiAdrRegion>

Region.

=item B<CreatorContactInfoCiEmailWork>

Email.

=item B<CreatorContactInfoCiTelWork>

Phone number.

=item B<CreatorContactInfoCiUrlWork>

URL.

=back

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

=head1 FILES

=over

=item

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

=over

=item B<~/.renrot/>

directory under user's home place

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

system directory

=item B</etc/renrot/>

system directory

=back

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

=item

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

=over

=item B<colors.conf>

colors setup for different output facilities

=item B<tags.conf>

different tags setup

=back

=item

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

=over

=item B<.keywords>

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

=item B<.rank>

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

=back

=back

=head1 BUGS

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

=over

=item 1.

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

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

B<renrot> aborts with the error message:

=over

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

=back

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

=item 2.

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

=back

=head1 AUTHORS

Copyright 2005-2012, Zeus Panchenko, Andy Shevchenko.

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

=head1 SEE ALSO

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

=cut

