#!/cygdrive/c/strawberry/perl/bin/perl
#/usr/bin/perl -d
# Program to process my bird database and my places database to
# create the varous web pages.
# makeclass is the companion program that creates the classification pages.
# The program assumes that the birds are in inventory.txt and the places
# in places.txt
#   Usage:   ./makebirds
#            mv bird* ..
#
# Original line from the excel spreadsheet for birds and places database
#   date priority breeding filename bird_name picture_location notes
#
# after sort
#   bird_name breeding priority date filename picture_location notes
#

	# File pointer variables
$inven = "inventory.txt";	# name of the bird database
$place = "place.txt";		# name of the place database
$class_file ="in_class";	# file which holds the birds in each classification
$filename = "";			# holds filename of the current open bird file
$video_file = "videos.txt";	# file for video information
$video_dir = "videos/";		# directory where videos kept
$bib_file = "bibliography.txt"; # file for bibliography info
$file_txt = "../text/";		# directory that points to old short descriptions
$desc_txt = "../Descriptions/";	# directory that points to new full descriptions
$file_place = "../text_place/"; # directory that points to descriptions for places
$file_bib = "Bibliography.shtml"; # The file to contain the bibliography

	# Important variables
$fbird = "";		# holds full name of bird/place with spaces and apostrophes
$sbird = "";		# holds name of bird/place WITHOUT spaces
$bbird = "";		# holds name of bird/place WITHOUT spaces and apostrophes

$new = 1;		# if 1, need a new bird file opened for writing
$count = 1;		# current number of birds pictures in a row
$number = 1;		# number of pictures for a bird
$row_max = 3;		# number of pictures per row
$previous = "";		# name of previous bird processed, new bird = new file.
@favorites = "";	# holds the pictures ranked #1 for a separate web page
$classification = 0;	# used to make sure I print out the bird right menu
$tab = '\t';		# database separator - tab for inventory databases
$colon = ':';		# database separator - color for in_class database
			# Name of the three titles for the breeding category
@breed_type = ("Juvenile", "Breeding Adult", "Non-breeding Adult", "Adult");
$lastbreed = 0;		# flag for controlling when the "breeding" header is printed
$highdir = "highslide";	# Highslide directory
@class_list;		# Holds the pointer for right menu for birds/places
@video_birds; 		# will hold the name of birds with videos for the "video" page
%video;			# hash array for videos, complete bird name points to video
			# text

