#!/usr/bin/perl

# Generates a small fragment of HTML to present a collection of images.
#
# Arguments are:
#  ID value for DIV section in HTML fragment
#  Size of thumbnails, for example 100x100 or 128x80
#  All other arguments are the names of the directories containing the images
#
# Thumbnails are automatically generated and placed in a .thumbs directory
# alongside the existing iamges.


use Image::Magick;

$id = "photos";
@gm = ();

# Parse arguments
while($arg = shift @ARGV)
{
    SWITCH:
    {
	$id         = (shift @ARGV), last SWITCH if $arg eq "-id";
	$gm[$#gm+1] = (shift @ARGV), last SWITCH if $arg eq "-geom" || $arg eq "-geometry";
	$dn[$#dn+1] = $arg;
    }
}

print "<div class=\"thumbs\" id=\"$id\">\n";

$gm[0]="128x128" if $#gm<0;
$thumb = $gm[0];
@gm = sort {$a <=> $b} @gm;

foreach my $dn (@dn)
{
    $image= Image::Magick->new;
    if(opendir(dh, $dn))
    {
	FILE: foreach $fn (grep(-f "$dn/$_" && -r "$dn/$_" && !/.*~$/ && !/.*html$/, sort readdir(dh)))
	{
	    foreach $gm (@gm)
	    {
		if(((-d "$dn/.$gm") || (mkdir "$dn/.$gm")) && !(-f "$dn/.$gm/$fn.jpg"))
		{
		    undef $image;
		    $image = Image::Magick->new;
		    next FILE if $image->Read("$dn/$fn");
		    
		    $image->Scale(geometry=>$gm);
		    $avg = $image->Average();
		    if(ref($avg))
		    {
			undef $image;
			$image = $avg;
		    }
		    $image->Write("$dn/.$gm/$fn.jpg");
		}
	    }
	    
	    print "<table><tr><td>\n";	    
	    if(-f "$dn/.$thumb/$fn.jpg")
	    {
		undef $image;
		my $image = Image::Magick->new;
		($width, $height) = $image->Ping("$dn/.$thumb/$fn.jpg");
		print "<a href=\"$dn/$fn\">";
		print "<img src=\"$dn/.$thumb/$fn.jpg\" width=\"$width\" height=\"$height\">";
		print "</a>\n";
	    }
	    else
	    {
		print "<a href=\"$dn/$fn\">$fn</a>\n";
	    }
	    print "</td></tr><tr><td>\n";
	    foreach $gm (@gm)
	    {
		print "<a href=\"$dn/.$gm/$fn.jpg\">$gm</a>\n" if -f "$dn/.$gm/$fn.jpg";
	    }
	    print "</td></tr></table>\n";
	}
	closedir dh;
    }
}

undef $image;

print "</div>\n";
