#!/bin/sh
set -e

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

if [ $# -ne 17 ] ; then
  echo "Error in $0: invalid number of arguments $#"
  exit 1
fi
pfx=$1
sr01=$2
sr02=$3
sr03=$4
sr04=$5
sr05=$6
sr06=$7
sr07=$8
sr08=$9
sr09=${10}
sr10=${11}
sr11=${12}
sr12=${13}
sr13=${14}
sr14=${15}
sr15=${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=\$sr$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             SR               $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
