#!/usr/bin/perl -w

# include perl packages
use strict;
use warnings;
use diagnostics;

use Tk;
use Tk::FileSelect;
use File::Basename;

my $nr = @ARGV;

if ($nr < 1) {
  print "Error: $0 called with just $nr arguments\n";
  usage();
  exit();
}


my $dir = $ARGV[0];
if (-d $dir) {
  print "Error: first argument ($dir) is a valid directory.\nThis Mapivi Plug-In is developed for Mapivi version >= 0.7.5\n";
  usage();
  exit();
}

my $top = MainWindow->new;
$top->title("MaPiVi Plugin RGB Separator");

$top->Label(-text => "Create a", 
		   )->pack();
$top->Button(-text => "red, green and blue (RGB)", 
			 -command => sub { my @list = qw/Red Green Blue/;
							   export(@list); })->pack();
$top->Button(-text => "cyan, magenta and yellow (CMY)", 
			 -command => sub { my @list = qw/Cyan Magenta Yellow/;
							   export(@list); })->pack();
$top->Button(-text => "matte, opacity and black", 
			 -command => sub { my @list = qw/Matte Opacity Black/;
							   export(@list); })->pack();
$top->Label(-text => "channel picture of the $nr selected pictures", 
		   )->pack();

$top->Button(-text => "exit plugin", -command => \&exit)->pack();

$top->MainLoop;


sub export {

  my @list = @_;

  for (0 .. $nr-1) {
	my $dpic  = $ARGV[$_];
	next if (!-f $dpic);
	print "processing $dpic ($_/$nr) ...\n";
	foreach my $color (@list) {
	  my $rgb = $dpic;
	  $rgb    =~ s/(.*)(\.jp(g|eg))/$1-$color$2/i;
	  print "rgb = $rgb\n";
	  if (-f $rgb) {
		my $rc = $top->messageBox(-icon  => 'warning', -message => "file $rgb exist. Ok to overwrite?",
								  -title => "Plugin",   -type    => "OKCancel");
		next if ($rc !~ m/Ok/i);
	  }
	  my $command = "convert -quality 95 -channel $color \"$dpic\" \"$rgb\" ";
	  (system "$command") == 0 or print "Error: $command failed: $!\n";
	}
  }

  print "Plugin finished successfully!\n";
  exit();
}

##############################################################
# usage
##############################################################
sub usage {
  my $prog = basename($0);
  print "\nUsage: $prog file1 [file2] [file3] [...]\n\n";
  print "This is a plugin for mapivi (see http://mapivi.de.vu)\n";
  print "It will split the selected pictures from mapivi\n";
  print "into RGB or other channel pictures\n";
  print "Author:  Martin Herrmann <martin-herrmann\@gmx.de>\n";
  print "License: GNU General Public License, version 2\n";
}


# Tell Emacs that this is really a perl script
# Local Variables:
# mode:perl
# End:
