: find the perl interpreter as long as it's in the user's path
eval 'exec perl -wS $0 ${1+"$@"}'
	if 0;

############################################################################
# please change this accordingly if you change the DESTDIR in the tarball 
# distribution Makefile or the --prefix of the RPM installation
$LIBDIR = "/usr/local/lib/igal";
# for example if you make DESTDIR=/usr then $LIBDIR="/usr/lib/igal"
############################################################################
# if you KNOW you have the ImageMagick package installed (e.g commands like
# identify and mogrify) 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 = 0;
############################################################################
# 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.2, 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

use FileHandle;
use Getopt::Long;

# some constants
$itile = "tile.gif";
$slidetemplate = "slidetemplate.html";
$indextemplate = "indextemplate.html";
$captionfile = ".captions";
$userigaldir = "$ENV{'HOME'}/.igal";
$thumbprefix = ".thumb_";
$slideprefix = ".slide_";
STDOUT->autoflush("1");

# default command-line argument values
$opt_d = ".";          # look in current directory "."
$opt_e = "";           # consider all (jpg and gif) files by default
$opt_y = "0";          # max height of a thumbnail (defaults to 75 below)
$opt_w = "5";          # index rows are 5 images wide by default
$opt_t = "28";         # height of the .tile.gif tiled image
$opt_b = "000000";     # color of the thumbnail background
$opt_p = "3";          # cellpadding value for the thumbnail index tables
$opt_i = "index.html"; # name of the main thumbnail index file
$opt_c = "0";          # -c to use user-supplied captions
$opt_C = "0";          # same as -c, but preserve image names as captions
$opt_f = "0";          # -f to force thumbnail regeneration
$opt_n = "0";          # -n to use image file names for the .html files
$opt_k = "0";          # -k for the captions to also be used as slide titles
$opt_x = "0";          # -x to omit the image count from the caption
$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_a = "0";          # to write image size under thumbnails in index page
$opt_ad = "0";         # write out only dimensions
$opt_as = "0";         # write out only file size
$opt_xy = "0";         # scale thumbs to n pixels in their longer dimension
$opt_help = "0";       # displays brief usage message; same as -h
$opt_bigy = "0";       # max height of the slides.  use if images are huge.
$opt_h = "0";
$opt_www = "0";        # makes everything world-readable

$usage = <<"END_OF_USAGE";
This is igal 1.2 an HTML image slide show generator.
Syntax:  igal [-option -option ...]
Options:      -d <dir>    operate on files in directory <dir> (.)
              -y <n>      scale all thumbnails to the same height <n> (75)
              -w <n>      rows in thumbnail index are <n> images wide (5)
              -b <n>      6-digit hex color of thumbnail background (000000)
              -p <n>      cellpadding value of thumbnail index tables (3)
              -t <n>      height of the film reel tiled image (28)
              -i <file>   name of the main thumbnail index file (index.html)
              -e <ext>    consider only image files with extension <ext>
              -c          first generate and then use captions
              -C          like -c, but preserve file names as captions
              -f          force thumbnail regeneration
              -n          use image file names for the HTML slide files
              -k          use the image captions for the HTML slide titles
              -x          omit the image count from the captions
              -r          omit the film reel effect altogether
              -s          make no HTML slides, link thumbnails to images
              -a          write image sizes under thumbnails on index page
              --ad        like -a, but write only the image dimensions
              --as        like -a, but write only the file size (in kbytes)
              --xy <n>    scale thumbs to <n> pixels in their longer dimension
              --www       make all igal files world-readable
              --help      displays this brief help; same as -h
              --bigy <n>  like -y, to shrink huge image slides on the fly
Note:    default values are given in parentheses (where applicable).
Author:  Eric Pop <epop\@stanford.edu>
URL:     http://www.stanford.edu/~epop/igal
END_OF_USAGE

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

die $usage if ($opt_help or $opt_h);
# 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
} else {
	$opt_f = "1";   # if either is specified, force thumbnail regeneration
}
die "Please only specify one of the -y and --xy options\n" if ($opt_y and $opt_xy);
# other error (sanity) checks
die "Please choose either .jp(e)g or .gif image files.\nThe file extension is case-insensitive.\n" if (!($opt_e =~ m/gif$/i) and !($opt_e =~ m/jpe?g$/i) and ($opt_e ne ""));
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 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";
# if -e jpg then read all jpg, jpeg, JPG, JpeG files together...
if ($opt_e =~ m/jpe?g$/i) {
	@jpgfiles = grep((!/^\.thumb/ and !/^\.slide/ and !/^\.tile/ and /\.jpe?g$/i), readdir DIR);
	@imgfiles = @jpgfiles;
	@giffiles = ();
# if -e gif then read only gif (or GIF) files
} elsif ($opt_e =~ m/gif/i) {
	@giffiles = grep((!/^\.thumb/ and !/^\.slide/ and !/^\.tile/ and /\.gif$/i), readdir DIR);
	@jpgfiles = ();
	@imgfiles = @giffiles;
# otherwise read all jpg and gif files we find
} else {
	@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);
	@imgfiles = @jpgfiles;
	push(@imgfiles, @giffiles);
}
@imgfiles = sort @imgfiles;      # sort alphabetically, by file name
@captions = @imgfiles;           # default captions are same as image names
closedir DIR;
$njpg = @jpgfiles;
$ngif = @giffiles;
$nfiles = $njpg + $ngif;         # how many image files i've loaded
die "Can't find any image files in directory $opt_d\n" if ($nfiles == 0);

# Deal with malformed image names (as in RFC2396) and store image extensions
$first = 1; $input = 1; @imgext = ();
foreach $file (@imgfiles) {
	if ($file =~ m/(\#|<|>|%|\"|\s)/) {
		if ($first) {
			print "\nAt least one of your files ($file) contains a character ($1) which\nis not allowed inside an IMG SRC tag.  See the official URI syntax specs at:\nhttp://info.internet.isi.edu/in-notes/rfc/files/rfc2396.txt\nsection 2.4.3.  URIs may not contain delimiters such as <, >, #, %, \" or \nwhite space.  iGal can rename all your files to suppress or replace these\ncharacters.  Please choose one option:\n\n";
			print "   1. Suppress symbols, replace spaces with underscores.\n";
			print "   2. Replace all with underscores.\n";
			print "   3. Supress all.\n\nWhat now?  [1]:  ";
			$input = <STDIN>; chop($input);
			$first = 0;
			print "\n";
		}
		$old = $file;
		if ($input =~ m/^2/) {
			$file =~ s/(\#|<|>|%|\")/_/g;
			$file =~ s/\s+/_/g;
		} elsif ($input =~ m/^3/) {
			$file =~ s/(\#|<|>|%|\"|\s)//g;
		} else {
			$file =~ s/(\#|<|>|%|\")//g;
			$file =~ s/\s+/_/g;
		}
		print "Renaming $old --> $file\n";
		if ($old =~ m/\"/) {
			system("mv -f '$opt_d/$old' \"$opt_d/$file\"");
		} else {
			system("mv -f \"$opt_d/$old\" \"$opt_d/$file\"");
		}				
	}
	# store image extensions in a separate array along the way
	$temp = $file;
	$temp =~ s/^.*\.//;
	push(@imgext, $temp);
}
print "\n" unless ($first);

# 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 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
		@captions = (); @imgext = (); $ngif = 0; $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/^.*\.//;
				if ($opt_e =~ m/jpe?g/i) {
					if ($temp =~ m/jpe?g$/i) {
						push(@imgfiles,$arr[0]);
						push(@imgext, $temp);
						push(@arr,"") if (scalar @arr == 1);
						push(@captions,$arr[1]);
						$njpg++;
					}
				} elsif ($opt_e =~ m/gif/i) {
					if ($temp =~ m/gif/i) {
						push(@imgfiles,$arr[0]);
						push(@imgext, $temp);
						push(@arr,"") if (scalar @arr == 1);
						push(@captions,$arr[1]);
						$ngif++;
					}
				} else {
					push(@imgfiles,$arr[0]);
					push(@imgext, $temp);
					push(@arr,"") if (scalar @arr == 1);
					push(@captions,$arr[1]);
					$njpg++ if ($opt_e =~ m/jpe?g/i);
					$ngif++ if ($opt_e =~ m/gif/i);
				}
			}
		}
		close(CAP);
		$nfiles = @imgfiles;
		if ($opt_e =~ m/jpe?g/i) {
			print "found $nfiles JPG files.\n";
		} elsif ($opt_e =~ m/gif/i) {
			print "found $nfiles GIF files.\n";
		} else {
			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 command identify exists
$haveim = (&exist("identify") and &exist("mogrify")) unless ($haveim);
print "\nWARNING:  at least one of the commands \"identify\" and \"mogrify\" from the\nImageMagick package (imagemagick.org) is not installed.  Image dimensions\nwill not be available in the generated HTML slide show.  Only JPG images\nare supported.\n\n" unless ($haveim);
# find out if the libjpeg commands exist
$havelj = (&exist("cjpeg") and &exist("djpeg") &exist("pnmscale")) unless ($havelj or ($njpg == 0));
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/\nFalling back on ImageMagick for JPG support.\n\n" unless ($havelj or ($njpg == 0));
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=();

# 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 ($imgext[$i] =~ m/gif/i) {
			die "\n\nYou need ImageMagick (imagemagick.org) to properly deal with GIF images.\n" unless ($haveim);
			system("cp -f \"$fullfile\" \"$fullthumb\"");
			$command = "mogrify -geometry x$opt_y \"$fullthumb\"";
			# this opt_xy handling should probably be fixed for GIFs!
			$command = "mogrify -geometry x$opt_xy \"$fullthumb\"" if ($opt_xy);
		} elsif ($imgext[$i] =~ m/jpe?g/i) {
			if ($havelj) {
				$com1 = "djpeg \"$fullfile\"";
				$com3 = "cjpeg -outfile \"$fullthumb\"";
				$scale = "pnmscale -ysize $opt_y";
				$scale = "pnmscale -xysize $opt_xy $opt_xy" if ($opt_xy);
				$command = $com1 . " | " . $scale . " | " . $com3;
			} else {
				system("cp -f \"$fullfile\" \"$fullthumb\"");
				$command = "mogrify -geometry x$opt_y \"$fullthumb\"";
			}
		}
		system("$command");
		print "$thumbprefix$file ";
	}
}
print "... done!\n";

