#!/usr/local/bin/perl

use Getopt::Std;

# By John Flynn - lynx@zorin.org. Started 6/15/2002
# Copyleft 2002,2004 
# Requires cjpeg, pnmscale, djpeg, pnmdepth, pnmtopng, pngtopnm, giftopnm
# (The latter three for PNGs)
# PNG support added by J. L. Blank <jlb@twu.net>
# GIF support added by J. L. Blank <jlb@twu.net>

# 1.06PNG: Zorin's changes involving preloading merged in (8/7/2004)
#          OFFICIAL RELEASE BRANCH
# 1.05PNG: PNG thumbnails done as JPEGs.
#          User has the option to turn off display of filenames.
#          Small space below image when no date (to better separate the images
#          and avoid confusion as regards "which image goes with which
#          caption".
#          GIF support.
#          Improved JPEG file detection (now detects any variant on "JPG" or
#             "JPEG" regardless of capitalization)
#          (8/03/2004) -- JLB
# 1.02PNG: Addition of filenames added (8/02/2004) -- JLB
# 1.01PNG: PNG support added. (8/02/2004) -- JLB

# This is hacker-ware. Distribution is completely free. You are encouraged
# to make improvements and distribute it further. I'd appreciate your sending
# me a copy of whatever improvements you make, though, as a diff.

# Makes a quick photo album.
# Image files: blah.jpg in the root directory
# Caption files: blah.jpg.txt in the root directory
# Album page descriptions: albumN-header.html in root dir where
#   N is the page number
# Album title: albumtitle.txt in root dir

# Options:
#  -d : If no caption, insert file date

getopts("hrfnpPvdDlt:s:T:S:H:W:");


# Defaults
$imageswide=4;
$imageshigh=3;
$smallerquality=85;
$thumbquality=75;
$smallersize=500000;
$thumbsize=22000;
$srcdirectory=".";
# Page colors
$bgcolor="#222222";
$textcolor="#FFFFFF";
$linkcolor="#9999CC";
$vlinkcolor="#CCCC99";
$alinkcolor="#CCCCCC";
$tablebgcolor="#333333";
if ($opt_h) {
	print STDERR "Usage: makealbum2.pl [ options ]\n\nPage generation options:\n(You must delete the album*.html files and imagepages directory if you don't\n want stray files when the number of images is reduced.)\n\n -W <n>: n images wide per page (default: $imageswide)\n -H <n>: n images high per page (default: $imageshigh)\n -d: Add date to images with no caption\n -r: Reverse sort the album\n -D: Sort (or reverse sort) by date\n -h: You're looking at it\n -n: Display filenames above each thumbnail.\n -l: Make links to other directories containing albums\n -p: Generate seperate HTML pages for each image to allow for navigation\n -P: Include HTML to 'preload' next and previous images on each HTML page generated with -p\n -v: Be verbose (VERY SPAMMY!!)";
	print STDERR "\nOptions for thumbnails and smaller images:\n(You must delete the thumbs and smaller directories before re-running with\nthese options changed.)\n\n -s <n>: Smaller image size (in total pixels) Default: $smallersize\n -t <n>: Thumbnail image size (in total pixels) Default: $thumbsize\n -S <n>: Smaller image quality (1-100), default is $smallerquality\n -T <n>: Thumbnail quality (1-100), default is $thumbquality\n -f: DON'T create \"smaller\" images. Make links to the full sized image only.\n";
	exit(0);
}

if ($opt_W) {
	$imageswide=$opt_W;
}

if ($opt_H) {
	$imageshigh=$opt_H;
}


if ($opt_n) {
        $DISPLAY_FILENAMES = 1;
} else {
        $DISPLAY_FILENAMES = 0;
}

if ($opt_d) {
	$insertdate=1;
} else {
	$insertdate=0;
}

if ($opt_D) {
	$sortbydate=1;
} else {
	$sortbydate=0;
}

if ($opt_p) {
	$seperatepages=1;
} else {
	$seperatepages=0;
}

