#!/usr/bin/perl
# #################################################################
# make thumbnails from files in directory
# Vulcho Nedelchev: <kumcho@vulcho.com>
#
# USAGE: Just put it in the directory contains the images and don't
# forget to set up your webserver to execute this script.
# 
# Have a nice day ;)
#
# #################################################################
use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser);

my $cgi      = new CGI;
my $width    = 100;
my $height   = 100;
my $prefix   = 'thumb_';
my $htmlname = 'index.html';
my $title    = 'My Gallery';
my $htmlcols = 4;

opendir(IMG, ".") or die "Cannot open dir: $!\n";
my @images = grep{/\.png|\.gif|\.jpg$/i}readdir(IMG);
closedir IMG;

# Make thumbs here and store it into array 
# for later make HTML index page to display thumbs.
my @thumbed;
for my $image (sort @images)
{
    my $thumb_name = $prefix.$image;
    next if $image =~ /^$prefix/;
    push @thumbed, $thumb_name;
    next if -f $thumb_name;
    eval{system("/usr/bin/convert", "-resize", $width.'x'.$height, $image, $thumb_name) };
    die "$@ kurec" if $@;
};

# Make an html page that contains all thumbnails on it
# as hyper links and display it.
my $html =
    $cgi->start_html(-title=>$title,
		     -bgcolor=>'#cccccc',
		     -style=>{'src'=>'/thumbs.css'},)."\n".
    $cgi->h2({-align=>'center'},$title)."\n".
    $cgi->start_table({-align=>'center',-cellspacing=>1,-cellpading=>1,-bgcolor=>'#aaaaaa'})."\n".
    $cgi->td({-colspan=>$htmlcols, -bgcolor=>'#bbbbbb'},$cgi->a({-href=>"../"},'Directory Up'));

my $rows = int(scalar @thumbed/$htmlcols) + 1;
$htmlcols = scalar @thumbed if scalar @thumbed < $htmlcols;

for (1..$rows)
{
    $html.= $cgi->start_Tr."\n";
    for (1..$htmlcols)
    {
	my($file, $src);
	
	$file = shift @thumbed;
	$file=~ /$prefix(.*?)$/;
	$src = $1;
	
	$html.= $cgi->td({-align=>"center",-valign=>"top",-bgcolor=>'#cccccc'});
	$html.= 
	    ($file and $src)
	    ? $cgi->a({-href=>$src,-title=>$src,-border=>'0'},
		      $cgi->img({-alt=>$file,-src=>$file,-border=>'0'})).
		      "<br><font size=-1>".
		      $cgi->a({-href=>$src,-title=>$src}, $src).
		      "</font>"
	    : '&nbsp';
	$html.= $cgi->end_td."\n";
    };
    $html.= $cgi->end_Tr."\n";
};
$html.=
    $cgi->td({-colspan=>$htmlcols, -bgcolor=>'#bbbbbb', -align=>'center'},
	     $cgi->a({-href=>"http://www.vulcho.com/"},
		     '<b>Copyright Vulcho.com 2003</b>')).
    $cgi->end_table."\n".
    $cgi->end_html;

# We have created an html document and now we will
# store the page as file
#open  HTML, "> $htmlname" or die "Cannot open $htmlname";
#print HTML $html;
#close HTML;

print 
    $cgi->header,
    $html;