# determine image file sizes
if ($haveim && !($opt_bigy)) {
	print "Determining image sizes ";
	foreach $file (@imgfiles) {
		$fullfile = "$opt_d/$file";
		$temp = `identify -ping \"$fullfile\"`;
		$temp =~ m/^\S*\s(\d+)x(\d+).*?(\d+k*b)/;
		push(@xdim,$1);	push(@ydim,$2); $temp = $3;
		# round nicely in kb if identify returned the size in bytes
		$temp = sprintf ("%.0fkb", $temp/1000) if ($temp =~ s/(\d+)b$/$1/);
		push(@isiz,$temp);
		print ".";
	}
	print " done!\n";
}

# scale down slides if the --bigy <n> option was given
if ($opt_bigy and !($opt_s)) {
	$opt_f = 1;  # if --bigy <n> is specified, automatically force regeneration
	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 ($imgext[$i] =~ m/gif/i) {
				die "\nYou need ImageMagick (imagemagick.org) to properly deal with GIF images.\n" unless ($haveim);
				system("cp -f \"$fullfile\" \"$fullslide\"");
				$command = "mogrify -geometry x$opt_bigy \"$fullslide\"";
			} elsif ($imgext[$i] =~ m/jpe?g/i) {
				if ($havelj) {
					$com1 = "djpeg \"$fullfile\"";
					$com3 = "cjpeg -outfile \"$fullslide\"";
					$scale = "pnmscale -ysize $opt_bigy";
					$command = $com1 . " | " . $scale . " | " . $com3;
				} else {
					system("cp -f \"$fullfile\" \"$fullslide\"");
					$command = "mogrify -geometry x$opt_bigy \"$fullslide\"";
				}
			}
			system("$command");
			print "$slideprefix$file ";
		}
		if ($haveim) {
			$temp = `identify -ping \"$fullslide\"`;
			$temp =~ m/^\S*\s(\d+)x(\d+).*?(\d+k*b)/;
			push(@xdim,$1);	push(@ydim,$2); $temp = $3;
			# round nicely in kb if identify returned the size in bytes
			$temp = sprintf ("%.0fkb", $temp/1000) if ($temp =~ s/(\d+)b$/$1/);
			push(@isiz,$temp);
		}
	}
	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 = $imgfiles[$i];
			$temp =~ s/\..+?$/\.html/;
			push(@slides,$temp);
			$captions[$i] = $captions[$i] . "&nbsp;&nbsp;&nbsp;(" . ($i+1) ."/$nfiles)" if (! $opt_x);
		}
	} else {
		for ($i = 0; $i < $nfiles; $i++) {
			push(@slides, $i+1 . ".html");
			$captions[$i] = $captions[$i] . "&nbsp;&nbsp;&nbsp;(" . ($i+1) ."/$nfiles)" if (! $opt_x);
		}
	}
	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";
	}
	print "Creating individual slides:  ";
	for ($i = 0; $i < $nfiles; $i++) {
		open(SR,"$opt_d/.$slidetemplate") or die "Can't open the slide template file\n";
		open(SW,">$opt_d/$slides[$i]") or die "Can't create slide file\n";
		print "$slides[$i] ";
		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/\..+?$//;
		}
		while (defined($line = <SR>)) {
			$line =~ s/<!--SLIDE-TITLE-->/$title/g;
			if ($line =~ m/<!--THIS-IMAGE-->/g) {
				if ($haveim) {
					if ($opt_bigy) {
						$slide = $slideprefix . $imgfiles[$i];
						$line =~ s/(<.*)<!--THIS-IMAGE-->(.)(.*>)/<a href=\"$imgfiles[$i]\">$1$slide$2 width=$xdim[$i] height=$ydim[$i] $3<\/a>/;
					} else {
						$line =~ s/<!--THIS-IMAGE-->(.)/$imgfiles[$i]$1 width=$xdim[$i] height=$ydim[$i] /g;
					}
				} else {
					$line =~ s/<!--THIS-IMAGE-->/$imgfiles[$i]/g;
				}
			}
			$line =~ s/<!--IMAGE-CAPTION-->/$captions[$i]/g;
			$line =~ s/<!--INDEX-FILE-->/$opt_i/g;
			if ($i == 0) {
				$line =~ s/<!--NEXT-IMAGE-->/$imgfiles[$i+1]/g;
				$line =~ s/<!--PREV-SLIDE-->/$slides[$nfiles-1]/g;
				$line =~ s/<!--NEXT-SLIDE-->/$slides[$i+1]/g;
			} elsif ($i == $nfiles-1) {
				$line =~ s/<!--NEXT-IMAGE-->/$imgfiles[0]/g;
				$line =~ s/<!--PREV-SLIDE-->/$slides[$i-1]/g;
				$line =~ s/<!--NEXT-SLIDE-->/$slides[0]/g;
			} else {
				$line =~ s/<!--NEXT-IMAGE-->/$imgfiles[$i+1]/g;
				$line =~ s/<!--PREV-SLIDE-->/$slides[$i-1]/g;
				$line =~ s/<!--NEXT-SLIDE-->/$slides[$i+1]/g;
			}
			print SW "$line";
		}
		close(SW);
		close(SR);
	}
	print "... done!\n";
}