if ($opt_P) {
        $preload=1;
} else {
        $preload=0;
}


if ($opt_T) {
        if ($opt_T < 1 || $opt_T > 100) {
                print STDERR "Qualities must be between 1 and 100! Exiting...\n";
                exit(1);
        }

	$thumbquality=$opt_T;
}

if ($opt_S) {
	if ($opt_S < 1 || $opt_S > 100) {
		print STDERR "Qualities must be between 1 and 100! Exiting...\n";
		exit(1);
	}
	$smallerquality=$opt_S;
}

if ($opt_t) {
        if ($opt_t < 1) {
                print STDERR "Image size must be greater than 1! (preferably greater than 1000) Exiting...\n";
                exit(1);
        }
	$thumbsize=$opt_t;
}

if ($opt_s) {
        if ($opt_s < 1) {
                print STDERR "Image size must be greater than 1! (preferably greater than 1000) Exiting...\n";
                exit(1);
        }
	$smallersize=$opt_s;
}

if ($opt_r) {
	$reversesort=1;
} else {
	$reversesort=0;
}

sub by_file_date {
	($dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$mtimea,$dud,$dud,$dud) = stat "$srcdirectory/$a";	
	($dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$mtimeb,$dud,$dud,$dud) = stat "$srcdirectory/$b";	
	($mtimea <=> $mtimeb);
}



# Get the album's title
#$albumtitle = `cat $srcdirectory/albumtitle.txt`;
if ( -e "$srcdirectory/albumtitle.txt" ) {
	open (TITLE,"$srcdirectory/albumtitle.txt");
	while (<TITLE>) {
		$line=$_;
		chomp($line); # Fucking newlines...
		$albumtitle = $albumtitle . $_;
	}
} else {
	$albumtitle = "Photo Album";
}

# First, let's shove all the files in the current directory into an array.
# They will be shoved in alphabetical order; this is how the order in
# the album will be determined.

$imagecount=0;
opendir (DIR, $srcdirectory);
while (defined($srcfile = readdir(DIR))) {
	# jpe? I dunno what software uses this extension for jpegs, but..hey
	if ($srcfile =~ /.*([Jj][Pp][Ee]?[GgEe]|[Pp][Nn][Gg]|[Gg][Ii][Ff])$/) {  # only deal with jpg, gif, png
		push @IMAGELIST,$srcfile;
		++$imagecount;
	}

	# If it's a directory, see if there's an album in it.
	# If so, add it to the dirlist.
	if ( $opt_l && -d $srcfile && -e "$srcfile/album1.html" && !($srcfile eq ".")) {
		push @DIRLIST,$srcfile;
		$dirs=1;
	}
}

if ($sortbydate) {
	@IMAGELIST = sort by_file_date (@IMAGELIST);
} else {
	@IMAGELIST = sort (@IMAGELIST);
}

if ($reversesort) {
	@IMAGELIST = reverse(@IMAGELIST);
}

# Create the "smaller" and "thumbs" directories if they don't exist already. 

if (!$opt_f) {
	mkdir "$srcdirectory/smaller", 0755 unless -d "$srcdirectory/smaller";
}
mkdir "$srcdirectory/thumbs", 0755 unless -d "$srcdirectory/thumbs";
if ($seperatepages) {
	mkdir "$srcdirectory/imagepages", 0755 unless -d "$srcdirectory/imagepages";
}

# Find out how many pages there will be and round the number up.
$imagesperpage = $imageswide * $imageshigh;
$totalpages=$imagecount / $imagesperpage;
if ($totalpages != int($totalpages)) {
	$totalpages = int($totalpages) + 1;
}

# Make smaller versions of all the images. Might as well get it over
# with.

