#!/bin/ksh
set verbose echo
#
# This script will interpolate horizontaly ERA-I
# output to the desired model grid 
#
# Contact Josefine Ghattas
###############################################################################
###############################################################################
###############################################################################
# BEGIN USER DEFINITION
###############################################################################

# gridfile : file grilles_gcm.nc containing longitudes and latitudes of the destination grid
gridfile=/ccc/store/cont003/dsm/p86ghatt/IGCM_OUT/LMDZ/ELI-144x142x79/ATM/Output/Grid/ELI-144x142x79_1979_grilles_gcm.nc

# indir : path for directory containing the files to interpolate
#indir=/u/rech/psl/rpsl376/ERAI/NETCDF/GLOBAL_075/4xdaily/AN_PL
indir=/ccc/work/cont003/subipsl/subipsl/ERAI/NETCDF/GLOBAL_075/4xdaily/AN_PL/
# insuffix : suffix in input files
insuffix=.aphei.GLOBAL_075.nc

# varlist : list of variables to interpolate
varlist="u v ta r"

# Variables for output :
# outdir : directory to store output files
outdir=$WORKDIR/NUDGEFILES/ERAI-144x142x79
# outsuffix : suffix to output files
outsuffix=_erai.nc

# Time variables :
# first_year : first year to interpolate
first_year=1979
# last_year : last year to interpolate
last_year=2016

# Frequency of output files : yearly or monthly
# OutFreq='monthly' or OutFrequ='yearly'
OutFreq='yearly'
 
# rundir : temporary run directory
rundir=`pwd`/rundir
echo rundir=$rundir

###############################################################################
# END USER DEFINITION
###############################################################################
###############################################################################
###############################################################################
if [ ! -d ${rundir} ] ; then
    mkdir -p ${rundir}
fi
cp -f era2gcm.ksh $rundir/.
cd $rundir

###############################################################################
# For all variables do :
#   1) Interpolate all month and years for each variable
#   2) Add a time step last in each file coming from next month 
###############################################################################
# Loop over all variables
for var in $varlist ; do
    year=$first_year
    month=01

    # 1 - Loop over all files and interpolate the variable
    while [[ ${year} -le ${last_year} ]] ; do
        # Create output directory if it does not exist
	if [ ! -d $outdir/${year} ] ; then
	    mkdir -p $outdir/${year}
	fi

	# Define source and target file
	filein=${indir}/${year}/${var}.${year}${month}${insuffix}
	fileout=${outdir}/${year}/${var}_${year}${month}${outsuffix}

	# Interpolate filein and save in fileout
	echo Interpolate file $filein and save in file $fileout
	./era2gcm.ksh $gridfile $filein tmp.nc $var
	mv tmp.nc $fileout
	echo


	# Find next month and year
	case $month in
	    12)
		nextyear=`expr $year + 1`
		nextmonth=01
		;;
	    *)
		nextyear=$year
		nextmonth=`expr $month + 1`
		if [[ $nextmonth -le 9 ]] ; then
		    nextmonth=0$nextmonth
		fi
		;;
	esac
	# Update month and year
	year=$nextyear
	month=$nextmonth
    done


    # Do different treatement if monthly or yearly output files are wanted
    if [[ $OutFreq = 'monthly' ]] ; then
      # 2 - Loop over all files and add a time step : 
      #     take the first time step from next coming month and add last in current month
      echo Before add step

      year=$first_year
      month=01
      while [[ ${year} -le ${last_year} ]] ; do
	# Find next month and year
	case $month in
	    12)
		nextyear=`expr $year + 1`
		nextmonth=01
		;;
	    *)
		nextyear=$year
		nextmonth=`expr $month + 1`
		if [[ $nextmonth -le 9 ]] ; then
		    nextmonth=0$nextmonth
		fi
		;;
	esac
	
	file=${outdir}/${year}/${var}_${year}${month}${outsuffix}
	nextfile=${outdir}/${nextyear}/${var}_${nextyear}${nextmonth}${outsuffix}
	if [ -f ${nextfile} ] ; then
	    echo First time step from file ${nextfile} will be added last in file ${file}
	    cp -f $file file.nc
	    cp -f $nextfile next.nc
	    ncks -O -d TIME,0,0 next.nc tmp.nc
	    ncrcat -O file.nc tmp.nc tmptot.nc
	    mv tmptot.nc $file
	else
	    echo Next file ${nextfile} does not exist. Nothing will be done for ${file}
	fi

	# Update month and year
	year=$nextyear
	month=$nextmonth
      done

    elif [[ $OutFreq = 'yearly' ]] ; then
	# 3a. Concate the monthly files into yearly files
        mkdir -p  ${outdir}/allyears
	
	year=$first_year
	while [[ ${year} -le ${last_year} ]] ; do
        echo Now merge year=$year for variable $var
	    cdo mergetime ${outdir}/${year}/${var}_${year}* ${outdir}/allyears/${var}_${year}${outsuffix}
	    year=`expr $year + 1`
	done

        # 3b.Add a last timestep in the end of the yearly files from next coming year
	    year=$first_year
	    while [[ ${year} -le ${last_year} ]] ; do
	      # Find next month and year
	      nextyear=`expr $year + 1`
		
	      file=${outdir}/allyears/${var}_${year}${outsuffix}
	      nextfile=${outdir}/allyears/${var}_${nextyear}${outsuffix}
	      if [ -f ${nextfile} ] ; then
   	         echo First time step from file ${nextfile} will be added last in file ${file}
		 cp -f $file file.nc
		 cp -f $nextfile next.nc
		 ncks -O -d TIME,0,0 next.nc tmp.nc
		 ncrcat -O file.nc tmp.nc tmptot.nc
		 mv tmptot.nc $file
	      else
	  	 echo Next file ${nextfile} does not exist. Nothing will be done for ${file}
	      fi

              # Update month and year
	      year=$nextyear
	  done
    fi
    
# End of loop variable list
done

### Copy gridfile in output dir
cp -f $gridfile $outdir/grilles_gcm.nc
    
exit
