#!/bin/sh

# usage:  arg1 = UTC time (0, 6, 12, 18)
#         arg2 = download if not present, skip download if >0
#
# N.B. We don't check the date on downloaded files!  
#      This can bite you if you skip downloading and process files blindly.

TIME="t${1}z"
TODAY=$(date +%Y%m%d)
URL="https://nomads.ncep.noaa.gov/pub/data/nccf/com/hiresw/prod/hiresw.${TODAY}"
FILE1="hiresw.${TIME}.arw_2p5km.f"
FILE2=".conus.grib2"
WGRIB2="./wgrib2"
GEO=0   # no height values yet

cd /home/obs/www/MGIO

if [ -z $2 ]; then
    rm -f *.grib2
    for i in `seq -w 0 48`
    do
	/usr/local/bin/wget -q -c -nc -nd ${URL}/${FILE1}${i}${FILE2}
    done
else echo "Skipping download phase, proceeding to calculation..."
fi

rm -f pwat.txt clouds.txt

for i in `seq -w 00 48`
do    
    if [ -f ${FILE1}${i}${FILE2} ]; then
	echo $i $(${WGRIB2} ${FILE1}${i}${FILE2} -match ":PWAT:" -lon 250.111 32.701 -lon 249.212 32.443 -lon 248.40 31.96 -lon 249.047 32.232) >> pwat.txt
	echo $i $(${WGRIB2} ${FILE1}${i}${FILE2} -match ":TCDC:" -lon 250.111 32.701 -lon 249.212 32.443 -lon 248.40 31.96 -lon 249.047 32.232) >> clouds.txt
	
	if [ $GEO -eq 0 ]; then
	    RESULT=$(${WGRIB2} ${FILE1}${i}${FILE2} -match "HGT:surface" -lon 250.111 32.701 -lon 249.212 32.443 -lon 248.40 31.96 -lon 249.047 32.232)
	    if [ `expr "$RESULT" : '.*'` -gt 1 ]; then  # make sure it's not empty
		echo $i $RESULT > hgt.txt
		GEO=1   # got geopotential; don't need to do this again
	    fi
	fi

    else echo "File: ${FILE1}${i}${FILE2} not found."
    fi
done

