#! /bin/ksh

set -x

if [[ "$PARAFLAG" == YES ]] ; then
    # We must turn on set -e in PARA mode or we cannot catch 
    # failures of the scp script
    set -u -e
fi

now="${1:-$YMDH}"
CASE_ROOT="${2:-CASE_ROOT}"
winddest="${ATMOS_INPUT:-}"
oceanparent="${SPINUP_DATA:-}"
yyyy=$( echo "$now" | cut -c1-4 )
ymd=$( echo "$now" | cut -c1-8 )
hh=$( echo "$now" | cut -c9-11 )
oceandest="$oceanparent/$now"

# Set defaults if winddest or oceandest are missing
if [[ "$PARAFLAG" == NO ]] ; then
    winddest="${winddest:-$DATA/WINDS/gfs.$ymd}"
else
    winddest="${winddest:-$CDSCRUB/$user/DATA/WINDS/gfs.$ymd}"
fi
if [[ "$PARAFLAG" == NO ]] ; then
    oceandest="${oceandest:-$DATA/OCEAN/$now}"
else
    oceandest="${oceandest:-$CDSCRUB/$user/DATA/OCEAN/$now}"
fi

# Make sure the data destination directories exist:
$USHhwrf/hwrf_mkdirp.sh $winddest $oceandest

# Copy or link the GFS input:
if [[ "$PARAFLAG" == NO ]] ; then
    # In NCO mode, link to the operational locations:
    ymdh_m6=$( ndate -6 $now )
    ymd_m6=$( echo "$ymdh_m6" | cut -c1-8 )
    "$USHhwrf/hwrf_link_input.sh" \
        --gdas-satang "${COMINGDAS:-/com/gfs/prod}"/gdas.$ymd_m6 \
        "$now" "$winddest" "$oceandest" \
        "${COMINGFS:-/com/gfs/prod}"/gfs.$ymd
else
if [[ "$CASE_ROOT" == HISTORY ]] ; then
    "$USHhwrf/hwrf_para_input.sh" "$now" "$winddest" "$oceandest"
else  # CASE_ROOT" == FORECAST
    ymdh_m6=$( ndate -6 $now )
    ymd_m6=$( echo "$ymdh_m6" | cut -c1-8 )
    "$USHhwrf/hwrf_link_input.sh" --gdas-satang "${COMINGDAS:-/com/gfs/prod}"/gdas.$ymd_m6 \
         "$now" "$winddest" "$oceandest" \
         "${COMINGFS:-/com/gfs/prod}"/gfs.$ymd
fi
fi

# Copy or link the loop current file, but only in North Atlantic:
if [[ "$basin" == AL ]] ; then
    if [[ "$PARAFLAG" == NO ]] ; then
        "$USHhwrf/hwrf_get_oper_loop.sh" "$ymd" "$oceandest"
    else
if [[ "$CASE_ROOT" == HISTORY ]] ; then
        "$USHhwrf/hwrf_get_para_loop.sh" "$ymd" "$oceandest"
else
        "$USHhwrf/hwrf_get_oper_loop.sh" "$ymd" "$oceandest"
fi
    fi
fi

# Subset the grib file or files:
RUN_PREP_HYBRID=${RUN_PREP_HYBRID:-YES}
if [[ "$RUN_PREP_HYBRID" == NO ]] ; then
    $USHhwrf/hwrf_subset_gribs.sh "$now" "$winddest" 0 6 126
else
    $USHhwrf/hwrf_subset_gribs.sh "$now" "$winddest" 0 6 0
fi

# Get all tcvitals for the storm
vit=${VITAL_DATA:-/com/arch/prod/syndat/}syndat_tcvitals.$yyyy
if [[ "$PARAFLAG" == YES ]] ; then
    vit=$( $USHhwrf/hwrf_syndat_tcvitals.sh "$now" '' '' "$CASE_ROOT" )
fi
cat $vit | grep -E "^.....$ATCFID ......... $yyyy" \
    > "$DATA/$stormlabel.vitals"

exit 0
