#!/usr/bin/perl

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

=pod

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

Requires enblend and ImageMagick.

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

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

=cut

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 =~ /\.tif$/i) {push @files, $arg}
    else {push @parameters, $arg}
}

my $index = 0;

for my $file (@files)
{
    my $mask = $file;
    $mask =~ s/\.tif$/_mask.tif/i;
    if (-e $mask)
    {
        print STDERR "Using mask $mask\n";
        my $tempfile = File::Spec->catfile ($tempdir, "$index.tif");
        `composite -compose CopyOpacity $mask $file $tempfile`;
        push @parameters, $tempfile;
        $index++;
    }
    else
    {
        push @parameters, $file;
    }
}

my $exec = 'enblend '. (join ' ', @parameters);

`$exec`;

