#!/bin/sh
set -e
# 1m -> 1y and then expand 2D var to 3D -- DY, Feb/2019.

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

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

# 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 nemo_mesh_mask
rm -f tmp* tmask tmask2

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

# Select tmask
ncks -F -v tmask nemo_mesh_mask tmask

# Rename t to time_counter, z to depthw in tmask
ncrename -d t,time_counter -d z,depthw tmask tmask2

# 1m to 1y for inp1
cdo yearmonmean inp1 tmp1
chmod ug+w tmp1

# Append tmask to inp1
ncks -A tmask2 tmp1

# Expand inp1 from 2D to 3D
ncap2 -O -s "${inp1}=${inp1}*tmask" tmp1 tmp2
chmod ug+w tmp2

# Select depthw from inp2
ncks -O -C -a -v depthw inp2 tmp3

# Append depthw to tmp2
ncks -A tmp3 tmp2

# Remove tmask
ncks -v tmask -x tmp2 ${pfx}_${out}

release inp1 inp2 nemo_mesh_mask
rm -f tmp* tmask tmask2

exit 0