@bot_des;		# arry to hold the description that goes after the pics
@books;			# array to hold the bibliography for books
@mags;			# array to hold the bibliography for journals/mags
@web;			# array to hold the bibliography for web
{
			##########  Read in Inventory bird database ############

			# read in the bird inventory database, from this create the
			# array for the bird pages, the favorite page, and the
			# "Recent" page.
   unless (open INPUT, "<$inven") {
	   die "Cannot open the inventory database: $invent\n";
   }
   $date_rec = &get_date_rec;	# get today's data - "n" days for most "latest" pics
   				# "n" defined in &get_date_rec
   while (chomp($line = <INPUT>)) {
	@name = &process_line($line, $tab);
			# skip if a zero'd or comment line (excel did this) 
	next if (!@name);
	$newline = $name[4] . "\t" . $name[2] . "\t" . $name[1] . "\t" . $name[0] .
		"\t" .  $name[3] . "\t " .  $name[5] . "\t" . $name[6];
	push (@barray, $newline);
			# Add favorite birds "priority 1" to array
	if ($name[1] == 1) {
		$name[4] . "\t " .  $name[5] . "\t" . $name[6];
		push (@favorites, $newline);
	}
			# store pictures that are less than "n" days old
			# for "Recent" page
	if ($name[0] > $date_rec && $name[1] < 5) {
		$newline = $name[4] . "\t" . $name[1] . "\t" . $name[0] . "\t" .
			$name[2] . "\t" .  $name[3] . "\t " .  $name[5] . "\t" .
			$name[6];
		push (@latest, $newline)
	}
   }
   close INPUT;

			##########  Read in Places database ############

   unless (open INPUT, "<$place") {
	   die "Cannot open the place database: $place\n";
   }
   while (chomp($line = <INPUT>)) {
	@name = &process_line($line, $tab);
			# skip if a zero'd or comment line
	next if (!@name);
	$newline = $name[4] . "\t" . $name[2] . "\t" . $name[1] . "\t" . $name[0]
		. "\t" .  $name[3] . "\t " .  $name[5] . "\t" . $name[6];
	push (@parray, $newline);
   }
   close INPUT;

			##########  Read in Video Database ############

   			# read in the video database & create a hash table.
			# Birds with multiple videos have the info concantenanted
			# together, seperated by ':'.  The video number & text are
			# separated by a ";"
			# Input:   bird_name_video Number, text to print
			# Hash table: bird_name videoNumber;text(:videoNumber;text)
			# If multiple entries, they are seperated by colons
   unless (open INPUT, "<$video_file") {
	   die "Cannot open the video file: $video_file\n";
   }
   foreach (<INPUT>) {
	   @field = split/\t/;
	   		# save the bird name for later use in the "Videos" page
	   push (@video_birds, $field[0]);
	   		# in a hash array, save the all the video text and video
			# number for each bird
	   if (exists $video{$field[0]}) {
			  $video{$field[0]} = $video{$field[0]} . ":" . $field[1] .
			 	 ";" . $field[2]; 
	   }else{
			  $video{$field[0]} = $field[1] . ";" . $field[2]; 
	   }
   }
   close INPUT;
			##########  Read in the Bibliography database ############
			# Create three arrays:  books, journals/mags, and web pages
			# All of them will create the bibliography page and some will
			# be on the individual bird page.  I will use their index
			# (minus 1) to get them
   unless (open INPUT, "<$bib_file") {
	   die "Cannot open the video file: $bib_file\n";
   }
   foreach (<INPUT>) {
	   @field = process_line ($_, "\t");
	   next if (!@field);
	   if ($field[0] eq "Books:") {$flag = 0; next;}
	   if ($field[0] eq "Web:") {$flag = 1; next;}
	   if ($field[0] eq "Journals:") {$flag = 2; next;}
   	   		# now process cited line, how I format it depends
			# on type of cite
	   if ($flag == 0) {
		   		#books
		   $temp = $field[1] . " <i>" . $field[2] . "</i> " . $field[3];
		   push (@books, $temp);
	   }elsif ($flag == 1) {
		   		#web
		   $temp = '<a href="' . $field[1] . '">' . $field[1] . "</a> \t " .
		  	 $field[2];
		   push (@web, $temp);
	   }elsif ($flag == 2) {
		   		#journals/magazines
		   $temp = $field[1] . '"' . $field[2] . '"' . "<i>$field[3]</i>," .
		  	 $field[4];
		   push (@mags, $temp);
	   }
   }
   close INPUT;

			##########  Sort various arrays ############
   			# sort bird array so all the birds of one species are together
			# sort is bird, breeding field, pic priority, date pic taken
   @bsorted = (sort {$b cmp $a} @barray);
   			# sort places array so all the places are together
   @psorted = (sort {$b cmp $a} @parray);
   			# sort books, web and journals
   @sbooks = (sort {$b cmp $a} @books);
   @sweb = (sort {$b cmp $a} @web);
   @smags = (sort {$b cmp $a} @mags);

   			# Cull out 40 images from images from the "latest" pics gathered
			# above.  Returns a sorted array
   @latest = &compute_latest;

			##########  Read in in_class database ############
			# Now read in the in_class file.  From this file I get each
			# bird/place and the classification it belongs to (line begins
			# with "title: or ptitle:".  I use this information to create
			# the right hand menu on the individual bird/place pages which
			# has all the birds listed for a particular classification.
			# I also get the breeding dates if they are available. 
			# This goes into two hash arrays, one for breeding (breed),
			# and one for non_breeding (nonbreed). I also use the info
			# read to create the index.


   unless (open CLASS, "<$class_file") {
	   die "Cannot open the in_class file\n";
   }
   $flag = 0;
   foreach (<CLASS>) {
	chomp;
	@in = &process_line($_, $colon);
			# skip empty or comment lines
	next if (!@in);
			# skip sub-class & text lines, they are
			# used only in the makeclass program
	next if ($in[0] =~ /^header/);
	next if ($in[0] =~ /^text/);
			# each bird classification creates a hash table
	if ($in[0] =~ /title/) {
			# if not the very first title, build the previous title's menu
		if ($flag) {
			&create_rightmenu;
				# empty out last set of birds
			undef @class_birds;
		}
		$flag = 1;
		$classification = $in[1];
	}
	if ($in[0] =~ /^bird/) {
			# need to reverse the bird name, e.g.,
			# Common Loon becomes Loon, Common
		@fields = split / /, $in[1];
			# get the last word and put it first
		$nam = pop (@fields);
		$num = @fields;
		if ($num > 0) {
			$nam = $nam . ",";
		}
		foreach $i (@fields) {
			$nam = $nam . " " . $i;
		}
		push (@class_birds, "$nam:$in[2]");
			# put bird name into the secondary hash table
		$class_list{$in[1]} = $classification;
	}
	if ($in[0] =~ /^place/ ) {
			# put in the place name, I don't want it
			# stored like the bird name with last name first
		push (@class_birds, "$in[1]:$in[2]");
			# put bird name into the secondary hash table
		$class_list{$in[1]} = $classification;
	}
			# do breeding and non-breeding dates
	$sbird = $in[1];
	$sbird =~ s/\s//g;
	if ($in[4]) {
		$breed{$sbird} = " (" . $in[4] . ")";
	}
	if ($in[5]) {
		$nonbreed{$sbird} = " (" . $in[5] . ")";
	}
  }
  &create_rightmenu;
  close CLASS;
 
			##########  Start Processing Data ############

		# Do the individual bird/places pages.  I do this by going
		# through the main loop twice, first for birds, second for places.
   
   for ($j=0; $j<2; ++$j) {
	   		# first do the birds (bsorted) and then the places (psorted)
			# this also effects the menu displayed on the left
     @sorted = @bsorted;
     $left_menu = "birds_menu.html";		# bird left menu
     if ($j > 0) {
	     @sorted = @psorted;
	     $left_menu = "places_menu.html";	# places left menu
     }
     while ($line = pop(@sorted)) {
	@name = split /\t/, $line;
		# close previous file if the bird/place name has changed
	if ($name[0] ne $previous && !$new)
		{
		&print_end1;
		$temp = $class_list{$previous};
		print OUT ($class{"$temp"});
		&print_end2;
		$new = 1;
		$number = 1;
		}
	if ($new) {
		# need to open the bird/place file for writing out html
	   $sbird = $name[0];
	   $fbird = $name[0];	# full bird name for videos
	   		# get rid of spaces
	   $sbird =~ s/\s+//g;
	   $filename = "bird_" . $sbird . ".shtml";
	   open OUT, ">$filename" or die "Can't open $filename for writing\n";
	   $new = 0;
	   $count = 1;
	   $previous = $name[0];
	   $lastbreed = 0;
	   &print_header1 ($name[0]);
	   &print_header1_bird;
			# execute routine to print out any text and links
			# to feet, tongue, etc.
	   &extras ($j);
	   &print_end_text;
	}
		# check to see if a new sub-header needs printing
		# (e.g., Juvenile, Breeding-Adult, etc.)
	$space16 = "                ";
	if ($name[1] && ($lastbreed != $name[1])) {
		print OUT $space16,
		   '<tr class="extras"> <th colspan="3">', "\n",
		   $space16, '<b class="largef">';
				# if Breeding or non-breeding title, print out the
				# months for each if such info is available
		if ($name[1] == 2) {
						# breeding
			print OUT "$name[0] - $breed_type[$name[1]-1] ",
					"$breed{$sbird}</b> </th> \n",
				        $space16, "</tr> \n";
		}elsif ($name[1] == 3) {
						# non-breeding
			print OUT "$name[0] - $breed_type[$name[1]-1] ",
					"$nonbreed{$sbird}</b> </th> \n",
					$space16, "</tr>\n";
		}else {
		     				#default situation
			print OUT "$name[0] - $breed_type[$name[1]-1]</b>",
			       	"</th> \n", $space16, "</tr> \n";

		}
		print OUT $space16, "<tr>\n";
		$count=1;
		$lastbreed = $name[1];


	if ($count > $row_max) {
		print OUT "		</tr>\n";
		print OUT "		<tr>\n";
		$count=1;
	}
	$dir = &find_dir($name[3]);
		# Now print the individual bird picture
		# First get rid of any quotes that excel adds
	$name[6] =~ s/\"//g;
	$name[5] =~ s/\"//g;
	$day = $name[3] - int($name[3]/100)*100;
	$month = int($name[3]/100);
	$month = $month - int($month/100)*100;
	$year = int($name[3]/10000);
	$date = $month . "/" . $day . "/" . $year;
	&print_rows ($date, "");
	$number = $number +1;
	$count = $count+1;

     }
   }
	&print_end1;
	$temp = $class_list{$previous};
	print OUT ($class{"$temp"});
	&print_end2;
			#
			# now process "Favorites" Page
			#
	$number = 1;
	$filename = "bird_Favorites.shtml";
	open OUT, ">$filename" or die "Can't open $filename for writing\n";
	$left_menu = "birds_menu.html";
	 &print_header1 ("Favorites");
	 &print_header1_bird;
			# execute routine to print out any text and links to
			# feet, tongue, etc.
	$sbird = "Favorites";
	$j = 0;
	&extras (0);
	&print_end_text;
	print OUT "		<tr>\n";
			# now print out the "favorite" images
	$count = 1;
	foreach $line (@favorites) {     # what 1st element of the array
		next if (!$line);	 # ignore blank line at beginning
		@name = split /\t/, $line;
		#$bird = $name[0];
		#$bird =~ s/\s+//g;
		$dir = &find_dir($name[3]);
			# Get rid of any quotes that excel adds
		$name[5] =~ s/\"//g;
		$day = $name[3] - int($name[3]/100)*100;
		$month = int($name[3]/100);
		$month = $month - int($month/100)*100;
		$year = int($name[3]/10000);
		$date = $month . "/" . $day . "/" . $year;

		$temp = $name[0];
			# add dash after bird name if there are notes
		if ($name[6]) {
			$ temp = $temp . " &mdash; ";
		}

		&print_rows ($date, $temp);
		$number = $number +1;
		$count = $count+1;
		if ($count > $row_max) {
			print OUT "        </tr>\n";
			print OUT "        <tr>\n";
			$count=1;
		}

   	}
	&print_end1;
	&print_endv;
	close OUT;
			#
			# now create the "Bibliography" page
			#
	$filename = $file_bib;
	local $space = "       ";
	open OUT, ">$filename" or die "Can't open $filename for writing\n";
	&print_header1 ("Bibliography for Bird Journal");
	&print_header1_bird;
			# Print intro
	print OUT $space, "<p>Below are the important books, web pages, and \n",
		$space, "journals and magazines that I have used to create these \n",
	       	$space, "web pages.  The list is still being developed.</p>\n";
		
			# do the web stuff first
        local @sweb = (sort {$b cmp $a} @web);
	print OUT  $space, "<b> Web: </b>\n";             
	print OUT $space, '<ul class="NoBullet">', "\n";
	while ($bline = pop (@sweb)) {
		chomp $bline;
		@fields = &process_line($bline, '\t');
		print OUT $space, "<li>$fields[0] - $fields[1]<li>\n";
   	}
	print OUT $space, '</ul>', "\n";

			# do the books
        local @sbook = (sort {$b cmp $a} @books);
	print OUT  $space, "<b> Books: </b>\n";             
	print OUT $space, '<ul class="NoBullet">', "\n";
	while ($bline = pop (@sbook)) {
		chomp $bline;
		print OUT $space, "<li>$bline</li>\n";
   	}
	print OUT $space, '</ul>', "\n";

			# do the journals
        local @smag = (sort {$b cmp $a} @mags);
	print OUT  $space, "<b> Journals and Periodicals: </b>\n";             
	print OUT $space, '<ul class="NoBullet">', "\n";
	while ($bline = pop (@smag)) {
		chomp $bline;
		print OUT $space, "<li>$bline</li>\n";
   	}
	print OUT $space, '</ul>', "\n";
	print OUT $space, '</div>', "\n";

	#&print_end1;
	&print_endv;
	close OUT;
			# ******** Print Video Page *******
			#
			# now create the "Video" page, which is the bird name,
			# video text, and a link to that birds's main page. 
			# Multiple videos are listed.
			#
	$filename = "videos.shtml";
	open OUT, ">$filename" or die "Can't open $filename for writing\n";
	$left_menu = "birds_menu.html";
	&print_header1 ("Bird Videos");
#			# execute routine to print out any text and links to feet,
			# tongue, etc.
#	$bird = "Bird Videos";
			# reverse sort names
        @bsorted = (sort {$b cmp $a} @video_birds);

	&print_video_text;
	&print_header1_vid;
	$temp = "";
	while ($abird = pop (@bsorted)) {
		my $spaces = "              ";
			# skip multiple instances of a bird, they are handled another
			# way
		next if ($abird eq $temp);
		my $link = $abird;		#used for link to .shtml file
			# get rid of all spaces and quotes for filename
		$link =~ s/\s+//g;
			# $plink points to bird web page, $vlink
		$plink = $link . ".shtml";

			# split to get the individual videos, multiple videos separated
			# by colon
		@bird_num = split /:/, $video{$abird};
		while ($bird_tx = shift(@bird_num)) {
					# separate video number from text
				print OUT "$spaces <tr>\n";
				my @bird_tx1 = split (/;/, $bird_tx);
						# need to make this not just for mp4 movies
				$video_name = "videos/$link" . "_" . $bird_tx1[0] . ".mp4";
				$video_name =~ s/'//g;
				print OUT $spaces . '<td class="vcol1"><a href="bird_' . $plink . '">' . $abird . "</a>" .
					"</td>\n";
	  			print OUT $spaces .'<td class="vcol2"> <a href="' . $video_name . '">' . "Movie </a></td>\n"; 
				chomp (@bird_tx1[1]);
	  			print OUT $spaces .'<td class="vcol3">' .  "@bird_tx1[1]</td>\n"; 
				print OUT $spaces ."</tr>\n";
		}
		$temp = $abird;
   	}

	print OUT '<tr><td><a href="#atop"><b>Top of Page</b></a></td></tr>' . "\n";
	print OUT $spaces . "</table>\n";
	print OUT $spaces . "</div>\n";
	&print_endv;
	close OUT;
			#
			# now process "Latest or most Recent photos"
			#
	$number = 1;
	$filename = "bird_Latest.shtml";
	open OUT, ">$filename" or die "Can't open $filename for writing\n";
	$left_menu = "birds_menu.html";
	 &print_header1 ("Latest Photos");
	 &print_header1_bird;
			# execute routine to print out any text
	$sbird = "Latest";
	&extras (0);
	&print_end_text;
	print OUT "		<tr>\n";
			# now print out the "latest" images
	$count = 1;
	while ($line = pop (@latest)) {
		@name = split /\t/, $line;
		$bird = $name[0];
		$bird =~ s/\s+//g;
		$dir = &find_dir($name[3]);
			# Get rid of any quotes that excel adds
		$name[5] =~ s/\"//g;
		$day = $name[3] - int($name[3]/100)*100;
		$month = int($name[3]/100);
		$month = $month - int($month/100)*100;
		$year = int($name[3]/10000);
		$date = $month . "/" . $day . "/" . $year;

		$temp = $name[0];
			# add dash after bird name if there are notes
		if ($name[6]) {
			$ temp = $temp . " &mdash; ";
		}

		&print_rows ($date, $temp);
		$number = $number +1;
		$count = $count+1;
		if ($count > $row_max) {
			print OUT "        </tr>\n";
			print OUT "        <tr>\n";
			$count=1;
		}

   	}
	&print_end1;
	&print_endv;
	close OUT;

}

sub process_line {
	local  $line = $_[0];
	local $sep = $_[1];
			# get rid of beginning spaces	
	$line =~ s/^\s+//;
			# break line using the seperator
	local @name = split /$sep/, $line;
	$num = @name;
			# return 0, if blank line
	if ($num < 0) {return NULL;}
			# skip comment lines
	if ($name[0] =~ /#/) {return NULL};
			# get rid of any extra spaces at the beginning and end of
			# of each element in the array
	for ($i=0; $i<$num; ++$i) {
		$name[$i] =~ s/^\s+//;		# get rid of any beginning spaces
		$name[$i] =~ s/\s+$//;		# get rid of any ending spaces
	}
	return @name;
}
sub find_dir {
#	finds the directory where the images are.  The directory is a
#	combination of the year and the month
# 	category name of the bird
   my $year = substr($_[0], 0, 4);
   my $month = substr ($_[0], 4, 2);
   $return_dir = $year . "/" . $month;
   return $return_dir
   }

sub create_rightmenu {
# loads the hash table with the information for the right menu
# depending on the title in "in_class"
   $class{$classification} =
	"     <!-- Row 1, column 4 (secondary bird menu) -->" .
	'     <td style="vertical-align:top">' . "\n" .
	'     <table border="0" RULES="none">' . "\n" .
	'     <tr>' . "\n" .
	'     <td class="right_menu">' . "\n" .
	"     All  &#8220;$classification&#8221;<hr> </td>\n" .
	"      </tr> <tr>\n" .
	'     <td class="right_menu">' . "\n" .
	'     <dl>';

		# sort the bird names before putting them in
   @sortb = (sort {$b cmp $a} @class_birds);
   @class_birds = @sortb;
   		# when I put the names in the right menu, I want
		# to avoid duplication of the last (proper) name.
		# For example, I want
		# Cormorant
		#   Brandt's
		#   Double-crested
   $last = "";
   $num = @class_birds;
   for ($i=$num - 1; $i >= 0; --$i ) {
	   @nam = split /:/, $class_birds[$i];
	   	# need bird name of current location
	   ($curr, $first) = &get_last_name($class_birds[$i]);
	   	# get the last name from field that is last,first
	   ($next, $temp) = &get_last_name($class_birds[$i-1]);
	   	# don't want to go outside the data
	   if ($i-1 < 0 ) {$next = " ";}
	   if ($curr eq $last) {
			# same last name, so print just the bird
			# first name with the link to the bird
		$class{$classification} = $class{$classification} .
		        "      <dt>\n" .
			'      &nbsp;&nbsp;&nbsp;<a class="right" href="' .
			"      $nam[1]\">$first</a> </dt>\n";
		$last = $curr;
	   }else{
   		if ($curr eq $next) {
				# only print lastname if it is a new bird
			if ($curr ne $last) {
			     $class{$classification} = $class{$classification} .
		        "      <dt>\n" .
			"      $curr </dt>\n";
			}
			$class{$classification} = $class{$classification} .
		        "      <dt>\n" .
			'      &nbsp;&nbsp;&nbsp;<a class="right" href="' .
			"      $nam[1]\">$first</a> </dt>\n";
			$last = $curr;
		}else{
			$class{$classification} = $class{$classification} .
		        "      <dt>\n" .
			'      <a class="right" href="' .
			"      $nam[1]\">$nam[0]</a> </dt>\n";
		}
	    }
   }
   $class{$classification} = $class{$classification} . "</dl>\n";
}
sub get_last_name {
	local @n = split/:/, $_[0];
	local @l = split/,/, $n[0];
	return $l[0], $l[1];
}

sub print_header1 {
# prints out most of the header that is used by all pages.
	print OUT <<HTML;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<meta name ="keywords" content="Pictures of $_[0]">
<meta name ="keywords" content="$_[0] Information">
<meta name ="description" content="Pictures and description of $_[0]">
<title> Bird pictures of $_[0] </title>
<!-- 
    1) Reference to the file containing the javascript. 
       This file must be located on your server. 
-->
<script type="text/javascript" src="$highdir/highslide-with-gallery.js"> </script>
<link rel="stylesheet" href="$highdir/highslide.css" type="text/css">
<link rel="stylesheet" href="birds.css" type="text/css">


<!-- 
   2) Initialize the hs object and optionally override the settings
      defined at the top of the highslide.js file. The parameter
      hs.graphicsDir is important!
-->
<script type="text/javascript">
	hs.graphicsDir = 'highslide/graphics/';
	hs.align = 'center';
	hs.transitions = ['expand', 'crossfade'];
	hs.outlineType = 'rounded-white';
	hs.wrapperClassName = 'controls-in-heading';
	hs.fadeInOut = true;
	//hs.dimmingOpacity = 0.75;

	// Add the controlbar
	if (hs.addSlideshow) hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 5000,
		repeat: false,
		useControls: true,
		fixedControls: false,
		overlayOptions: {
			opacity: 1,
			position: 'top right',
			hideOnMouseOut: false
			}
	})

