#!/bin/sh
set -e

# For the 15 reflectivity/height bins for CloudSat generated by the CloudSat simulator.
# Mask out the missing points and combine into a single file with
# ibuf(7) corresponding to a bin, i.e., ZE01 -> ZE, ibuf(7)=1, etc.

if [ $# -ne 17 ] ; then
  echo "Error in $0: invalid number of arguments $#"
  exit 1
fi
pfx=$1
ze01=$2
ze02=$3
ze03=$4
ze04=$5
ze05=$6
ze06=$7
ze07=$8
ze08=$9
ze09=${10}
ze10=${11}
ze11=${12}
ze12=${13}
ze13=${14}
ze14=${15}
ze15=${16}
out=${17}

mtype=`uname -s|tr '[A-Z]' '[a-z]'`
case $mtype in
    aix) BINDIR=~ccc101/gcm2nc/cmip5_scripts/bin_aix ;;
  linux) BINDIR=~ccc101/gcm2nc/cmip5_scripts/bin_linux ;;
      *) echo "Unkown kernel type $mtype"
         exit 1 ;;
esac
PATH="${BINDIR}:$PATH"
export PATH

files=""
n=1
while [ $n -le 15 ] ; do
  n=`echo $n | awk '{printf "%02d", $1}'`

  eval v=\$ze$n

  access $v ${pfx}_$v
  echo "C* FMSKPLT        -1 NEXT   GT     -999.    1     1.E38    1" | ccc fmskplt $v m$v

  # Relabel the name and ibuf(7)
  echo "C*RELABL   GRID
C*         GRID             ZE               $n" | ccc relabl m$v f$n

  release $v m$v

  files="$files f$n"
  n=`expr $n + 1`
done

# merge all files into one
rmergel ${pfx}_${out} $files

rm $files .ccc_cards
