#!/bin/sh
set -e
# Subtract a NEMO scalar timeseries from a 2d or 3d array
# Usage:
#   sub_timeseries inp1 invar1 inp2 invar2 out
#       inp1    : Full name of the input file containing the array
#       invar1  : Name of the variable of the array
#       inp2    : Full name of the input file containing the timeseries
#       invar2  : Name of the variable of the timeseries
#       out     : Name of the output file of the difference between the array and the timeseries

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

inp1=$1
invar1=$2
inp2=$3
invar2=$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

access inp1 ${inp1}.nc
access inp2 ${inp2}.nc

cdo --reduce_dim select,name=${invar1} inp1 ${invar1}.nc
cdo --reduce_dim select,name=${invar2} inp2 ${invar2}.nc
cdo enlarge,${invar1}.nc ${invar2}.nc tmp.nc

cdo sub ${invar1}.nc tmp.nc ${out}


release inp1 inp2
rm -f ${invar1}.nc ${invar2}.nc
rm -f tmp.nc
