#!/bin/sh
set -e
# jcl - 29 Feb 2016
#     - Updated script to handle new method to save the histogram data (CanAM4.1 and later).  It is
#       saved in a single variable (ICTP) not 49 separate variables (IT*).  This is reflected below.
#
# For the 49 variables in the cloud top pressure/cloud optical thickness histograms generated by the ISCCP simulator
# Compute the mean for each bin by dividing each by SUNL and set to missing where SUNL=0.
# To do this we need to work with single levels of ICTP at a time and merge them at the end.

if [ $# -ne 4 ] ; then
  echo "Error in $0: invalid number of arguments $#"
  exit 1
fi
pfx=${1}
inp=${2}
sunl=${3}
out=${4}

access inp ${pfx}_${inp}
access sunl ${pfx}_${sunl}

files=""
t=1
while [ $t -le 7 ] ; do
  l=1
  while [ $l -le 7 ] ; do
   l=`echo $l | awk '{printf "%05d", $1}'`
   t=`echo $t | awk '{printf "%05d", $1}'`
   n=`echo $l $t | awk '{printf "%02d", 7*($1-1) + $2}'`
   echo ${l} ${t} ${n}

   # select the specific pressure level
    
   echo "C*SELLEV     1    ${n}"|ccc sellev inp it 

# division and masking
   div it sunl temp
   echo "C* FMSKPLT        -1 NEXT   GT      0.00    1     1.E38    1" | ccc fmskplt temp mtemp sunl

   # relabel the name and level
    echo "C*RELABL   GRID
C*         GRID             IT$l          $t" | ccc relabl mtemp f${n}
   
  rm it temp mtemp

  files="$files f${n}"
  l=`expr $l + 1`
  done
  t=`expr $t + 1`
done

# Merge the levels back into a single file
echo ${files}
rmerge ${pfx}_${out} $files

release inp sunl
rm .ccc_cards ${files}

