#!/bin/ksh -x

########## config.fcst ##########
# Forecast specific

echo "BEGIN: config.fcst"

# Source model specific information that is resolution dependent
. $EXPDIR/config.fv3 $CASE
[[ "$CDUMP" == "gfs" ]] && export nth_fv3=$nth_fv3_gfs

# Get task specific resources
. $EXPDIR/config.resources fcst

if [ $DONST = "YES" ]; then
    . $EXPDIR/config.nsst
fi

export FORECASTSH="$HOMEgfs/scripts/exglobal_forecast.sh"
export FCSTEXECDIR="$HOMEgfs/exec"
export FCSTEXEC="global_fv3gfs.x"
export npe_fv3=$npe_fcst 

if [[ "$CDUMP" == "gfs" ]] ; then
   export npe_fv3=$npe_fcst_gfs
   export layout_x=$layout_x_gfs
   export layout_y=$layout_y_gfs
   export WRITE_GROUP=$WRITE_GROUP_GFS
   export WRTTASK_PER_GROUP=$WRTTASK_PER_GROUP_GFS
fi

if [ $QUILTING = ".true." ]; then
    export npe_fv3=$(echo " $npe_fv3 + $WRITE_GROUP * $WRTTASK_PER_GROUP" | bc)
    export npe_fcst=$npe_fv3
    export npe_fcst_gfs=$(echo " $npe_fcst_gfs  + $WRITE_GROUP_GFS * $WRTTASK_PER_GROUP_GFS" | bc)
fi

if [ $DO_WAVE = "YES" ] ; then
  export npe_fcst=$((npe_fcst + npe_wav))
  if [ "$WAVE_CDUMP" = "gfs" -o "$WAVE_CDUMP" = "both" ]; then
     export npe_fcst_gfs=$((npe_fcst_gfs + npe_wav_gfs))
     if [ "$CDUMP" = "gfs" ]; then npe_wav=$npe_wav_gfs ; fi
  fi
fi

# Model configuration
export TYPE="nh"
export MONO="non-mono"

# Use stratosphere h2o physics
export h2o_phys=".true."

# Options of stratosphere O3 physics reaction coefficients
export new_o3forc="YES"

# do_ugwp=T: use unified CGWD and OGWD, and turbulent orographic form drag (TOFD)
# do_ugwp=F: use unified CGWD but old OGWD, TOFD is not uded.
export do_ugwp=".false."
export do_tofd=".true."
export launch_level=$(echo "$LEVS/2.35" |bc)

export  n_sponge=42
export  d2_bg_k1=0.20
export  d2_bg_k2=0.04

# Sponge layer settings for L127
if [ $LEVS = "128" -a "$CDUMP" = "gdas" ]; then
   export  tau=5.0
   export  rf_cutoff=1.0e3
   export  d2_bg_k1=0.20
   export  d2_bg_k2=0.0
fi

# PBL/turbulance schemes
export hybedmf=".false."
export satmedmf=".true."
export isatmedmf=1
tbf=""
if [ $satmedmf = ".true." ]; then tbf="_satmedmf" ; fi

# Land surface model. (2--NoahMP, landice=F); (1--Noah, landice=T)
export lsm=1
if [ $lsm -eq 2 ]; then
    export lheatstrg=".false."
    export landice=".false."
else
    export lheatstrg=".false."
    export landice=".true."
fi

# Radiation options 
export IAER=5111    ;#spectral band mapping method for aerosol optical properties
export iovr_lw=3    ;#de-correlation length cloud overlap method (Barker, 2008)
export iovr_sw=3    ;#de-correlation length cloud overlap method (Barker, 2008)
export icliq_sw=2   ;#cloud optical coeffs from AER's newer version v3.9-v4.0 for hu and stamnes


# Microphysics configuration
export dnats=0
export cal_pre=".true."
export do_sat_adj=".false."
export random_clds=".true."

if [ $imp_physics -eq 99 ]; then # ZhaoCarr
    export ncld=1
    export FIELD_TABLE="$HOMEgfs/parm/parm_fv3diag/field_table_zhaocarr${tbf}"
    export nwat=2

elif [ $imp_physics -eq 6 ]; then # WSM6
    export ncld=2
    export FIELD_TABLE="$HOMEgfs/parm/parm_fv3diag/field_table_wsm6${tbf}"
    export nwat=6

elif [ $imp_physics -eq 8 ]; then # Thompson
    export ncld=2
    export FIELD_TABLE="$HOMEgfs/parm/parm_fv3diag/field_table_thompson${tbf}"
    export nwat=6

elif [ $imp_physics -eq 11 ]; then # GFDL
    export ncld=5
    export FIELD_TABLE="$HOMEgfs/parm/parm_fv3diag/field_table_gfdl${tbf}"
    export nwat=6
    export dnats=1
    export cal_pre=".false."
    export do_sat_adj=".true."
    export random_clds=".false."
    export lgfdlmprad=".true."
    export effr_in=".true."
    export reiflag=2

    export hord_mt_nh_nonmono=5
    export hord_xx_nh_nonmono=5
    export vtdm4_nh_nonmono=0.02
    export nord=2
    export dddmp=0.1
    export d4_bg=0.12

else
    echo "Unknown microphysics option, ABORT!"

fi
#---------------------------------------------------------------------

# ideflate: netcdf zlib lossless compression (0-9): 0 no compression
# nbits: netcdf lossy compression level (0-32): 0 lossless
export ideflate=1
export nbits=14
export ishuffle=0
# compression for RESTART files written by FMS 
export shuffle=1
export deflate_level=1

