#!/usr/bin/perl

open OUTFILE,">index.tmp.html";

print OUTFILE "<html><head><title>Pictures</title></head>\n";
print OUTFILE "<body><table align=center cellpadding=9>\n";
opendir DIR,".";
$dircount = 0;
$needsclosing = 0;
@dirlist = readdir DIR;
@sorteddir = sort @dirlist;

for($i = 0; defined $sorteddir[$i]; $i++) {
	$curname = $sorteddir[$i];
	if( grep(/^\./,$curname) ) {
		next;
	}
	
	$isblacklisted = 0;
	open BLACKLIST,"<blacklist.txt";
	while(<BLACKLIST>) {
		chomp;
		if( $curname eq $_ ) {
			$isblacklisted = 1;
			last;
		}
	}
	close BLACKLIST;

	if( $isblacklisted ) {
		next;
	}

	if( -d $curname ) {
		if( $dircount % 3 == 0 ) {
			if( $needsclosing ) {
				print OUTFILE "</tr>";
			}
			print OUTFILE "<tr>"
		}
		$dircount++;
		print OUTFILE "<td>\n";
		print OUTFILE "<a href=\"$curname\">";
		$foundthumb = 0;
		$founddesc = 0;
		if( -d "$curname/thumbnails" ) {
			opendir THUMBDIR, "$curname/thumbnails";
			while( $curthumb = readdir THUMBDIR ) {
				if( grep(/^\./,$curthumb) ) {
					next;
				}
				$foundthumb = 1;
				$thumbpath = "$curname/thumbnails/$curthumb";
				last;
			}
			close THUMBDIR;
		}
		if( -f "$curname/desc.txt" ) {
			open DESCFILE, "<$curname/desc.txt";
			$desc = <DESCFILE>;
			close DESCFILE;
			$founddesc = 1;
		}
		if( $foundthumb ) {
			print OUTFILE "<img src=\"$thumbpath\"><br>";
		}
		if( $founddesc ) {
			print OUTFILE $desc;
		} else {
			print OUTFILE "$curname";
		}
		print OUTFILE "</a>\n";
		print OUTFILE "</td>";
	}
}
print OUTFILE "</tr></table></body></html>";
closedir DIR;
close OUTFILE;
unlink "index.bak.html";
rename "index.html","index.bak.html";
rename "index.tmp.html","index.html";
