#!/bin/ksh

set -x

#------------------------------------------------------------------
# Automated retrieval of NESDIS fire file and HYSPLIT submit
#------------------------------------------------------------------
#      22 May 2008 (RRD/GSM) - modifed to run over Alaskan domain
#      17 Feb 2010 (GSM) - get input file locally
#------------------------------------------------------------------
#Overview
#The dispersion model is preconfigured to run from selected regions using 
#a daily NAM meteorological forecast. Hourly average output maps of soot air
#concentration are produced. The fire locations for each day are tabulated
#and two dispersion simulations are produced.  A 24 h analysis simulation
#is run for the previous day using that day's fire locations.  The smoke
#particle positions at the end of the day are used to intitialze the 48 h
#dispersion forecast simulation.  The next day, the same initialization file
#is used to start the analysis simulation, prior to running the forecast.
# run submission date should be after meteorology is available    

  RUNDATE=${PDY}

  echo " rundate= ",$RUNDATE

# fire points date is valid for the previous day
  export FIREDATE=${PDYm1}
  echo " firedate= ",$FIREDATE

# working directory for model results.
# OLD variable was removed and placed with COMINm1.
#
# message log file
#  log=$COMOUT/"log.fire"
  echo "**Starting fire pm25 smoke simulation: `date`"


#------------------------------------------------------------------
# FINAL FILE FIRST ...
# Construct NESDIS file name from previous local date (i.e. PDYm1).
# Copy the file from /dcom.
#------------------------------------------------------------------

FILE="hmshysplit${FIREDATE}.txt"
cp /dcom/us007003/${FIREDATE}/wtxtbul/${FILE} .

#------------------------------------------------------------------
# PRELIM FILE NEXT ...
# Construct NESDIS file name from previous local date (i.e. PDYm1).
# Copy the file from /dcom.
#------------------------------------------------------------------

if [ ! -f ${FILE} ];then
   FILE="hmshysplit${FIREDATE}.prelim.txt"
   cp /dcom/us007003/${FIREDATE}/wtxtbul/${FILE} .
fi
#------------------------------------------------------------------
# if there is no current fire location file in /dcom, was there a valid
# run yesterday as shown by FIRES.NEW?      
#------------------------------------------------------------------

if [ ! -f ${FILE} ];then
   if [ -f ${COMINm1}/FIRES.NEW ];then
#     set dummy file name to one that exists to submit std job
      FILE="${COMINm1}/FIRES.NEW"
      echo "** Alaskan Wildfire locations today are from yesterday"
   else
      echo "** No Alaskan wildfire locations today or yesterday"
      err_exit "** No wildfire locations file today and no cycled smoke from yesterday"
   fi 

#------------------------------------------------------------------
# check file sizes to determine Email notification:
# 17 bytes = header record only, no fire locations
# 34 bytes = header record plus one data record
#------------------------------------------------------------------

else
   let flen=0
   echo "`wc -c ${FILE}`" | read flen tmp

   if [ $flen -gt 10 ];then
      echo "**${FILE} found and is of length: ${flen}"
      if [ $flen -gt 30 ];then
         echo "** Wildfire locations today"
         cp ${FILE} FIRES.TXT
      else
         echo "** HMShysplit file <=30 bytes!"
         echo "~s HMShysplit file <=30 bytes! \n No fires" | mail SABSupervisor@noaa.gov
         exit
      fi
   else
      echo "** HMShysplit file <=10 bytes!"
      echo "~s HMShysplit file <=10 bytes! \n Empty file" | mail SABSupervisor@noaa.gov
   fi
fi



#------------------------------------------------------------------
# Submit standard simulation if fires available or submit test
#------------------------------------------------------------------

if [ -f ${FILE} ];then

# Step 2
    ${USHsmoke}/smoke_config_ak.sh
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN smoke_config.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN smoke_config.sh"
      err_chk
    else
      echo "Alaskan smoke_config.sh Completed Normally."
    fi

#  Step 3
    export pgm=hysplit_hymodelm
    . prep_step
    msg="Starting Hysplit_hymodelm run" 
    startmsg
    $EXEChysplt/hysplit_hymodelm >> $pgmout 2>errfile
    export err=$?;err_chk

# Run with smoke_regional
    ${USHsmoke}/smoke_regional_ak.sh
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN smoke_regional.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN smoke_regional_ak.sh"
#      err_chk
    else
      echo "Alaskan smoke_regional.sh Completed Normally"
    fi 
#
# Generate Grib and Ascii files.
    ${USHsmoke}/smoke_grib_ak.sh ${RUNDATE}
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '***************************************'
      echo '*** FATAL ERROR IN smoke_grib_ak.sh ***'
      echo '***************************************'
      echo ' '
      postmsg "ERROR IN smoke_grib_ak.sh"
      err_chk
      exit
    else
      echo "Smoke_grib_ak.sh Completed Normally."
    fi
