#!/bin/bash

## Just run code in recipes, use it carefully
## example: use cdo to make cache file. Since cdo is quicker than ncl.
#;DIAG_NORCPM; RUNTHESECODES: echo '    no codes run here.'

a='1'
while [ ! -z "${a}" ] ; do
a=$(ncl -Q << EOF
load "/cluster/projects/nn9039k/people/pgchiu/diag_norcpm/diag_norcpm/Codes/func_read_all_members.ncl"
begin
forecastdirs=systemfunc("ls -d BASEDIR/RUNPRE{1,2}???10??|sort")
varname = "sst"
ocngridfile = "/cluster/shared/noresm/inputdata/ocn/blom/grid/grid_tnx1v4_20170622.nc"
component = "ocn"
cacheprefix = "ts_amo_noano"
yearbe = (/1870,2018/)
years = ispan(min(yearbe),max(yearbe),1)
months = (/1,2,3,4,5,6,7,8,9,10,11,12/)
if(any(months.eq.0))then
    months := ispan(1,12,1)
end if
latbe = (/0.,60./)
lonbe = (/-80.,0./)

nfcast = dimsizes(forecastdirs)
do i = 0, nfcast -1
forecache = cacheprefix+"_f"+sprinti("%2.2d",i)+".nc"
if(isfilepresent(forecache))then
continue
end if
print("make cache:"+forecache)
wcS = toint(systemfunc("date +%s"))
var = read_norcpm_forecast_members_var_season_latbe_lonbe_yearly(forecastdirs(i),component,varname,months,(/-90,90/),(/0,360/),ocngridfile) ;; monthly xy
var = where(var.lt.0,var@_FillValue,var)
ts = mean_with_latbe_lonbe(var,latbe,lonbe)
globalts = mean_with_latbe_lonbe(var,(/-90,90/),(/0.,360./))
ts = ts-globalts
delete(var)
delete(globalts)

f = addfile(forecache,"c")
f->ts = ts
wcE = toint(systemfunc("date +%s"))
print( "make cache in "+(wcE-wcS)+" seconds.")
print("CONTINUE")
exit ;; make 1 cache per run, avoid memory issue
end do
end
EOF
)
echo $a
if [ -z  "$(echo $a | grep 'CONTINUE')" ] ; then
exit
fi
done