</script>


<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-29073508-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>


<body>
<div id="highslide-container"> </div>
<!--
   4) Create an empty container for the Highslide popups to live in.
      This container must be defined directly after the body tag.
-->
<!-- Include Header -->
<!--#include virtual="birds_header.html"-->

<!-- Start main table and one row for holding both the left menu,
     the main body (bird information area) and the right menu -->
<table class="maintable">
	<tr>
	<td>

	<!-- Row 1, column 1 (Classification menu) -->
	<!-- Include menu -->
	<!--#include virtual="$left_menu"-->
	</td>
	<!-- Row 1, column 2 (Spacing) -->
	<td style="width:15px"> </td>
	<!-- Row 1, column 3 (Main Area - bird pictures & descriptions) -->
	<td>
	<a name="atop"> </a>
	<h3>$_[0]</h3>
HTML
}
sub print_header1_vid {
#	header used by video pages
		print OUT <<HTML1;
	      <table class="tvideo">
HTML1
}
sub print_header1_bird {
# 	header used by birds, places, etc.
		print OUT <<HTML2;
		<div class="small" style="width:450px">
HTML2
}
sub extras {
#   If a place ($j=1), print the descrition.  If a bird ($j=0), print the
#   description, links to tongue, feet, etc.
   $bbird = $sbird;
   $sub_flag = 0;
 	# get rid of any "'" in the bird name
   $bbird =~ s/\'//;
   		# Until I get all the birds with the new more complete descriptions
		# there will have to be some hand waving to print the right stuff
		# First off, the old way was a small description in the text/
		# directory for birds.  The new way is a more complete descrition]
		# in the Description/ directory.  If there is a file in the new
		# complete directory, the old one will be used.
		#
		# The new setup has a lot more information.  The Intro and Description
		# are printed before the pictures.  The rest, is printed after the pics.

	   	# If there is a "txt" file for the current bird or place, open it
		# and add the contents to the web page.  Otherwise, just print an
		# intro sentence.  # I keep the text files for the birds in ../text/.
		# and for places in ../text_place/.  I need to check both places to
		# find the text.

   		# first deal with text for birds
		# new complete description?
   $file_d = $desc_txt . $bbird . ".txt";   # pointer to complete desc.
   $file_t = $file_txt . $bbird . ".txt";	  # pointer to partial desc.
   if ($_[0] > 0) {
	   $file_t = $file_place . $bbird . ".txt";	# place pointer
   }
   	
   if (-f  $file_d) {
	   open TEXT, "<$file_d" or die "Can't open $file_d for reading\n";
	   &parse_desc;
   }elsif (-f $file_t) {
	   open TEXT, "<$file_t" or die "Can't open $file_t for reading\n";
	   while (<TEXT>) {
		        print OUT "		", $_;
	   }
	   close TEXT;
   }else {
	   print OUT "		<p>This page contains pictures I have taken of the $name[0]</p>\n";
   }

	   
	   	# If there is a "Tongue" file for the current bird, open it and add the
		# contents to the web page.
   $file_tongue = "../Tongue/" . $bbird . ".jpg";
   $tongue_text = "../Tongue/" . $bbird . ".txt";
   if (-f  $file_tongue) {
	   &print_extra ("tongue", $file_tongue, $tongue_text);
    }
	   
	   	# If there is  "feet" file for the current bird, open it and add the
		# contents to the web page.
   $file_feet = "../feet/" . $bbird . ".jpg";
   $feet_text = "../feet/" . $bbird . ".txt";
   if (-f  $file_feet) {
	   &print_extra ("feet", $file_feet, $feet_text);
   }
   if ($sub_flag) {
   	print OUT "</p>\n";
   }
   		# Now check for video clips
   $dir_video = "../videos/";
   if (exists $video{$fbird}) {
	   	# get number of movies for a bird and cycle through them looking for
		# multiple video encodings.  I.e., Canvasback_1.mov and Canvasback_1.mpg.
	   @list = split /:/, $video{$fbird};
	   print OUT "<p>\n";
	   while ($v = pop (@list)) {
 		   @vv = split /;/, $v;
  		   $bird_v = "../" . $video_dir . $bbird . "_" . $vv[0] . "*";
		   		# get rid of any quotes excel adds
		   $vv[1] =~ s/"//g;
 		   print OUT $vv[1], "\n";
 		   @in = `ls $bird_v`;
 		   while ($vvv = pop (@in)) {
			   chomp($vvv);
 			   $vvv =~ s,\.\.\/,,;
 			   ($dum, $exten) = split /\./, $vvv;
			   			# leaving in this quicktime check because
						# I might add these later or some other
						# extension.  Right now I only do mp4
 			   if (($exten =~ /mov/i) || ($exten =~ /qt/i)) {
 				   print OUT '<a href="videos/', $bbird,  "_$vv[0].",
 				   	$exten, '"> <b>(Quicktime)</b>&nbsp;&nbsp; </a>';
 			   }
			   if (($exten =~ /mp4/i) || ($exten =~ /mpg/i)) {
 				   print OUT '<a href="videos/', $bbird,  "_$vv[0].",
 				   	$exten, '"> <b>(MP4)</b> </a>&nbsp;&nbsp;';
 			   }
		   }
	   }
	   print OUT "		</p>\n";
   }
   print OUT "		</div>\n";
}
sub get_index {
# finds the file number for the movie files that is embedded in the text field,
# i.e., <1> is file1.
   my $start, $end, $diff, $length, $v1, $v2, $html;
   $start = index($line, "<");
   $end = index($line, ">");
   $diff = $end - $start - 1;
   $num = substr ($line, $start+1, $diff);
   $num =~ s/\s+//;
   print OUT substr($line, 0, $start), "\n";
   $v1 = $dir_video . $abird . $num . ".mov";
   if (-f $v1) {
	   $v1 = substr $v1, 3;
	   print OUT '<a href="', $v1, '"> (Quicktime) </a>', "\n";
   }
   $v1 = $dir_video . $abird . $num . ".mpg";
   if (-f $v1) {
	   $v1 = substr $v1, 3;
	   print OUT '<a href="', $v1, '"> (MPEG) </a>', "\n";
   }
   print OUT substr($line,$end+1);
}

