#!/cygdrive/c/strawberry/perl/bin/perl
# Program to check the image files saved against the inventory database (input argument).
# It does this by reading in the database into a hash table and then walking the
# file system looking for images.  Each image is checked against the file system to make
# sure there is an entry.  If not, an error statement is printed.
#
# The corresponding program for this is check_inventory which make sure there are three files
# for each entry into the database.
#
# Original line from excel
#   date priority filename bird_name bird_category picture_location notes
#
#$root_dir = "../";		# root dir for finding birds images
$root_dir = "/cygdrive/c/htdocs/birds/";		# root dir for finding birds images
@dir_sub = ("Images_sm/",  "Images/", "Images/Full_res/");	# directory for original full images

{
   print "Checking to make every file in the database directories has a corresponding\n",
  	 "  entry in the database (standard in).  If the file is not in the databse\n",
	 "  the filename is printed.\n\n";
   while ( <STDIN> ) {
			# read in the inventory and create a hash table.  The hash
			# table name is made up of the date (year+month) and the
			# file name (minus .jpg).
 			# get rid of any beginning spaces or tabs (comment lines)
	s/^\s+//;
	@name = split /\t/;
	$num = $#name;
			# skip if a zero'd line (excel did this) 
	next if ($num <= 0);
			# skip comment lines
	next if ($name[0] =~ /#/);
			# get the year and month
	$date =  substr($name[0],0,6);
			# get rid of any extra spaces at the beginning or end of
			# the bird file name
	$name[3] =~ s/^ +//;		# get rid of any beginning spaces
	$name[3] =~ s/ +$//;		# get rid of any ending spaces
	$bird = $date . $name[3];
	if (! exists $bird{$bird}) {
		$birds{$bird} = 1;
	}
   }
   @k = keys %birds;
   $searchdir = $root_dir . "200*/*";
   @dirs = `ls -d $searchdir`;
   foreach $d (@dirs) {
	@parts = split /\//, $d;
	$base = $parts[5] . $parts[6];
	$base =~ chomp($base);
	foreach $sub (@dir_sub) {
		$d =~ chomp($d);
		$chdir =  $d . "/" . $sub;
		#chdir "$chdir" or die "cannot chdir to $chdir\n";
		@files = `ls $chdir`;
		foreach $_ (@files) {
			chomp;
			if (! (/jpg/ || /JPG/)) {next;}
			@name = split/\./;
			$thefile = $base . $name[0];
			if (! exists $birds{$thefile}) {
				print "$base $name[0] in directory $chdir not found\n";
			}
		}
	}
   }
}
