#!/usr/bin/perl

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

# Splits an SVG file into layers, then creates a PREFIX_mask.tif file for
# each image using SVG clip mask as basis, then runs enblend-mask on the
# images referenced. (c) July 2007 Bruno Postle <bruno@postle.net>

my $tempdir = tempdir (CLEANUP => 1);
my $file = pop @ARGV || die 'No SVG file specified';
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;

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";

    $xml =~ s/<image/<rect/g;
    $xml =~ s/style=".*?"/style="fill:#00FF00"/g;
    $xml =~ s/xlink:href="(.*?)"//;
    my $image = $1;
    # if image is JPEG then it must be a proxy generated by tif2svg
    $image =~ s/\.jpg$/.tif/;
    push @files, $image;
    $image =~ s/\.[^.[:space:]]+$/_mask.tif/;

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

    print STDOUT "Creating $image ... ";
    system ('convert', '-channel', 'R', '-separate', '-compress', 'FAX', $out, $image);
    system ('mogrify', '-negate', $image);
    print STDOUT "Done.\n";

    close OUT;
    unlink $out;
    $index++;
}

chdir $curdir;

system ('enblend-mask', @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 program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

=head1 See Also

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

=head1 Author

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