# create the main index file with all the thumbnails
if (! -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";
}
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";
}
$rows = int $nfiles/$opt_w;     # number of film rows
$rem = $nfiles % $opt_w;        # number of thumbnails on last (incomplete) row
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";
while (defined($line = <IXR>)) {
	print IXW "$line";
	last if ($line =~ m/\*{10}/);
}
# write out the tables with full rows
for ($i = 1; $i <= $rows; $i++) {
	print IXW "<table border=0 cellspacing=0 cellpadding=$opt_p>\n";
	print IXW "  <tr><td height=$opt_t background=\".$itile\" colspan=", $opt_w+2, ">&nbsp;</td></tr>\n" unless ($opt_r);
	print IXW "  <tr>\n    <td bgcolor=\"#$opt_b\">&nbsp;</td>\n";
	for ($j = 1; $j <= $opt_w; $j++) {
		print IXW "    <td bgcolor=\"#$opt_b\" valign=middle align=center>\n      ";
		if ($opt_s) {
			print IXW "<a href=\"", $imgfiles[($i-1)*$opt_w+$j-1], "\">";
		} else {
			print IXW "<a href=\"", $slides[($i-1)*$opt_w+$j-1], "\">";
		}
		print ".";
		$thumb = $thumbprefix . $imgfiles[($i-1)*$opt_w+$j-1];
		if ($haveim) {
			$temp = `identify -ping \"$opt_d/$thumb\"`;
			$temp =~ m/^\S*\s(\d+)x(\d+)\+*/; $x=$1; $y=$2;
			print IXW "<img src=\"$thumb\" width=$x height=$y border=0>";
		} else {
			print IXW "<img src=\"$thumb\" border=0>";
		}
		print IXW "</a></td>\n";
	}
	print IXW "    <td bgcolor=\"#$opt_b\">&nbsp;</td>\n  </tr>\n";
	print IXW "  <tr><td height=$opt_t background=\".$itile\" colspan=", $opt_w+2, ">&nbsp;</td></tr>\n" unless ($opt_r);
	if (($opt_a or $opt_ad or $opt_as) and $haveim) {
		print IXW "  <tr>\n    <td>&nbsp;</td>\n";
		for ($j = 1; $j <= $opt_w; $j++) {
			print IXW "    <td valign=middle align=center>";
			$printdim = "$isiz[($i-1)*$opt_w+$j-1]" if $opt_as;
			$printdim = "$xdim[($i-1)*$opt_w+$j-1]x$ydim[($i-1)*$opt_w+$j-1]" if $opt_ad;
			$printdim = "$xdim[($i-1)*$opt_w+$j-1]x$ydim[($i-1)*$opt_w+$j-1] ($isiz[($i-1)*$opt_w+$j-1])" if $opt_a;
			print IXW $printdim;
			print IXW "</td>\n";
		}
		print IXW "  </tr>\n";
	}
	print IXW "</table>\n<br>\n";
}
# write out the incomplete row if it exists
if ($rem >= 1) {
	print IXW "<table border=0 cellspacing=0 cellpadding=$opt_p>\n";
	print IXW "  <tr><td height=$opt_t background=\".$itile\" colspan=", $rem+2, ">&nbsp;</td></tr>\n" if (! $opt_r);
	print IXW "  <tr>\n    <td bgcolor=\"#$opt_b\">&nbsp;</td>\n";
	for ($i = 1; $i <= $rem; $i++) {
		print IXW "    <td bgcolor=\"#$opt_b\" valign=middle align=center>\n      ";
		if ($opt_s) {
			print IXW "<a href=\"", $imgfiles[$rows*$opt_w+$i-1], "\">";
		} else {
			print IXW "<a href=\"", $slides[$rows*$opt_w+$i-1], "\">";
		}
		print ".";
		$thumb = $thumbprefix . $imgfiles[$rows*$opt_w+$i-1];
		if ($haveim) {
			$temp = `identify -ping \"$opt_d/$thumb\"`;
			$temp =~ m/^\S*\s(\d+)x(\d+)\+*/; $x=$1; $y=$2;
			print IXW "<img src=\"$thumb\" width=$x height=$y border=0>";
		} else {
			print IXW "<img src=\"$thumb\" border=0>";
		}
		print IXW "</a></td>\n";
	}
	print IXW "    <td bgcolor=\"#$opt_b\">&nbsp;</td>\n  </tr>\n";
	print IXW "  <tr><td height=$opt_t background=\".$itile\" colspan=", $rem+2, ">&nbsp;</td></tr>\n" if (! $opt_r);
	if (($opt_a or $opt_ad or $opt_as) and $haveim) {
		print IXW "  <tr>\n    <td>&nbsp;</td>\n";
		for ($i = 1; $i <= $rem; $i++) {
			print IXW "    <td valign=middle align=center>";
			$printdim = "$isiz[$rows*$opt_w+$i-1]" if $opt_as;
			$printdim = "$xdim[$rows*$opt_w+$i-1]x$ydim[$rows*$opt_w+$i-1]" if $opt_ad;
			$printdim = "$xdim[$rows*$opt_w+$i-1]x$ydim[$rows*$opt_w+$i-1] ($isiz[$rows*$opt_w+$i-1])" if $opt_a;
			print IXW $printdim;
			print IXW "</td>\n";
		}
		print IXW "  </tr>\n";
	}
	print IXW "</table>\n<br>\n";
}
while (!(<IXR> =~ m/\*{10}/)) {};
while (defined($line = <IXR>)) {
	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*.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;
}
