#!/usr/local/bin/perl -w

use CGI qw/:standard :html3/;
use Date::Calc qw(Day_of_Year check_date);
use Date::EzDate;
use HTML::Escape qw/escape_html/;

print header('text/html');

my $xlatest=param("LATEST");
if ($xlatest) {
   if (($xlatest != 1)&&($xlatest != 0)) {
      errout("Invalid LATEST input\n");
   }
}
my $xyear=param("YEAR");
if ($xyear) {
   if (length($xyear)!=4) {
      errout("Invalid YEAR input\n");
   }
}
my $xmonth=param("MONTH");
if ($xmonth) {
   if (length($xmonth) > 2) {
      errout("Invalid MONTH input\n");
   }
}
my $xday=param("DAY");
if ($xday) {
   if (length($xday) > 3) {
      errout("Invalid DAY input\n");
   }
}
my $xdoy=param("DOY");
if ($xdoy) {
   if (length($xdoy) > 3) {
      errout("Invalid DOY input\n");
   }
}

our $dbug = 0;

my $latest=0;

my $mydate = Date::EzDate->new();
$mydate->set_warnings(0);
my $year=$mydate->{'year'};
my $month=$mydate->{'month number base1'};
my $day=$mydate->{'day of month'};
my $doy=-1;

my $eyear=-1;
my $edoy=-1;

$latest=param("LATEST");

my $scandir="/usr/local/htdocs/ACE/ASC/DATA/level3/swepam";
if($dbug) {
  $latest = 1 if( !defined $latest) ;
  $scandir=".";
}

my $scanstr="swepam_pa_summary";
my $plotypext="png";

if( !-d $scandir ) {
  errout("Ln35: Not a directory: $scandir\n");
}

# Early ONETIME fetch of all filenames
#       in given dir & with given extension 
our @allfiles=();
my $list_of_files="./swepam_pa_summary.lst";
open LOFILES,"<$list_of_files" or 
      errout("Cannot open $list_of_files\n\t$!\n"); 
@allfiles = <LOFILES>;
close LOFILES;

if (!$latest) {
   $year=param("YEAR");
   $month=param("MONTH");
   $day=param("DAY");
   $doy=param("DOY");

   if($dbug) {
     $year=2008;
     $month=7;
     $day=20;
     $doy=-1;
   }
   if ($doy <= 0) {
      if (!check_date($year,$month,$day)) {
         errout("Year:$year  Month:$month  Day:$day  is not a valid date\n");
      }
      $doy = Day_of_Year($year,$month,$day);
      $mydate->{'year'} = $year;
      $mydate->{'dayofyearbase1'} = $doy;
   }
   else {
      # strip any leading zeros from doy
      $doy = $doy + 0;
      # calculate month and day from year and doy
      $mydate->{'year'} = $year;
      $mydate->{'dayofyearbase1'} = $doy;
      # check doy requested by user does not change the year
      if ($mydate->{'year'} != $year) {
         errout("Year:$year  DayofYear:$doy is not a valid date.\n(Well it is, sortof, but I'm not sure it's what you want...)\n");
      }
      $month=$mydate->{'month number base1'};
      $day=$mydate->{'day of month'};
   }
   my $gotit = 0;
   my $origyear = $year;
   my $origdoy = $doy;
   for ($ii=0;$ii<4;$ii++) {
      if (exists_plotyp( $scandir, $scanstr, $year, $doy, $plotypext)) {
         $gotit = 1;
         last;
      }
      $mydate->{'epochday'}--;
      $year = $mydate->{'year'};
      $doy = $mydate->{'dayofyearbase1'};
      $month = $mydate->{'month number base1'};
      $day = $mydate->{'day of month'};
   }
   if (!$gotit) {
      errout("Plots containing data for Year:$origyear  DayofYear:$origdoy were not found, sorry...\n");
   }
   my $edate = $mydate->clone();
   $edate->{'epochday'} +=3;
   $eyear = $edate->{'year'};
   $edoy = $edate->{'dayofyearbase1'};
}
else {
   # show webpage with plots for latest day available
   ($year,$doy,$eyear,$edoy) = cur_yrdoy_ptype( $scandir, $scanstr, $plotypext );
   if ( $year == 0 ) {
      errout("Error scanning for latest $scanstr plot.\n");
   }
   # calculate month and dayofmonth from year,doy
   $mydate->{'year'} = $year;
   $mydate->{'dayofyearbase1'} = $doy;
   $month=$mydate->{'month number base1'};
   $day=$mydate->{'day of month'};
}

### adds zero's to the front of doy's that are less than 3 digits
$doy = $doy + 0;
$edoy = $edoy + 0;
$doy < 10 and $doy = "0$doy";
$doy < 100 and $doy = "0$doy";
$edoy < 10 and $edoy = "0$edoy";
$edoy < 100 and $edoy = "0$edoy";

