#!/bin/ksh
######################################################################
# SCRIPT: create_observation_archive_files.ksh
# LANGUAGE: Korn Shell                                               #
# MACHINE: CF
#--------------------------------------------------------------------#
# INITIATION SCRIPT: automated_gridded_2x2deg_surface_obs_production.ksh
# CALLING SCRIPT: produce_gridded_2x2deg_surface_obs.ksh
#--------------------------------------------------------------------#
# PURPOSE: 1) Converts input observations to 2 degree x 2 degree grid.
#          2) Produces binary archive files of all observations from
#             1995 to the present
# USAGE: create_observation_archive_files.ksh ${1} ${2} ${3}
#--------------------------------------------------------------------#
# INPUT FILES: 
#    cpc_0.25x0.25degree_gridded_precip.template.ctl - control file
#       template for input daily precipitation observation grids
#    us.tmax_nohads_ll.template.ctl - control file template for input
#       daily maximum temperature observation grids
#    us.tmin_nohads_ll.template.ctl - control file template for input
#       daily minimum temperature observation grids
# OUTPUT_FILES:
#    NONE
# SOURCED FILES:
#    ${HOME}/.profile - User's .profile
#--------------------------------------------------------------------#
# SUBROUTINES USED:
#    getnummo.ksh - Calculates number of months between two input dates
#    seasonal_prec_real.gs - Generates 2 degree x 2 degree precipitation
#       observation grids. Output grids are for a single month or season.
#    seasonal_temp_real.gs - Generates 2 degree x 2 degree mean temperature
#       observation grids. Output grids are for a single month or season.
#    udft - Grads user defined functions
# EXECUTABLES USED:
#    combine_realtime_forecast.Linux.exe - Combines all 2x2 observation grids
#       for a partucular observing period and parameter into a single
#       binary archive file 
#    seasonal_verif.Linux.exe - Categorizes observations using class limits
#       and generates binary categorical observation grids for a partucular
#       observing period and parameter
#--------------------------------------------------------------------#
# COMMAND-LINE VARIABLES:                                            #
#    ${1}= Observation Parameter [T|P]
#    ${2}= Observation Period [monthly|seasonal]
#    ${3}= Observation Center Month [YYYYMM format]
# GLOBAL VARIABLES:
#    DATA_OUT - compute farm data area
# LOCAL VARIABLES:
#    all_ranges_directory - output directory for binary gridded
#       output files
#    amon - 1st month of valid period
#    center_month - center month and year of observation period
#    cline - flag indicating whether command line arguments were correctly
#            entered by user
#    GAUDFT - path to Grads user defined functions
#    i - number of months in valid period
#    m1 - abbreviation for 1st month in valid period
#    m2 - abbreviation for 2nd month in valid period
#    m3 - abbreviation for 3rd month in valid period
#    mm - center month of observation period
#    month_after_valid_period - month after valid period ends
#    parameter - observed parameter
#    parm - abbreviation for observed parameter
#    period - observation period
#    period_abbreviation - abbreviation of observation period
#    qmon - 1st month of valid period
#    qyear - 1st year of valid period
#    recno - record number of current observation period in output
#       archive binary file (indexed to 1st month of valid period)
#    season - month abbreviations in valid period
#    this_month - current month
#    ydate - date after valid period ends
#    yearmo - 1st year and month of valid period
#    yyyy - center year of observation period
#    zday - last day of valid period
#    zmon - month abbreviation for last month of valid period
#    zyear - last year of valid period
#--------------------------------------------------------------------#
# AUTHOR: SCOTT HANDEL
#--------------------------------------------------------------------#
# DATE: April 23, 2012
#--------------------------------------------------------------------#
# MODIFICATIONS:                                                     #
######################################################################
######################################################################
# QUALITY CONTROL COMMAND-LINE ARGUMENTS
######################################################################
cline="TRUE"
case $# in
   3) case ${1} in
      T|P) cline=${cline}
           parameter=${1} ;;
      *) cline="FALSE" ;;
      esac
      case ${2} in
         monthly) cline=${cline}
                  period=${2}
                  period_abbreviation=mons ;;
         seasonal) cline=${cline}
                  period=${2}
                  period_abbreviation=seas ;;
         *) cline="FALSE" ;;
      esac
      case ${3} in
         [0-9][0-9][0-9][0-9][0-9][0-9]) cline=${cline}
                                         center_month=${3} ;;
          *) cline="FALSE" ;;
      esac ;;
   *) cline="FALSE" ;;
