#!/bin/csh -f

set MSROOT = $1
set CASENAME = $2
@ yr0 = $3
@ yr1 = $4
set outfile = "temp.out"
set finalout = $5
set workdir = $6
set TOOL_LIB = $7
set NEEDTAVG = $8
set NEED_CLIM = $9

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

set year0 = `printf "%04d" $yr0`
set year1 = `printf "%04d" $yr1`

@ yr = $yr0
@ s = 0

if (-e $outfile) rm $outfile
printf "Blank\n" >> $outfile

while ($yr <= $yr1)
  set year = `printf "%04d" $yr`
  setenv INMON 0
  setenv INANN 0
  setenv CREATE 0
  hsi -P "ls ${MSPY}/${CASENAME}.pop.h.${year}.nc"
  if ($status == 0 ) setenv INANN 1
  hsi -P "ls ${MSP}/${CASENAME}.pop.h.${year}.nc"
  if ($status == 0 ) setenv INMON 1
  if ($INANN == 0 && $INMON == 0) setenv CREATE 1
  
   if (($NEEDTAVG == 1 && $CREATE == 1) || $NEED_CLIM == 1 ) then
      echo "Check for monthly average files: "
     hsi  "ls ${MSP}/${CASENAME}.pop.h.${year}-{01,02,03,04,05,06,07,08,09,10,11,12}.nc"
     if ($status == 0)then
       foreach mon (01 02 03 04 05 06 07 08 09 10 11 12)
         set filename = ${CASENAME}.pop.h.${year}-${mon}.nc
         if !(-e $workdir/$filename) then
           printf "$filename\n" >> $outfile
           @ s++ 
          endif
       end 
     else
       echo "Check for yearly tarred files: "
       hsi -P "ls ${MSP}/${CASENAME}.pop.h.${year}.tar"
       if ($status == 0)then
         set current = $PWD
         cd $workdir
         $TOOL_LIB/mssuntar.csh ${MSROOT} ${CASENAME} $yr $yr 
         cd $current
       endif
     endif
   endif
@ yr++
end
if ($s == 0) printf " \n" >> $outfile
cp $outfile $finalout