#
    cp ${DATA}/FIRES.NEW ${COMOUT}/.
    cp ${DATA}/PARDUMP* ${COMOUT}/.
    cp ${DATA}/bin* ${COMOUT}/.
    cp ${DATA}/grib* ${COMOUT}/.
    cp ${DATA}/noaasmk* ${COMOUT}/.
    cp ${DATA}/MESSAGE* ${COMOUT}/.
    cp icon* ${COMOUT}/.
    cp ${DATA}/files_fires_ak.tar ${COMOUT}/.
    cp ${DATA}/EMITIMES ${COMOUT}/.

# make grib2
    $EXECUTILsmoke/cnvgrib -g12 -m0 -p32 gribak_pbl.1hr grib2ak_pbl.1hr
    $EXECUTILsmoke/cnvgrib -g12 -m0 -p32 gribak_sfc.1hr grib2ak_sfc.1hr

    cp grib2ak_pbl.1hr ${COMOUT}/.
    cp grib2ak_sfc.1hr ${COMOUT}/.

# interpolate to 198
   echo ' &NLCOPYGB IDS(164)=2, IBS(164)=-1 /' > smoke_scale
   $EXECUTILsmoke/smoke_copygb -N smoke_scale -g 198 -x gribak_pbl.1hr gribak_pbl.1hr_198
   $EXECUTILsmoke/smoke_copygb -N smoke_scale -g 198 -x gribak_sfc.1hr gribak_sfc.1hr_198

     cp gribak_pbl.1hr_198 ${COMOUT}/.
     cp gribak_sfc.1hr_198 ${COMOUT}/.

# convert to grib2
    export DBNALERT_TYPE=${DBNALERT_TYPE:-GRIB_LOW}
    export NET=smoke

    cd $DATA
    $EXECUTILsmoke/cnvgrib -g12 -m0 -p2 gribak_pbl.1hr_198 grib2ak_pbl.1hr_198
    $EXECUTILsmoke/cnvgrib -g12 -m0 -p2 gribak_sfc.1hr_198 grib2ak_sfc.1hr_198
    cp grib2ak_pbl.1hr_198 ${COMOUT}/${RUN}.${cycle}.grib2ak_pbl.1hr_198
    cp grib2ak_sfc.1hr_198 ${COMOUT}/${RUN}.${cycle}.grib2ak_sfc.1hr_198

##################################
#   Send grib2 files to the WOC
##################################
    if [ "$SENDDBN" = 'YES' ] ; then
         $DBNROOT/bin/dbn_alert MODEL SMOKE $job ${COMOUT}/${RUN}.${cycle}.grib2ak_pbl.1hr_198
         $DBNROOT/bin/dbn_alert MODEL SMOKE $job ${COMOUT}/${RUN}.${cycle}.grib2ak_sfc.1hr_198
    else
         msg="File ${COMOUT}/${RUN}.${cycle}.grib2ak_pbl.1hr_198 not posted to dbnet."
         postmsg "$jlogfile" "$msg"
         msg="File ${COMOUT}/${RUN}.${cycle}.grib2ak_sfc.1hr_198 not posted to dbnet."
         postmsg "$jlogfile" "$msg"
    fi
    ##############################
    # Create AWIPS GRIB data
    ##############################

    for type in pbl sfc
    do
        echo 0 > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=grib2ak_${type}.1hr_198
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=smoke_ak_${type}.1hr_198.grib2.temp
        $EXECUTILsmoke/tocgrib2super < $PARMutil/grib2_smoke_ak_${type}.198

        echo `ls -l smoke_ak_${type}.1hr_198.grib2.temp | awk '{print $5} '` > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=smoke_ak_${type}.1hr_198.grib2.temp
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=smoke_ak_${type}.1hr_198.grib2
        $EXECUTILsmoke/tocgrib2super < $PARMutil/grib2_smoke_ak_${type}.198

        ##############################
        # Post Files to PCOM
        ##############################

        if test "$SENDCOM" = 'YES'
        then
            cp smoke_ak_${type}.1hr_198.grib2  $pcom/smoke_ak_${type}.1hr_198.grib2.${job}

            ##############################
            # Distribute Data
            ##############################

            if [ "$SENDDBN" = 'YES' ] ; then
               $DBNROOT/bin/dbn_alert $DBNALERT_TYPE $NET ${job} $pcom/smoke_ak_${type}.1hr_198.grib2.${job}
            else
               msg="File ${pcom}/smoke_ak_${type}.1hr_198.grib2.${job} not posted to dbnet."
               postmsg "$jlogfile" "$msg"
            fi
        fi
    done
else
  echo "** HMShysplit file not found! No Alaskan Smoke Run Today!"
  exit
fi
