#!/usr/bin/perl

use strict;
use warnings;
use File::Temp qw/tempdir/;
use File::Spec;

my @parameters;
my @files;
my $tempdir = tempdir (CLEANUP => 1);

while (@ARGV)
{
    my $arg = shift @ARGV;
    if ($arg =~ /-o/)
    {
        push @parameters, $arg;
        push @parameters, shift @ARGV;
        next;
    }
    if ($arg =~ /\.[[:alnum:]]+$/i) {push @files, $arg}
    else {push @parameters, $arg}
}

my $index = 0;

for my $file (@files)
{
    my $tempfile = File::Spec->catfile ($tempdir, "$index.tif");
    my $mask = $file;
    $mask =~ s/\.[[:alnum:]]+$/_mask.tif/i;
    my $svg = $file;
    $svg =~ s/\.[[:alnum:]]+$/.svg/i;
    $file = $svg if (-e $svg);
    if (-e $mask)
    {
        print STDERR "Using mask $mask\n";
        system ('composite', '-compose', 'CopyOpacity', $mask, $file, $tempfile);
        push @parameters, $tempfile;
    }
    elsif ($file !~ /\.tif$/i)
    {
        print STDERR "Converting $file to TIFF\n";
        system ('convert', '-background', 'transparent', $file, $tempfile);
        push @parameters, $tempfile;
    }
    else
    {
        push @parameters, $file;
    }
    $index++;
}

system ('enblend', @parameters);

__END__

=head1 NAME

enblend-mask - Wrapper around enblend for managing external masks

=head1 Synopsis

  enblend-mask [options] -o OUTPUT INPUTS

=head1 DESCRIPTION

Wrapper around enblend.  Usage is exactly the same as for enblend,
except that if files named '<prefix>_mask.tif' exist, they are
inserted as alpha masks before blending.

Some examples of valid image pairs:

  image0000.tif image0000_mask.tif
  foo.jpg foo_mask.tif

Note masks can be any bit depth, but must have no alpha channel.  Black
indicates areas to be ignored, any other colour indicates areas that may be
blended.

Note also that only masks need to be TIFF files, input images can be any
filetype supported by ImageMagick.

Requires enblend and ImageMagick.

L<http://www.bruno.postle.net/neatstuff/enblend-mask/>
L<http://enblend.sourceforge.net/>

=head1 License

This software is distributed under the same terms as enblend itself.

=head1 See Also

L<perl>, L<Panotools::Script>

=head1 Author

October 2006, Bruno Postle <bruno AT postle.net>

