#!/bin/sh
set -e
# Cmorization of basin -- DY, Feb/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 basin_fx
rm -f tmp*

# access inp & basin_fx
access inp ${pfx}_${inp}.nc
access basin_fx basin_fx_cnrm-cm5-2_1pctco2_r0i0p0.nc

# Select i,j,basin from basin_fx
ncks -O -C -a -v basin basin_fx tmp1

# Rename i,j as x,y
ncrename -d i,x -d j,y -v basin,areacello tmp1 ${pfx}_${out}
chmod uo+w ${pfx}_${out}

# Select nav_lon & nav_lat from inp
ncks -O -C -a -v nav_lon,nav_lat inp tmp2

# Append nav_lat & nav_lon
ncks -A tmp2 ${pfx}_${out}

release basin_fx inp
rm -f tmp*
