#!/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.'

ncl -Q << EOF
load "/cluster/projects/nn9039k/people/pgchiu/diag_norcpm/diag_norcpm/Codes/func_read_framework.ncl" ;; prototype reading function for obs data
load "/cluster/projects/nn9039k/people/pgchiu/diag_norcpm/diag_norcpm/Codes/func_read_all_members.ncl" ;; for mean_with_latbe_lonbe()
begin
varname = "sst"
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./)
obsdir = "/cluster/projects/nn9039k/NorCPM/Obs"
obsdataset = "SST/HADISST"
obsvn = "sst"

obscache = cacheprefix+"_obs.nc"
if(isfilepresent(obscache))then ;; skip if file present
    exit
end if
print("make cache:"+obscache)
var = read_obs_framework_season(obsdir,obsdataset,obsvn,years,months,-1,(/-90,90/),(/0,360/))
var = where(var.lt.0,var@_FillValue,var) ;; remove values below 0 in sst
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(obscache,"c")
f->obsts = ts
exit ;; make only one cache per run, avoid memory issue
end
EOF


