#!/bin/bash
set -evx 
# 
# This script prepares the Tofill.nc file to be split afterwards between
# Tofill.clim.nc and Tofill.extrap.nc
#
# History : Virginie Guemas - Initial version                     March 2014  
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
restart=$1 # Output restart after skipping the extrapolation and filling of
           # empty seas to be able to compute Tofill.nc
meshmask=$2 # Mask of the grid that restart should have after extrapolation 
            # and filling of empty seas
Tofill=$3 # Name of the output Tofill.nc file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

lstmasks=('tmask' 'umask' 'vmask' 'fmask')

cdo setmisstoc,1e19 $1 tmp1.nc
cdo gtc,1e18 tmp1.nc tmp2.nc

for mask in ${lstmasks[@]} ; do
  case $mask in
    'tmask' ) var='tn';;
    'umask' ) var='un';;
    'vmask' ) var='vn';;
    'fmask' ) var='rotn';;
  esac

  cdo selvar,$var tmp2.nc tmp2_${var}.nc 
  cdo add -chvar,$var,$mask tmp2_${var}.nc -selvar,$mask $2 sum.nc
  cdo gtc,1.5 sum.nc Tofill_${mask}.nc
  rm -f tmp2_${var}.nc sum.nc
  
  if [ -e $3 ] ; then
    ncks -A Tofill_${mask}.nc $3 
    rm -f Tofill_${mask}.nc
  else
    mv Tofill_${mask}.nc $3
  fi  

done
rm -f tmp1.nc tmp2.nc

echo "You have just built Tofill.nc : "$3
echo "Now you can use :"
echo "    1) cdo setcindexbox,c,idx1,idx2,idy1,idy2 ifile ofile to set seas at 0"
echo "       and build Tofill.extrap.nc"
echo "    2) cdo sub to get Tofill.clim.nc from Tofill.nc and Tofill.extrap.nc"