sub print_extra {
# prints the feet/tongue/video for each bird page
   my ($extra, $extra_file, $extra_txt);
   ($extra, $extra_file, $extra_txt) = @_;
   $extra_file =~ s,../,,;
   if (!$sub_flag) {
	print OUT "<p>\n";
	print OUT "\n";
   }
   if (-f  $extra_txt) {
		   open TEXT, "<$extra_txt" or die "Can't open $extra_txt for reading\n";
	   	   while (<TEXT>) {
		        print OUT  "		", $_;
	           }
		   close TEXT;
   		   print OUT '(see <a href="' . $extra_file . '">' . $name[0] . "'s $extra</a>.)  ";
    }else{
   		   print OUT '<a href="' . $extra_file . '">' . $name[0] . "'s $extra</a>.  ";
    }

   $sub_flag = 1;
}
   
sub print_end1 {
	print OUT <<HTML1;
		</tr>
	     </table>
	     </div>
	     <div class="small">
	     <table style="width:435px">
	        <tr>
	        <td>
HTML1
   			# if there is a complete description, print the bottom part now
	if (@bot_des) {
		print OUT @bot_des;
	}
	print OUT <<HTML2;
	        </td></tr>
		<tr><td>
		<a href="#atop"> <br> <b>Top of Page</b> </a>
		</td></tr>
	     </table>
	     </div>
HTML2
	@bot_des = ();
}
sub print_endv {
	print OUT <<HTML1;
	     
</td>
</tr>
</table>
HTML1
}
sub print_end2 {
	print OUT <<HTML2;
	</td></tr>
	</table>
</td>
</tr>
</table>
<!-- 
	7 This is the markup for the controlbar. The controlbar is tied
	to the expander in the script tag at the top of the file.
-->
<div id="controlbar" class="highslide-overlay controlbar">
	<a href="javascript:void(0)" onclick="return hs.previous(this)" title="Previous (left arrow key)"> </a>
	<a href="javascript:void(0)" onclick="return hs.next(this)" title="Next (right arrow key)"> </a>
    <a href="javascript:void(0)" class="highslide-move" title="Click and drag to move"
    	style="margin-left: 10px"> </a>
    <a href="javascript:void(0)" onclick="hs.close(this)" title="Close"> </a>

</div>
</body>
</html>
HTML2
}


