#!/bin/csh

#script gets run once every 10 minutes by getmetar


###### regulate how many instances of this script can run concurrently 
set instances=`ps -ef | grep "${0} ${1}" | grep "/bin/csh" | wc -l`
echo "`date` - For logging purposes the number of instances of this script $0 presently running is $instances"
if ($instances > 1) then
        echo "Including this, there are presently ${instances} instances of '$0' running, only 1 allowed so exiting the script."
	ps -ef | grep "$0"
        goto EXITING
endif


# get into our working directory 
cd $SCRIPTS/metar/webloop


# get file name via user input, or if that's not supplied then by name with current time -- either way bail out if file not found
set RAWFILE=$1
set LATESTFILE="$LATESTDATA/metar/`date -u +%Y%m%d_%Hz.metar`"
if ($1 == "") then
	echo "Need the name of a raw metar file (example - $LATESTDATA/metar/YYYYMMDD_HHz.metar)"
	echo "OR enter the string    latest   will use if it exists $LATESTFILE"
	goto EXITING
endif


# if the userinput is the string  "latest"  then use the file name based on the current time 
if ($1 == latest) set RAWFILE="$LATESTFILE"
if (! -e $RAWFILE) then
	echo "$RAWFILE does not exist - script ending"
	goto EXITING
endif


# copy data containing hourlies  locally so we wont be decoding a moving target -- and from that name get the YMD and HHNN
touch dum.metar; /bin/rm *.metar
cp $RAWFILE . 
set YMD=`echo $RAWFILE | awk -F / '{print $NF}' | cut -f 1 -d z | awk -F _ '{print $1}'`
set HHNN=`echo $RAWFILE | cut -f 1 -d z | awk -F _ '{print $2}'`"00"


# do a first pass filter on the file to make decoding go faster - limit obs to north america 
echo "`date` - filtering obs to just North America"
touch sorted.obs; /bin/rm sorted.obs
cat -v $RAWFILE | sort -nr -k 2 | awk '{CID=substr($0,1,1); if (CID == "K" || CID == "C" || CID == "M" || CID == "T") if (index(STNLIST,$1) == 0) { STNLIST=STNLIST" " $1;print $0 } }' | sort -k 1 > sorted.obs
if (! -e sorted.obs) then
	echo "$RAWFILE was not decoded into sorted.obs - script will exit"
	goto EXITING
endif

# now run these sorted obs through an awk decoder 
echo "`date` - decoding obs"
touch latest.data; /bin/rm latest.data
dcmetar sorted.obs > latest.data
if (! -e latest.data) then
	echo "sorted.obs as not decoded into latest.data - script will exit"
	goto EXITING
endif

# From latest.data make the output file, and while we are at it get the lat lon -- only retaining lines that have a lat lon
echo "YMD,HHNN,STN,'STNFULLNAME',LAT,LON,TMPF,SUSMPH,GUSTMPH,PKWNDMPH,MAXMPH,DWPF,'RAWOB'" > hrly.final
echo "`date` - determining lat lon of each station"
cat latest.data | grep -v "STN,DD" | awk -F , '{                                                                				\
	STN=$1;																	\
        # get full name lat lon of station and if not missing print out data to be captued in output file - store in var data			\
        cmd="cat -v $SCRIPTS/stationdata/stations.csv | grep "STN", | cut -f 5,7-8 -d ,";                          				\
        data=""; cmd|getline data;close(cmd); 													\
	# split data into name, lat and lon, then merge latlon into one string									\
        split(data,info,","); name=info[1]; latlon=info[2]","info[3];	                                                  			\
        # for ref latest.data header  STN,DD,HHMM,COR,AUTO,T(c),TD(c),ALT,VIS(sm),SKY,WX,VV,DIR,KTS,GUST(KT),PKDIR,PKKTS,PKHH,PKMM,RVR,OB	\
        # decode the needed fields and print them out												\
	TF =$6; if (TF  != "m")  TF=int( (( (9*TF) +160 )/5)+.5);										\
	TDF=$7; if (TDF != "m") TDF=int( (( (9*TDF)+160 )/5)+.5);										\
	# make the gust and peak null so if they are not reported they dont appear as annoying "m" all over the map				\
	# but do make the sustained "m" to show the report is missing 										\
	# it is debatable if we actually need to track the max wind here -- lobby for IT to exclude this field					\
	# and during that lobby why not reorder theoutput so that temp and dewp are next to each other in this string vs dewp at end		\
	SUSMPH="m"; GMPH=""; PKMPH=""; MXMPH=SUSMPH												\
	if ($14 != "m" && $14 != "") {SUSMPH=int(($14*1.15)+.5); MXMPH=SUSMPH};									\
	if ($15 != "m" && $15 != "") {  GMPH=int(($15*1.15)+.5); MXMPH=GMPH};									\
	if ($17 != "m" && $17 != "") { PKMPH=int(($17*1.15)+.5); MXMPH=PKMPH};									\
	# if the lat lon is viable plot include the ob  in the output file -- the \047 are single quotes needed to bound the name and the ob	\
        if (latlon != "-99.99,-99.99") print YMD","HHNN","STN",\047"name"\047,"latlon","TF","SUSMPH","GMPH","PKMPH","MXMPH","TDF",\047"$NF"\047"\
}' YMD=$YMD HHNN=$HHNN >> hrly.final


# reorder 12 frame web files given we have a new file -- so WHEN they are shipped off to web they are already in proper named order 
echo "`date` - restacking latest 12 files for web use"
set webfilebasename="hrly_web"
set c=2
while ($c <= 12)
	@ cminusone = $c - 1
	touch ${webfilebasename}_${c}.txt
	mv ${webfilebasename}_${c}.txt ${webfilebasename}_${cminusone}.txt
	@ c ++
end
cp hrly.final ${webfilebasename}_12.txt


# exit routine
EXITING:
echo "`date` - exiting script"
exit(0)