export OUTPUT_FILETYPES="$OUTPUT_FILE"
if [[ "$OUTPUT_FILE" == "netcdf" ]]; then
    export  ichunk2d=0; export jchunk2d=0
    export  ichunk3d=0; export jchunk3d=0;  export kchunk3d=0
    RESTILE=`echo $CASE |cut -c 2-`
    if [[ "$RESTILE" -ge "768" ]]; then
        export OUTPUT_FILETYPES=" 'netcdf_parallel' 'netcdf_parallel' "
    elif [[ "$RESTILE" = "384" && "$machine" = "WCOSS2" ]]; then
        export OUTPUT_FILETYPES=" 'netcdf' 'netcdf' "
    else
        export OUTPUT_FILETYPES=" 'netcdf_parallel' 'netcdf' "
    fi
    if [[ "$RESTILE" -ge "768" ]]; then
        export ichunk3d=$((4*RESTILE))
        export jchunk3d=$((2*RESTILE))
        export kchunk3d=1
        export ichunk2d=$((4*RESTILE))
        export jchunk2d=$((2*RESTILE))
    fi
fi


#---------------------------------------------------------------------
# Disable the use of coupler.res; get model start time from model_configure
export USE_COUPLER_RES="NO"

if [[ "$CDUMP" == "gdas" ]] ; then # GDAS cycle specific parameters

    # Variables used in DA cycling
    if [ $QUILTING = ".true." -a $OUTPUT_GRID = "gaussian_grid" ]; then
        export DIAG_TABLE="$HOMEgfs/parm/parm_fv3diag/diag_table_da"
    else
        export DIAG_TABLE="$HOMEgfs/parm/parm_fv3diag/diag_table_da_orig"
    fi

    # Write restart files, where $number is current model start time. 
    # restart_interval:        $number
    #    number=0, writes out restart files at the end of forecast. 
    #    number>0, writes out restart files at the frequency of $number and at the end of forecast.
    # restart_interval:        "$number -1"
    #    writes out restart files only once at $number forecast hour.
    # restart_interval:        "$number1 $number2 $number3 ..."
    #    writes out restart file at the specified forecast hours 
    export restart_interval=${restart_interval:-6}

    # For IAU, write restarts at beginning of window also
    if [ $DOIAU = "YES" ]; then
       export restart_interval="6 9"
       if [[ "$SDATE" = "$CDATE" && $EXP_WARM_START = ".false." ]]; then export restart_interval="3 6"; fi # Cold starting
    fi

    # Choose coupling with wave
    if [ $DO_WAVE = "YES" ]; then export cplwav=".true." ; fi

    # Turn on dry mass adjustment in GDAS
    export adjust_dry_mass=".true."

elif [[ "$CDUMP" == "gfs" ]] ; then # GFS cycle specific parameters

    # Write more variables to output
    if [ $QUILTING = ".true." -a $OUTPUT_GRID = "gaussian_grid" ]; then
        export DIAG_TABLE="$HOMEgfs/parm/parm_fv3diag/diag_table"
    else
        export DIAG_TABLE="$HOMEgfs/parm/parm_fv3diag/diag_table_orig"
    fi

    # Write gfs restart files to rerun fcst from any break point         
    export restart_interval_gfs=${restart_interval_gfs:-0}
    if [ $restart_interval_gfs -le 0 ]; then
        export restart_interval=0
    else
        rst_list=""
        IAU_OFFSET=${IAU_OFFSET:-0}
        [[ $DOIAU = "NO" ]] && export IAU_OFFSET=0
        xfh=$((restart_interval_gfs+(IAU_OFFSET/2)))
        while [ $xfh -le $FHMAX_GFS ]; do
          rst_list="$rst_list $xfh"
          xfh=$((xfh+restart_interval_gfs))
        done
        export restart_interval="$rst_list"
    fi

    
    # Choose coupling with wave
    if [ $DO_WAVE = "YES" -a "$WAVE_CDUMP" != "gdas" ]; then 
        export cplwav=".true."
    fi

    # Turn off dry mass adjustment in GFS
    export adjust_dry_mass=".false."

    # Write each restart file in 16 small files to save time
    if [ $CASE = C768 ]; then
      export io_layout="4,4"
    else
      export io_layout="1,1"
    fi


fi

    ## Debug load balancing
    # export KEEPDATA="YES"
    # export ESMF_RUNTIME_PROFILE=ON
    # export ESMF_RUNTIME_PROFILE_OUTPUT=SUMMARY


# Regrid tiles to global Gaussian grid in NEMSIO
export REGRID_NEMSIO_SH="$HOMEgfs/ush/fv3gfs_regrid_nemsio.sh"
if [ $DONST = YES ]; then
    export REGRID_NEMSIO_TBL="$HOMEgfs/parm/parm_fv3diag/variable_table_da.txt"
else
    export REGRID_NEMSIO_TBL="$HOMEgfs/parm/parm_fv3diag/variable_table_da_nonsst.txt"
fi

# Remap tiles to global latlon grid in NetCDF
export REMAPSH="$HOMEgfs/ush/fv3gfs_remap.sh"
export master_grid="0p25deg"                   # 1deg 0p5deg 0p25deg 0p125deg etc
export npe_remap=$((npe_fcst < 240 ? npe_fcst : 240))

# Global latlon NetCDF to nemsio utility parameters
export NC2NEMSIOSH="$HOMEgfs/ush/fv3gfs_nc2nemsio.sh"

# Remember config.efcs will over-ride these values for ensemble forecasts
# if these variables are re-defined there.
# Otherwise, the ensemble forecast will inherit from config.fcst

echo "END: config.fcst"