#!/usr/bin/perl

print "Content-type: text/html\n\n";
$curdir=`pwd`;
chomp $curdir;
$curdir=~s:^/home/www/html::;

if ( -e "gallery.header" &&
    open(HEADER, "gallery.header")) {
	while (<HEADER>) {
		print "$_\n";
	}
	close (HEADER);
} else {
	print "<HTML>\n<HEAD><TITLE>Gallery</TITLE></HEAD>\n";
	print "<BODY>";
	print "<H1>Art Gallery</H1><P>\n\n";
}


mkdir("thumbs",0755) if(! -e "thumbs");
mkdir("big",0755) if(! -e "big");

opendir(DIR,".");
opendir(BIGDIR,"big");

print "<TABLE>\n";

$count = 0;

$lastfile = "";

foreach $n (sort(readdir(DIR),readdir(BIGDIR))) {
	next if ($n eq $lastfile);
	$lastfile = $n;
	if ($n=~/jpe?g$/ ||
	    $n=~/JPE?G$/) {
		$command = "djpeg big/$n | pnmscale -xysize 100 100 | " .
			"cjpeg > thumbs/$n";
		$commandbig = "djpeg $n | pnmscale -xysize 800 600 | " .
			"cjpeg > big/$n";
	} elsif ($n=~/gif$/ ||
	         $n=~/GIF$/) {
		$command = "giftopnm big/$n | pnmscale -xysize 100 100 | " .
			"pnmtogif > thumbs/$n";
		$commandbig = "giftopnm $n | pnmscale -xysize 800 600 | " .
			"pnmtogif > big/$n";
	} elsif ($n=~/png$/ ||
	         $n=~/PNG$/) {
		$command = "pngtopnm big/$n | pnmscale -xysize 100 100 | " .
			"pnmtopng > thumbs/$n";
		$commandbig = "pngtopnm $n | pnmscale -xysize 800 600 | " .
			"pnmtopng > big/$n";
	} elsif ($n=~/mpg$/ ||
	         $n=~/MPG$/ ||
		 $n=~/mpeg$/ ||
	         $n=~/MPEG$/ ||
		 $n=~/avi$/ ||
	         $n=~/AVI$/ ||
		 $n=~/mov$/ ||
	         $n=~/MOV$/) {
		print "<TR>" if(($count++ % 6) == 0);
		print "<TD><A HREF=\"$n\">$n<BR>(movie)</A>\n";
		next;
	} else {
		next;
	}

	print "<TR>" if(($count++ % 6) == 0);
	print "<TD><A HREF=\"view.cgi?$n\"><IMG SRC=\"thumbs/$n\"><BR>$n</A>\n";
	
	if ( ! -e "big/$n" ) {
		system $commandbig;
	} elsif ( -e $n ) {
		@ts = stat("big/$n");
		@s = stat($n);

		system $commandbig if($ts[9]<$s[9]);
	}
	if ( ! -e "thumbs/$n" ) {
		system $command;
	} elsif ( -e "big/$n" ) {
		@ts = stat("thumbs/$n");
		@s = stat("big/$n");

		system $command if($ts[9]<$s[9]);
	}

	unlink $n if ( -e $n );
}

print "</TABLE>\n";

closedir DIR;
closedir BIGDIR;

if (-e gallery.footer &&
    open(FOOTER, "gallery.footer")) {
	while (<FOOTER>) {
		print "$_\n";
	}
	close (FOOTER);
} else {
	print "</BODY>\n</HTML>\n";
}
