#!/bin/sh
set -e
# 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
# Combine the 49 varables into a single variable IT_div_SUNL for which each level corresponds to a bin, i.e., IT01 -> level 1, etc..

if [ $# -ne 52 ] ; then
  echo "Error in $0: invalid number of arguments $#"
  exit 1
fi
pfx=$1
# $2...$50 are it01...it49
sunl=${51}
out=${52}

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
    access it ${pfx}_it$n

    # 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

    release it
    rm temp mtemp

    files="$files f$n"
    l=`expr $l + 1`
  done
  t=`expr $t + 1`
done
release sunl

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

rm $files .ccc_cards