esac
######################################################################
# IF ANY OF COMMAND LINE ARGUMENT CONDITIONS ARE NOT MET, ALERT USER #
# OF PROPER USAGE                                                    #
######################################################################
if [ ${cline} = "FALSE" ]; then
   echo 'USAGE: create_observation_archive_files.ksh ${1} ${2} ${3}'
   echo "--------------------------------"
   echo '${1}= Observation Parameter [T|P]'
   echo '${2}= Observation Period [monthly|seasonal]'
   echo '${3}= Observation Center Month [YYYYMM format]'
   exit
fi
##################################################################
# ACCESS GRADS USER DEFINED FUNCTIONS
##################################################################
#!!!# export GAUDFT="${HOME}/udf/udft"

##################################################################
# GET MONTH AFTER OBSERVATION VALID PERIOD (USED FOR ESTABLISHING
# CORRECT RECORD NUMBER IN OBSERVATION ARCHVIE FILE AND FOR DATE
# QUALITY CONTROL CHECK)
##################################################################
yyyy=`echo ${center_month} | cut -c1-4`
mm=`echo ${center_month} | cut -c5-6`
case ${period_abbreviation} in
   mons) ydate=`date -d"${yyyy}-${mm}-02 +1 month" +"%Y-%m-%d"` ;;
   seas) ydate=`date -d"${yyyy}-${mm}-02 +2 month" +"%Y-%m-%d"` ;;
esac

###################################################################
# PERFORM DATE QUALITY CONTROL CHECK
###################################################################
echo ${ydate}
this_month=`date +"%Y%m"`
month_after_valid_period=`date -d"${ydate}" +"%Y%m"`
if [ ${month_after_valid_period} -gt ${this_month} ]; then
   echo "It is too early to create ${period} ${parameter} OBS for center month ${center_month}"
   exit 1
fi

##################################################################
# DETERMINE GRADS OUTPUT FILENAME PARAMETER BASED ON WHETHER
# OBS ARE MONTHLY OR SEASONAL
##################################################################
case ${period_abbreviation} in
   mons) i='1'
        season=`date -d"$ydate -1month" "+%b" | cut -c 1-3` ;;
   seas) i='3'
         m1=`date -d"$ydate -3month" "+%b" | cut -c 1-1`
         m2=`date -d"$ydate -2month" "+%b" | cut -c 1-1`
         m3=`date -d"$ydate -1month" "+%b" | cut -c 1-1`
         season=`echo ${m1}${m2}${m3} | tr "[A-Z]" "[a-z]"` ;;
esac
##################################################################
# ESTABLISH AND CREATE OUTPUT DIRECTORY
##################################################################
#!!!# all_ranges_directory="${DATA_OUT}/observations/land_air/long_range/conus/gridded_surface/all_ranges"
all_ranges_directory="/cpc/home/sparker/lrf/reproc/ob_glbt/output/all_ranges"
if [ ! -d ${all_ranges_directory} ]; then
   mkdir -p ${all_ranges_directory}
fi

