#!/usr/bin/perl

####################################################################
# Mike's Photo Gallery Script
# Version 2.6
# 
# This script is part of Mike's Perl Script Archive at
# www.mikespice.com/perl/
#
# This script allows you to easily create and maintain photo collections
# on the web. Simply FTP up your pictures and directories, and
# the thumbnails, and pages are all generated for you.
####################################################################

#if you had to install Image Magick as NON-root, please add the
# use lib line
#use lib "";
BEGIN {
    open(STDERR,">/tmp/indexlog");
}

use CGI qw(:standard);
use Image::Magick;
if($exif=~ /yes/i){
    use Image::Info qw(image_info);
}
require "common.pl";
require "sitevariables.pl";
srand();
############ BEGIN MAIN PROGRAM ################################
$cur = CGI->new();
$mode = "default";
if($cur->param("mode")) {
	$mode = $cur->param("mode");
}
if($cur->param("album")) {
	$selectedalbum = $cur->param("album");
	$htmlalbum = $selectedalbum;
	$htmlalbum =~ s/ /%20/g;
}
if($cur->param("picture")) {
	$selectedpicture= $cur->param("picture");
	$htmlpicture = $selectedpicture;
	$htmlpicture =~ s/ /%20/g;
}
if($cur->param("movie")) {
	$selectedmovie = $cur->param("movie");
	$htmlmovie = $selectedmovie;
	$htmlmovie =~ s/ /%20/g;
}
if($cur->param("maxWidth")) {
	$maxWidth= $cur->param("maxWidth");
	print "Set-Cookie: maxWidth=$maxWidth\n"; #set a cookie for the maxWidth preference
} else {
	$maxWidth = 640;

	#check for cookie
	if($ENV{'HTTP_COOKIE'}) { #get cookie and set it as the customer_id
		@cookies=split(/;/,$ENV{'HTTP_COOKIE'});
		foreach $cookie (@cookies) {
			($name,$value) = split (/=/,$cookie);
			$crumbs{$name}=$value;
		}
		if($crumbs{"maxWidth"}){$maxWidth = $crumbs{"maxWidth"};}
	}
}
printstarthtml();
if($selectedalbum =~ /\.\./){
    dienice("Bad boy!  Don't do that please!");
}
checkforbadthings();
if($mode eq "default"){
	#open news.html for display on the main page 
	open (INFILE, "news.html")|| ($news = "Cound not open news file!");
	flock (INFILE, 2);
	while(<INFILE>){
		$news .= $_;
	}
	close(INFILE);

	$content = "
<br><br>
$news
";
	printpage2($content);
}
if($mode eq "view"){
	checkdirectories(); #check for thumbnail and descriptions directories
	$content = generatealbum2("$selectedalbum"); 
	printpage2($content);
}
if($mode eq "viewpicture"){
	if($cur->param("comment")){
		getcomment();
	}
	$content = generatepicture($selectedalbum,$selectedpicture); 
	printpage2($content);
}
if($mode eq "viewmovie"){
	if($cur->param("comment")){
		getcomment();
	}
	$content = generatemovie($selectedalbum,$selectedmovie); 
	printpage2($content);
}
if($mode eq "search"){
	if($cur->param("q")){
		$q=$cur->param("q");
	}
	$content .= searchpicturenames($q);
	$content .= "<br>searched for \"$q\".";
	printpage2($content);
}


printendhtml();

############ BEGIN SUBROUTINES #################################


sub printpage2 {
	my @albums = glob "$photoroot/*/"; #returns all of the directories
	my $album;
	my $albumcount=0;

	#begin main table
	print "<center>";
	print "<table bgcolor=#FFFFFF width=$defaultwidth border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=$rowcolor valign=\"top\" width=200>";

	#begin side table with album list
	print "<table border=0 cellspacing=0 cellpadding=0 width=100%>";
	foreach $album (sort @albums){
		unless($album eq "$photoroot/site-images/" 
                || $album eq "$photoroot/thumbnails/" 
                || $album eq "$photoroot/protected/" 
                || $album eq "$photoroot/descriptions/"){
			fileinfo($album);
			$albumcount++;
			$albumcount2++; #for albumwrap
			$album =~ s#.*/(.*)/#\1#;  #leaves only directory names
			my ($prettyalbum) = $album;
			$prettyalbum =~ s/_/ /g;
			if($selectedalbum =~ /^$album/) {
				$album =~ s/ /+/g;
				print "<tr><td></td><td></td><td align=right valign=bottom><img src=\"$htmlroot/site-images/corner_top_right.gif\"></td></tr>";
				print "<tr>
				<td align=right>
					<table border=0 cellspacing=0 cellpadding=0>
						<tr><td align=right valign=top><img src=\"$htmlroot/site-images/corner_top_left.gif\"></td></tr>
						<tr><td bgcolor=#FFFFFF>&nbsp;</td></tr>
						<tr><td align=right valign=bottom><img src=\"$htmlroot/site-images/corner_bottom_left.gif\"></td></tr>
					</table>
				</td>
				<td bgcolor=#FFFFFF><a href=index.cgi?album=$album&mode=view><font color=$textcolor>$prettyalbum</font></a><br><font size=-2 color=red>Updated: $time</font></td>
				<td bgcolor=#FFFFFF>&nbsp;</td></tr>";
				print "<tr><td></td><td></td><td align=right valign=bottom><img src=\"$htmlroot/site-images/corner_bottom_right.gif\"></td></tr>";
		
			}else{
				$album =~ s/ /+/g;
				print "<tr><td></td><td>&nbsp;</td><td></td></tr>"; # horizontal line in table
				print "<tr>
				<td>&nbsp;</td>
				<td><a href=index.cgi?album=$album&mode=view><font color=$textcolor>$prettyalbum</font></a><br><font size=-2 color=red>Updated: $time</font></td>
				<td>&nbsp;</td></tr>";
				print "<tr><td></td><td>&nbsp;</td><td></td></tr>"; # horizontal line in table
			}
		}
	}

	
	print "<tr><td></td><td><hr></td><td></td></tr>"; # horizontal line in table
	print "<tr><td></td><td><form method=post>
	<input type=hidden name=mode value=search>
	<input type=text name=q size=10>
	<input type=submit value=search>
	</form></td><td></td></tr>";

	#end side table with album list
	print "</table>";

	#end main table
	print "</td><td valign=top>";
    #	my $shutterflytext;
    #	if($allowshutterfly eq 'YES'){
    #		$shutterflytext="<hr>
    #		<img src=$htmlroot/site-images/printsbyshutterfly.gif align=left><font size=-1>
    #		This gallery has support for Shutterfly. Click the \"order this photo\" button to quickly and easily order high-quality photographic prints of your favorite pictures
    #                through Shutterfly.com";
    #	}
	print <<HTML;
$_[0]
</td></tr>
</table>
HTML
}