my $prevdate = $mydate->clone();
$prevdate->{'epochday'} -=1;
my $prevyear = $prevdate->{'year'};
my $prevmonth = $prevdate->{'month number base 1'};
my $prevday = $prevdate->{'day of month'};
my $prevdoy = $prevdate->{'dayofyearbase1'};
#if (!exists_plotyp( $scandir, $scanstr, $prevyear, $prevdoy, $plotypext)) {
#  # IF NOT Found back off one more day
#  $prevdate->{'epochday'} -=1;
#  $prevyear = $prevdate->{'year'};
#  $prevmonth = $prevdate->{'month number base 1'};
#  $prevday = $prevdate->{'day of month'};
#  $prevdoy = $prevdate->{'dayofyearbase1'};
#}

my $nextdate = $mydate->clone();
$nextdate->{'epochday'} +=1;
my $nextyear = $nextdate->{'year'};
my $nextmonth = $nextdate->{'month number base1'};
my $nextday = $nextdate->{'day of month'};
my $nextdoy = $nextdate->{'dayofyearbase1'};
#if (!exists_plotyp( $scandir, $scanstr, $nextyear, $nextdoy, $plotypext)) {
#  # IF NOT Found bump up one more day
#  $nextdate->{'epochday'} +=1;
#  $nextyear = $nextdate->{'year'};
#  $nextmonth = $nextdate->{'month number base1'};
#  $nextday = $nextdate->{'day of month'};
#  $nextdoy = $nextdate->{'dayofyearbase1'};
#}

my $cmd="";
my $cmd1="sed -e 's/'YYYY'/'$year'/g' -e 's/'DDD'/'$doy'/g'";
my $cmd2="-e 's/'YYY2'/'$eyear'/g' -e 's/'DD2'/'$edoy'/g'";
my $cmd3="-e 's/'MNTH'/'$month'/g' -e 's/'MDAY'/'$day'/g'";
my $cmd4="-e 's/'PYPY'/'$prevyear'/' -e 's/'PMPM'/'$prevmonth'/' -e 's/'PDPD'/'$prevday'/'";
my $cmd5="-e 's/'NYNY'/'$nextyear'/' -e 's/'NMNM'/'$nextmonth'/' -e 's/'NDND'/'$nextday'/'";
my $cmd6="< ./$scanstr.tmpl";
$cmd = join ' ',$cmd1,$cmd2,$cmd3,$cmd4,$cmd5,$cmd6;
my @htmldata=`$cmd`;

# Adjust the year selection menu to years available in plot directory
setYearSelectionMenu(\@htmldata);

my $prevok = 1;
my $nextok = 1;
if (!exists_plotyp( $scandir, $scanstr, $prevyear, $prevdoy, $plotypext)) {
   $prevok = 0;
}
if (!exists_plotyp( $scandir, $scanstr, $nextyear, $nextdoy, $plotypext)) {
   $nextok = 0;
}

my $idx=0;

for ($idx=0; $idx<=$#htmldata; $idx++) {

   if ($htmldata[$idx] =~ m/!YEAR/) {
      my ($junk1, $curryear, $junk2) = split /\"/, $htmldata[$idx];
      if ($curryear == $year) {
         $htmldata[$idx] =~ s/option/option selected/ ;
      }
   }
   elsif ($htmldata[$idx] =~ m/!DAY/ ) {
      my ($junk1, $currday, $junk2) = split /\"/, $htmldata[$idx];
      if ($currday == $day) {
         $htmldata[$idx] =~ s/option/option selected/;
      }
   }
   elsif ($htmldata[$idx] =~ m/!MONTH/ ) {
      my ($junk1, $currmonth, $junk2) = split /\"/, $htmldata[$idx];
      if ($currmonth == $month) {
         $htmldata[$idx] =~ s/option/option selected/;
      }
   }
   elsif (($htmldata[$idx] =~ m/Next plot/ ) && ($nextok == 0)){
      $htmldata[$idx] = "<font color=\"gray\">Next plot</font>";
   }
   elsif (($htmldata[$idx] =~ m/Previous plot/ ) && ($prevok == 0)){
      $htmldata[$idx] = "<font color=\"gray\">Previous plot</font>";
   }
}

print @htmldata;

exit(0);


###=======   setYearSelectionMenu   ==========

