#!/bin/ksh

set -x

#------------------------------------------------------------------
# runs hysplit dust system over CONUS 
#------------------------------------------------------------------
# Revised: 03 Apr 2010 (RRD,GSM) - Initial version
#------------------------------------------------------------------
#Overview
#  This dust system is configured to create hourly output for surface layer
# (0-100 m) and tropospheric (0-5 km) air concentrations in g/m^3 (adjusted
# to micrograms for output) on a 5 km (0.05 deg) resolution grid covering the
# CONUS. The emission locations are defined using a new procedure where the
# threshold friction velocity and soil texture coefficients were computed
# on a monthly basis on a 0.25 degree grid overthe CONUS.   The computation
# is based upon a statistical analysis of Ginoux's MODIS Deep Blue level-2
# AOD FOO (Frequency of Occurrence) data where grid cells with an AOD of
# 0.75 or greater were assumed to be the result of natural dust emissions.
# The AOD FOO was related to the friction velocity FOO, thereby defining the
# threshold velocity as well as the soil texture coefficient from the slope
# of friction velocity to AOD, which was converted to an emission rate.
# Although the emission algorithm was initially calibrated for PM10 sources,
# according to Ginoux, atmospheric mineral dust is dominated by particles
# with a radius of about 2 um.  The inconsistency is not expected to be 
# significant because potential emission points were identified using MODIS
# derived airborne dust. Large particles (10 um) gravitationally settle
# very quickly (25% mass loss within 6 h) so that the remaining airborne
# mass will be dominated by the smaller particles.  Both gravitational 
# settling and wet removal are turned on for the simulation.
#
#
# Configuration Details
#
#        Forecast Duration:      48 h
#        Concentration Grid:     25x60 deg span with 0.05 deg resolution
#                                   and center at 37.5N 95.0W
#                                SW corner - 25N 125W
#                                NE corner - 50N 65W
#        Vertical Resolution:    Grid1 - 0 to 100 m
#                                Grid2 - 0 to 10 km
#        Temporal Resolution:    One hour averages
#        Gravitational Settling: 4.0 um diameter and 2.5 g/cc density
#        Maximum particle age:   48 hours (all particles deleted after 
#                                           48 h transport)
#        Integration step:       6 minutes
#        Distribution:           3D particle
#        Particle number:        1 released per time step per source location
#        Number of sources:      2500 max if all sites exceed the
#                                     threshold velocity
#        Initialization:         All particles in domain from previous cycle
#-----------------------------------------------------------------------------

  echo "**Starting conus dust simulation: `date`"


# Step 1
    ${USHdust}/dust_config_conus.sh
    err=$?

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

#  Step 2
    export pgm=dust_hymodelm
    . prep_step
    msg="Starting dust_hymodelm run" 
    startmsg
    export MP_LABELIO=YES
    poe $EXECdust/dust_hymodelm >> $pgmout 2>errfile
    export err=$?;err_chk
#
#   Step 3: Generate Grib and Ascii files.
    ${USHdust}/dust_grib_conus.sh 
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN dust_grib_conus.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN dust_grib_conus.sh"
      err_chk
      exit
    else
      echo "Dust_grib_conus.sh Completed Normally."
    fi
#
    cp ${DATA}/PARDUMP* ${COMOUT}/.
    cp dustsfc ${COMOUT}/bin_dustconus_sfc.t${cyc}z
    cp dustpbl ${COMOUT}/bin_dustconus_pbl.t${cyc}z
    cp ${DATA}/bin* ${COMOUT}/.
    cp ${DATA}/grib* ${COMOUT}/.
    let task=1
    num=`printf %3.3d $task`
    while [ -f ${DATA}/MESSAGE.${num} ]; do
      cp ${DATA}/MESSAGE.${num} ${COMOUT}/MESSAGE.${num}_${PDY}${cyc}
      let task=$task+1
      num=`printf %3.3d $task`
    done

# convert to grib2
    export DBNALERT_TYPE=${DBNALERT_TYPE:-GRIB_HIGH}
    export NET=dustconus

    cd $DATA

    cp grib2_pbl.t${cyc}z.1hr_227 ${COMOUT}/${RUN}.${cycle}.grib2_pbl.1hr_227
    cp grib2_sfc.t${cyc}z.1hr_227 ${COMOUT}/${RUN}.${cycle}.grib2_sfc.1hr_227

    ##############################
    # Create AWIPS GRIB data
    ##############################

    for type in pbl sfc
    do
        echo 0 > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=grib2_${type}.t${cyc}z.1hr_227
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=dustconus_${type}.t${cyc}z.1hr_227.grib2.temp
        $EXECUTILdust/tocgrib2super < $PARMutil/grib2_dustconus_${type}.t${cyc}z.227

        echo `ls -l dustconus_${type}.t${cyc}z.1hr_227.grib2.temp | awk '{print $5} '` > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=dustconus_${type}.t${cyc}z.1hr_227.grib2.temp
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=dustconus_${type}.t${cyc}z.1hr_227.grib2
        $EXECUTILdust/tocgrib2super < $PARMutil/grib2_dustconus_${type}.t${cyc}z.227

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

        if test "$SENDCOM" = 'YES'
        then
            cp dustconus_${type}.t${cyc}z.1hr_227.grib2  $pcom/dustconus_${type}.t${cyc}z.1hr_227.grib2.$job

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

            if [ "$SENDDBN" = 'YES' ] ; then
               $DBNROOT/bin/dbn_alert $DBNALERT_TYPE $NET $job $pcom/dustconus_${type}.t${cyc}z.1hr_227.grib2.$job
            else
               msg="File $pcom/dustconus_${type}.t${cyc}z.1hr_227.grib2.$job not posted to db_net."
               postmsg "$jlogfile" "$msg"
            fi
        fi
    done
