#! /bin/ksh

# Takes a .atcfunix track as input.  If the track has only analysis
# time, and the location or intensity are zeros, then replaces the
# track with tcvitals.  Also, if the track is empty, it will be
# replaced with tcvitals.
#
# Inputs:
#    $1 -- the track file
#    $2 -- the $DATA/tmpvit file
set -x
trakfile="$1"
tmpvit="$2"

fake_track=NO
num_lines=$( echo $( cat $trakfile | wc -l ) )
if ( ! cat "$trakfile" | grep -v 'HWRF, 000' ) ; then
    # The track file has only hour 0.  Is the first line bad?
    bad_lat=NO
    bad_lon=NO
    bad_wind=NO
    bad_pres=NO

    if ( cat "$trakfile" | head -1 | cut -c '35-38' | grep -E '^[ 0]*$' > /dev/null ) ; then
        bad_lat=YES
    fi
    if ( cat "$trakfile" | head -1 | cut -c '41-45' | grep -E '^[ 0]*$' > /dev/null ) ; then
        bad_lon=YES
    fi
    if ( cat "$trakfile" | head -1 | cut -c '48-51' | grep -E '^[ 0]*$' > /dev/null ) ; then
        bad_wind=YES
    fi
    if ( cat "$trakfile" | head -1 | cut -c '53-57' | grep -E '^[ 0]*$' > /dev/null ) ; then
        bad_pres=YES
    fi

    if [[ ( "$bad_lat" == YES && "$bad_lon" == YES ) || \
            "$bad_wind" == YES || "$bad_pres" == YES ]] ; then
        fake_track=YES
    fi
elif [[ ! -s "$trakfile" ]] ; then
    # The track file is empty.
    fake_track=YES
fi

if [[ "$fake_track" == YES ]] ; then
    /bin/cp -pf "$trakfile" "$trakfile.bad"
    "$USHhwrf/hwrf_vitals_track.pl" "$tmpvit" > $trakfile.fake
    if [[ -s "$trakfile.fake" ]] ; then
        /bin/mv -f "$trakfile.fake" "$trakfile"
        echo "Due to errors in tracker file,"
        echo "atcfunix file:   $trakfile"
        echo "is now replaced with tcvitals values:"
        echo
        cat $trakfile
        echo
        echo "Original values can be found here:"
        echo "    $trakfile.bad"
    fi
fi