print STDERR "...creating thumbnails. This may take a while!\n" unless !$opt_v;
foreach $image (@IMAGELIST) {
		print "Processing $image...";
	if (!$opt_f) {

                if ($image =~ /[Pp][Nn][Gg]$/) { # PNG
   		   system("pngtopnm -mix -background=rgb:22/22/22 \"$srcdirectory/$image\" | pnmscale -pixels $smallersize |pnmtopng > \"$srcdirectory/smaller/$image\"") unless -e "$srcdirectory/smaller/$image";
                } else {
                  if ($image =~ /[Gg][Ii][Ff]$/) { # GIF
      		      system("giftopnm \"$srcdirectory/$image\" | pnmdepth 24 | pnmscale -pixels $smallersize | cjpeg -quality $smallerquality > \"$srcdirectory/smaller/$image\"") unless -e "$srcdirectory/smaller/$image";
                  } else { # JPEG, presumably
      		      system("djpeg \"$srcdirectory/$image\" | pnmscale -pixels $smallersize |cjpeg -quality $smallerquality > \"$srcdirectory/smaller/$image\"") unless -e "$srcdirectory/smaller/$image";
                  }
                }
	}
        if ($image =~ /[Pp][Nn][Gg]$/) { # PNG
	system("pngtopnm -mix -background=rgb:33/33/33 \"$srcdirectory/$image\" | pnmscale -pixels $thumbsize | pnmdepth 24 | cjpeg -quality 90 > \"$srcdirectory/thumbs/${image}.jpg\"") unless -e "$srcdirectory/thumbs/${image}.jpg";
        } else {
           if ($image =~ /[Gg][Ii][Ff]$/) { # GIF
  	      system("giftopnm \"$srcdirectory/$image\" | pnmdepth 24 | pnmscale -pixels $thumbsize |cjpeg -quality $thumbquality > \"$srcdirectory/thumbs/$image\"") unless -e "$srcdirectory/thumbs/$image";
           } else { # JPEG, presumably
  	      system("djpeg \"$srcdirectory/$image\" | pnmscale -pixels $thumbsize |cjpeg -quality $thumbquality > \"$srcdirectory/thumbs/$image\"") unless -e "$srcdirectory/thumbs/$image";
           }
        }
	print "\n";
}

# If we DON'T want smaller images, make the $smaller variable . so that
# This directory name isn't provided.
if ($opt_f) {
	$smaller=".";
} else {
	$smaller="smaller";
}

# Now let's create all the HTML pages.

