#!/usr/bin/perl
use Image::ExifTool;
use Image::Magick;

$map=$ARGV[0];
$newpref=$ARGV[1];
if ($newpref eq "") {
	die "you need to give a second argument: prefix of the newly generated files";
}
my $exifTool = new Image::ExifTool;


# $info = $exifTool->ImageInfo($bestandsnaam);
#foreach (keys %$info) {
#    print "$_ => $$info{$_}\n";
#}

# open(DAT,">test");
# $test = $$info{"ThumbnailImage"};
# print DAT $$test;
# close(DAT);

open (FIND, "find \"$map\" -type f -iname \"*.jpg\" |");
foreach $bestandsnaam (<FIND>) {
	
	chop($bestandsnaam);
	@delen = split('/',$bestandsnaam); # splits de naam per slash /
	$ndelen = @delen; # sla de lengte van @delen op in ndelen
	$naam = $delen[$ndelen - 1]; # de naam van het oorspronkelijke bestand
	print "\nNow processing: $bestandsnaam";
	$image = Image::Magick->new;
	$image->Read(filename=>$bestandsnaam);
	$info = $exifTool->ImageInfo($bestandsnaam);
	print "\nOld Orientation $$info{'Orientation'}\n";
	print "Old AutoRotate $$info{'AutoRotate'}\n";
	$image->Resize(geometry=>'1600x1600');

	if ($$info{'AutoRotate'} eq "Rotate 90 CW") {
		print "->Will now autorotate\n";
		$image->Rotate(degrees=>90);
		$image->Write(filename=>$newpref.$naam);
		$exifTool->SetNewValue(AutoRotate => "None" );
		$exifTool->SetNewValue(Orientation => "Horizontal (normal)");
		$exifTool->WriteInfo($newpref.$naam);
		
	} elsif ($$info{'AutoRotate'} eq "Rotate 270 CW") {
		print "Will now autorotate\n";
		$image->Rotate(degrees=>270);
		$image->Write(filename=>$newpref.$naam);
		$exifTool->SetNewValue(AutoRotate => "None" );
		$exifTool->SetNewValue(Orientation => "Horizontal (normal)");
		$exifTool->WriteInfo($newpref.$naam);
	} else {
		$image->Write(filename=>$newpref.$naam);
	}
}
close(FIND);
