#!/bin/ksh
#set -xv
# Function that does a linear interpolation of the variable in 
# filein towards the destionation grid in gridfile. Results in are 
# stored in fileout.
#
# Exemple for use :
# ./era2gcm.ksh grilles_gcm.nc u_filein.nc u_fileout.nc u
#
###################################################################
# O - Input arguments
###################################################################
# gridfile : File containing the target grid (grilles_gcm.nc)
    gridfile=$1
# filein : File containing the variable at source grid
    filein=$2
# fileout : Output file with the variable at target grid
    fileout=$3
# varin : Variable name in source file
    varin=$4

###################################################################
# 1 - Define variables
###################################################################
# Find number of time step
    tmax=`ncdump -h ${filein} | grep time | head -1 | awk ' { print $6 } '`
    tmax=$( echo ${tmax} | awk '-F(' '{print $2}' )
    
# Choose grid and output variable name 
    if [ ${varin} = 'u' ] || [ ${varin} = 'vitu' ] ; then 
	varout=uwnd
	grille='grille_u'
    elif [ ${varin} = 'v' ] || [ ${varin} = 'vitv' ] ; then 
	varout=vwnd
	grille='grille_v'
    elif [ ${varin} = 'ta' ] || [ ${varin} = 'temp' ] ; then 
	varout=air
	grille='grille_t'
    elif [ ${varin} = 'r' ] || [ ${varin} = 'hur' ] ; then 
	varout=rh
	grille='grille_t'
    elif [ ${varin} = 'msl' ] ; then 
	varout=sp
	grille='grille_t'
    else 
	echo Error : ${varin} unknown!!!!
	exit
    fi 

###################################################################
# 2 - Create ferret script for interpolation
###################################################################
    cat << eod >  ${varin}.jnl
set memory/size=50

use "${gridfile}"
use "${filein}"
let ${varout}=${varin}

define grid/like=${varout}[d=2]/x=grille_u[d=1]/y=grille_u[d=1] grille_u
define grid/like=${varout}[d=2]/x=grille_v[d=1]/y=grille_v[d=1] grille_v
define grid/like=${varout}[d=2]/x=grille_v[d=1]/y=grille_u[d=1] grille_t

save/clobber/file="${fileout}" ${varout}[d=2,g=${grille},l=1]
repeat/l=1:${tmax} save/file="${fileout}"/append ${varout}[d=2,g=${grille}]

exit
eod
    
###################################################################
# 3 - Launch interpolation with ferret
###################################################################
    ferret -nojnl <<eod >  /dev/null
go ${varin}.jnl
quit
eod

#}
