#! /usr/bin/perl -W -w
#------------------------------------------------------------------------------
#
# Program Name: nos_glofs_get_glavewl.pl 
#
# Abstract: This script is used to read GLERL Great Lakes average water level file for each lake.
#           It outputs an ascii file.                                              
#
# 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);

# 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 average water level file for the Great Lakes from the date nearest to $time.\n";
}

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

# $ODAASDIR environment variable must be set
if ($ENV{'GLSEADIR'})
{
  $glseadir=$ENV{'GLSEADIR'};
}
else
{
  print "\nERROR: get_glavewl.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_glavewl.pl needs \$EXECutil environment variable to be defined before execution.\n";
  exit 5;
}

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

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

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

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

  $size=-s $searchpath;

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

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

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

     $searchpath=$glseadir . "/" . $searchdir . "/" . "wtxtbul" . "/nos_glavewl.dat";

    $size=-s $searchpath;
    if ($size == 145)
    {
      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;
}

print "File is current, and the required size\n";

use File::Copy;
#copy file to work directory
copy($searchpath, $workdir) or die "File cannot be copied.";

print "End nos_glofs_get_glavewl.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;      
}
      