##################################################################
# SET DATE PARAMETERS
##################################################################
zmon=`date -d"$ydate -2 day" +"%b"`
zyear=`date -d"$ydate -2 day" +"%Y"`
zday=`date -d"$ydate -2 day" +"%d"`
qyear=`date -d"$ydate -${i} month" "+%Y"`
qmon=`date -d"$ydate -${i} month" "+%b"`
##################################################################
# CREATE TEMPERATURE CONTROL FILE AND PROCESS TEMPERATURE OBS GRID
##################################################################
if [ ${parameter} = 'T' ]; then
##################################################################
# CREATE TEMPERATURE OBS CONTROL FILES USING TEMPLATE FILES
##################################################################
#   sed "s#INPUT_FILE#${DATA_IN}/cwlinks/temp/US/us_grid_nohads/%y4%m2%d2.tmax_nohads_ll#g" ../library/us.tmax_nohads_ll.template.ctl > ../library/us.tmax_nohads_ll.ctl
#   sed "s#INPUT_FILE#${DATA_IN}/cwlinks/temp/US/us_grid_nohads/%y4%m2%d2.tmin_nohads_ll#g" ../library/us.tmin_nohads_ll.template.ctl > ../library/us.tmin_nohads_ll.ctl
##################################################################
# CREATE TEMPERATURE OBS GRID
##################################################################
   echo "====> season = $season"
   echo "====> qyear = $qyear"
   echo "====> qmon = $qmon"
   echo "====> zday = $zday"
   echo "====> zmon = $zmon"
   echo "====> zyear = $zyear"
   grads -bpc "run ./seasonal_temp_real.gs $season $qyear $qmon $zday $zmon $zyear"
#   rm ../library/us.tmax_nohads_ll.ctl ../library/us.tmin_nohads_ll.ctl
fi
##################################################################
# CREATE PRECIPITATION CONTROL FILE AND PROCESS PRECIPITATION OBS GRID
##################################################################
if [ ${parameter} = 'P' ]; then
##################################################################
# CREATE PRECIPITATION OBS CONTROL FILES USING TEMPLATE FILES
##################################################################
   sed "s#INPUT_FILE#${DATA_IN}/cpcsat/cpcUniGaugeRT/PRODUCTS/GRID/%y4/gridCONUS/DEG0.250M/PRCP_CU_GAUGE_V1.0CONUS_0.25deg.lnx.%y4%m2%d2.RT#g" ../library/cpc_0.25x0.25degree_gridded_precip.template.ctl > ../library/cpc_0.25x0.25degree_gridded_precip.ctl
##################################################################
# CREATE PRECIPITATION OBS GRID
##################################################################
   grads -bpc "run ./seasonal_prec_real.gs $season $qyear $qmon $zday $zmon $zyear"
   rm ../library/cpc_0.25x0.25degree_gridded_precip.ctl
fi
##################################################################
# GET RECORD NUMBER FOR VERIFICATION PERIOD
##################################################################
amon=`date -d"$ydate -${i} month" "+%m"`
yearmo=`echo ${qyear}${amon}`
#!!!# recno=`./getnummo.ksh 199412 $yearmo`
recno=`ksh getnummo.ksh 199412 $yearmo`
echo $period_abbreviation $recno
##################################################################
# SET OUTPUT FILE NAME PARAMETER NAME
##################################################################
case ${parameter} in
   T) parm='temp' ;;
   P) parm='prec' ;;
esac 
##################################################################
# COMBINE 2x2 DEGREE GRIDDED OBS TO SINGLE ARCHIVE FILE
##################################################################
../build/combine_realtime_forecast.Linux.exe ../output/${season}${qyear}_${parm}_obs ${all_ranges_directory}/${parm}_${period_abbreviation}_archive.bi ${recno}
##################################################################
# CREATE VERIFICATION FILE USING CLASS LIMITS
##################################################################
../build/seasonal_verif.Linux.exe $recno ${parm} ${period_abbreviation} ${all_ranges_directory}
##################################################################
# REMOVE TEMPORARY FILES
##################################################################
#rm ../output/${season}${qyear}_${parm}_obs
