#!/usr/bin/perl -w

use Gimp qw(:auto N_);
use Gimp::Fu;
use Gimp::Util;

# Register plug-in
register("ani_gen",
	 "Crops and reduces IceCube event images",
	 "Sorry buddy...I can barely help myself right now...",
	 "",
	 "",
	 "03/11/05",
	 N_"<Toolbox>/Xtns/Perl-Fu/Generate IceCube Images",
	 "*",
	 [
	  [ PF_STRING, "files", "File name(s) (* is allowed)", "" ],
	  [ PF_INT, "large_edge_size", "The length of the long edge (in pixels) of the large image to be created", 700 ],
	  [ PF_STRING, "large_suffix", "The suffix to add to the new large image created", "_l" ]
         ],
	 \&ani_gen);

sub ani_gen {
  my($files, $lsize, $lsuf) = @_;

  my($file, $img, $drw, $x0, $y0, $x1, $y1, $x2, $y2);
  my($newfile);

  foreach $file (glob($files)) {

    if ($file =~ /$lsuf\.gif/) {
      print "File \"$file\" appears to be processed already...skipping\n";
      next;
    }

    # Load the file
    $img = file_gif_load(RUN_NONINTERACTIVE, $file, $file);
    $drw = $img->active_drawable();
    $img->autocrop(($img->channel_ops_duplicate())->flatten());

    # Get dimensions
    ($x0, $y0) = ($x1, $y1) = ($img->width(), $img->height());

    # Compute size of new image
    if ($x0 > $y0) {
      if ($x0 > $lsize) {
	$x1 = $lsize;
	$y1 = int($y0 * ($lsize / $x0) + 0.5);
      }
    }
    else {
      if ($y0 > $lsize) {
	$y1 = $lsize;
	$x1 = int($x0 * ($lsize / $y0) + 0.5);
      }
    }

    # If we are going to resize
    if ($x0 != $x1 and $y0 != $y1) {

      # Resize
      $img->scale($x1, $y1);
    }

    $img->convert_indexed(0,0,255,0,1,"");

    # Save the new image
    $newfile = $file;
    $newfile =~ s/(.*)\..*/$1${lsuf}.gif/;

    file_gif_save(RUN_NONINTERACTIVE, $img, $drw, $newfile, $newfile, 0, 1, 100, 0);

    # Don't forget to clean up memory
    $img->delete();
  }

  # Don't have an image, but make Gimp happy...
  return undef;
}

exit main;
