#! /bin/ksh

maxhour=999999
if [[ "$1" == -maxhr ]] ; then
    maxhour="$2"
    shift 2
fi

echo "REQUESTED MAXIMUM HOUR IS $maxhour" 1>&2

atcfunix_in="$1"
atcfunix_out="$2"

radii_in="${3:-}"
if [[ ! -z "$radii_in" ]] ; then
    radii_out="$4"
    echo "DELIVER RADII FILE $radii_in => $radii_out" 1>&2
    echo "BASED ON SANITY CHECK OF ATCFUNIX FILE $atcfunix_in" 1>&2
fi

finalhour=0
lines=0
cat "$atcfunix_in" | while read line ; do
    lines=$(( lines + 1 ))

    if [[ "$lines" -gt 2000 ]] ; then
        echo "TOO MANY LINES IN INPUT TRACK FILE" 1>&2
        echo "GOT >=$lines LINES.  CUTTING OFF TRACK AT HOUR $finalhour" 1>&2
    fi

    wind=$( echo "$line" | cut -c49-51 | awk '{print $1+0}' )
    pres=$( echo "$line" | cut -c54-57 | awk '{print $1+0}' )
    hour=$( echo "$line" | cut -c31-33 | awk '{print $1+0}' )

    if [[ "$lines" == 1 && "$hour" == 0 && "$wind" == 0 ]] ; then
        # Tracker could not find the vortex at the first hour,
        # probably due to an issue in the initialization.  The model
        # usually corrects itself by hour 3, so ignore this problem
        # and move on to the next forecast time.
        continue
    fi

    if [[ "$hour" -gt "$maxhour" ]] ; then
        # We've gone past the maximum allowed hour (such as when
        # generating a 12hr track).  Terminate track.
        break
    fi

    if [[ "$wind" -lt 10 || "$pres" -lt 850 || "$pres" -gt 1013 ]] ; then
        # Storm is no longer recognizably a tropical cyclone, 
        # so terminate the track.
        echo "BAD VALUE AT HOUR $hour: WIND=$wind PRES=$pres" 1>&2
        break
    fi
    finalhour=$hour
done

echo "TERMINATE TRACK AT HOUR $finalhour" 1>&2

if [[ "$atcfunix_out" != '-no-out' ]] ; then
    echo "DELIVER $atcfunix_in => $atcfunix_out" 1>&2
    cat "$atcfunix_in" | while read line ; do
        hour=$( echo "$line" | cut -c31-33 | awk '{print $1+0}' )    
        if [[ "$hour" -le "$finalhour" ]] ; then
            echo "$line" | cut -c1-112
        fi
    done > "$atcfunix_out"
fi

if [[ ! -z "$radii_in" ]] ; then
    echo "DELIVER $radii_in => $radii_out" 1>&2
    cat "$radii_in" | while read line ; do
        hour=$( echo "$line" | awk '{print substr($1,15,3)}' )    
        if [[ "$hour" -le "$finalhour" ]] ; then
            echo "$line" | cut -c1-112
        fi
    done > "$radii_out"
fi
