#!/bin/ksh
# Kornshell Script to extract E2OBS Meteorological forcing 
# "met_forcing_v0" : 1979-2012 tri-hourly (daily) global land, lakes, ocean
# Download from the Threads server: http://wci.earth2observe.eu/thredds
# Provider ECMWF 
# Script setup---------------------------------------------
set -x
forcing_version=met_forcing_v0
#data_label=daily_E2OBS           #obtain daily-mean fields
data_label=E2OBS                  #obtain tri-hourly fields
#Domain latmin latmax lonmin lonmax
echo 23 52 -127 -65>latlon_domain #domain corresponding to CONUS
echo 40 52 -7 13 >latlon_domain   #domain corresponding to AROME-France
echo 30 50.5 -10 30.75 >latlon_domain   #domain corresponding to WEU-EartH2Observe LAM
echo 25 75 -11 62 >latlon_domain  #domain corresponding to EuroMediterranean region

startdate=20120101
enddate=20120131
nstep=8 # Number of forcing timestep in a day (8=tri-hourly)
# End setup---------------------------------------------
dateloop=$startdate
date_label=$startdate"_to_"$enddate
yyyymmend=`echo $enddate | cut -c1-6`
latindex=`awk '{print int((90+$1)*2+1)","int((90+$2)*2+1)}' latlon_domain`
lonindex=`awk '{print int((180+$3)*2+1)","int((180+$4)*2+1)}' latlon_domain`
echo $latindex $lonindex

rm -rf ${data_label}_${date_label}.nc
# Loop on dates
while [ $dateloop -le $enddate ] ; do
	year=`echo $dateloop | cut -c1-4`
	month=`echo $dateloop | cut -c5-6`
	day=`echo $dateloop | cut -c7-8`
	# nextmonth=`newdate -D $dateloop +33 | cut -c1-6`01
    nextmonth=`date -d "$dateloop + 1 month" +%Y%m`01
	t1=`expr ${day} \* ${nstep} - 7`
	yyyymm=${year}${month}
	if [[ $yyyymm -eq $yyyymmend ]] ; then 
  		endday=`echo $enddate | cut -c7-8`
  		t2=`expr ${endday} \* ${nstep} + 1`
	else 
  	        # endday=`newdate -D $nextmonth -1 | cut -c7-8`
            endday=`date -d "$nextmonth - 1 day" +%d`
  		t2=`expr ${endday} \* ${nstep}`
	fi
	echo "Extracting "$yyyymm" days "$day" to "$endday
# Loop on meteorological variables
	for VAR in SWdown LWdown Rainf Snowf PSurf Tair Qair Wind ; do
   		ncks -A -F -d lat,$latindex -d lon,$lonindex -d time,$t1,$t2 \
		https://wci.earth2observe.eu/thredds/dodsC/ecmwf/met_forcing_v0/${year}/${VAR}_${data_label}_${yyyymm}.nc Point_${dateloop}.nc
	done
	# dateloop=`newdate -D $dateloop +33 |cut -c1-6`01
    dateloop=`date -d "$dateloop + 1 month" +%Y%m`01
done
# Concatenation to single file
ncrcat Point_*.nc ${data_label}_${date_label}.nc
rm -rf Point_*.nc
