#!/bin/csh -f

# Routine to read in monthly nc files
# make into timeseries for tropical SST.

set echo verbose

setenv OBS_DATA 1   #model=0, obs=1
setenv CASE_NAME b31.002
setenv mss_path /CCSM/csm/${CASE_NAME}/atm/hist
setenv mssread 1    
setenv CASE_NAME HadiSST
#setenv CASE_NAME Reynolds
setenv VAR_NAME TS
set latn = 10.
set lats = -10.
setenv START_YEAR 1905
setenv STOP_YEAR 2005

set ncl_home = /fis/cgd/home/yeager/ccsm_plots/ncl
set work_dir = /ptmp/yeager/$CASE_NAME/proc

if (! -e /ptmp/yeager/$CASE_NAME) then
    mkdir /ptmp/yeager/$CASE_NAME
endif

if (! -e $work_dir) then
    mkdir $work_dir
endif

cd $work_dir


if ($OBS_DATA != 1) then

echo " *** Producing SST timeseries for case" $CASE_NAME
echo " Selecting files for" $START_YEAR "to" $STOP_YEAR

set file_root = {$CASE_NAME}.cam2.h0.{$VAR_NAME}.{$START_YEAR}-{$STOP_YEAR}
setenv FILE_IN  ${file_root}.{$latn}N{$lats}S

if (! -e  ${FILE_IN}.nc) then

    if ($mssread == 1) msrcp "mss:${mss_path}/$CASE_NAME.cam?.h0.$START_YEAR-??.nc" .
    foreach i ($CASE_NAME.cam?.h0.$START_YEAR-??.nc)
      ncks -O -v ${VAR_NAME},gw,LANDFRAC  $i $i
    end
    ls $CASE_NAME.cam?.h0.$START_YEAR-??.nc > $CASE_NAME.monthly


    @ yr = $START_YEAR + 1
    while ($yr <= $STOP_YEAR)
	set year = `printf "%04d" $yr`
    if ($mssread == 1) msrcp "mss:${mss_path}/$CASE_NAME.cam?.h0.{$year}-??.nc" .
    foreach i ($CASE_NAME.cam?.h0.{$year}-??.nc)
      ncks -O -v ${VAR_NAME},gw,LANDFRAC  $i $i
    end
	ls $CASE_NAME.cam?.h0.{$year}-??.nc >> $CASE_NAME.monthly
	set nfiles = `ls $CASE_NAME.cam?.h0.{$year}-??.nc | wc` 
	if ($nfiles[1] != 12) then
	    echo "Insufficient number of files for year " $year " exiting..." && exit 1 	
	endif
    @ yr++
    end

    set file_list = `less $CASE_NAME.monthly`

    if (! -e ${file_root}.nc) then
        echo 'Concatonating files...'
        ncrcat $file_list ${file_root}.nc || echo ' --FAILED-- ' && exit 1
    endif
    echo 'Trimming to specified latitude range...'
    ncrcat -d lat,$lats,$latn ${file_root}.nc ${FILE_IN}.nc || echo ' --FAILED-- ' && exit 1
    /bin/rm ${file_root}.nc
endif

else
    if ($CASE_NAME == "HadiSST") then
	setenv FILE_IN sst.hadley.187001-200512
        if (! -e ${FILE_IN}.nc) then
          scp ahab.cgd:/project/cas/shea/hadley/${FILE_IN}.nc .
        endif 
    endif
    if ($CASE_NAME == "Reynolds") then                                
        setenv FILE_IN MODEL.OI2.sst.mnly.198111-200612.JAN2007.unf
        if (! -e ${FILE_IN}.nc) then
          scp ahab.cgd:/project/cas/shea/hadley/${FILE_IN}.nc .
        endif
    endif  
endif



echo "Performing ENSO ncl code"

ncl < $ncl_home/enso_wavelet.ncl
exit 0
