#!/bin/perl

#
#  This script finds all wfsgfs type files in /pcom/gfs and determines the time of file
#  creation and when it arrived at TOC. The information is sorted by WMOID and placed 
#  in a flat file in /pcom/gfs
#
#  Justin Cooke  
#  2005 Nov 17 PMB
#
#  2010 Nov 16 PMB - Modified to use an input file list instead of reading the contents
#                    of a directory.

# Create output file and place a header for the table

open (STATUSFILE, '>', "$ENV{COMOUT}/wfsgfs_log_times.$ENV{PDY}") or die "Could not open wfsgfs_log_times.$ENV{PDY}: $!";

printf {STATUSFILE} "WMOID                NCEP Creation Time   Time NCEP made\n";
printf {STATUSFILE} "                                          available at TOC\n";
printf {STATUSFILE} "-------------------------------------------------------------\n";

$log_date = $ENV{PDY};

# Only check files listed in wfs_timeliness_ISCS

$wfs_times="$ENV{FIXGLOBAL}/gfs_wfs_time_stat.list";

open (WFS_TIMES, $wfs_times) or die "Could not open $ENV{FIXGLOBAL}/gfs_wfs_time_stat.list: $!";

while (<WFS_TIMES>) {
  chop;
  $fileinlist = $_;

  # Determine if file was ever "Put" up at TOC, if so grab the time, otherwise exit with an error

  if ($atime = `grep $fileinlist $ENV{DATA}/toc_push.log.$log_date | grep Put | cut -c 1-6'`){
    $at_hour = substr($atime, 0, 2);
    $at_min = substr($atime, 2, 2);
    $at_sec = substr($atime, 4, 2);
    $at_year = substr($log_date, 0, 4);
    $at_mon = substr($log_date, 4, 2);
    $at_day = substr($log_date, 6, 2);
    $arrival_time = sprintf "%4d-%02d-%02d %02d:%02d:%02d",$at_year,$at_mon,$at_day,$at_hour,$at_min,$at_sec;
     
  # stat the file to get necessary time creation information, then correct the year and month
 
    $ctime = (stat "$fileinlist")[9];
    ($ct_sec,$ct_min,$ct_hour,$ct_mday,$ct_mon,$ct_year,$junk,$junk,$junk) = gmtime($ctime);
    $ct_year=1900+$ct_year;
    $ct_mon=1+$ct_mon;

    # Build the arrival and creation time values

    $arrival_time = sprintf "%4d-%02d-%02d %02d:%02d:%02d",$at_year,$at_mon,$at_day,$at_hour,$at_min,$at_sec;
    $creation_time= sprintf "%4d-%02d-%02d %02d:%02d:%02d",$ct_year,$ct_mon,$ct_mday,$ct_hour,$ct_min,$ct_sec;

    # Pull out the WMOIDs, then for each one create an entry in the output file 

    $WMOIDlist = `strings $fileinlist | grep \"[HY]..... KWBC\"`;
    @WMOIDfulllist = split /\n/, $WMOIDlist;
    while (@WMOIDfulllist) {
       $WMOIDindividual = shift(@WMOIDfulllist);
       $output_string = join '',$WMOIDindividual,"   ", $creation_time,"  ",$arrival_time,"\n";
       printf {STATUSFILE} $output_string; 
    }
  }
  else { exit 1; }
}

