#!/bin/sh
set -e
# jcl - 23 Aug 2019
#
# For the 112 bin variable in the cloud altitude/cloud optical thickness histograms generated by the MISR 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 at a time and merge them at the end.
# Note that the data in the bins are split across two time-series (MST1 nad MST2) which we handle here.

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

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

# Combine the two inputs

joinup inp inp1 inp2

files1=""
files2=""
alt=1
nf=0
while [ $alt -le 16 ] ; do
  tau=1
  while [ $tau -le 7 ] ; do
   tau=`echo $tau | awk '{printf "%05d", $1}'`
   alt=`echo $alt | awk '{printf "%05d", $1}'`
   n=`echo $alt $tau | awk '{printf "%02d", 7*($1-1) + $2}'`
   echo ${tau} ${alt} ${n}
   nf=`expr $nf + 1`

   # 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$tau          $alt" | ccc relabl mtemp f${n}
   
  rm it temp mtemp

  if [ `expr $nf % 2` -eq 1 ] ; then
    # odd files
    files1="$files1 f${n}"
  else
    # even files
    files2="$files2 f${n}"
  fi

  tau=`expr $tau + 1`
  done
  alt=`expr $alt + 1`
done

# Merge the levels back into a single file
echo ${files1}
rmerge subset1 $files1
echo ${files2}
rmerge subset2 $files2

rmerge ${pfx}_${out} subset1 subset2

#release inp inp1 inp2  sunl subset1 subset2
rm .ccc_cards ${files1} ${files2}

