#!/usr/bin/perl

############################################################################
# Please change this accordingly if you change the DESTDIR in the tarball 
# distribution Makefile or the --prefix of the RPM installation
$LIBDIR = "/usr/share/igal";
# for example if you make DESTDIR=/usr then $LIBDIR="/usr/lib/igal"
############################################################################
#
# Note to do-it-yourselvers and Computer Science types:  the IGAL code is
# UGLY.  I'm am amateur programmer, not a CS type.  If my scrappy code runs
# and gives the right results, I'm happy.  If others find it useful, that's
# wonderful.  I hope my comments can help decipher the mess below a bit.  I
# wrote IGAL partly because I wanted another excuse to learn Perl (it's
# useful for my research too) and because other image gallery generators
# had hairy dependencies and didn't do what I needed.  So... my apologies
# if the spaghetti below makes you cringe.  It works for me, so I don't
# really have plans (or time) to clean it up.
#
############################################################################
# If you KNOW you have the ImageMagick package installed (e.g commands like
# identify and convert) then setting this equal to 1 may speed up the code a
# bit (igal will stop checking for these commands every time it runs)
#
$HAVEIM = 1;
############################################################################
# If you KNOW you have the libjpeg stuff installed (e.g commands like cjpeg,
# djpeg and pnmscale) then setting this equal to 1 may speed up the code a
# bit (igal will stop checking for these commands every time it runs)
#
$HAVELJ = 0;
############################################################################

# This is IGAL version 1.4, an online Image GALlery generator.
#   Copyright (C) 2000 Eric Pop
#
#   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.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Eric Pop, Dept. of Electrical Engineering, Stanford University
# Email: epop@stanford.edu

# updated by Alexander Zangerl <az@debian.org> 2003 for Debianization
# building on modifications by Robert McQueen <robot101@debian.org>
# for the initial Debian package (copyright 2000 and 2001)

# this is az's local RCS version info: $Id: igal,v 1.20 2005/03/06 13:42:13 az Exp $ 

use FileHandle;
use Getopt::Long;
use Image::Size;
use URI::Escape;

# some constants
$Getopt::Long::ignorecase = 0;
$itile = "tile.png";
$slidetemplate = "slidetemplate.html";
$indextemplate = "indextemplate.html";
$csstemplate = "igal.css";
$captionfile = ".captions";
$userigaldir = "$ENV{'HOME'}/.igal";
$thumbprefix = ".thumb_";
$slideprefix = ".slide_";
STDOUT->autoflush("1");

# default command-line argument values
$opt_a = "0";          # to write image size under thumbnails in index page
#option -b no longer needed in IGAL 1.4 because i'm using style sheets
#$opt_b = "000000";     # color of the thumbnail background
$opt_c = "0";          # -c to use user-supplied captions
$opt_C = "0";          # same as -c, but preserve image names as captions
$opt_d = ".";          # look in current directory "."
$opt_f = "0";          # -f to force thumbnail regeneration
$opt_h = "0";
$opt_i = "index.html"; # name of the main thumbnail index file
$opt_k = "0";          # -k for the captions to also be used as slide titles
$opt_n = "0";          # -n to use image file names for the .html files
$opt_p = "3";          # cellpadding value for the thumbnail index tables
$opt_r = "0";          # -r to omit the film reel effect altogether
$opt_s = "0";          # -s to make no slides, just thumbnail links to images
$opt_t = "21";         # height of the .tile.png tiled image
$opt_u = "0";          # write captions under thumbnails on index page
$opt_w = "5";          # index rows are at most 5 images wide by default
$opt_x = "0";          # -x to omit the image count from the caption
$opt_y = "0";          # max height of a thumbnail (defaults to 75 below)
$opt_ad = "0";         # write out only dimensions
$opt_as = "0";         # write out only file size
$opt_bigy = "0";       # max height of the slides.  use if images are huge.
$opt_con = "";         # options to be passed to convert or cjpeg
$opt_help = "0";       # displays brief usage message; same as -h
$opt_www = "0";        # makes everything world-readable
$opt_wx = undef;       # to set index rows n pixels wide
$opt_xy = "0";         # scale thumbs to n pixels in their longer dimension
$opt_clean=0;		# clean up all generated files
$opt_title = "Index of Pictures";
$opt_tp = $thumbprefix; # changes the thumbnail filename prefix
$opt_sp = $slideprefix; # changes the slide filename prefix

