#!/bin/sh
set -e
# inp1 = inp1 / inp2 if inp2 > 0.0, otherwise, inp1 = 1e+20
# -- DY, Jan/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
rm -f tmp0 tmp1

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

# Append inp2 to inp1
ncks -A inp1 tmp0
chmod u+w tmp0
ncks -A inp2 tmp0

# inp1 = inp1 / inp2 if inp2 > 0.0, otherwise, inp1 = 1e+20
ncap2 -O -s "where(${inp2}>0.0) ${inp1}=${inp1}/${inp2}; elsewhere ${inp1}=1e+20" tmp0 tmp1

# remove inp2 from output file
ncks -x -v ${inp2} tmp1 ${pfx}_${out}

release inp1 inp2
rm -f tmp0 tmp1
