#!/usr/bin/perl

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

# Splits an SVG file into layers, then runs enblend-mask on the
# resulting SVG files. (c) July 2007 Bruno Postle <bruno@postle.net>

my $tempdir = tempdir (CLEANUP => 1);
my $file = pop @ARGV;
exit unless ($file =~ /\.svg$/i);
$file = File::Spec->rel2abs ($file);

open (FILE, $file) or die "Can't open $file: $!";
my @lines = <FILE>;
my $xml = join ('', @lines);

my @layers = $xml =~ /(<g.*?<\/g>)/gs;
exit unless @layers;

my @files;
my $index = 0;

# deal with imagemagick brokenness
my $curdir = File::Spec->curdir ();
$curdir = File::Spec->rel2abs ($curdir);
my ($v, $d, $f) = File::Spec->splitpath ($file);
my $basedir = File::Spec->catpath ($v, $d, '');
chdir $basedir;

for my $layer (@layers)
{
    $xml =~ s/<g.*<\/g>/$layer/gs;
    my $out = "$file-enblend-svg-$$-$index.svg";

    # switch out jpg if tif alternative exists
    my @jpeg = $xml =~ /"([^"]+)\.jpg"/gs;
    if (-e "$jpeg[0].tif")
    {
        print STDOUT "Switching $jpeg[0].jpg for $jpeg[0].tif\n";
        $xml =~ s/$jpeg[0].jpg/$jpeg[0].tif/g;
    }

    open (OUT, ">$out");
    print OUT $xml;

    my $tempfile = File::Spec->catfile ($tempdir, "$index.tif");
    print STDOUT "Creating $tempfile ... ";
    system ('convert', '-background', 'transparent', $out, $tempfile);
    print STDOUT "Done.\n";

    push @files, $tempfile;
    close OUT;
    unlink $out;
    $index++;
}

chdir $curdir;

system ('enblend', @ARGV, @files);

__END__

=head1 NAME

enblend-svg - Wrapper around enblend for blending SVG layers

=head1 Synopsis

  enblend-svg [options] -o OUTPUT INPUT

=head1 DESCRIPTION

Wrapper around enblend.  Usage is exactly the same as for enblend, except that
it takes a single SVG file as input.  The SVG file needs to contain multiple
Inkscape layers.  See tif2svg for a tool to create such SVG files.

Requires enblend and ImageMagick linked against librsvg.

L<http://enblend.sourceforge.net/>

Note that this tool expects that TIFF images are to be preferred to JPEG.  So
if JPEG images are referenced in the SVG file and TIFF equivalents exist, then
they will be used instead.

=head1 License

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

=head1 See Also

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

=head1 Author

September 2007, Bruno Postle <bruno AT postle.net>