$usage = <<"END_OF_USAGE";
This is iGal 1.4 an HTML image slide show generator.
Syntax:  igal [-option -option ...]
Options:      -a          write image sizes under thumbnails on index page
              -c          first generate and then use captions
              -C          like -c, but preserve file names as captions
              -d <dir>    operate on files in directory <dir> (.)
              -f          force thumbnail regeneration and scaled slides
              -h          displays this brief help; same as --help
              -i <file>   name of the main thumbnail index file (index.html)
              -k          use the image captions for the HTML slide titles
              -n          use image file names for the HTML slide files
              -p <n>      cellpadding value of thumbnail index tables (3)
              -r          omit the film reel effect altogether
              -s          make no HTML slides, link thumbnails to images
              -t <n>      height of the film reel tiled image (21)
              -u          write captions under thumbnails on index page
              -w <n>      rows in thumbnail index are at most <n> images wide (5)
              -x          omit the image count from the captions
              -y <n>      scale all thumbnails to the same height <n> (75)
              --ad        like -a, but write only the image dimensions
              --as        like -a, but write only the file size (in kbytes)
              --bigy <n>  like -y, use it if you have very large image files
              --con <>    options to pass to convert or cjpeg (e.g. -quality N)
              --help      displays this brief help; same as -h
              --www       make all iGal files world-readable
              --wx <n>    rows in thumbnail index are at most <n> pixels wide
              --xy <n>    scale thumbs to <n> pixels in their longer dimension
              --title <s> string to substitute for TITLE in index template
              --clean     remove all generated files
              --tp <s>    sets the thumbnail image prefix (\".thumb_\")
              --sp <s>    sets the slide image prefix (\".slide_\")
Note:      default values are given in parentheses (where applicable).
Author:    Eric Pop <epop\@stanford.edu>
URL:       http://www.stanford.edu/~epop/igal
Thanks:    If you really like iGal please see the THANKS file.
END_OF_USAGE

# store command-line options upfront to write in the index <HEAD>
@igal_options = @ARGV;

# process command-line arguments (overriding defaults above)
GetOptions('a','c','C','d=s','f','h','i=s','k','n','p=i',
           'r','s','t=i','u','w=i','x','y=i','ad','as','bigy=i',
           'con=s','help','im','www','wx=i','xy=i','clean','title=s',
           'tp=s','sp=s') or die "$usage";

die $usage if ($opt_help or $opt_h);

# change the thumbnail and/or prefix settings
$thumbprefix = $opt_tp if ($opt_tp);
$slideprefix = $opt_sp if ($opt_sp);

if ($opt_clean)
{
    print "Removing all igal files: ";
    opendir(D,$opt_d) || die "bad directory specification!\n";
    foreach (readdir(D))
    {
	/^($thumbprefix.*|$slideprefix.*|$csstemplate|$indextemplate|$slidetemplate|\.$itile|.*\.html|$captionfile)$/ 
	    && unlink("$opt_d/$_");
    }
    closedir(D);
    print "done!\n";
    exit 0;
}


# deal with the competing -y and --xy options
if (($opt_y == 0) and ($opt_xy == 0)) {
	$opt_y = 75;    # default, if neither -y nor --xy is specified
    }
die "Please only specify one of the -y and --xy options\n" if ($opt_y and $opt_xy);
# other error (sanity) checks
die "Please enter nonnegative thumbnail dimensions\n" if (($opt_y < 0) or ($opt_xy < 0));
die "Please enter a nonnegative cellpadding value\n" if ($opt_p < 0);
die "Please choose at least one image per index row\n" if ($opt_w <= 0);
die "Please allow at least one pixel per index row\n" if (defined $opt_wx 
							  && $opt_wx <= 0);
die "Please enter a nonnegative tiled image height\n" if ($opt_t < 0);

# check if the 6-digit thumbnail background color makes sense
# die "$opt_b is not a valid hex color code\n" unless ($opt_b =~ m/\b(\d|[a-f]){6}\b/i);

# strip any unnecessary slashes from the end of the given $opt_d directory
$opt_d =~ s/\/$//;

# let users store their templates in a $HOME/.igal directory, if it exists,
# instead of the site-wide /usr/local/lib/igal (from line 8 up top)
$LIBDIR = $userigaldir if ((-r $userigaldir) && (-d $userigaldir));

# load up image files from $opt_d into array @imgfiles
opendir DIR, $opt_d or die "Can't open directory $opt_d\n";

# find and read all jp(e)g, gif and png files
@jpgfiles = grep((!/^\.thumb/ and !/^\.slide/ and !/^\.tile/ and /\.jpe?g$/i), readdir DIR);
rewinddir DIR;   # this is CRUCIAL here!!!
@giffiles = grep((!/^\.thumb/ and !/^\.slide/ and !/^\.tile/ and /\.gif$/i), readdir DIR);
rewinddir DIR;   # this is CRUCIAL here!!!
@pngfiles = grep((!/^\.thumb/ and !/^\.slide/ and !/^\.tile/ and /\.png$/i), readdir DIR);
@imgfiles = @jpgfiles;
push(@imgfiles, @giffiles);
push(@imgfiles, @pngfiles);

@imgfiles = sort @imgfiles;      # sort alphabetically, by file name
$njpg = @jpgfiles;
$nfiles = @imgfiles;             # how many total image files i've loaded
closedir DIR;

die "Can't find any image files in directory $opt_d\n" if ($nfiles == 0);

# Store image extensions, fix problematic filenames and complain
@imgext = (); @captions = ();
my @safenames;
my $warned;
foreach $file (@imgfiles) 
{
    my $safe=uri_escape($file);
    # warn once, and only for non-ascii chars
    if (!$warned and $safe ne $file and $file=~/[\x80-\xFF]/)
    {
	warn "\nAt least one of your files ($file) contains non-ascii characters 
which are not safely representable in a URL. iGal has escaped them 
using the method RFC 2396 specifies, but this may not work out if 
your web server has a different notion of character encoding 
than the machine iGal runs on. YMMV.
See also: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2\n\n";
	$warned=1;
    }
    push @safenames,$safe;

	# store image captions & extensions in separate arrays along the way
	$temp = $file;
	$temp =~ m/(^.*)\.(\w{3,4})$/;
	push(@captions, $1);
	push(@imgext, $2);
}

# if the -c (or -C) option was supplied let user specify captions, else see below
if ($opt_c or $opt_C) {
	if (! -r "$opt_d/$captionfile") {
		# create $captionfile file if it doesn't exist
		print "Found $nfiles image files in ".($opt_d eq "."?"current directory":"directory $opt_d")."\n";
		die "Please select more files for your slide show!\n" if ($nfiles <= 1);
		open(CAP,">$opt_d/$captionfile") or die "Can't create $opt_d/$captionfile file\n";
		print "Creating the $captionfile file...\n";
		print CAP "# This is igal's $captionfile file, first generated ", scalar localtime, ".\n";
		print CAP "# To the left of the separator are the image file names.  Enter your captions\n# on the right side, one per line.  The captions may include HTML tags.\n# To add any comments to this file or to exclude any images from the slide \n# show, add a # sign at the beginning of their respective lines.  You may\n# also change the order of images in your slide show at this time.\n\n";
			for ($i = 0; $i < $nfiles; $i++) {
				print CAP "$imgfiles[$i] ---- ";
				print CAP "$captions[$i]" if $opt_C;
				print CAP "\n";
			}
		close(CAP);
		die "Now edit the $captionfile file to your liking and rerun igal -c\n";
	} else {
		# read in files specified in the .captions file
		open(CAP,"$opt_d/$captionfile") or die "Can't open $opt_d/$captionfile file\n";
		@imgfiles = ();     # reset arrays b/c we're rereading them
		@safenames = ();
		@captions = (); @imgext = (); $njpg = 0;
		print "Reading the $captionfile file ... ";
		while (defined($line = <CAP>)) {
			chomp($line); $line =~ s/^\s*//; $line =~ s/\s*$//;
			# only read lines with the ---- delimiter that don't start with #
			if (($line =~ m/\w\s*----\s*/) && !($line =~ m/^\#/)) {
				@arr = split(/\s*----\s*/,$line);
				# first check image extensions
				$temp = $arr[0]; $temp =~ s/^.*\.//;
				push(@imgfiles,$arr[0]);
				push(@imgext, $temp);
				push(@arr,"") if (scalar @arr == 1);
				push(@captions,$arr[1]);
				$njpg++ if ($arr[0] =~ m/jpe?g/i);
				# az fixme: i hate duplication, but i do not want to 
				# recode everything (and i would have to...)
				my $safe=uri_escape($arr[0]);
				# warn once, and only for non-ascii chars
				if (!$warned and $safe ne $arr[0] and $arr[0]=~/[\x80-\xFF]/)
				{
				    warn "\nAt least one of your files ($file) contains non-ascii characters 
which are not safely representable in a URL. iGal has escaped them 
using the method RFC 2396 specifies, but this may not work out if 
your web server has a different notion of character encoding 
than the machine iGal runs on. YMMV.
See also: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2\n\n";
				    $warned=1;
				}
				push @safenames,$safe;
			}
		}
		close(CAP);
		$nfiles = @imgfiles;
		print "found $nfiles image files.\n";
	}
} else {
	print "Found $nfiles image files in directory $opt_d\n";
}
die "Please select more files for your slide show!\n" if ($nfiles <= 1);


# find out if the imagemagick commands exist
$HAVEIM = (&exist("identify") and &exist("convert")) unless ($HAVEIM);
print "\nWARNING:  The ImageMagick package (imagemagick.org) doesn't seem to be\ninstalled.  Image dimensions will not be available in the generated HTML.\nOnly JPG images are supported... falling back onto cjpeg/djpeg/pnmscale.\n\n" unless ($HAVEIM);

# find out if the libjpeg commands exist
$HAVELJ = (&exist("cjpeg") and &exist("djpeg") &exist("pnmscale")) unless ($HAVELJ or ($njpg == 0) or $HAVEIM);
print "\nWARNING:  at least one of the commands \"cjpeg\", \"djpeg\" and \"pnmscale\" is not\ninstalled.  You can find these at rpmfind.net (inside libjpeg and libgr-progs)\nor you can download the source code from:\n    http://www.ijg.org/ and\n    http://netpbm.sourceforge.net/\n\n" unless ($HAVELJ or ($njpg == 0) or $HAVEIM);

# give up if no image processing commands can be found
die "ERROR:  the necessary image processing tools aren't installed on your system.\nPlease obtain them as specified above.\n\n" unless ($HAVEIM or $HAVELJ);

# initialize the arrays that will hold image file sizes
@xdim=(); @ydim=(); @isiz=();

# Jan 13, 2003:  i played around w/the various ways in which convert can
# resize images, i.e with -scale, -sample, -geometry (equivalent to -resize)
# and lo and behold, i realized that igal will run MUCH faster when resizing
# is done with -scale while quality is about same as with -geometry (in igal
# 1.3 and earlier).  using -sample gives me a bit more speed advantage but
# is not worth using as the scaled-down output seems to be pretty poor.
# here are some timed-runs on a directory w/some images:
# 	* w/convert -sample (poor quality) 7.24 sec
#	* w/convert -scale (ok quality) 9.14 sec
#	* w/convert -resize (ok quality) 23.8 sec
#	* w/cjpeg/djpeg (ok quality) 20.1 sec
# so from now on all convert -scale is used everywhere below because it seems
# to be the clear winner for quality vs speed.

# generate .thumbnails in the same directory with the original image files
# if they don't exist already or if the -f switch is given

print "Creating thumbnails: ";
for ($i = 0; $i < $nfiles; $i++) {
	$file = $imgfiles[$i];
	$fullfile = "$opt_d/$file";
	die "Can't open $fullfile\n" unless (-r $fullfile);
	$fullthumb = "$opt_d/$thumbprefix$file";
	if ((! -e $fullthumb) or $opt_f) {
		if ($HAVEIM) {
			$command = "convert +profile '*' $opt_con -scale x$opt_y \"$fullfile\" \"$fullthumb\"";
			# this opt_xy handling should probably be fixed...
			$command = "convert  +profile '*' $opt_con -scale x$opt_xy \"$fullfile\" \"$fullthumb\"" if ($opt_xy);
		} else {
			if ($imgext[$i] =~ m/(gif|png)/i) {
				print "\nIgnoring $file:  get ImageMagick (imagemagick.org) to process GIF and PNG files.\n";
				$command = 0;
			} else {
				$com1 = "djpeg \"$fullfile\"";
				$com3 = "cjpeg $opt_con -outfile \"$fullthumb\"";
				$scale = "pnmscale -ysize $opt_y";
				$scale = "pnmscale -xysize $opt_xy $opt_xy" if ($opt_xy);
				$command = $com1 . " | " . $scale . " | " . $com3;
			}
		}
		system("$command") if ($command);
		print "." if ($command);
	}
}
print " done!\n";

# determine image file sizes
if ($HAVEIM && !($opt_bigy)) {
	print "Determining image sizes: ";
	foreach $file (@imgfiles) {
		$fullfile = "$opt_d/$file";
		my ($x,$y,$kb)=getsize($fullfile);
		push(@xdim,$x);  push(@ydim,$y);  
		push(@isiz,$kb."kb");
		print ".";
	}
	print " done!\n";
}

# scale down slides if the --bigy <n> option was given
if ($opt_bigy and !($opt_s)) {
	if ($HAVEIM) {
		print "Scaling down big slides and determining new slide sizes:  ";
		@xdim=(); @ydim=(); @isiz=();    # reset image size arrays
	} else {
		print "Scaling down big slides:  ";
	}
	for ($i = 0; $i < $nfiles; $i++) {
		$file = $imgfiles[$i];
		$fullfile = "$opt_d/$file";
		die "Can't open $fullfile\n" unless (-r $fullfile);
		$fullslide = "$opt_d/$slideprefix$file";
		if ((! -e $fullslide) or $opt_f) {
			if ($HAVEIM) {

			    # only scale down, never up.
			    my $y=(getsize($fullfile))[1];
			    chomp $y;
			    if ($y<=$opt_bigy)
			    {
				$command="cp -f \"$fullfile\" \"$fullslide\"";
			    }
			    else
			    {
				$command = "convert  +profile '*' $opt_con -scale x$opt_bigy \"$fullfile\" \"$fullslide\"";
			    }
			} else {
				if ($imgext[$i] =~ m/(gif|png)/i) {
					print "\nIgnoring $file:  get ImageMagick (imagemagick.org) to process GIF and PNG files.\n";
					$command = 0;
				} else {
					$com1 = "djpeg \"$fullfile\"";
					$com3 = "cjpeg $opt_con -outfile \"$fullslide\"";
					$scale = "pnmscale -ysize $opt_bigy";
					$command = $com1 . " | " . $scale . " | " . $com3;
				}
			}
			system("$command") if ($command);
			print "." if ($command);
		}
		if ($HAVEIM) {
		    my ($x,$y,$kb)=getsize($fullslide);
		    push(@xdim,$x);  push(@ydim,$y); push(@isiz,$kb."kb");
		}
	}
	print " done!\n";
}

# create the individual slide show files
if ($opt_s) {
	print "Linking thumbnails directly to image files...  Making no html slides.\n";
} else {
	$nfiles = @imgfiles;      # total number of files (same as # of captions)
	@slides = ();
	if ($opt_n) {                       # decide on the slide html file names
		for ($i = 0; $i < $nfiles; $i++) {
			$temp = $safenames[$i];
			$temp =~ s/\..+?$/\.html/;
			push(@slides,$temp);
		}
	} else {
		for ($i = 0; $i < $nfiles; $i++) {
			push(@slides, $i+1 . ".html");
		}
	}
	system("rm -f \"$opt_d/*.html\"");
	if (! -e "$opt_d/.$slidetemplate") {
		print "No .$slidetemplate file ... getting a copy from $LIBDIR/\n";
		die "$LIBDIR cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r $LIBDIR);
		die "$LIBDIR/$slidetemplate cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r "$LIBDIR/$slidetemplate");
		system("cp -f $LIBDIR/$slidetemplate \"$opt_d/.$slidetemplate\"");
	} else {
		print "Found .$slidetemplate file ... using it.\n";
	}
	my @templtext;
	open(SR,"$opt_d/.$slidetemplate") or die "Can't open the slide template file\n";
	@templtext=<SR>;
	close SR;
	
	print "Creating individual slides: ";
	for ($i = 0; $i < $nfiles; $i++) {
		open(SW,">$opt_d/$slides[$i]") or die "Can't create slide file\n";
		print ".";
		if ($opt_k) {    # use image caption for the HTML slide title
			$title = $captions[$i];
		} else {         # otherwise use the image name (strip suffix)
			$title = $imgfiles[$i];
			$title =~ s/\.\w+?$//;
		}
		$title=~s/&/&amp;/g; $title=~s/"/&\#34;/g;  # " make this attribute-safe
		my @thistemplate=@templtext; # don't touch the original template
		for my $line (@thistemplate) {
			$line =~ s/<!--SLIDE-TITLE-->/$title/g;
			$line =~ s/<!--TITLE-->/$opt_title/g;
			if ($line =~ m/<!--THIS-IMAGE-->/g) {
				if ($opt_bigy) {
					$slide = $slideprefix . $safenames[$i];
					if ($HAVEIM) {
						$line =~ s/(<.*)<!--THIS-IMAGE-->(.)(.*>)/<A href=\"$safenames[$i]\">$1$slide$2 width=$xdim[$i] height=$ydim[$i] alt=\"$title\" title=\"click to see full-size\"$3<\/a>/;
					} else {
						$line =~ s/(<.*)<!--THIS-IMAGE-->(.)(.*>)/<A href=\"$safenames[$i]\">$1$slide$2 alt=\"$title\" title=\"click to see full-size\"$3<\/a>/;
					}
				} else {
					if ($HAVEIM) {
						$line =~ s/<!--THIS-IMAGE-->(.)/$safenames[$i]$1 width=$xdim[$i] height=$ydim[$i] alt=\"$title\"/g;
					} else {
						$line =~ s/<!--THIS-IMAGE-->/$safenames[$i]/g;
					}
				}
			}

			$imagecaption = $captions[$i];
			if (!$opt_C and !$opt_c)
			{
			    # escape "&" in filenames and only in filenames.
			    # if you make captions that aren't html it's your problem.
			    $imagecaption=~s/&/&amp;/g;	
			}
			# add in the image counter unless -x is specified
			$imagecaption.="&nbsp;&nbsp;&nbsp;("
			    .($i+1)."/$nfiles)" if (!$opt_x);
			
			$line =~ s/<!--IMAGE-CAPTION-->/$imagecaption/g;
			$line =~ s/<!--INDEX-FILE-->/$opt_i/g;
			$line =~ s/<!--THIS-SLIDE-->/$slides[$i]/g;
			if ($opt_bigy) {
				$pref = $slideprefix;
			} else {
				$pref = "";
			}

			if ($opt_k) # use caption for title attribute
			{    
			    $prev=$captions[$i-1];
			    $next=$captions[($i==$nfiles-1?0:$i+1)];
			} 
			else  # otherwise use the image name (strip suffix)
			{
			    $prev=$imgfiles[$i-1];
			    $next=$imgfiles[($i==$nfiles-1?0:$i+1)];
			    $next=~s/\.\w+?$//; $prev=~s/\.\w+?$//;

			    $prev=~s/&/&amp;/g; $prev=~s/"/&\#34;/g;  # " make this attribute-safe
			    $next=~s/&/&amp;/g; $next=~s/"/&\#34;/g;  # " make this attribute-safe
			}
			
			$line =~ s/<!--NEXT-IMAGE-->/$pref$safenames[($i==$nfiles-1?0:$i+1)]/g;
			$line =~ s/<!--PREV-SLIDE-->/\"$slides[$i-1]\" title=\"$prev\"/g;
			$line =~ s/<!--NEXT-SLIDE-->/\"$slides[($i==$nfiles-1?0:$i+1)]\" title=\"$next\"/g;

			print SW "$line";
		}
		close(SW);
		close(SR);
	}
	print " done!\n";
}

# create the main index file with all the thumbnails
if ($opt_r) {
	print "Got option -r... omitting film reel effect.\n";
} elsif (! -e "$opt_d/.$itile") {
	print "No .$itile file... getting a copy from $LIBDIR/\n";
	die "$LIBDIR cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r $LIBDIR);
	die "$LIBDIR/$itile cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r "$LIBDIR/$itile");
	system("cp -f $LIBDIR/$itile \"$opt_d/.$itile\"");
} else {
	print "Found .$itile file ... using it.\n";
}
# rescale the tiled image if the -t switch was called but -r wasn't
if (($HAVEIM) and (! $opt_r)) {
    my $tileh=(getsize("$opt_d/.$itile"))[1];
    system("mogrify -scale x$opt_t $opt_d/.$itile") if ($opt_t != $tileh);
}

if (! -e "$opt_d/.$indextemplate") {
	print "No .$indextemplate file... getting a copy from $LIBDIR/\n";
	die "$LIBDIR cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r $LIBDIR);
	die "$LIBDIR/$indextemplate cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r "$LIBDIR/$indextemplate");
	system("cp -f $LIBDIR/$indextemplate \"$opt_d/.$indextemplate\"");
} else {
	print "Found .$indextemplate ... using it.\n";
}

if (! -e "$opt_d/$csstemplate") {
    print "No CSS template file ... getting $LIBDIR/$csstemplate\n";
    die "$LIBDIR cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r $LIBDIR);
    die "$LIBDIR/$csstemplate cannot be read or does not exist.\nPlease install igal properly.\n" unless (-r "$LIBDIR/$csstemplate");
    system("cp -f $LIBDIR/$csstemplate \"$opt_d/\"");
} else {
    print "Found CSS template file $csstemplate ... using it.\n";
}


print "Creating the $opt_i file: ";
open(IXR,"$opt_d/.$indextemplate") or die "Can't open the index template file\n";
open(IXW,">$opt_d/$opt_i") or die "Can't create main $opt_i file\n";
# detect where the <!-- ********** --> line is
while (defined($line = <IXR>)) {
	$line =~ s/IGAL-OPTIONS/@igal_options/g;
        $line =~ s/<!--TITLE-->/$opt_title/g;
        $line =~ s/<!--FIRST-IMAGE-->/$imgfiles[0]/g;
	print IXW "$line";
	last if ($line =~ m/\*{10}/);
}
my $warned=0;
# write out the rows
for ($i = 0; $i < $nfiles; $i+=$num) {
# Figure out how many to put in next row. The text generated by -a* 
# is coerced into a TD of corresponding width. That results in 
# occasionally less than pleasant output but at least the wx limit
# is honoured.
        $width = 0; $num = 0;
	while(($i+$num < $nfiles) && ($num < $opt_w) && (!defined($opt_wx)
							 || $width < $opt_wx)) {
		$thumb = $thumbprefix . $imgfiles[$i+$num];
		if ($HAVEIM) {
		    ($x,$y)=getsize("$opt_d/$thumb");
		} else {
		    $x=0; $y=0;
		}
		$thumbx[$i+$num] = $x;
		$thumby[$i+$num] = $y;
		$width += $x + 2*$opt_p; # 2* or 1*?
		$num++;
        }
	if (defined($opt_wx) && $width > $opt_wx) 
	{ 
	    if ($num>=2)
	    {
		$num--; 
	    }
	    elsif (!$warned)
	    {
		warn("\n\n-wx $opt_wx is too small for even a single icon per row.\n");
		$warned=1;
	    }
	}

# Now output the row of thumbnails.
	print IXW "<TABLE border=0 cellspacing=0 cellpadding=$opt_p>\n";
	print IXW "  <TR><TD class=\"tiled\" height=$opt_t colspan=", ($opt_r?$num:$num+2), ">&nbsp;</TD></TR>\n" unless ($opt_r);
	print IXW "  <TR>";
	print IXW "\n    <TD class=\"thumb\">&nbsp;</TD>\n" unless ($opt_r);
	for ($j = 0; $j < $num; $j++) {
		print IXW "    <TD class=\"thumb\">\n      ";
		if ($opt_s) {
			print IXW "<A href=\"", $safenames[$i+$j], "\">";
		} else {
			print IXW "<A href=\"", $slides[$i+$j], "\">"; 
		}
		print ".";
		if ($opt_k) {    # use image caption for the alt attribute
		    $altname = $captions[$i+$j];
		} else {         # otherwise use the image name (strip suffix)
			$altname = $imgfiles[$i+$j];
			$altname =~ s/\.\w+?$//;
		}

		$altname=~s/&/&amp;/g; $altname=~s/"/&\#34;/g;  # " make this attribute-safe
		$thumb = $thumbprefix . $safenames[$i+$j];
		if ($HAVEIM) {
			print IXW "<IMG src=\"$thumb\" width=$thumbx[$i+$j] height=$thumby[$i+$j] alt=\"$altname\" title=\"$altname\" border=0>";
		} else {
			print IXW "<IMG src=\"$thumb\" alt=\"$altname\" title=\"$altname\" border=0>";
		}
		print IXW "</A></TD>\n";
	}
	print IXW "    <TD class=\"thumb\">&nbsp;</TD>" unless ($opt_r);
	print IXW "\n  </TR>\n";
	print IXW "  <TR><TD class=\"tiled\" height=$opt_t colspan=", $num+2, ">&nbsp;</TD></TR>\n" unless ($opt_r);
	if (($opt_a or $opt_ad or $opt_as) and $HAVEIM) {
		print IXW "  <TR>\n";
		print IXW "<TD>&nbsp;</TD>\n" unless ($opt_r);
		for ($j = 0; $j < $num; $j++) {
			print IXW "    <TD width=\"".$thumbx[$i+$j]."\">";
			$printdim = "$isiz[$i+$j]" if $opt_as;
			$printdim = "$xdim[$i+$j]x$ydim[$i+$j]" if $opt_ad;
			$printdim = "$xdim[$i+$j]x$ydim[$i+$j] ($isiz[$i+$j])" if $opt_a;
			print IXW $printdim;
			print IXW "</TD>\n";
		}
		print IXW "  </TR>\n";
	}
#	write image captions under images if option -u is given
	if ($opt_u) {
		print IXW "  <TR>\n";
		print IXW "<TD>&nbsp;</TD>\n" unless ($opt_r);
		for ($j = 0; $j < $num; $j++) {
			print IXW "    <TD>$captions[$i+$j]</TD>\n";
		}
		print IXW "  </TR>\n";
	}
	print IXW "</TABLE>\n<BR>\n";
}
while (!(<IXR> =~ m/\*{10}/)) {};
while (defined($line = <IXR>)) {
    $line =~ s/<!--TITLE-->/$opt_title/g;
	print IXW "$line";
}
close(IXW);
close(IXR);
print " done!\n";

# if --www was invoked make all images world-readable at the END
if ($opt_www) {
	$dir = "$opt_d/";
	$dir = "" if $opt_d eq ".";
	print "\nMaking all igal files world-readable for WWW publishing...\n";
	print "chmod a+r $dir$csstemplate\n";
	system("chmod a+r $dir$csstemplate");
	print "chmod a+r $dir*.html\n";
	system("chmod a+r $dir*.html");
	print "chmod a+r $dir$thumbprefix*.*\n";
	system("chmod a+r $dir$thumbprefix*.*");
	print "chmod a+r $dir$slideprefix*.*\n";
	system("chmod a+r $dir$slideprefix*.*");
	print "chmod a+r $dir.$itile\n";
	system("chmod a+r $dir.$itile");
	print "chmod a+r ";
	foreach $file (@imgfiles) {
		print "$dir$file ";
		system("chmod a+r $dir$file");
	}
	die "\nDone!\n";
}

##############################################################################

# subroutine that checks if a certain program is in the user's path
# usage &exist("identify") --> 1 (or 0 if it doesn't exist)
sub exist {
    local($program) = @_;
    foreach $dir (split(/:/,$ENV{'PATH'})) {
		return 1 if (-f "$dir/$program");
    }
	return 0;
}

# return x dim, y dim, rounded kb for image
# use Image::Size;
sub getsize 
{
    my ($fn)=@_;
    my ($x,$y,$kb);

    ($x,$y)=imgsize($fn);
    $kb=((stat($fn))[7])>>10;
    return ($x,$y,$kb);
}
