#!/bin/csh

# Create a file $OUTPUT  containing lat,lon,ptype that will be ingested by the objective analysis routine/script "pybarnes" 
# to create the ptype field that will eventually be used to create the color-coded ptype radar image for the FEWX web page
#
# Ptype is an integer determined per ob using the reported weather.  If the reported weather is "none", the ptype is determined by temperature
# 1 - rain 
# 2 - freezing 
# 3 - mix
# 4 - ice pellets
# 5 - snow
#
# Because there are rare times when the reported weather type is inconsistent with the temperature, the ptype code based on reported weather is always
# sanity-checked using the wet bulb temperature.  Example - occasionally Snow or Uknown Precipitation is reported in the ob when the temperature is in the 50's(F).


# obtain the name of the latest metar file in $LATESTDATA/metar -- in case that dir is empty, temporarily populate it with a dummy file so the ls command doesnt return an error
set DUMMYFILE=$LATESTDATA/metar/dummy.metar; touch $DUMMYFILE; /bin/rm $DUMMYFILE
set LATEST=`ls -tr $LATESTDATA/metar/*z.metar | grep -v dummy | tail -n 1`; 
if ($LATEST == "") then
	echo "There were no files in $LATESTDATA/metar"
	goto EXITING
endif


# Sort the obs in the $LATEST - retain only the most recent ob for a given station (sort -nr -k 2) - and ignore any non US ("K") and non Canadian obs ("C").
set jobid=$$ # this is necessary in case this script is run in multiple instances
set SORTEDOBS=${jobid}_sorted.obs
cat -v $LATEST | sort -nr -k 2 | awk '{ if (substr($0,1,1) == "K" || substr($0,1,1) == "C") if (index(STNLIST,$1) == 0) { STNLIST=STNLIST" " $1;print $0 } }' | sort -k 1 > $SORTEDOBS


# now run these obs through the awk decoder and for house
dcmetar $SORTEDOBS > latest.data
/bin/rm $SORTEDOBS # house cleaning -- dont need file anymore $SORTEDOBS


# Create output based on reported weather (per https://www.weather.gov/media/okx/Aviation/TAF_Card.pdf) and error check using wetb temp.  Use temperature if no weather is reported.
set OUTFILE=ptype.web
set RAWOUT=${OUTFILE}_raw
echo "stn,lat,lon,T,TD,poormanswetb,wx,wxflag,ptype" > $RAWOUT
cat latest.data | grep -v "STN,DD" | awk -F , '{ 								\
	# default ptype to rain (1)										\
	ptype=1; 												\
														\
	# for each ob get stnID, reported wx (field 11), temp (field 6) and dewp (field 7)			\
	STN=$1;WX=$11; T=$6; TD=$7;										\
														\
	# poormans wetb calc - set as default to -999 for missing						\
	poormanswetb=-999; if (T != "m" && TD != "m") {poormanswetb=(T+TD)/2;					\
														\
	# first guess ptype code - if T not missing and <30F set to snow (5) or >=30 and <=35F set to mix (3)	\
	if (T != "m") {												\
		if (T <  -1.1) ptype=5;										\
		if (T >= -1.1 && T < 1.67) ptype=3;								\
	}													\
														\
	# override  based on reported wx but only if if wetb is 32F or below 					\
	wxflag=0 # flag to tell if wxfield was used to over ride defaults					\
	if (poormanswetb != -999 && poormanswetb <= 0) {							\
		if (index(WX,"FZ")>0)                                         ptype=2;				\
		if (index(WX,"UP")>0 || index(WX,"GR")>0)                     ptype=3;				\
		if (index(WX,"PL")>0)                                         ptype=4;	  			\
		if (index(WX,"SN")>0 || index(WX,"GS")>0 || index(WX,"SG")>0) ptype=5;				\
		wxflag=(index(WX,"FZ")+index(WX,"UP")+index(WX,"GR")+index(WX,"PL")+index(WX,"SN")+index(WX,"GS")+index(WX,"SG"))>0; \
	}													\
														\
	# get lat lon of station										\
	cmd="cat -v $SCRIPTS/stationdata/stations.csv | grep "STN",| cut -f 7-8 -d, ";				\
	latlon=""; cmd|getline latlon;close(cmd);								\
														\
	# if lat lon not missing print out final string	to be captured in $OUTFILE				\
	if (latlon != "-99.99,-99.99") print STN","latlon","T","TD","poormanswetb","WX","wxflag","ptype}	\
}' >> $RAWOUT

# from the $RAWOUT print whats just needed for the objective anlysis routine's input file (lat,lon,ptype)
awk -F , '{if ($2 >=20  && $2 <=53  && $3 >=-131 && $3 <= -61) print $2","$3","$NF}' $RAWOUT > $OUTFILE

# exiting routine
EXITING:
exit()
