#! /usr/bin/perl -W -w
#------------------------------------------------------------------------------
#
# Program Name: get_glsea.pl
#
# Abstract: This script is used to read GLERL Great Lakes mean surface temperature.
#           It outputs an ascii file.                                              
#           It is a part of COMF (formerly NGOFS), and it gets obs files from
#           ODAAS.
#
# Location: $OQCSDIR/scripts/
#
# Technical Contacts:	Zack Bronder		 Org: NOAA/NOS/CO-OPS
#			Phone: 301-713-2890x152	 E-mail: Zachary.Bronder@noaa.gov
#                       Mark Vincent		 Org: NOAA/NOS/CO-OPS
#			Phone: 301-713-2890x151  E-mail: Mark.Vincent@noaa.gov
#
# Author: Zack Bronder       Creation Date: March 18, 2005       
#
# Language: Perl
#
# Usage: 	Interactively: get_glsea.pl time lake nowcastend         
#		      example: get_glsea.pl '2005 01 01 00 00' ERIE '2005 01 02 00 00'
# 		Automatically: get_glsea.pl can be called by model scripts,
#                              such as MAIN_LEOFS.sh, which are launched via cron.
#
# Input Parameters: "time" is the date from which the mean surface temperature will be returned.
#                   It consists of integers for year, month, day, hour, and minute.
#                   In model scripts it will usually be $time_hotstart.
#                   "lake" is the great lake at which the mean surface temperature will be returned.
#                   "nowcastend" is the time of the end of nowcast. This is used to make CORMS flags.
#
# Target computer: Runs on COMF computers, such as glofs.nos.noaa.gov.
#                  Gets input from ODAAS computers, such as odaas1.nos.noaa.gov.
#
# Estimated execution time:
#
# Error Conditions:
#
# Scripts/Programs Called:
# 	Name			Directory Location		Description
#
# Input Files:
#       Name                    Directory  Location             Description
#  YYYYMMDD_glsea-tmps.txt  $ODAASDIR/ocean/obs/ncep/archives/YYYYMM  obs text file
#
# Output Files:
#       Name                    Directory Location              Description
#       get_glsea.txt	.		            text file of lake surface temperature 
#             
# Revisions:
#      	Date       Author                          Description
#   2006-07-26   Greg Mott   Changed input time from '2006 07 25 00 00' to '2006072500'
#                            Changed path of data directory (still hardwired)
#                            Got rid of inputting nowcastendtime since no corms flags
#                            May need more developing!          
#
# Remarks: For debugging use #! /usr/bin/perl -W -w
#
# ------------------------------------------------------------------------------

#get $CORMSLOG environment variable, path of working directory
$workdir=`pwd`;
# remove carriage return
chomp ($workdir);

#set times
########################
#CCM commenting out the next 2 lines -- not used for now
#$time_nowcastend=$ENV{'time_nowcastend'};
#$time_forecastend=$ENV{'time_forecastend'};
########################
#Check for CORMS log file
if ($ENV{'FCSTSYSLOG'})
{
  $cormslog=$ENV{'FCSTSYSLOG'};
  chomp ($cormslog);
  print "\nStarting nos_get_glsea.pl with cormslog $cormslog.\n";
}
else
{
  $cormslog=$workdir . "/get_glsea.err";
  print "\nWarning: starting nos_get_glsea.pl with no CORMSLOG environment variable set!\n";
}

# assign variables
$time=$ARGV[0];
$model=$ARGV[1];
$argsum=@ARGV;
print "time=$time, lake=$model, argsum=$argsum.\n";

# check that right number of arguments has been given
if ( $argsum == 2 ) 
{
  if ( $model eq "leofs" )
  {
   $lake= "ERIE";
  }
  if ( $model eq "lmofs" )
  {
   $lake= "MICHIGAN";
  }
  if ( $model eq "lhofs" )
  {
   $lake= "HURON";
  }
  if ( $model eq "lsofs" )
  {
   $lake= "SUPERIOR";
  }
  if ( $model eq "loofs" )
  {
   $lake= "ONTARIO";
  }
  print "This job will get the mean surface temperature of the Great Lake $lake from the date nearest to $time.\n";
}

else
{
  print "ERROR: get_glsea.pl needs two arguments for time, and lake.\n";
  print "Example: get_glsea.pl '2006010112' ERIE\n";
  exit 1;
}

# $ODAASDIR environment variable must be set
if ($ENV{'GLSEADIR'})
{
  $glseadir=$ENV{'GLSEADIR'};
}
else
{
  print "\nERROR: get_glsea.pl needs \$GLSEADIR environment variable to be defined before execution.\n";
  exit 2;
}

# set utilexec environment variable
if ($ENV{'EXECutil'})
{
  $utilexec=$ENV{'EXECutil'};
}
else
{
  print "\nERROR: get_glsea.pl needs \$EXECutil environment variable to be defined before execution.\n";
  exit 5;
}

#print "Variables: time=$time, ODAASDIR=$odaasdir, glseadir=$glseadir.\n";
# dateformat program needs to be in $PATH for date limit variables

$firsttime=`$utilexec/ndate +1 $time`;