$currentimagenum=0;
for ($pagenum=1;$pagenum<=$totalpages;++$pagenum) {

	print STDERR "...Writing out $srcdirectory/album$pagenum.html\n" unless !$opt_v;
	open (HTMLFILE,">$srcdirectory/album$pagenum.html"); 
	print HTMLFILE "<!-- Automatically generated HTML, don't edit -->\n";
	print HTMLFILE "<html><head><title>$albumtitle - Page $pagenum</title></head>\n";
	print HTMLFILE "<body bgcolor=\"$bgcolor\" text=\"$textcolor\" link=\"$linkcolor\"  vlink=\"$vlinkcolor\"  alink=\"$alinkcolor\">\n";

	print HTMLFILE "<center><h2>$albumtitle</h2></center>\n";
	# Make links to other directories that have albums.
	if ($dirs) {
		print HTMLFILE "<center><p>Other Directories: ";
		foreach $dir (@DIRLIST) {
			print HTMLFILE "<a href=\"$dir/album1.html\">$dir</a> ";
		}
		print HTMLFILE "</p></center>";
	}


	# Make the "navigator" line
	$navigator= "<center>";
	
	if ($pagenum!=1) {
		$navigator = $navigator . "<a href=\"album" . ($pagenum-1) .".html\">&lt&lt</a> ";
	}

	$navigator = $navigator . "Go to page: ";
	for ($i=1; $i <= $totalpages; ++$i) {
		if ($pagenum==$i) {
			$navigator = $navigator . "$i ";
		} else {
			$navigator = $navigator .  "<a href=\"album$i.html\">$i</a> ";
		}
	}
	
	if ($pagenum!=$totalpages) {
		$navigator = $navigator . " <a href=\"album" . ($pagenum+1) .".html\">&gt&gt</a>";
	}
	$navigator = $navigator .  "</center>";


	# If there's an albumN-header.html file, print its contents before the images.
	if ( -e "$srcdirectory/header-album$pagenum.html" ) {
		open (HEADER,"$srcdirectory/header-album$pagenum.html");
		foreach (<HEADER>) {
			print HTMLFILE "$_\n";
		}

		print HTMLFILE "<br>\n";
	}
	print HTMLFILE "<p>$navigator</p>";
	# Now let's put $imagesperpage images on the page. If we run out of
	# images, just stop there.

	print HTMLFILE "<center><table border=\"0\" width=\"95%\"><tr>\n";	
	for ($i=1 ; $i <= $imagesperpage ; ++$i) {
		if ( -f "$srcdirectory/$IMAGELIST[$currentimagenum]" ) {
			if ($seperatepages) {
				# Open the upcoming HTML image file
				print STDERR "...writing out $srcdirectory/imagepages/$IMAGELIST[$currentimagenum].html\n" unless !$opt_v;
				open (IMAGEHTMLFILE,">$srcdirectory/imagepages/$IMAGELIST[$currentimagenum].html");
				# Write the HTML that links to the page
				print HTMLFILE "<td bgcolor=\"$tablebgcolor\" valign=\"top\"><center>";
                                if ($DISPLAY_FILENAMES == 1) {
                                   print HTMLFILE "<div style=\"font-family: Arial, Helvetica, Sans-Serif, Sans Serif; line-height: 2;\"><font size=\"-2\"><a href=\"$srcdirectory/$smaller/$IMAGELIST[$currentimagenum].html\" style=\"text-decoration: none; color: #EEEEEE;\">$IMAGELIST[$currentimagenum]</a></font><br></div>";
                                }
                                print HTMLFILE "<a href=\"$srcdirectory/imagepages/$IMAGELIST[$currentimagenum].html\"><img src=\"$srcdirectory/thumbs/$IMAGELIST[$currentimagenum]";
                                if ($IMAGELIST[$currentimagenum] =~ /png$/i) {
                                   # Image is a PNG.. but thumb is a jpeg
                                   print HTMLFILE ".jpg";
                                }
                                print HTMLFILE "\" border=0></a><br><font size=-3><a href=\"$srcdirectory/$IMAGELIST[$currentimagenum]\">fullsized</a>";
				if (!$opt_f) {
					print HTMLFILE " | <a href=\"$srcdirectory/$smaller/$IMAGELIST[$currentimagenum]\">websized</a>";
				}
				print HTMLFILE "<br></font>";
			} else {
				print HTMLFILE "<td bgcolor=\"$tablebgcolor\" valign=\"top\"><center>";
                                if ($DISPLAY_FILENAMES == 1) {
                                   print HTMLFILE "<div style=\"font-family: Arial, Helvetica, Sans-Serif, Sans Serif; line-height: 2;\"><font size=\"-2\"><a href=\"$srcdirectory/$smaller/$IMAGELIST[$currentimagenum]\" style=\"text-decoration: none; color: #EEEEEE;\">$IMAGELIST[$currentimagenum]</a></font><br></div>";
                                }
                                print HTMLFILE "<a href=\"$srcdirectory/$smaller/$IMAGELIST[$currentimagenum]\"><img src=\"$srcdirectory/thumbs/$IMAGELIST[$currentimagenum]";
                                if ($IMAGELIST[$currentimagenum] =~ /png$/i) {
                                   # Image is a PNG.. but thumb is a jpeg
                                   print HTMLFILE ".jpg";
                                }
                                print HTMLFILE "\" border=0></a><br><font size=-3><a href=\"$srcdirectory/$IMAGELIST[$currentimagenum]\">fullsized</a>";
                                if (!$opt_f)  {
                                        print HTMLFILE " | <a href=\"$srcdirectory/$smaller/$IMAGELIST[$currentimagenum]\">websized</a>";
                                }
                                print HTMLFILE "<br></font>";

			}
	
			if ($seperatepages) {
				print IMAGEHTMLFILE "<html><head><title>$IMAGELIST[$currentimagenum]</title></head><body bgcolor=\"$bgcolor\" text=\"$textcolor\" link=\"$linkcolor\"  vlink=\"$vlinkcolor\"  alink=\"$alinkcolor\"><center>\n";
				print IMAGEHTMLFILE "<p>";

				# Print "navigation" bar. Note, if sort was reversed, print it
				# Backwards so previous and next still make sense.
				if ($reversesort) {
					$qualifier=-1;
				} else {
					$qualifier=1;
				}
				if ((0 <= ($currentimagenum-$qualifier)) && (($currentimagenum-$qualifier) < $imagecount)) {
					print IMAGEHTMLFILE "<a href=\"$IMAGELIST[$currentimagenum-$qualifier].html\">&lt&lt Previous Image</a> | ";
				}
				print IMAGEHTMLFILE "<a href=\"../album$pagenum.html\">Back to Album</a>";
				if ((0 <= ($currentimagenum+$qualifier)) && (($currentimagenum+$qualifier) < $imagecount)) {
					print IMAGEHTMLFILE " | <a href=\"$IMAGELIST[$currentimagenum+$qualifier].html\">Next Image &gt&gt</a>";
				}
				print IMAGEHTMLFILE "</p>";
				print IMAGEHTMLFILE "<p><a href=\"../$IMAGELIST[$currentimagenum]\"><img border=0 src=\"../$smaller/$IMAGELIST[$currentimagenum]\"></a></p>\n";
			}
			
			# If there is a caption file, throw it in.
			if ( -e "$srcdirectory/$IMAGELIST[$currentimagenum].txt" ) {
				open (CAPTION,"$srcdirectory/$IMAGELIST[$currentimagenum].txt");
				foreach (<CAPTION>) {		
					chomp ($_);
					print HTMLFILE "<font size=-1>$_</font>";
					if ($seperatepages) {
						print IMAGEHTMLFILE "<p>$_</p>\n";
					}
				}
			} else {
				if ($insertdate) {
					($dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$dud,$mtime,$dud,$dud,$dud) = stat "$srcdirectory/$IMAGELIST[$currentimagenum]";
					($sec,$min,$hour,$mday,$mon,$year,$dud,$dud,$dud)=localtime($mtime);
					$year += 1900;
					++$mon;
					$datestring="$mon/$mday/$year";
					print HTMLFILE "<font size=-2></font><font size=-1>$datestring</font>";
					if ($seperatepages) {
						print IMAGEHTMLFILE "<p>$datestring</p>\n";
					}
				} else {
                                   print HTMLFILE "<font size=\"-3\"><br></font>";
                                }
			}
			if ($seperatepages) {
                                # Preload next and previous pic
                                if ($preload) {
                                        print IMAGEHTMLFILE "<p><img height=0 width=0 border=0 style=\"display: none\" src=\"../$smaller/$IMAGELIST[$currentimagenum + 1]\"><img height=0 width=0 border=0 style=\"display: none\" src=\"../$smaller/$IMAGELIST[$currentimagenum - 1]\"></p>";
                                }
				print IMAGEHTMLFILE "</center></html>";
				close (IMAGEHTMLFILE);
			}

			++$currentimagenum;
			++$imagesonthisline;
			print HTMLFILE "</td></center>\n";
			if ($imagesonthisline >= $imageswide) {
				print HTMLFILE "</tr><tr>";
				$imagesonthisline = 0;
			}
		} else {
			break;
		}	
	}
	print HTMLFILE "</tr></table></center>\n";
	print HTMLFILE "<p>$navigator</p>\n";
	print HTMLFILE "<p><center><font size=-3>Page created with <a href=\"http://www.cs.fiu.edu/~flynnj/makealbum2/\">makealbum2.pl</a></font></center></p>\n";
	print HTMLFILE "</html>\n";
	close (HTMLFILE);
}
	print STDERR "Album created with $totalpages pages, $imagecount images.\n";