sub generatealbum2 ($) {
    my $return;
    #sanity check
    if(!$selectedalbum){
		dienice("No album was selected");
	}
    my $selectedalbum = $_[0];
	$return .= print_location($selectedalbum);    
    
    $_[0] =~ s/ /\\ /g; #fix spaces for globbing and file opening
    
    ###########################################
    #get the hits and stuff for this album
    ###########################################
	my $hits = logpicture("$selectedalbum/");
	my $hitstring = "<font size =-1 color=blue>album viewed <b>$hits</b> times</font>";

    ###########################################
	#check for description of this album 
    ###########################################
	my $description;
	if(open (INFILE, "$photoroot/$selectedalbum/descriptions/album.txt")){ 
		$description .= '';
		flock (INFILE, 2); #locks the file for exclusive access.
		while(<INFILE>){
			$description .= "$_";
		}
		flock (INFILE, 8); #unlocks the file
		close(INFILE);
	}
	unless($description){
		$description ="No album description.";
	}
	$return .= "<center><table bgcolor=#000000 cellspacing=0 cellpadding=2 border=0>
			<tr><td align=middle>
			<table bgcolor=#e0e0e0 width=400 border=0 cellspacing=0 cellpadding=5>
				<tr>
					<td>$description
					<br>$hitstring</td>
				</tr>
			</table>
			</td></tr>
		</table></center>";

    $return .= "<table width=100% border=0 cellpadding=5 width=100%>";
	my @files= glob "$photoroot/$_[0]/*"; #find a better way to do this
    my $count =0;
    foreach $file (@files){
        if(-d $file){ # it is a directory
            unless (($file =~ /1024/)
            	||($file =~ /800/)
            	||($file =~ /640/)
            	||($file =~ /comments/)
            	||($file =~ /descriptions/)
            	||($file =~ /thumbnails/)){
            $file =~ s/.*\/(.*)/$1/g;
            my $cgihtmlalbum = $selectedalbum;
            $cgihtmlalbum =~ s/ /+/g;
            my $cgihtmlsubdirectory = $file;
            $cgihtmlsubdirectory =~ s/ /+/g;

			$count++;
			$return .= "<td align=middle><a href=\"index.cgi?mode=view&album=$cgihtmlalbum/$cgihtmlsubdirectory\"><img src=\"$htmlroot/site-images/folder-grey.jpg\" border=0></a><br><a href=\"index.cgi?mode=view&album=$cgihtmlalbum/$cgihtmlsubdirectory\"><font size=-1>$file</font></a></td>";
            }
        }elsif($file =~ /\.(jpg|png|gif)\b/i){ #this is a supported image format (jpeg,png, or gif)
            fileinfo($file);
            $file =~ s/.*\/(.*)/$1/g;

            ################################################
            # lets check for a thumbnail ###################
            ################################################
            my $thumbnail = $file;
            $thumbnail =~ s/(.*)\.(jpg|png|gif)\b/$1SMALL.jpg/i;
            unless(-e "$photoroot/$selectedalbum/thumbnails/$thumbnail"){
                #print "creating thumbnail for $thumbnail<br>\n";   
                my($imageToScale) = Image::Magick->new;
				my($itemToDisplay) = "$photoroot/$selectedalbum/$file";
				my($x) = $imageToScale->Read($itemToDisplay); # read in the picture
				warn "$x" if "$x";
                $imageToScale->Set(quality=>75);
				my($xSize, $ySize) = $imageToScale->Get('width', 'height'); # Get the pictures dimensions
				my($scaleFactor) = $xSize/$previewWidth;
				#print "$scaleFactor<br>";
				$x = $imageToScale->Scale(width=>($previewWidth), height=>($ySize/$scaleFactor)); #scale the image to the correct display size
				warn "$x" if "$x";
		
				$x = $imageToScale->Border(color=>'black',width=>2, height=>2);
				warn "$x" if "$x";
			
                if($mag_on_thumbnails =~ /yes/i){
                    ########################################################
                    # making a little picture of a magnifying glass on thumbs
                    ########################################################
                    my $image_overlay = Image::Magick->new();
                    $status = $image_overlay->Read("$photoroot/site-images/mag.png");
                    print "Error opening magnifying glass image to lay over the corner of your thumbnails: $status" if "$status";
                    $status = $imageToScale->Composite(
                        compose=>Over,
                        image=>$image_overlay,
                        gravity=>SouthEast
                    );
                    print "Error: $status" if "$status";
                    undef $image_overlay
                    ########################################################
                }
                
				#write out the thumbnail image file in JPEG format
				$x = $imageToScale->Write("$photoroot/$selectedalbum/thumbnails/$thumbnail");
				warn "$x" if "$x";
				
				undef $imageToScale;
            }
            my $cgihtmlalbum = $selectedalbum;
            $cgihtmlalbum =~ s/ /+/g;
            my $cgihtmlpicture = $file;
            $cgihtmlpicture =~ s/ /+/g;

            my $prettypicture = makepretty($file);

            #fix spaces for old netscape and such
            $thumbnail =~ s/ /%20/i;
            
            #NOTE to self: each line below has a <a> tag because the new
            #netscape was putting a funky line because of the line break
			$return .= "<td align=middle valign=center>
			<a href=\"index.cgi?album=$cgihtmlalbum&mode=viewpicture&picture=$cgihtmlpicture\">
			<img src=\"$htmlroot/$htmlalbum/thumbnails/$thumbnail\" width=\"$previewWidth\" alt=\"$file\" border=0></a>
			<br><a href=\"index.cgi?album=$cgihtmlalbum&mode=viewpicture&picture=$cgihtmlpicture\"><font size=-1>$prettypicture</a></font>
			<br><b></b><font color=green size=-2>$time</font></font></td>\n"; 
            $count++;
            #not to me....this line broken ... get extention and look it up to display icon
        }elsif( ($file =~ /.*(\..*)\b/i) && (defined $filetypes{"$1"})){
            fileinfo($file);
            my $ext = $1;
            $file =~ s/.*\/(.*)/$1/g;
            my $htmlfile = $file;
            $htmlfile =~ s/ /%20/g;
            $return .= "<td valign=center align=middle>
            <a href=\"$htmlroot/$htmlalbum/$htmlfile\"><img src=\"$htmlroot/site-images/$filetypes{\"$ext\"}\" border=0></a><br>
            <a href=\"$htmlroot/$htmlalbum/$file\"><font size=-1>$file</font></a><br>
            <font size=-2 color=green>$time ($kfilesize)</font>
            </td>";
            $count++;
        }else{ #we don't know what kind of file this is
            fileinfo($file);
            $file =~ s/.*\/(.*)/$1/g;
            my $htmlfile = $file;
            $htmlfile =~ s/ /%20/g;
            $return .= "<td valign=center align=middle>
            <a href=\"$htmlroot/$htmlalbum/$htmlfile\"><img src=\"$htmlroot/site-images/unknown.jpg\" border=0></a><br>
            <a href=\"$htmlroot/$htmlalbum/$file\"><font size=-1>$file</font></a><br>
            <font size=-2 color=green>$time ($kfilesize)</font>
            </td>";
            $count++;
        }
        if($count >= $thumbnails_per_row){
            $count =0;
            $return .= "\n</tr><tr>";
        }
    }
    $return .= "</table>";
    
    return $return;
}

