#!/usr/bin/perl -w

use IO::File;
use File::Find;
use File::Basename;
use Gimp; 
use Gimp::Fu; 

sub pt_image_scale {
	my ($ImagePath, $newImagePath ) = @_;

	# Create a temporary file to hold the file names of the images to be process.
	$fh = IO::File->new("> /tmp/img.txt") || die "Unable to create a new temporary file: $!";

	find (\&write_files, $ImagePath );

	# Close temp file.
	$fh->close();

	# Read the temp file.
	$input = IO::File->new("< /tmp/img.txt") || die "Unable to open temporary file for reading: $!";

	while( defined( $fullImagePath = $input->getline())) 
		{
		chomp ( $fullImagePath );
		$image_name = $fullImagePath;

		# Load image from disk
		print "Loading next image to process --> $image_name \n";
		$image = file_jpeg_load(RUN_NONINTERACTIVE, "$image_name","$image_name");

		# Scale Image
		print "Scaleing image. \n";
		gimp_image_scale($image, 100, 100);
		print "Display the new image \n";
		gimp_display_new($image);

		$imageName = basename($fullImagePath);
		$newImageFullPath = "$newImagePath" . "/" . "$imageName";
		print "Save the new image to -->$newImageFullPath \n";

		# Write the new file
#This does not work!!! 	file_jpeg_save( RUN_NONINTERACTIVE,$image,-1,
#				"$newImageFullPath","$newImageFullPath",1,0,0) 
#				or die "Could not save file $newImageFullPath\n";

		print "Saving image $newImageFullPath...";
		Gimp::Fu::save_image( $image,"JPG-Q100-S:$newImageFullPath" );
		print "Done! \n";

		print "Deleting image $image... ";
		$image->delete();
		print "Done!\n ";
		}

	$input->close();
	return $newImageFullPath;
}

sub write_files {
        ($name, $path, $suffix) = fileparse( $File::Find::name, '\.jpg','\.jpeg','\.JPG','\.JPEG','\.gif','\.GIF');

        if ( $suffix ne "")
                {
		print "Name -> $name, Path -> $path, Suffix -> $suffix \n";
                print $fh "$File::Find::name\n";
#		print "$name\n";
#		print "$path\n";
#		print "$suffix\n";
                }
}


register 
	"pt_image_scale",                         #  
	"Sacle a image to the desired size",      #  
	"A test script",                          #  
	"MB",                                     #  
	"(c) badona.com",                         #  
	"03/30/2000",                             #  
	"<Toolbox>/Xtns/Perl-Fu/Badona/ScaleImage",# menu path 
	"*",					# Image types 
	[
	[PF_STRING, "path_in","image path in","/home/mihail/projects/badona/OLD/"],
	[PF_STRING, "path_out","image path out","/home/mihail/projects/badona/NEW/"]
	],
	\&pt_image_scale; 
   
  exit main();
