#!/bin/csh -f
#
#  Computes annual means from monthly POP history files, with
#    mass store read checks.  Must inherit the
#    following environment variables from parent
#    shell:  MSPROJ, MSRPD
#
#  Invoke as
#	pop_ann_mean.csh MSROOT CASENAME startyear endyear
#

set MSROOT = $1
set CASENAME = $2
@ yr0 = $3
@ yr1 = $4

setenv MSP /${MSROOT}/${CASENAME}/ocn/hist
setenv MSPY /${MSROOT}/${CASENAME}/ocn/proc/tavg/annual

@ yr = $yr0
while ($yr <= $yr1)

    set year = `printf "%04d" $yr`
    ls ${MSPY}/${CASENAME}.pop.h.${year}.nc
    if ($status == 0) then
      echo "reading hpss:${MSPY}/${CASENAME}.pop.h.${year}.nc"
      hsi -P "get ${MSPY}/${CASENAME}.pop.h.${year}.nc" &
    else
      ls ${MSP}/${CASENAME}.pop.h.${year}.nc
      
      if ($status == 0 ) then
	echo "reading hpss:${MSP}/${CASENAME}.pop.h.${year}.nc"
	hsi -P "get ${MSP}/${CASENAME}.pop.h.${year}.nc" &
      else
         echo "creating annual mean: ${CASENAME}.pop.h.${year}.nc"
	 ls ${MSP}/${CASENAME}.pop.h.${year}-01.nc
           ncra ${MSP}/${CASENAME}.pop.h.${year}-??.nc ${CASENAME}.pop.h.${year}.nc
           mkdir -p $MSPY ;cp ${CASENAME}.pop.h.${year}.nc $MSPY
          else
            echo "CANNOT CREATE ${CASENAME}.pop.h.${year}.nc" && exit 1
          endif
#TS         \rm -f ${CASENAME}.pop.h.${year}-??.nc
      endif
    endif
  @ yr++
end

#  check that all files were created successfully
set allgood = 1
@ yr = $yr0
while ($yr <= $yr1)
  set year = `printf "%04d" $yr`
  if (! -e ${CASENAME}.pop.h.${year}.nc) set allgood = 0
  @ yr++
end
if ($allgood == 1) then
  exit 0
else
  echo "ERROR in gen_pop_annmean.csh"
  exit 1
endif
