#!/usr/bin/perl

#   Generate gallery.xml 4 AutoViewer 1.4
#   http://www.airtightinteractive.com/projects/autoviewer/
#
#   Author: Kemar - http://marcarea.com/
#   Version: 1.0 - 15.07.2008
#   Requires Image::Size - http://search.cpan.org/dist/Image-Size/lib/Image/Size.pm
#
#   Warning:
#   AutoViewer is designed for viewing at most around 30 images per gallery.
#   More images than this can cause slow performance on older machines, as all the images are loaded into memory simultaneously.
#   http://www.airtightinteractive.com/projects/autoviewer/faq.html
#
#   Usage:
#   perl generate_autoviewer_xml.pl folder_of_images_path

use strict;
use warnings;
use Image::Size;

print "Running generate_autoviewer_xml.pl\n";

my $path_to_images = $ARGV[0];

if ( $path_to_images ) {
    CreateXML();
}
else {
    die "Error : generate_autoviewer_xml.pl requires folder_of_images_path as argument\n";
}

sub CreateXML {

    $path_to_images .= '/'
       if $path_to_images !~ /\/$/;

    my @images    = GetImages( $path_to_images );
    my $images_nb = scalar(@images);

    PrintOutputXml( @images );

    print "Done: gallery.xml generated with $images_nb images\n";

}

sub GetImages {

    my ( $Dir ) = @_;
    opendir( DIR, $Dir ) || die "Error: Can't open $Dir";
    my @files = readdir( DIR );
    closedir( DIR );
    my @images;

    foreach my $file ( @files )
    {
        # since autoviewer 1.4 requires Flash 8, loadMovie loads only JPEG, GIF, or PNG
        # http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002479.html
        if ( $file =~ /\.(png|gif|jpg|jpeg)$/i ) {
            push @images, $file;
        }
    }

    if ( scalar(@images) > 0 ) {
        return @images;
    }
    else {
        die "Error: no images found in $Dir directory\n";
    }

}

sub PrintOutputXml {

    my @images = @_;

    open (OUTPUT, "> gallery.xml")
       or die "Error: Can't create or open gallery.xml: $!\n";

print OUTPUT <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<gallery frameColor="0xFFFFFF" frameWidth="15" imagePadding="20" displayTime="6" enableRightClickOpen="true">
EOF

    foreach my $img ( @images )
    {
        my( $width, $height ) = imgsize( $path_to_images . $img );
print OUTPUT <<EOF;
    <image>
       <url>$path_to_images$img</url>
       <caption></caption>
       <width>$width</width>
       <height>$height</height>
    </image>
EOF
    }

print OUTPUT <<EOF;
</gallery>
EOF

    close (OUTPUT);

}


__END__

