function extrap {
  typeset var restartin=$1
  typeset var var=$2
  typeset var meshin=$3
  typeset var lon=$4
  typeset var lat=$5
  typeset var maskextrap=$6
  typeset var maskclim=$7
  typeset var varmask=$8
  typeset var restartout=$9
  typeset var flag=${10}
  typeset var cfutools=${11}
  typeset var confout=${12}
  typeset var mon=${13}
  typeset var fac

  case $flag in
   '3d') script=${cfutools}/interpolation/extrap.py ;;
   '2d') script=${cfutools}/interpolation/extrap2d.py ;;
  esac
  python ${script} ${restartin} ${var} ${meshin} ${lon} ${lat} ${maskextrap} ${varmask} tmp1.nc
  cdo ltc,0.5 -selvar,${varmask} ${maskclim} tmp.nc
 # Below here the script fills with climatology the points based on maskclim. In GloSea5 there is no need to do that since
 # there is no closed seas to be filled.  
   if    [[ ${confout} != *"75"* ]]  ; then 
  case $var in
   'tn'|'tb'|'votemper')
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,votemper,$var /cfu/pub/scripts/prep_restarts/auxfiles/filesclim/${confout}/temperature_m$mon.nc ${restartout}
   ;;
   'sst_m')
    cdo mulc,5 /cfu/pub/scripts/prep_restarts/auxfiles/filesclim/${confout}/sst_m$mon.nc titi.nc
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,votemper,$var titi.nc ${restartout}
    rm -f titi.nc
   ;;
   'sst_io')
    cdo addc,273.15 /cfu/pub/scripts/prep_restarts/auxfiles/filesclim/${confout}/sst_m$mon.nc titi.nc
    cdo mulc,2 titi.nc toto.nc
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,votemper,$var toto.nc ${restartout}
    rm -f titi.nc toto.nc
   ;;
   'sn'|'sb'|'vosaline')
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,vosaline,$var /cfu/pub/scripts/prep_restarts/auxfiles/filesclim/${confout}/salinity_m$mon.nc ${restartout}
   ;;
   'sss_m'|'sss_io')
    case $var in
      'sss_m' ) fac=5;;
      'sss_io') fac=2;;
    esac
    cdo mulc,$fac  /cfu/pub/scripts/prep_restarts/auxfiles/filesclim/${confout}/sss_m$mon.nc titi.nc
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,vosaline,$var titi.nc ${restartout}
    rm -f titi.nc
   ;;
   *)
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,${varmask},$var tmp.nc ${restartout}
   ;;
  esac
  else
      # so: wehn the file confout contans 75 vertical levels, then do not fill with climatology, because it is not available
      # (and in Glosea5 not needed) 
    cdo ifthenelse -chvar,${varmask},$var tmp.nc tmp1.nc -chvar,${varmask},$var tmp.nc ${restartout}
 fi 
     rm -f tmp.nc tmp1.nc
}

function gathervar {
 typeset var restfile=$1
 typeset var newvar=$2
 if [[ -e ${restfile} ]] ; then
   ncks -A ${newvar} ${restfile}
 else
   cp ${newvar} ${restfile}
 fi
}

function applymask {
  typeset var maskfile=$1
  typeset var maskvar=$2
  typeset var file=$3
  typeset var varname=$4
  typeset var outfile=$5
  cdo selvar,$maskvar $maskfile tmpmask.nc
  cdo ifthen -chvar,${maskvar},${varname} tmpmask.nc $file $outfile 
  rm -f tmpmask.nc 
}
