#!/usr/bin/perl
#
# Prabu 9/2/04
#
# This script file has been customized for Windows 32
#
# This perl script copies all JPG files in the given directory (recursively)
# and stores them in the destination folder based on the image resolution
#
#  usage: perl GroupFlowers.pl FlowersForYou classifiedFlowers
#

use Image::Size; # import Perl module -> ...\Perl\lib\CGI\Size.pm
use File::Copy;

# Constants
use constant STEP => 2; # nested indentation increment


if ($#ARGV != 1) { # in Perl, argcnt is zero for one argument
    die "Usage: $0 srcImageDir destImgDir \n";
}

$indent = 0; # no. of spaces to be indented
$imgfilecount = 0;

$srcDir = $ARGV[0];
$destDir = $ARGV[1];

#print "srcDir: $srcDir \n";

&processDir($srcDir, $destDir, $indent, 1);

print "\n Number of image files grouped: $imgfilecount \n\n";


exit(0);


sub processDir {
#process the files recursively
  if ($#_ != 3) {
      die "Invalid no. of arguments $#_ for processDir \n";
  }

  my $childDir = $_[0];
  my $destDir = "..\\" . $_[1];
  my $indentLen = $_[2];
  my $recurse = $_[3];
# if (!($childDir =~ /\\$/ )) { # ensure that childDir ends with '\' for DOS
#   $childDir .= "\\" ;
# }
  chdir($childDir) or die "Unable to enter dir $childDir:$!\n";
  opendir(DIR, ".") or die "Unable to open $childDir:$!\n";
  my @names = sort readdir(DIR) or die "Unable to read $childDir:$!\n";
  closedir(DIR);
  $indentLen += STEP;

  foreach my $name (@names){
   if (($name eq ".") || ($name eq "..")) {
      next;
   }
#   print " " x $indentLen;
    if (-d $name) {
#       print "$name\\";
    } elsif (($name =~ /\.jp/oi) || ($name =~ /\.tif/oi) || ($name =~ /\.gif/oi)){
        ($width, $height) = imgsize("$name");
        $aspect = sprintf "%.2f", $width / $height;

        $grpDir = "$destDir\\$aspect"; # Win32 folder notation
        if (!(-d $grpDir)) {
          mkdir($grpDir) || die "Unable to create $grpDir:$!\n";
        }
        $grpDir .= "\\$width" . "x" ."$height"; # Win32 folder notation
        if (!(-d $grpDir)) {
          mkdir($grpDir) || die "Unable to create $grpDir:$!\n";
        }

        if (-e "$grpDir\\$name") { # Win32 folder notation
          print "Duplicate file at $grpDir\\$name \n";
        } else {
          copy($name, "$grpDir\\$name"); # Win32 folder notation
          $imgfilecount++;
        }
#       print "$name  $width x $height ($aspect)";
    }
    else {
        print " Remove file $childDir\\$name \n";
    }
#   print "   Destn: $destDir \n";

    if (-d $name) {
      if ($recurse) {
        # traverse the sub dir
        $newChild = $name;
        &processDir($newChild, $destDir, $indentLen, $recurse);
      }
    }
  }
  chdir("..") or die "Unable to enter parent dir of $childDir:$!\n";
}