# variables for output directories
$outfile=$workdir . "/get_glsea.txt";
unlink ($outfile);
# change directory to the glsea archives
system ("pwd");
chdir ($glseadir);
# Search for glsea date closest to requested date, no more that +/- 32 days from requested date
for ($i = 0; $i < 33; $i++)

{
   $searchtime=`$utilexec/ndate -$i $firsttime`;

   $searchdir=substr($searchtime,0,8);
 
   $searchpath=$glseadir . "/" . $searchdir . "/" . "wtxtbul" . "/glsea-temps.dat";

  $size=-s $searchpath;

  print "  searchpath=$searchpath, size=$size.\n";  

  if ($size == 18202)
  {
    print "  $searchpath is correct size.\n";
    $foundpath=$searchpath;   
    last;
  }
  else
  {

    $searchtime=`$utilexec/ndate -$i $firsttime`;
    $searchdir=substr($searchtime,0,8);

     $searchpath=$glseadir . "/" . $searchdir . "/" . "wtxtbul" . "/glsea-temps.dat";

    $size=-s $searchpath;
    if ($size == 18202)
    {
      print "  $searchpath is correct size.\n";
      $foundpath=$searchpath;
      last;
    }
    else
    {  
      print "  Didn't find dated file of +/- $i days with correct size.\n";
    }    
  }
}
#
unless ( defined($foundpath) )
{
  print "\nERROR: get_glsea.pl didn't find a dated archive file of the correct size with an acceptable date.\n";
  exit 3;
}
# Get last line of archived mean surface temperature file
open(FILE,"<$searchpath");
while(<FILE>)
{
  $line=$_;
}
# fields & chars: year,1-4; day,6-8; Sup,13-16; Mich,21-24; Hur,29-32; Er,37-40; Ont,45-48.
# the line form 
@linefields=split(/\s+/,$line);
#print "line=$line, linefields=@linefields.\n";
$lineyear=$linefields[0];    
$lineday=$linefields[1];        
if ($lake eq "SUPERIOR")
{
  $temp=$linefields[2];
}
elsif ($lake eq "MICHIGAN")
{
  $temp=$linefields[3];         
}
elsif ($lake eq "HURON")
{
  $temp=$linefields[4];         
}
elsif ($lake eq "ERIE")
{
  $temp=$linefields[5];        
}
elsif ($lake eq "ONTARIO")
{
  $temp=$linefields[6];        
}
else
{
  print "\nERROR: get_glsea.pl needs second input arguement to be one of the following;\n";
  print "SUPERIOR, MICHIGAN, HURON, ERIE, ONTARIO.\n";
  exit 4;
}
# Get month and day of month from the day of year listed in the line from the archive file
@monthanddayout=&year_day_to_month_day($lineyear, $lineday);
$outmonth=sprintf("%02d",$monthanddayout[0]);
$outday=sprintf("%02d",$monthanddayout[1]);
#print "monthandday=@monthanddayout, outmonth=$outmonth, outday=$outday.\n";
open (OUT,">>$outfile");
print "$lineyear $outmonth $outday $lineday $temp LAKE $lake AVG WATER TEMP\n";
print OUT "$lineyear $outmonth $outday $lineday $temp LAKE $lake AVG WATER TEMP\n";
close (OUT);

# Make CORMS flags
#@timediff=split(/\s+/,`datemath $lineyear $outmonth $outday 12 00 - $nowcastend`);
#$hourdiff=($timediff[2]*24)+($timediff[3]);

$nowlaketime=$lineyear . $outmonth . $outday . "12";

print "nowlaketime $nowlaketime\n";

#CCM $hourdiff=`/nwprod/util/exec/nhour $nowlaketime $time_nowcastend`;
$hourdiff=`$utilexec/nhour $nowlaketime $time`;
# Write CORMS flags
open (CORMS,">>$cormslog");
print "LAKETEMP AGE $hourdiff\n";
print CORMS "LAKETEMP AGE $hourdiff";
close (CORMS);

print "End get_glsea.pl\n";
exit;

####################################################################################
# SUBROUTINES
####################################################################################

# This subroutine takes in year and day of year, and gives back numeric month and day of month.
sub year_day_to_month_day
{
  my $year=$_[0];
  my $day=$_[1];
  my @monthdays=(31,28,31,30,31,30,31,31,30,31,30,31);
  my $nonleapyear=$year%4;
  unless ( $nonleapyear )
  {
    $monthdays[1]=29;
  }
  if (($day < 1) or (($nonleapyear) && ($day > 365)) or ((! $nonleapyear) && ($day > 366)))
  {
    print "Day is out of bounds: it should be more than 0 and less than 365, or 366 if it's a leap year.\n";
    return;  
  }
  #print "Subroutine year_day_to_month_day variables: year=$year, day=$day, nonleapyear=$nonleapyear, monthdays=@monthdays.\n";
  my $index; 
  for ( $index=0; $index<12; $index++ )
  {
    if ( $day < $monthdays[$index] )
    {
      last;
    }
    else 
    {
      $day=$day - $monthdays[$index];
    }
  }
  my $month=$index + 1;
  my @monthandday=($month,$day);
  print "@monthandday\n";
  @monthandday;      
}
      