sub generatealbum {
	my $return;
	if(!$selectedalbum){
		dienice("No album was selected");
	}	

	$return .= "Album: ";
	@steps = split (/\//,"$_[0]");
	foreach $step (@steps){
		if($not_the_first){$sofar .= "/$step";}else{$sofar .= "$step";}
		$not_the_first = 1;
		$return .="<a href=\"index.cgi?mode=view&album=$sofar\">$step</a> > ";
	}

	$_[0] =~ s/ /\\ /g;
	my $hits = logpicture("$selectedalbum/");
	my $hitstring = "<font size =-1 color=blue>album viewed <b>$hits</b> times</font>";

	#check for description of this album 
	my $description;
	if(open (INFILE, "$photoroot/$selectedalbum/descriptions/album.txt")){ 
		$description .= '';
		flock (INFILE, 2); #locks the file for exclusive access.
		while(<INFILE>){
			$description .= "$_";
		}
		flock (INFILE, 8); #unlocks the file
		close(INFILE);
	}
	unless($description){
		$description ="No album description.";
	}

	$return .= "<center><table bgcolor=#000000 cellspacing=0 cellpadding=2 border=0>
			<tr><td align=middle>
			<table bgcolor=#e0e0e0 width=400 border=0 cellspacing=0 cellpadding=5>
				<tr>
					<td>$description
					<br>$hitstring</td>
				</tr>
			</table>
			</td></tr>
		</table></center>";


	####################################################################################################
	# List all of the subdirectories in the directory.  
	#
	####################################################################################################
	my $subdirectory;
	my $subdirectorycount=0;
	my @subdirectories= glob "$photoroot/$_[0]/*/"; #find a better way to do this
	$return .= "<table width=100% border=0 cellpadding=5><tr>";
	foreach $subdirectory (sort @subdirectories) {
		if (-d $subdirectory 
				&&!($subdirectory =~ /1024/)
				&&!($subdirectory =~ /800/)
				&&!($subdirectory =~ /640/)
				&&!($subdirectory =~ /comments/)
				&&!($subdirectory =~ /descriptions/)
				&&!($subdirectory =~ /thumbnails/)){
			$subdirectory =~ s#(.*)/#$1#;
			$subdirectory =~ s#.*/##;
			my $cgihtmlalbum = $selectedalbum;
			$cgihtmlalbum =~ s/ /+/g;
			my $cgihtmlsubdirectory = $subdirectory;
			$cgihtmlsubdirectory =~ s/ /+/g;

			$subdirectorycount++;
			$return .= "<td align=middle><a href=\"index.cgi?mode=view&album=$cgihtmlalbum/$cgihtmlsubdirectory\"><img src=\"$htmlroot/site-images/folder-grey.jpg\" border=0></a><br><a href=\"index.cgi?mode=view&album=$cgihtmlalbum/$cgihtmlsubdirectory\">$subdirectory</a></td>";
			if($subdirectorycount >= ($thumbnails_per_row)){
				$subdirectorycount=0;
				$return .= "\n</tr>\n<tr>";
			}
		}
	}
	$return .="</tr></table>";

	####################################################################################################
	# List all of the pictures in the directory.  Must end in .jpg
	#
	####################################################################################################
	@pictures = glob ("$photoroot/$_[0]/*.jpg");
	#fix for people with .JPG extension insted of .jpg
	@pictures = (@pictures, glob ("$photoroot/$_[0]/*.JPG"));

	my $picture;
	my $picturecount=0;
	$return .= "<table border=0 width=100%>
<tr>";
	foreach $picture (sort @pictures) {
		unless (-d $picture){
			fileinfo($picture);
			$picturecount++;
			$picture =~ s#.*/##;

			#check for thumbnail and creat one if it doesn't exist
			my $thumbnail = $picture;
			$thumbnail =~ s#(.*)\.jpg#\1SMALL\.gif#;

			#create thumbnail if it doesnt exist or the thumbnail is older than the picture
			unless((-e "$photoroot/$selectedalbum/thumbnails/$thumbnail")){

                #print "Created thumbnail $selectedalbum/thumbnails/$thumbnail<br>"; #prints out text for each thumbnail created
				my($imageToScale) = Image::Magick->new;
				my($itemToDisplay) = "$photoroot/$selectedalbum/$picture";
				my($x) = $imageToScale->Read($itemToDisplay); # read in the picture
				warn "$x" if "$x";
				$imageToScale->Set(quality=>75);
				my($xSize, $ySize) = $imageToScale->Get('width', 'height'); # Get the pictures dimensions
				my($scaleFactor) = $xSize/$previewWidth;
				#print "$scaleFactor<br>";
				$x = $imageToScale->Scale(width=>($previewWidth), height=>($ySize/$scaleFactor)); #scale the image to the correct display size
				warn "$x" if "$x";
		
				$x = $imageToScale->Border(color=>'black',width=>2, height=>2);
				warn "$x" if "$x";
				
				#write out the thumbnail image file in JPEG format
				$x = $imageToScale->Write("$photoroot/$selectedalbum/thumbnails/$thumbnail");
				warn "$x" if "$x";
				
				undef $imageToScale;
			}

			if($picturecount >= ($thumbnails_per_row + 1)){
				$picturecount=1;
				$return .= "\n</tr>\n<tr>";
			}
			#take out all undesireable filename stuff.  Subroutine is responsable for
			#checking to see if the user specified to do this in the config file
			my ($prettypicture)= $picture;
			
			#fixing spaces for html for both cgi links and images 
			my $cgihtmlalbum = $selectedalbum;
			$cgihtmlalbum =~ s/ /+/g;
			my $cgihtmlpicture = $picture;
			$cgihtmlpicture =~ s/ /+/g;
			$thumbnail =~ s/ /%20/g;

			$prettypicture = makepretty($prettypicture);
            #NOTE to self: each line below has a <a> tag because the new
            #netscape was putting a funky line because of the line break
			$return .= "<td align=middle valign=top>
			<a href=\"index.cgi?album=$cgihtmlalbum&mode=viewpicture&picture=$cgihtmlpicture\">
			<img src=\"$htmlroot/$htmlalbum/thumbnails/$thumbnail\" width=\"$previewWidth\" alt=\"$picture\" border=0></a>
			<br><a href=\"index.cgi?album=$cgihtmlalbum&mode=viewpicture&picture=$cgihtmlpicture\"><font size=-1>$prettypicture</a></font>
			<br><b></b><font color=green size=-2>$time</font></font></td>\n";
		}
	}
	$return .= "</tr></table>";
	####################################################################################################
	# List all of the movies in the directory.  Must end in .mpg or .avi
	#
	####################################################################################################
	my $movie;
	my $moviecount=0;
	my @movies = glob ("$photoroot/$_[0]/*.mpg");
	my @avis = glob ("$photoroot/$_[0]/*.avi");
	my @movs = glob ("$photoroot/$_[0]/*.mov");
	my @rams = glob ("$photoroot/$_[0]/*.ram");
	@movies = (@movies,@avis,@movs,@rams);
	if(@movies){
		$return .= "<br><center><big>Movies</big></center><br>";
	}
	$return .= "<table width=100% border=0 cellpadding=5><tr>";
	foreach $movie (sort @movies) {
		unless (-d $movie){
			$movie =~ s#.*/##;
			my $cgihtmlalbum = $selectedalbum;
			$cgihtmlalbum =~ s/ /+/g;
			my $cgihtmlmovie = $movie;
			$cgihtmlmovie =~ s/ /+/g;

			$moviecount++;
			$return .= "<td align=middle>
				<a href=\"index.cgi?mode=viewmovie&movie=$cgihtmlmovie&album=$cgihtmlalbum\">
				<img src=\"$htmlroot/site-images/genericmovie.jpg\" border=0>
				<br>$movie</a></td>";
			if($moviecount >= ($thumbnails_per_row)){
				$moviecount=0;
				$return .= "\n</tr>\n<tr>";
			}
		}
	}
	$return .="</tr></table>";
	$return .= "
<br> ";

	return $return;
}

sub checkforbadthings {
	if($selectedalbum eq ".."){
		dienice("Illegal!  You should be ashamed. ");
	}
	if($cur->param("q") =~ /\.\./){
		dienice("Illegal!  You should be ashamed. ");
	}

}

#maybe I will add this later.  This eventually may extract the EXIF data from each
#picture
sub get_exifdata ($) {
	my $exifdata="";
    my $info = image_info("$_[0]");
    my $Make = $info->{'Make'};
    my $Model = $info->{'Model'};
    my $ISOSpeedRatings = $info->{'ISOSpeedRatings'};
    unless(defined $ISOSpeedRatings){$ISOSpeedRatings ="<i>unknown</i>";}
    my $top;

    ###########################################################
    # get the exposure time (shutterspeed)
    # thanks to John at ids.sourceforge.net for this
    # #########################################################
    #exposure time
    #if (defined($info->{'ExposureTime'})) {
    #    my @I_exp = $nfo->{'ExposureTime'};
    #    $top = $I_exp[0][1] / $I_exp[0][0], unless ($I_exp[0][1] == 0);
    #} elsif (defined($info->{'ShutterSpeedValue'})) {
    #    my @frac = $info->{'ShutterSpeedValue'};
    #    my $time;
    #    if ($frac[0][1] == 0) {
    #        $time = $frac[0][0];
    #    } else {
    #        $time = $frac[0][0] / $frac[0][1];
    #    }
    #    $top = int (0.5 + exp($time * log(2)));
    #}
    #my $cam_exp;
    #unless ($top <= 1) {
    #   $cam_exp = '1/' . int($top) . ' sec.';
    #} else {
    #    $cam_exp = "<i>unknown</i>";
    #}

    if(defined ($info->{'ExposureTime'})){
        my ($exp_num,$exp_den);
        $cam_exp = $info->{'ExposureTime'}[1]/$info->{'ExposureTime'}[0];
        $cam_exp = "1/$cam_exp sec.";
    }elsif(defined($info->{'ShutterSpeedValue'})) {
        #my ($exp_num,$exp_den);
        #$cam_exp = $info->{'ShutterSpeedValue'}[1]/$info->{'ShutterSpeedValue'}[0];
        #$cam_exp = "1/$cam_exp sec.";
        $cam_exp .= "<i>unknown (bug in ShutterSpeedValue EXIF)</i>";
    }else{
        $cam_exp = "<i>unknown</i>";
    }
    my $cam_flash;
    if (defined($info->{'Flash'})) {
        $cam_flash = $info->{'Flash'};
    } else {
        $cam_flash = "<i>unknown</i>";
    }
    my $cam_date;
    if ((defined($info->{'DateTimeOriginal'})) && ($info->{'DateTimeOriginal'} ne '0000:00:00 00:00:00')) {
       $cam_date = $info->{'DateTimeOriginal'};
       my ($date,$time) = split(/ /,"$cam_date");
       my ($year,$month,$day) = split(/:/,"$date");
       my ($hours,$minutes,$seconds) = split(/:/,"$time");
       my @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
       $month = $months[$month];
       if($hours > 11 && $hours != 0){
           $hours = $hours-12;
           $ampm = "PM";
       }else{
           if($hours == 0){$hours = 12;}
           $ampm = "AM";
       }
       $cam_date = "$month $day, $year at $time $ampm";
    } else {
        $cam_date = "<i>unknown</i>";
    }

    # f number
    my @f_n;
    if (defined($info->{'FNumber'})) {
        @f_n = $info->{'FNumber'};
    } elsif (defined($info->{'ApertureValue'})) {
        @f_n = $info->{'ApertureValue'};
    }
    my ($cam_f, $cam_flen);
    if (!scalar @f_n || $f_n[0][1] == 0) {
        $cam_f = "f" . $f_n[0] if scalar @f_n && defined $f_n[0];
    } else {
        $cam_f = "f" . $f_n[0][0] / $f_n[0][1],
    }
    if ($cam_f eq "") {
        $cam_f = "<i>unknown</i>";
    }
    #focal length
    my @fl_n = $info->{'FocalLength'};
    if (defined($info->{'FocalLength'})) {
        if ($fl_n[0][1] == 0) {
                $cam_flen = int($fl_n[0]*5) . "mm";
        } else {
                $cam_flen = int(5*$fl_n[0][0]/$fl_n[0][1]) . "mm", unless ($fl_n[0][1] == 0);            }
    } else {
        $cam_flen = "<i>unknown</i>";
    }

    ###########################################################
    
#        my $ExposureTime = $info->{'ExposureTime'};
#        my $ShutterSpeedValue = $info->{'ShutterSpeedValue'};
#        my $FNumber = $info->{'FNumber'};
#        my $ApertureValue= $info->{'ApertureValue'};
#
    if(defined $Make){
        $exifdata .= "<table border=0 cellpadding=0 cellspacing=2>
                      <tr>
                        <td><font size=-2><b>Camera:</b></font></td>
                        <td><font size=-2>$Make $Model</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>Flash:</b></font></td>
                        <td><font size=-2>$cam_flash</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>ISO:</b></font></td>
                        <td><font size=-2>$ISOSpeedRatings</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>Shutterspeed:</b></font></td>
                        <td><font size=-2>$cam_exp</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>Aperture:</b></font></td>
                        <td><font size=-2>$cam_f</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>Focal length:</b></font></td>
                        <td><font size=-2>$cam_flen</font></td>
                      </tr>
                      <tr>
                        <td><font size=-2><b>Date taken:</b></font></td>
                        <td><font size=-2>$cam_date</font></td>
                      </tr>
                      </table>";
	    $exifdata = "
    <table bgcolor=#000000 border=0 cellspacing=0 cellpadding=1><tr><td>
    <table bgcolor=#B6B6B6 border=0 cellspacing=0 cellpadding=2>
    <tr><td bgcolor=#000000><font color=#FFFFFF size=-2><b>embedded EXIF data</b></font></td></tr>
    <tr><td>$exifdata</td></tr>
    </table>
    </td></tr></table>";
    }
    return $exifdata;
}

sub generatepicture {
	
	getPrevNextButtons($selectedalbum,$selectedpicture);

	#get width and height
	my($imageToPing) = Image::Magick->new;
	my($itemToDisplay) = "$photoroot/$selectedalbum/$selectedpicture";

	#starting with Image Magick version 5.3.6 a new return value for
	#pinging an image is used.
	if($old_imagemagick =~ /no/ig){
		@pingdata = $imageToPing->Ping($itemToDisplay);
		undef $imageToPing;

		$width =0;
		$height = 0;
		$width = @pingdata[0];
		$height = @pingdata[1];
	}else{
		$pingdata = $imageToPing->Ping($itemToDisplay);
		undef $imageToPing;
		$width =0;
		$height =0;
		if($pingdata =~ /([0-9]+),([0-9]+),.*/){
			$width = $1;
			$height = $2;
		}else {
			warn "Unexpected ping result: $pingdata";
		}
	}

	#fixing spaces for cgi link
	my $cgihtmlalbum = $selectedalbum;
	$cgihtmlalbum =~ s/ /+/g;
	my $shutterflytext;
	if($allowshutterfly eq 'YES'){
		my $thumbnail = $htmlpicture;
        $thumbnail =~ s/(.*)\.(jpg|png|gif)\b/$1SMALL.jpg/i;
		$shutterflytext = "
<form name=\"sflyc4p\" action=\"http://www.shutterfly.com/c4p/UpdateCart.jsp\" method=\"post\">
<input type=submit value=\"order this photo\">
<input type=hidden name=addim value=1>
<input type=hidden name=protocol value=\"SFP,100\">
<input type=hidden name=pid value=C4P>
<input type=hidden name=psid value=AFFL>
<input type=hidden name=referid value=mikespice>
<input type=hidden name=returl value=\"$ENV{'HTTP_REFERER'}\">
<input type=hidden name=imraw-1 value=\"$htmlroot/$htmlalbum/$htmlpicture\">
<input type=hidden name=imrawheight-1 value=\"$height\">
<input type=hidden name=imrawwidth-1 value=\"$width\">
<input type=hidden name=imthumb-1 value=\"$htmlroot/$htmlalbum/thumbnails/$thumbnail\">
<input type=hidden name=imbkprntb-1 value=\"provided by a FREE script from www.fuzzymonkey.org\">
</form>";
		$shutterflytext =~ s/\n//g;
	}	

	$saveWidth = $width;
	$saveHeight= $height;
	$sizewarning = "";
	if($width > $maxWidth){
		createNewWidthPicture();

		#fix a few things when printing the picture out
		$htmlpicture = "$maxWidth/$htmlpicture";
		$height =int ($height/($width/$maxWidth));
		$width = int ($maxWidth);
		$sizewarning = "(viewing at $width x $height)";
	}
	my $resizebutton ="
	<form method=post>
		<input type=hidden name=mode value=viewpicture>
		<input type=hidden name=album value=\"$selectedalbum\">
		<input type=hidden name=picture value=\"$selectedpicture\">
		<select name=maxWidth>";

	if($maxWidth eq "640"){
		if($saveWidth > 640){ $resizebutton .= "<option value=640 selected>small (640)";}
	} else {
		if($saveWidth > 640){ $resizebutton .= "<option value=640>small (640)";}
	}
	if($maxWidth eq "800"){
		if($saveWidth > 800){ $resizebutton .= "<option value=800 selected>medium (800)";}
	} else {
		if($saveWidth > 800){ $resizebutton .= "<option value=800>medium (800)";}
	}
	if($maxWidth eq "1024"){
		if($saveWidth > 1024){ $resizebutton .= "<option value=1024 selected>large (1024)";}
	} else {
		if($saveWidth > 1024){ $resizebutton .= "<option value=1024>large (1024)";}
	}
	if($maxWidth eq "9999"){
		$resizebutton .= "<option value=9999 selected>full size";
	} else {
		$resizebutton .= "<option value=9999>full size";
	}


	$resizebutton .= "
		</select>
		<input type=submit value=\"resize\">
	</form>";
	my ($prettypicture) = $selectedpicture;
	$prettypicture = makepretty($prettypicture);
	my $return;
    $return .= print_location($selectedalbum);
	$return .= "
<center>
<br>
<table bgcolor=#FFFFFF border=0 cellspacing=0 cellpadding=2><tr><td>
<table cellpadding=5 border=0 cellspacing=0 bgcolor=$rowcolor>
<tr><td align=left>
	<table><tr>
	<td valign=middle align=middle><a href=index.cgi?mode=view&album=$cgihtmlalbum><img src=$htmlroot/site-images/back.gif border=0><br><font size=-1>back to gallery</font></a></td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle>$prev</td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle><b><big><big>$prettypicture</big></big></b></td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle>$next</td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	</tr></table>
</td></tr>";
	my $picture = "$photoroot/$selectedalbum/$selectedpicture";
	fileinfo($picture);
	my $hits = logpicture("$selectedalbum/$selectedpicture");
	my $hitstring = "<tr><td><b><font size=-2>viewed:</b></td>
		<td><font size=-2>$hits times</td></tr>";
	
	my $description = getdescription($selectedalbum,$selectedpicture);
	my $commentmsg ='';
	if($allowcomments =~ /YES/i){
	$commentmsg = "<font size=-2>Users may add comments <a href=#comments>below</a></font>";
	}
	$shadowwidth=$width -16; #lower left shadow is 16 pixels wide. Current table layout requires the bottom shadow to that much less.
    if($exif=~ /yes/i){
        $exifdata = get_exifdata("$picture");
    }else{
        $exifdata = "<small>exif disabled</small>";
    }
	$return .= "

<tr bgcolor=$descriptioncolor><td>$description</td></tr>
<tr bgcolor=$descriptioncolor><td><table width=$width><tr><td align=left>$commentmsg</td><td align=middle>$resizebutton</td><td align=right>$shutterflytext</td></tr></table></tr>
<tr bgcolor=#FFFFFF><td><center>

	<table border=0 cellspacing=0 cellpadding=0>
		<tr>
			<td colspan=2><img src=\"$htmlroot/$htmlalbum/$htmlpicture\" width=$width height=$height border=0></td>
			<td align=left valign=top background=\"$htmlroot/site-images/shadow_middle_right.jpg\"><img src=\"$htmlroot/site-images/shadow_top_right.jpg\"></td>
		</tr>
		<tr>
			<td align=left valign=top><img src=\"$htmlroot/site-images/shadow_bottom_left.jpg\"></td>
			<td width=$shadowwidth background=\"$htmlroot/site-images/shadow_middle_bottom.jpg\">&nbsp;</td>
			<td align=right valign=top><img src=\"$htmlroot/site-images/shadow_bottom_corner.jpg\"></td>
		</tr>
	</table>

</center></td></tr>
<tr bgcolor=$descriptioncolor><td>

<table width=100%><tr><td>
	<table cellspacing=0 cellpadding=0 border=0>
			<tr><td><b><font size=-2>uploaded: </b></td><td><font size=-2>$time</td></tr>
			<tr><td><b><font size=-2>file size: </td><td><font size=-2>$kfilesize</td></tr>
			$hitstring
			<tr><td><b><font size=-2>image size: </b></td><td><font size=-2>$saveWidth x $saveHeight $sizewarning</td></tr>";

	$return .="
	</table>

	</td><td align=right valign=top>
    $exifdata
	</td></tr>
</table>

</td></tr>
<tr bgcolor=#FFFFFF>
	<td ><center> 
		<table><tr>
			<td valign=middle align=left>$prev</td>
			<td valign=middle align=left>$prevThumb</td>
			<td valign=middle><font size=-1>$pictureNumber out of $numberofpictures</font></td>
			<td valign=middle align=right>$nextThumb</td>
			<td valign=middle align=right>$next</td>
		</tr></table>
	</center></td></tr>
</table>
</td></tr></table>
</center>
";

	if($allowcomments eq 'YES') {
		$return .= getcomments();
	}
   	my $shutterflytext;
   	if($allowshutterfly eq 'YES'){
   		$shutterflytext="<hr>
   		<img src=$htmlroot/site-images/printsbyshutterfly.gif align=left><font size=-1>
   		This gallery has support for Shutterfly. Click the \"order this photo\" button to quickly and easily order high-quality photographic prints of your favorite pictures
                   through Shutterfly.com";
   }
   $return .= "$shutterflytext";

	return $return;
}

sub generatemovie {
	
	#getPrevNextButtons($selectedalbum,$selectedpicture);

	#get width and height
	#fixing spaces for cgi link
	my $cgihtmlalbum = $selectedalbum;
	$cgihtmlalbum =~ s/ /+/g;

	my $prettymovie = $selectedmovie;
	$prettymovie =~ s/_/ /g;

	my $movie = "$photoroot/$selectedalbum/$selectedmovie";
	fileinfo($movie);

	my $return;
	$return .= "
<center>
<br>
<table bgcolor=#FFFFFF border=0 cellspacing=0 cellpadding=2><tr><td>
<table cellpadding=5 border=0 cellspacing=0 bgcolor=$rowcolor>
<tr><td align=left>
	<table><tr>
	<td valign=middle align=middle><a href=index.cgi?mode=view&album=$cgihtmlalbum><img src=$htmlroot/site-images/back.gif border=0><br><font size=-1>back to gallery</font></a></td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle>$prev</td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle><b><big><big>$prettymovie</big></big></b></td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td valign=middle align=middle>$next</td>
	<td valign=middle align=middle>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
	</tr></table>
</td></tr>";
	my $hits = logpicture("$selectedalbum/$selectedmovie");
	my $hitstring = "<tr><td><b><font size=-2>viewed:</b></td>
		<td><font size=-2>$hits times</td></tr>";
	
	my $description = getdescription($selectedalbum,$selectedmovie);
	my $commentmsg ='';
	if($allowcomments eq 'YES'){
	$commentmsg = "<font size=-2>Users may add comments <a href=#comments>below</a></font>";
	}
	$shadowwidth=$width -16; #lower left shadow is 16 pixels wide. Current table layout requires the bottom shadow to that much less.
	$return .= "

<tr bgcolor=$descriptioncolor><td>$description</td></tr>
<tr bgcolor=$descriptioncolor><td><table width=$width><tr><td align=left>$commentmsg</td><td align=middle></td><td align=right></td></tr></table></tr>
<tr bgcolor=#FFFFFF><td><center>
	<a href=\"$htmlroot/$htmlalbum/$htmlmovie\">
	<img src=\"$htmlroot/site-images/genericmovie.jpg\" border=0>
	<br>click to download</a>
	<br><br><font size=-1 color=red>(you may need to right click and choose \"save as\")</font>
</center></td></tr>
<tr bgcolor=$descriptioncolor><td>

<table><tr><td>
	<table cellspacing=0 cellpadding=0 border=0>
			<tr><td><b><font size=-2>uploaded: </b></td><td><font size=-2>$time</td></tr>
			<tr><td><b><font size=-2>file size: </td><td><font size=-2>$kfilesize</td></tr>
			$hitstring
			<tr><td><b><font size=-2>dimensions: </b></td><td><font size=-2>N/A</td></tr>";

	$return .="
	</table>

	</td><td align=right valign=top>
	</td></tr>
</table>

</td></tr>
<tr bgcolor=#FFFFFF>
	<td ><center> 
	</center></td></tr>
</table>
</td></tr></table>
</center>
";
	if($allowcomments eq 'YES') {
		$return .= getcomments();
	}
	return $return;
}


sub logpicture {
	#needs to have the name of the picture passed as an argument. Opens log file. Increments for
	#that picture, and write the data file back out.
	
	#open datafile and get info
	open (INFILE, "log.txt")|| 
	dienice("could not open the log file!  If this is your first time running it,
			please manually create a blank data file.  See the README file for more information.");
	flock (INFILE, 2); #locks the file for exclusive access.
	while(<INFILE>){
		chomp();
		my ($picture,$hits) = split(/=/,$_); #read in each timeslot one per line
		$picturelog{"$picture"} = $hits;
	}
	flock (INFILE, 8); #unlocks the file
	close(INFILE);

	#incriment hit counter for the current picture
	$picturelog{$_[0]}++;
	
	#re-write data file with new info
	open(OUTFILE,">log.txt") || dienice("Cound not open data file for writing!");
	flock (OUTFILE, 2);
	foreach $key (sort keys %picturelog) {
		print OUTFILE "$key=$picturelog{\"$key\"}\n";
	}
	flock (OUTFILE, 8);
	close(OUTFILE);

	print "";
	return $picturelog{$_[0]};

}


sub getdescription($$) {
	my $return = "";
	
	#open datafile 
	if(open (INFILE, "$photoroot/$_[0]/descriptions/$_[1].txt")){ 
		flock (INFILE, 2); #locks the file for exclusive access.
		while(<INFILE>){
			$return .= "$_";
		}
		flock (INFILE, 8); #unlocks the file
		close(INFILE);
	}
	
	return $return;
}

sub makepretty {

	if($prettypicturenames =~ /YES/i) {
		$_[0]=~ s/_/ /g;
		$_[0] =~ s/(.*)\..*/\1/g;
	}
	return $_[0];

}

#########################################################################
## open comments file and return a pretty table of the comments##########
#########################################################################
sub getcomments {
	my $return;
	my $count=0;
	my @comments;
	my $selecteditem;
	#make comments directory if it doesn't exist
	unless(-e "$photoroot/$selectedalbum/comments"){
        #print "Making directory $photoroot/$selectedalbum/comments...<br><br>";
		mkdir("$photoroot/$selectedalbum/comments",0755) || print "Error, could not make comments directory
			please check the permissions!<br><br>";
	}

	#little trick to get comments on movies to work :-)
	if(!($selectedpicture)){
		$selectedpicture = $selectedmovie;
	}

	#open datafile 
	if(open (INFILE, "$photoroot/$selectedalbum/comments/$selectedpicture.txt")){ 
		flock (INFILE, 2); #locks the file for exclusive access.
		while(<INFILE>){
			chomp();
			push (@comments,$_);
		}
		flock (INFILE, 8); #unlocks the file
		close(INFILE);
	}
	my $cgihtmlalbum = $selectedalbum;
	$cgihtmlalbum =~ s/ /+/g;
	my $cgihtmlpicture = $selectedpicture;
	$cgihtmlpicture =~ s/ /+/g;
	$return .= "
<center>
<form method=post>
<table width=99% border=0 cellspacing=0>";
	
	$return .= "<tr bgcolor=$rowcolor><td colspan=2 align=middle><a name=comments><b>Comments</b></td></tr>";
	my $commentcolor ='#acf9b8';
	foreach $comment (@comments) {
		$count++;
		my ($time,$name,$email,$comment) = split(/=/,$comment);
		#alternate row colors
		if($commentcolor eq '#acf9b8'){
			$commentcolor ='#edf2f4';	
		}else {
			$commentcolor ='#acf9b8';
		}
		my $email_comment;
		if ($email){ $email_comment = "<a href=mailto:$email><img src=$htmlroot/site-images/email.gif border=0></a>";}
		$return .="
<tr bgcolor=$commentcolor><td><b>$name $says[int(rand(@says))] : </b></td><td align=right>&nbsp;$email_comment</td></tr>
<tr bgcolor=$commentcolor><td colspan=2>$comment</td></tr>
<tr bgcolor=$commentcolor><td colspan=2 align=right><font size=-1>$time</font></td></tr>
";

	}
	unless($count){
		$return .= "<tr><td colspan=2>There are currently no comments for this item.</td></tr>";
	}
	$mode = $cur->param("mode");
	if($mode =~ /picture/i){
		$return .= "
<tr bgcolor=$rowcolor><td colspan=2 align=middle><b>Add Comment</b></td></tr>
<tr><td valign=top>Name:</td><td><input type=text name=name size=30></td></tr>
<tr><td valign=top>Email:</td><td><input type=text name=email size=30></td></tr>
<tr><td valign=top>Comments:</td><td><textarea name=comment rows=3 cols=30 wrap=soft></textarea></td></tr>
<tr><td colspan=2 align=middle>
<input type=hidden name=mode value=viewpicture>
<input type=hidden name=album value=\"$selectedalbum\">
<input type=hidden name=picture value=\"$selectedpicture\">
<input type=submit value=\"Add Comment\"></td></tr>";
	} else {
		$return .= "
<tr bgcolor=$rowcolor><td colspan=2 align=middle><b>Add Comment</b></td></tr>
<tr><td valign=top>Name:</td><td><input type=text name=name size=30></td></tr>
<tr><td valign=top>Email:</td><td><input type=text name=email size=30></td></tr>
<tr><td valign=top>Comments:</td><td><textarea name=comment rows=3 cols=30 wrap=soft></textarea></td></tr>
<tr><td colspan=2 align=middle>
<input type=hidden name=mode value=viewmovie>
<input type=hidden name=album value=\"$selectedalbum\">
<input type=hidden name=movie value=\"$selectedmovie\">
<input type=submit value=\"Add Comment\"></td></tr>";
	}
	$return .="</table></form></center>";

	return $return;
}

#########################################################################
# takes comments from a form and adds them to the comments file #########
#########################################################################
sub getcomment {
	my $name = $cur->param("name");
	my $email= $cur->param("email");
	my $comment = $cur->param("comment");
	my $time = localtime(time());
	my $body;

	$name= &stripBadHtml($name);	
	$email = &stripBadHtml($email);	
	$comment = &stripBadHtml($comment);	
	$comment =~s /\n/<br>/g;

	#little trick to get comments on movies to work :-)
	if(!($selectedpicture)){
		$selectedpicture = $selectedmovie;
	}

	#append new comment to data file
	if(open(OUTFILE,">>$photoroot/$selectedalbum/comments/$selectedpicture.txt")) {
		flock (OUTFILE, 2);
		print OUTFILE "$time=$name=$email=$comment\n";
		flock (OUTFILE, 8);
		close(OUTFILE);
		
		if($email_comments_to_admin =~ /YES/i){
			$body = "$name ($email) posted a comment to your photo gallery at $ENV{'HTTP_REFERER'} on $time.
			\nAlbum:\t\t$selectedalbum\nPicture:\t$selectedpicture\n\nThey commented:\n$comment
			\nProvided by a a FREE script from http://www.fuzzymonkey.org/";
			email("comment posted on photo gallery",$admin_email,$email,$email,$body);
		}

		print "";
		return $picturelog{$_[0]};
	}else {
		print "There was an error writing to the comments file.  This script does
		not have the proper file permissions to write to the comments file!  
		Please see the README or the CGI tutorial on fuzzymonkey.org for more information.";
	}
}

# searches current directory for current picture in order to get previous
# and next pictures.  This will be used to make previous and next buttons.
# the text for the previous and next buttons will be stored in
# global varaibles $next and prev
sub getPrevNextButtons {

	my $album = $_[0];
	my $picture = $_[1];
	$album =~ s/ /\\ /g; #make spaces glob friendly
	my @files= glob ("$photoroot/$album/*");
	$album =~ s/\\ /+/g; #make glob friendly spaces, cgi friendly
	my @pictures;
	#discard directories
	foreach $file (@files){
		if($file =~ /\.(jpg|png|gif)\b/i){
			push(@pictures,$file);
		}
	}
	my $offset;
	$prev = '&nbsp;';
	$next = '&nbsp;';
	$prevThumb = '&nbsp;';
	$nextThumb = '&nbsp;';

	
	
	#Find the offset of the current picture	
	for($offset=0;$offset<(@pictures);$offset++){
		if($pictures[$offset] eq "$photoroot/$_[0]/$_[1]"){ #current picture
			if($offset > 0) { 
				#this is not the first picture we make a prev button

				my $prevPicture = $pictures[$offset-1];
				$prevPicture =~ s#.*/##; # remove directory crap
				my $htmlprevPictureThumb = $prevPicture; #make a version for html (for thumbnail)
				$htmlprevPictureThumb =~ s/ /%20/g;	
                $htmlprevPictureThumb =~ s/(.*)\.(jpg|png|gif)\b/$1SMALL.jpg/i;
				$prevPicture =~ s/ /+/g; # make a cgi link friendly one
				$prev = "
<a href=\"index.cgi?album=$album&mode=viewpicture&picture=$prevPicture\">
<img src=\"$htmlroot/site-images/prev.gif\" border=0><br><font size=-1>previous</font></a>";
				$prevThumb = "
<a href=\"index.cgi?album=$album&mode=viewpicture&picture=$prevPicture\">
<img src=\"$htmlroot/$htmlalbum/thumbnails/$htmlprevPictureThumb\" border=0></a>";
			}
			if($offset < ((@pictures)-1)){
				#this is not the last picture we make next button

				#prepair picture for link (get ride of 
				#directory info and spaces
				my $nextPicture = $pictures[$offset+1];
				$nextPicture =~ s#.*/##;
				my $htmlnextPictureThumb = $nextPicture; #make a version for html (for thumbnail)
				$htmlnextPictureThumb =~ s/ /%20/g;	
                $htmlnextPictureThumb =~ s/(.*)\.(jpg|png|gif)\b/$1SMALL.jpg/i;
				$nextPicture =~ s/ /+/g;	
				$next = "
<a href=\"index.cgi?album=$album&mode=viewpicture&picture=$nextPicture\">
<img src=\"$htmlroot/site-images/next.gif\" border=0><br><font size=-1>next</font></a>";
				$nextThumb = "
<a href=\"index.cgi?album=$album&mode=viewpicture&picture=$nextPicture\">
<img src=\"$htmlroot/$htmlalbum/thumbnails/$htmlnextPictureThumb\" border=0></a>";
			}
			$pictureNumber = $offset+1; #to know which picture out of how many we are viewing
		}
	}
	$numberofpictures = @pictures; #for use in the main script

}

##############################################################################
# Creates a new picture in the subdirectory for the current width
##############################################################################
sub createNewWidthPicture{

	#Make sure it is an allowed width
	if(!($maxWidth eq 640 || $maxWidth eq 800 || $maxWidth eq 1024 || $maxWidth eq 9999)){
		dienice("$maxWidth is an invalid perameter for the picture width!");
	}

        #make directory for smaller pictures if it doesn't exist
        unless(-e "$photoroot/$selectedalbum/$maxWidth"){
                #print "Making directory $photoroot/$selectedalbum/$maxWidth ...<br><br>";
                mkdir("$photoroot/$selectedalbum/$maxWidth",0755) || print "Error, could not make directory for this size image
                        please check the permissions!<br><br>";
        }


	#create smaller size if it doesnt exist or the thumbnail is older than the picture
	unless((-e "$photoroot/$selectedalbum/$maxWidth/$selectedpicture")){

		#print "Created thumbnail for $thumbnail<br>"; #prints out text for each thumbnail created
		my($imageToScale) = Image::Magick->new;
		my($itemToDisplay) = "$photoroot/$selectedalbum/$selectedpicture";
		my($x) = $imageToScale->Read($itemToDisplay); # read in the picture
		warn "$x" if "$x";
		$imageToScale->Set(quality=>80);
		my($xSize, $ySize) = $imageToScale->Get('width', 'height'); # Get the pictures dimensions
		my($scaleFactor) = $xSize/$maxWidth;
		#print "$scaleFactor<br>";
		$x = $imageToScale->Scale(width=>($maxWidth), height=>($ySize/$scaleFactor)); #scale the image to the correct display size
		warn "$x" if "$x";
		
		#write out the thumbnail image file in JPEG format
		$x = $imageToScale->Write("$photoroot/$selectedalbum/$maxWidth/$selectedpicture");
		warn "$x" if "$x";
				
		undef $imageToScale;
	}

}

sub searchpicturenames{
	my $q = $_[0];
	my $return;
	my $matches=0;

	my @albums = glob "$photoroot/*/"; #returns all of the directories
	
	#foreach $album (sort @albums){
	foreach $album (sort {-M $a <=> -M $b} @albums){
		#$return .= "Looking in $album <br>";	
		$album =~ s/ /\\ /g;
		@pictures = glob ("$album/*");
		foreach $picture (sort @pictures) {
			$album =~ s/(.*)\//$1/; #get rid of trailing slash
			$album =~ s/.*\/(.*)/$1/; #get rid of directories before it
			$picture =~ s/.*\/(.*)/$1/; #get rid of directories before i
			if($picture =~ /$q/){ # we have a match
				$return .= printsearchmatch($album,$picture,"image name");
				$matches++;
			}

			#search each pictures comments
			$album =~ s/\\ / /g;	
			$picture=~ s/\\ / /g;	
			if(open (INFILE, "$photoroot/$album/comments/$picture.txt")){ 
				flock (INFILE, 2); #locks the file for exclusive access.
				while(<INFILE>){
					chomp();
					if($_ =~ /$q/){ # we have a match
						$return .= printsearchmatch($album,$picture,"comments");
						$matches++;
					}
				}
				flock (INFILE, 8); #unlocks the file
				close(INFILE);
			}


			#search each pictures description
			if(open (INFILE, "$photoroot/$album/descriptions/$picture.txt")){ 
				flock (INFILE, 2); #locks the file for exclusive access.
				while(<INFILE>){
					chomp();
					if($_ =~ /$q/){ # we have a match
						$return .= printsearchmatch($album,$picture,"description");
						$matches++;
					}
				}
				flock (INFILE, 8); #unlocks the file
				close(INFILE);
			}

		}
	}
	$return .= "<br><br>returned $matches matches.";
	return $return;
	
}

sub printsearchmatch {
	my $album = $_[0];
	$album =~ s/\\ /+/g; #make web link friendly
	$album =~ s/ /+/g; #make web link friendly
	my $picture = $_[1];
	$picture =~ s/\\ /+/g; #make web link friendly
	$picture =~ s/ /+/g; #make web link friendly
	if($picture =~ /.*\.(mpg|avi|mov|ram)/){ # we have a movie
		$mode = 'viewmovie';
		$arg = "movie=$picture";
	} else {
		$mode = 'viewpicture';
		$arg = "picture=$picture";
	}
	my $return = "<blockquote>
<table border=0 cellspacing=0>
<tr><td bgcolor=$descriptioncolor>Image: </td><td><a href=index.cgi?album=$album&mode=$mode&$arg>$picture</a></td></tr>
<tr><td bgcolor=$descriptioncolor>Album: </td><td>$album</td></tr>
<tr><td bgcolor=$descriptioncolor>Found in: </td><td>$_[2]</td></tr>
</table><br></blockquote>";
	return $return;
}

#####################################################3
#subs from slashdot to remove bad html
#####################################################
# Thanks to Slashdot for these
# Approved HTML tags for HTML posting
@approvedtags = (
        'B','I','P .*','P','A',
        'LI','OL','UL','EM','BR',
        'STRONG','BLOCKQUOTE',
        'HR','DIV .*','DIV','TT'
        );

sub stripBadHtml
{
        my ($str) = @_;

        $str =~ s/(\S{90})/$1 /g;
        $str =~ s/<(?!.*?>)//;
        $str =~ s/<(.*?)>/approvetag($1,@approvedtags)/sge; #replace
tags with approved ones
        return $str;
}

sub approvetag
{
        my ($tag,@apptag) = @_;

        $tag =~ s/^\s*?(.*)\s*?$/$1/e; #trim leading and trailing spaces

        if (uc(substr ($tag, 0, 2)) eq 'A ')
        {
                $tag =~ s/^.*?href="?(.*?)"?$/A HREF="$1"/i; #enforce "s
                return "<" . $tag . ">";
        }

        foreach my $goodtag (@apptag)
        {
                $tag = uc $tag;
                if ($tag eq $goodtag || $tag eq '/' . $goodtag)
                        {return "<" . $tag . ">";}
                #check against my list of tags
        }
        return "";
}

