#!/bin/sh
set -e
# input variable * rhozero * cpocean * e3t, where 
# rhozero is reference sea water density, 1035 kg/m3 for LIM2,
# cpocean is specific heat capacity of sea water, 4000 J/(kgC),
# and e3t is thickness on T grid -- DY, Jan/2019.

if [ $# -ne 3 ] ; then
  echo "Error in $0: invalid number of arguments $#"
  exit 1
fi

pfx=$1
inp=$2
out=$3

# Get CDO / TEMPORARY!
export PATH=/fs/ssm/hpco/exp/mib002/anaconda/anaconda-4.4.0/anaconda_4.4.0_ubuntu-14.04-amd64-64/envs/cdo-1.9.0/bin:$PATH

release inp nemo_mesh_mask

# access inp nemo_mesh_mask.nc
access  inp ${pfx}_${inp}.nc
access nemo_mesh_mask nemo_mesh_mask_rc3.nc

# get e3t
ncks -v e3t nemo_mesh_mask e3t.nc

# remove t from e3t.nc
ncwa -O -a t e3t.nc tmp1

# rename z to deptht in e3t.nc
ncrename -d z,deptht tmp1 tmp2

# rhocp = rhozero * cpocean = 4140000 J/m2/degC
# e3t * rhocp
cdo mulc,4140000 tmp2 tmp3

# Append e3t to inp
ncks -A inp tmp4
chmod u+w tmp4
ncks -A tmp3 tmp4

# inp * e3t * rhocp
ncap2 -s "${inp}=${inp}*e3t" tmp4 tmp5

# remove e3t from output file
ncks -x -v e3t tmp5 ${pfx}_${out}

release inp nemo_mesh_mask
rm -f e3t.nc tmp1 tmp2 tmp3 tmp4 tmp5
