#!/bin/sh
set -e
# (inp1 + inp2 - inp3) * rhozero * 1e-3 * e3t, where 
# rhozero is reference sea water density, 1035 kg/m3 for LIM2,
# and e3t is thickness on T grid -- DY, Jan/2019.

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

pfx=$1
inp1=$2
inp2=$3
inp3=$4
out=$5

# 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 inp1 inp2 inp3 nemo_mesh_mask

# access inp1, inp2, inp3 and nemo_mesh_mask.nc
access  inp1 ${pfx}_${inp1}.nc
access  inp2 ${pfx}_${inp2}.nc
access  inp3 ${pfx}_${inp3}.nc
access nemo_mesh_mask nemo_mesh_mask_rc3.nc

# inp1 + inp2 - inp3
cdo sub -add inp1 inp2 inp3 tmp0

# 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

# rhoe-3 = rhozero * 0.001 = 1.035 kg/m3
# e3t * rhoe-3
cdo mulc,1.035 tmp2 tmp3

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

# (inp1 + inp2 -inp3) * e3t * rhoe-3
ncap2 -s "${inp1}=${inp1}*e3t" tmp4 tmp5

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

release inp1 inp2 inp3 nemo_mesh_mask
rm -f e3t.nc tmp0 tmp1 tmp2 tmp3 tmp4 tmp5