sub get_date_rec {
	# program to get today's date minus 'n' days.  This is used to find the most
	# recent photos for the current page
	my $num_days = 75;
	
	my $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst;
	my @month = ("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
		# get current time in epoch
	my $t = time;
		# get epoch date minus $num_days.
	my $days = $num_days * 24 * 60 * 60;
	my $nt = $t - $days;
		# convert to yyyymmdd
	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $nt;
		# want day to have a leading zero
	my $aday = $mday;
	if ($mday < 10) {$aday = "0" . $mday;}
	$date_rec = $year+1900 . $month[$mon] . $aday;
}

sub compute_latest {
	# program to take the latest photos and display approximately 30-45 photos
	# for the recent page.  To figure out what pictures to display, the
	# following is done: sort by priority, bird, date. If less than 40, print
	# all if greater than 40,  only use one picture per bird (one with lowest
	# priority)
	my $line, @name, $lastbird, @keep;
        my @bsort = (sort {$b cmp $a} @latest);
	my $total = $#bsort;
	$lastbird = "";
     	while ($line = pop(@bsort)) {
		@name = split /\t/, $line;
		if ($total < 40 ) {
			my $l = $name[0] . "\t" . $name[3] . "\t" . $name[1] .
				"\t" . $name[2] . "\t" .  $name[4] . "\t " .
			       	$name[5] . "\t" . $name[6];
			push (@keep, $l);
		}elsif ($name[0] ne $lastbird) {
			my $l = $name[0] . "\t" . $name[3] . "\t" . $name[1] .
				"\t" . $name[2] . "\t" .  $name[4] . "\t " .
			       	$name[5] . "\t" . $name[6];
			push (@keep, $l);
			$lastbird = $name[0];
		}
	}
	return @keep;
}
sub print_rows {

	print OUT <<HTML2;
		<td>
	      <!-- Start of Picture -->
		<a id="thumb$number" href="$dir/Images/$name[4].jpg" class="highslide"
			onclick="return hs.expand(this)">
		<img src="$dir/Images_sm/$name[4].jpg"  alt="Picture/image of $name[0]" /> </a>
	        <!-- Heading for Image -->
        	<div class="highslide-heading">
        	$_[0] - $name[5]
        	</div>
        	<!-- Caption for Image -->
        	<div class='highslide-caption' id='caption-for-thumb$number'>
        	$_[1]  $name[6]
        	</div>
        	<div class="bird_text">
        	$_[1] $name[6]
        	</div>
        	<div class="th_text">
        	$_[0] - $name[5]
        	</div>
        	</td>
HTML2
}

sub print_end_text{
	print OUT <<HTML2;
	      <div class="highslide-gallery">
	      <table style="width:435px">
HTML2
}
sub print_video_text {
	print OUT <<HTML2;
		<div class="small" style="width:435px">
		<p>
		<a name="atop"> </a>
		I have slowly been creating and putting videos of birds on my web
		site.  Some of the videos are made up of still images, others
		started life as a video.  The birds that have videos are:
		</p>
HTML2
}
sub parse_desc {
# reads the complete description file and breaks it into two parts.  The first
# is printed before the bird pics, the second after the bird pics and includes
# the references.  In both cases html formatting is added.
	   local $space = "                ";
	   local $bib = 0;
	   local $flag = 0;
	   local @t = ();		# hold lines for top description	
	   local @b = ();		# hold lines for bottom description	
	   @bot_des = ();
	   local @desc1 = ();
	   local @desc2 = ();

	   while (<TEXT>) {
		   s/^\s+//;
	           if ( /^Intro:/ || /^Description:/ || 
			/^Diet:/ || /^Courtship:/ || /^Nesting:/ ||
			/^Habitat and Range:/ || /^Plumage/ || /^Migration:/ ||
			/^Vocalization:/ || /^Tongue/ || /^Bibliography:/) {
			$_ = ";" . $_;
		   }
		   push (@desc1, $_);
           }
	   		# now get rid of any blank lines that don't signify
			# paragraphs, i.e., the ones around the titles
	   $len1 = @desc1;
	   for ($i=0; $i<$len1; ++$i) {
		   chomp $desc1[$i];
		   local $l = length($desc1[$i]);
		   if ($l == 0 && ($desc1[$i-1] =~ /^;/ ||
				   $desc1[$i+1] =~ /^;/)) {
			$local = 1;
		   }else {
		   	push (@desc2, "$desc1[$i]\n");
	           }
           }
	   		# break up the file into two pieces, one goes above the
			# pics, the other below. At the same time add the
			# paragraph markers to the remaining blank lines
	  local $fl = 0;
	  while ($item = shift(@desc2)) {
		  if ($item =~ /^\s+/) {
			  $item = "</p><p>\n";
		  }
		  if ($item =~ /^;Diet/  || $fl > 0) {
			  push (@b, $item);
			  $fl = 1;
		  }else{
			  push (@t, $item);
		  }
	  }

	   		# now process the general desc that goes at the top
	   $len = @t;
	   for ($i=0; $i<$len; ++$i) {
		   if ($t[$i] =~ /^;Description:/) {
			   $t[$i] = "</p><p>\n";
		   }elsif ($t[$i] =~ /^;Intro:/) {
			   $t[$i] = "<p>\n";
		           chomp ($t[$i+1]);
		           $t[$i+1] = "<i> $t[$i+1] </i> - \n";
			   $i = $i + 1;
		   }
	     }
	     push (@t, "</p>\n");
	     		# now print out the description for the top
	     foreach $line (@t) {
	     	    print OUT "$space $line";
	     }
	     print OUT '<a href="#moreinfo">more info</a>';
	     		# now save the lines for the bottom description
			# at this time we add the bibliography info
				# put in the internal link from the top
	   $len = @b;
	   local $fl = '<ul class="NoBullet">' . "\n";
	   for ($i=0; $i<$len; ++$i) {
	   	if ( $b[$i] =~ /^;/) {
			chomp ($b[$i]);
			$b[$i] =~ s/^;//;
			if ($b[$i] =~ /^Diet/) {
				$b[$i] = "\n<b>$b[$i]</b>\n $space <p>\n";
			}else{
				$b[$i] = "</p><b>$b[$i]</b>\n $space <p>\n";
			}
		   	if ($b[$i] =~ /Bibliography:/) {
		   		$bib = 1;
			}
		}elsif ($bib) {
		   	$b[$i] =~ s/\s+//;
			if ($b[$i] =~ /^[bB]/) {
				$b[$i] =~ s/^[bB]//;
				$b[$i] = $fl . "<li> $books[$b[$i]-1] </li>\n";
				$fl = "";
	         }elsif ($b[$i] =~ /^[mM]/) {
				$b[$i] =~ s/^[mM]//;
				$b[$i] = $fl . " <li> $mags[$b[$i]-1] </li>\n";
				$fl = "";
	         }elsif ($b[$i] =~ /^[wW]/) {
				$b[$i] =~ s/^[wW]//;
				$b[$i] =~ s/\t/ - /;
				$b[$i] = $fl . "<li> $web[$b[$i]-1] </li>\n";
				$fl = "";
	         }
	       }
	    }
	    push (@b, "</ul>\n");
	    $len = @b;
	    push (@bot_des, '<a name="moreinfo"></a>');
	    for ($i=0; $i<$len; ++$i) {
	    	push (@bot_des, "$space @b[$i]");
	    }
}
