#!/bin/sh
set -e
# add two files and add 3 top model levels with zeros from a third file (CanESM4.1)
# add two files and add 9 top model levels with zeros from a third file (CanESM4.2)

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

release inp1 inp2 inp3
access  inp1 ${pfx}_${inp1}
access  inp2 ${pfx}_${inp2}
access  inp3 ${pfx}_${inp3}

stamp=`ggstat inp1 |grep GRID|head -1|cut -c9-22`
levs=`ggstat inp1 |grep GRID|head -200|grep "$stamp"|wc -l`

add inp1 inp2 inp12
if [ $levs -eq 32 ]; then
  echo "C*SELLEV      3 -102 -265 -612" | ccc sellev inp3 inp31
  echo "C*XLIN          0.E0      0.E0  ADD" | ccc xlin inp31 inp31zero
  murge inp12 inp31zero ${pfx}_${out}
elif [ $levs -eq 40 ]; then
  echo "C*SELLEV      9 -108 -144 -190 -250 -327 -426 -550 -708 -904" | ccc sellev inp3 inp31
  echo "C*XLIN          0.E0      0.E0  ADD" | ccc xlin inp31 inp31zero
  murge inp12 inp31zero ${pfx}_${out}
elif [ $levs -eq 35 -o $levs -eq 49 ]; then
  cp inp12 ${pfx}_${out}
fi

release inp1 inp2 inp3 inp12 inp31 inp31zero