sub setYearSelectionMenu {
  my ( $rhtml )= $_[0];
  our @allfiles;

  # Get years of 1st and last plots in directory
  # use names in @allfiles

  my @temp = ();
#  my $ptrn = "_(\\d\\d\\d\\d)_(\\d\\d\\d)_(\\d\\d\\d\\d)_(\\d\\d\\d)";
  my $ptrn = get_ptrn( $plotypext );
  $allfiles[0] =~ /$ptrn/ ;
  my $firstYear = $1;
  $allfiles[$#allfiles] =~ /$ptrn/ ;
#  my $lastYear = $3;
  my $lastYear = $1;

  # Append new option values in year selection menu
  my $idx = -1;
  @temp = ();	# Start with whole new @htmldata array of strings
  my $i = 0;
  while( $i <= $#$rhtml ) {
    last if( $$rhtml[$i] =~ /<!YEAR> <option VALUE/ ) ;
    push @temp, $$rhtml[$i];	# copy all up to the Selection YEAR menu
    $i++;
  }
  $idx = $i;
  # insert the new option values for sel menu (year values)
  for( my $i=$firstYear; $i<=$lastYear; $i++ ) {
    my $str = sprintf "<!YEAR> <option VALUE=\"%4d\">%4d\n", $i, $i ;
    push @temp, $str;
  }
  while( $$rhtml[$idx] =~ /option VALUE/ ) {
    $idx++;
    next;
  }
  for( my $i=$idx; $i<=$#$rhtml; $i++ ) {
    push @temp, $$rhtml[$i];	# append all remaining to the @temp
  }
  @$rhtml = ();			# Rewrite the $htmldata array
  push @$rhtml, @temp;

  return;
}

###=======   errout   ==========

sub errout {
        my ( $message )= @_;
        my $escaped = escape_html($message);
         print start_html('Error Message');
         print "<pre>$escaped</pre>\n";
         print end_html;
         exit(1);
}

###=======   exists_plotyp   ==========

###	$directory/$string_$Year_$DayofYear_hskp_0.xxx,
###     where $directory, $string, $year, and $dayofyear are
###	parameters provided by the calling routine.
###     $year is a four-digit year, and $dayofyear is 
###	a three-digit DayofYear.
###	xxx is (dot) file extension; e.g. jpg, gif
###     Return TRUE (Non-zero) if the pattern is matched, 
###	Return FALSE (0) otherwise.
###

### Initialization 
sub exists_plotyp {
  
  # Check command line args
  return 0 if( $#_ != 4 );

  my ($dir, $strng, $year, $DOY, $dotypext) = @_ ;
  our @allfiles;

  return( 0 ) if( ! -d $dir ) ;		# is directory?

  # Get names of all (dot) file extension files
  return( 0 ) if( $#allfiles < 0 );	# no files?

# Look for the specific string/date match
  $DOY = $DOY + 0;
  $DOY < 10 and $DOY = "0$DOY";
  $DOY < 100 and $DOY = "0$DOY";
  
  my $i=0;
  my $ptrn="";

  if ( $dotypext eq "jpg" ) {
    $ptrn = "${strng}_${year}-${DOY}";
  }
  if ( $dotypext eq "png" ) {
    $ptrn = "${year}-${DOY}";
  }
  while( $i <= $#allfiles ) {
    if( $allfiles[$i] !~ $ptrn ) { # Matches ??
      $i++;
      next;
    }
    return( 1 ) ;	# Match found
  }
  return( 0 );		# no match
}


###=======   cur_yrdoy_ptype   ==========
###     find the file with
###	the most recent year and doy, and return that year and doy 
###	to the calling routine (in some simple data structure).
###	If no files matching the pattern are found, then return 0,0.
###

### Initialization
sub cur_yrdoy_ptype {

  # Check command line args
  return 0 if( $#_ != 2 );
  my ($dir, $strng, $ptype) = @_ ;
  return( 0, 0 ) if( ! -d $dir ) ;		# is directory?

  # Get names of all $plotypext files
  our @allfiles;

  return( 0, 0 ) if( $#allfiles < 0 );

  my $val = 0;
  #latest date is the last member of the list...
  my $ptrn = get_ptrn( $plotypext );

  $allfiles[$#allfiles] =~ /$ptrn/ ;	# Capture yr & DOY from most recent filename
  $val = ($1 * 1000) + $2 ;
  return(0,0) if( $val <= 0 );		# in case none found

  $yr1 = $1;	# because filename format is "2008-204-00.png"
  $doy1= $2;
  $yr2 = $1;
  $doy2= $2;

  return( $yr1, $doy1, $yr2, $doy2 ) ; # Largest/Latest date ??
}


###=======   get_ptrn   ==========
sub get_ptrn {

# Returns pattern string for capturing start&end dates
  my $plotypext = $_[0];
  my $str = "";
  if( $plotypext eq "gif" ) {
    $str="_(\\d\\d\\d\\d)-(\\d\\d\\d).*(\\d\\d\\d\\d)-(\\d\\d\\d)";
  }
  elsif ( $plotypext eq "jpg" ) {
    $str="_(\\d\\d\\d\\d)-(\\d\\d\\d).*";
  }
  elsif ( $plotypext eq "png" ) {
    $str="(\\d\\d\\d\\d)-(\\d\\d\\d)-(\\d\\d).*";
  }

  return($str);
}
