#!/usr/bin/perl
###########################################
# picfix - Fix image colors
# Mike Schilli, 2008 ([email protected])
###########################################
use warnings;
use strict;

use Gimp qw(:auto);
use Gimp::Fu;
use ColorCast;
use Getopt::Std;
use Log::Log4perl qw(:easy);

my $viewer = "eog";

Log::Log4perl->easy_init($DEBUG);

getopts("xl:c:a:s:", \my %opts);

$opts{a} ||= "green"; # color adjust
$opts{s} ||= "1000";  # size
$opts{l} ||= 1;       # autolevel

DEBUG "Starting up";

my $menu =
   "<Toolbox>/Xtns/Perl-Fu/Picfix";

my $file = $ARGV[0];
die "No file"
     unless defined $file;

register(
 "perl_fu_picfix",    # Name
 "Fix Colors and More", # Explain
 "",                  # Help
 "",                  # Author
 "",                  # Copyright
 "",                  # Date
 $menu,               # Menu
 "*",                 # Images accepted
 [ undef ],           # No parameters
 \&picfix             # Function
);

exit main();

###########################################
sub picfix {
###########################################

 my $img = gimp_file_load(
     RUN_NONINTERACTIVE, $file, $file);

 die "Can't load $file" unless $img;

 my $layer = image_get_active_layer($img);

 scale_image_down($img, $opts{s});

 $layer = $img->get_active_layer();
 if($opts{l}) {
   DEBUG "Autolevel [$file]";
   gimp_levels_stretch($layer);
 }

 if($opts{c}) {
   my $colorcast = ColorCast->new(
     yml_file => $opts{c},
     drawable => $layer,
   );
   $colorcast->load();
   $colorcast->adjust_to($opts{a});
 }

 DEBUG "Sharpening $file";
 $img->plug_in_sharpen($layer, 20);

 $file =~ s/\./-1./g;
 $file =~ s/\.nef$/.png/g;

 DEBUG "Saving $file";
 gimp_file_save(
   RUN_NONINTERACTIVE,
   $img,
   $layer,
   $file,
   $file);

 system("$viewer $file") if $opts{x};
 return $img;
}

###########################################
sub scale_image_down {
###########################################
 my($img, $size) = @_;

 my $w = $img->image_width();
 my $h = $img->image_height();

 if($w >= $h) {
     if($w > $size) {
         $h = int($h * $size/$w);
         $w = $size;
     } else {
         return 1;
     }
 } else {
     if($h > $size) {
         $w = int($w * $size/$h);
         $h = $size;
     } else {
         return 1;
     }
 }

 DEBUG "Resizing to $w x $h";
 $img->image_scale($w, $h);
}