#!/bin/ksh

################################################################################
####  UNIX Script Documentation Block
#                      .                                             .
# Script name:         radmon_err_rpt.sh
# Script description:  Compare the contents of error files from two different 
#                      cycles.
#
# Author:        Ed  Safford       Org: NP23         Date: 2012-02-02
#
# Abstract:  This script compares the contents of two error files from two different
#            sets of radiance diagnostic files (which are an output from GSI runs).
#            All unique satellite instrument/channel/region combinations that appear
#            in both files are reported.
#
#            This script is a child script of radmon_verf_time.sh.  The parent
#            script creates/copies the error files into a temporary working 
#            directory before invoking this script.
#
#
# Script history log:
# 2012-02-02  Safford  initial script
#
# Usage:  radmon_err_rpt.sh file1 file2 type cycle1 cycle2 diag_rpt outfile
#
#   Input script positional parameters:
#     file1		obs, penalty, or channel error file
#                       required
#     file2		obs, penalty, or channel error file
#                       required
#     type              type of error file
#                       choises are obs, pen, or chan; required
#     cycle1		first cycle processing date
#                       yyyymmddcc format; required
#     cycle2		second cycle processing date
#                       yyyymmddcc format; required
#     diag_rpt          diagnostic report text file
#                       required
#     outfile           output file name
#                       required
#
#   Imported Shell Variables:
#
#     USHgfs            scripts directory
#                       defaults to pwd
#     INISCRIPT         preprocessing script
#                       defaults to none
#     LOGSCRIPT         log script
#                       defaults to none
#     ERRSCRIPT         error processing script
#                       defaults to 'eval [[ $err = 0 ]]'
#     ENDSCRIPT         postprocessing script
#                       defaults to none
#     VERBOSE           Verbose flag (YES or NO)
#                       defaults to NO
#
#   Exported Shell Variables:
#     err           Last return code
#
#   Modules and files referenced:
#     scripts    : $INISCRIPT
#                  $LOGSCRIPT
#                  $ERRSCRIPT
#                  $ENDSCRIPT
#
#     programs   : radmon_getchgrp.pl 
#                 
#
#     fixed data : $ctlfile
#
#     input data : $file1
#                  $file2
#
#     output data: $outfile
#
# Remarks:
#
#   Condition codes
#      0 - no problem encountered
#     >0 - some problem encountered
#
#  Control variable resolution priority
#    1 Command line argument.
#    2 Environment variable.
#    3 Inline default.
#
# Attributes:
#   Language: POSIX shell
#   Machine: IBM SP
####################################################################
#  Command line arguments.
file1=${1:-${file1:?}}
file2=${2:-${file2:?}}
type=${3:-${type:?}}
cycle1=${4:-${cycle1:?}}
cycle2=${5:-${cycle2:?}}
diag_rpt=${6:-${diag_rpt:?}}
outfile=${7:-${outfile:?}}

# Directories
USHgfs=${USHgfs:-$(pwd)}

# File names
INISCRIPT=${INISCRIPT:-}
LOGSCRIPT=${LOGSCRIPT:-}
ERRSCRIPT=${ERRSCRIPT:-}
ENDSCRIPT=${ENDSCRIPT:-}

# Other variables
VERBOSE=${VERBOSE:-NO}
err=0

if [[ "$VERBOSE" = "YES" ]]; then
   echo EXECUTING $0 $* >&2
   set -ax
fi

#export list=$list0

   have_diag_rpt=0
   if [[ -s $diag_rpt ]]; then
      have_diag_rpt=1
   else
      err=1
   fi


#-----------------------------------------------------------------------------
#  read each line in the $file1 
#  search $file2 for the same satname, channel, and region 
#  if same combination is in both files, add the values to the output file
#  
   { while read myline;do
      bound=""

      echo $myline
      satname=`echo $myline | nawk '{print $1}'`
      echo satname = $satname
      channel=`echo $myline | nawk '{print $3}'`
      echo channel = $channel
      region=`echo $myline | nawk '{print $5}'`
      echo region = $region
      value1=`echo $myline | nawk '{print $7}'`
      echo value1 = $value1
      bound=`echo $myline | nawk '{print $9}'`

#
#     Check findings against diag_report.  If the satellite/instrument is on the 
#     diagnostic report it means the diagnostic file file for the
#     satelite/instrument is missing for this cycle, so skip any additional
#     error checking for that source.  Otherwise, evaluate as per normal.
#

      diag_match=""
      diag_match_len=0 

      if [[ $have_diag_rpt == 1 ]]; then
         diag_match=`nawk "/$satname/" $diag_rpt`
         diag_match_len=`echo ${#diag_match}`
      fi


      if [[ $diag_match_len == 0 ]]; then  

         if [[ $type == "chan" ]]; then
            match=`nawk "/$satname/ && /channel=  $channel/" $file2`
         else
            match=`nawk "/$satname/ && /channel=  $channel / && /region=  $region /" $file2`
         fi
         match_len=`echo ${#match}`

         if [[ $match_len > 0 ]]; then
            echo $match_len
            value2=`echo $match | nawk '{print $7}'`
            bound2=`echo $match | nawk '{print $9}'`

            if [[ $type == "chan" ]]; then
               tmpa="$satname  channel= $channel"
               tmpb=""

            elif [[ $type == "pen" ]]; then
               tmpa="$satname  channel= $channel region= $region"
               tmpb="$cycle1         	$value1	$bound"

            else
               tmpa="$satname  channel= $channel region= $region"
               tmpb="$cycle1: $type= $value1"
            fi

            line1="$tmpa $tmpb"
            echo "$line1" >> $outfile

            if [[ $type != "chan" ]]; then
               tmpc=`echo $tmpa |sed 's/[a-z]/ /g' | sed 's/[0-9]/ /g' | sed 's/=/ /g' | sed 's/_/ /g' | sed 's/-/ /g'`

               if [[ $type == "pen" ]]; then
                  line2=" $tmpc $cycle2         	$value2	$bound2"
               else
                  line2=" $tmpc $cycle2: $type= $value2"
               fi 

               echo "$line2" >> $outfile
            fi

            #----------------------------------------------------------
            #  Access the control file to deterimine channel grouping 
            #  number.  Not all sources have consecutively numbered 
            #  channels, and we need to map the channel to the correct
            #  grouping number in order to produce an accurate hyperlink.
            #
            ctlfile="${satname}.ctl"
            changrp=`${USHgfs}/radmon_getchgrp.pl ${ctlfile} ${channel}`
            echo changrp = $changrp
            line3="   http://www.emc.ncep.noaa.gov/gmb/gdas/radiance/esafford/opr/index.html?sat=${satname}&region=region${region}&channel=${changrp}&stat=${type}"
            if [[ $changrp -gt 0 ]]; then
               echo "$line3" >> $outfile
               echo "" >> $outfile
            fi
         fi
      fi
   done } < $file1


################################################################################
#  Post processing
$ENDSCRIPT
set +x

if [[ "$VERBOSE" = "YES" ]]; then
   echo $(date) EXITING $0 with error code ${err} >&2
fi

exit ${err}

