#!/usr/bin/env Rscript

source('/cfu/pub/scripts/R/common_diagnostics.txt')
library(ncdf)
args=commandArgs(TRUE)

comptrend=F
compcor=F
comprms=F
compspread=F
plotano=F

var=args[1]   # sie/sia/tos/tas/prlr/ohc/lohc/mohc/uohc/amoc
pole=args[2]  # N/S only for sia/sie
nltimemax=124 # number of leadtimes max in the experiments (in months)
nltimeout=36  # number of leadtimes to postprocess(in months)
lstmemb=c(0,1,2,3,4) # list of members
lstexpid=c('i00k') # list of ids
mon0=11       # initial month
year0=1960    # first start date
yearf=2005    # last start date
intsdate=5    # interval between start dates
runmeanlen=12 # length of the window for running mean (in months)

obs=switch(var,'sia'=c('HadISST'),'sie'=c('HadISST'),'tas'=c('NCEP','ERA40'),'tos'=c('ERSST','HadISST'),'prlr'=c('CRU','GPCC'),'ohc'=c('NEMOVAR_S4'),'mohc'=c('NEMOVAR_S4'),'uohc'=c('NEMOVAR_S4'),'lohc'=c('NEMOVAR_S4'),'amoc'=c('NEMOVAR_S4'))
toptitle2=switch(var,'sia'="sea ice area",'sie'="sea ice extent",'siv'="sea ice volume",'tas'="global T2m",'tos'="global SST (60S-65N)",'prlr'='land precipitation (60S-65N)','ohc'="global ocean heat content",'lohc'='global 800m-bottom ocean heat content','mohc'='global 350m-800m ocean heat content','uohc'='global 0-350m ocean heat content','amoc'='Atlantic Overturning Streamfunction (40-55N, 1-2km)')
ytitle1=switch(var,'sia'="Millions km2",'sie'="Millions km2",'tas'='K','tos'='K','prlr'='mm/day','ohc'='10e22 Joules','lohc'='10e22 Joules','mohc'='10e22 Joules','uohc'='10e22 Joules','amoc'='Sv')

syears=seq(year0,yearf,intsdate)
imon2=paste("0",as.character(mon0),sep="")
sdates=paste(as.character(syears),substr(imon2,nchar(imon2)-1,nchar(imon2)),'01',sep="")
toptitle1=paste(switch(pole,'N'="Arctic",'S'="Antarctic",""),toptitle2)

savename=paste(var,switch(pole,'N'=paste('_',pole,sep=''),'S'=paste('_',pole,sep=''),''),sep='')
for (expid in lstexpid ){
  savename=paste(savename,'_',expid,sep='')
}
if (file.exists(paste(savename,'.sav',sep=''))){
  load(paste(savename,'.sav',sep=''))
}else{

 if( var == 'sia' | var == 'sie' | var == 'ohc' | var == 'mohc' | var == 'uohc' | var == 'lohc' | var == 'amoc' ) {

  toto1_obs=array(dim=c(length(obs),switch(obs[1],'NEMOVAR_S4'=5,1),length(sdates),nltimeout))
  toto1_mod=array(dim=c(length(lstexpid),length(lstmemb),length(sdates),nltimeout))

  lstobs=list()
  indo=1
  for (jo in obs) {
    filein=switch(var,'sia'=paste('/cfu/diagnostics/postprocessed/ice/',switch(jo,'HadISST'='ukmo/ice_hadisst','NSIDC'='nsidc/ice_nsidc'),'_',pole,'.nc',sep=''),'sie'=paste('/cfu/diagnostics/postprocessed/ice/',switch(jo,'HadISST'='ukmo/ice_hadisst','NSIDC'='nsidc/ice_nsidc'),'_',pole,'.nc',sep=''),'ohc'='/cfunas/exp/ECMWF/NEMOVAR_S4/monthly_mean/heatc/heatc_nemovar_s4_19570901_fc0-4_195709_201108.nc','lohc'='/cfunas/exp/ECMWF/NEMOVAR_S4/monthly_mean/heatc/800-5350_heatc_nemovar_s4_19570901_fc0-4_195709_201108.nc','mohc'='/cfunas/exp/ECMWF/NEMOVAR_S4/monthly_mean/heatc/373-657_heatc_nemovar_s4_19570901_fc0-4_195709_201108.nc','uohc'='/cfunas/exp/ECMWF/NEMOVAR_S4/monthly_mean/heatc/0-315_heatc_nemovar_s4_19570901_fc0-4_195709_201108.nc','amoc'='/cfunas/exp/ECMWF/NEMOVAR_S4/monthly_mean/moc/moc_40N55N_1-2km_nemovar_s4_19570901_fc0-4_195709_201108.nc')
    fnc=open.ncdf(filein)
    tmp=get.var.ncdf(fnc,switch(var,'ohc'='thc','lohc'='thc','mohc'='thc','uohc'='thc','amoc'='zomsfatl',var))/switch(var,'ohc'=1e22,'lohc'=1e22,'uohc'=1e22,'mohc'=1e22,1.0)
    close.ncdf(fnc)
    system(paste('cdo showmon ',filein,'> mons 2>/dev/null'))
    mons=read.table('mons')
    system(paste('cdo showyear ',filein,'> years 2>/dev/null'))
    years=read.table('years')
    system('rm -f mons years')
    tmp_ts=ts(switch(obs[1],'NEMOVAR_S4'=t(tmp),tmp),start=c(years[[1]],mons[[1]]),end=c(years[[length(years)]],mons[[length(mons)]]),frequency=12)
    lstobs[[indo]]=tmp_ts
    indo=indo+1
  }
  ind=1
  for (jyear in syears) {
    indo=1
    for (jo in obs) {
      tmp=window(lstobs[[indo]],start=c(jyear,mon0),end=c(jyear+nltimeout/12,(mon0-2)%%12+1),frequency=12,extend=TRUE)
      toto1_obs[indo,,ind,]=switch(obs[1],'NEMOVAR_S4'=as.matrix(t(tmp))[,],tmp)
      indo=indo+1
    }
    nexp=1
    for (jexp in lstexpid) {  
      files=system(paste('ls /cfunas/exp/ecearth/',jexp,'/monthly_mean/',switch(var,'ohc'='heatc','mohc'='heatc','uohc'='heatc','lohc'='heatc','amoc'='moc','sia'='ice','sie'='ice'),'/',switch(var,'ohc'='heatc','uohc'='0-315_heatc','mohc'='373-657_heatc','lohc'='800-5350_heatc','amoc'='moc_40N55N_1-2km','sia'=paste('siasiesiv_',pole,sep=''),'sie'=paste('siasiesiv_',pole,sep='')),'_',jexp,'_',as.character(jyear),as.character(mon0),'01','_fc*_',as.character(jyear),as.character(mon0),'_*.nc',sep=""),intern=T)
      fnc=open.ncdf(files[length(files)])
      tmp=get.var.ncdf(fnc,switch(var,'ohc'='thc','lohc'='thc','mohc'='thc','uohc'='thc','amoc'='zomsfatl',var))/switch(var,'ohc'=1e22,'lohc'=1e22,'uohc'=1e22,'mohc'=1e22,1.0)
      if ( is.na(dim(tmp)[2]) ) { tmp=CFU_insertdim(tmp,1,1) }
      close.ncdf(fnc)
      toto1_mod[nexp,1:min(dim(tmp)[1],length(lstmemb)),ind,1:min(dim(tmp)[2],nltimeout)]=tmp[1:min(dim(tmp)[1],length(lstmemb)),1:min(dim(tmp)[2],nltimeout)]/switch(var,'sia'=1e3,'sie'=1e3,1)
      nexp=nexp+1
    }
    ind=ind+1
  }

  toto1=list(mod=toto1_mod,obs=toto1_obs)
 }else{
  fnc=open.ncdf('/home/vguemas/analysis_hui/constant_files/ecearth_mm_lsm.nc'    )
  mask=get.var.ncdf(fnc,'LSM')
  close.ncdf(fnc)
  if (var == 'prlr') {
    fnc=open.ncdf('/cfu/data/dwd/gpcc_combined1x1_v4/constant_fields/land_sea_mask.nc')
    mask_gpcc=get.var.ncdf(fnc,'lsm')
    close.ncdf(fnc)
    fnc=open.ncdf('/cfu/data/cru/mask_cru_land.nc')
    mask_cru=get.var.ncdf(fnc,'pre')
    close.ncdf(fnc)
    fnc=open.ncdf('/cfu/data/noaa/gpcp_v2.2/constant_fields/land_sea_mask.nc')
    mask_gpcp=get.var.ncdf(fnc,'LSM')
    close.ncdf(fnc)
    lstmaskobs=list(mask_cru,mask_gpcc)
  }else{
    if (var == 'tos')  {
      mask=1-mask
    }else{
      mask[,]=1
    }
    lstmaskobs=list(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
  }
  lstmask=list()
  for (iexp in 1:length(lstexpid)) {
     lstmask[[iexp]]=mask
  }
  latbnd=switch(var,'tos'=c(-60,65),'prlr'=c(-60,65),c(-90,90))
  toto1=CFU_load(var,lstexpid,obs,sdates,latmin=latbnd[1],latmax=latbnd[2],nleadtime=nltimemax,leadtimemax=nltimeout,maskmod=lstmask,maskobs=lstmaskobs)
 }
  save(toto1,file=paste(savename,'.sav',sep=''))
}

toto2a=CFU_clim(toto1$mod,toto1$obs,memb=F)
toto2b_ano_exp=CFU_ano(toto1$mod,toto2a$clim_exp)
toto2b_ano_obs=CFU_ano(toto1$obs,toto2a$clim_obs)
toto3=CFU_smoothing(toto2b_ano_exp,runmeanlen,4)
toto4=CFU_smoothing(toto2b_ano_obs,runmeanlen,4)
lims=switch(var,'sia'=c(0,25),'sie'=c(0,25),'tas'=c(284,292),'tos'=c(292,294))
suf=switch(pole,'N'=paste('_',pole,sep=''),'S'=paste('_',pole,sep=''),'')
CFU_plotano(toto1$mod,toto1$obs,sdates,toptitle=paste(lstexpid,toptitle1),ytitle=c(ytitle1,ytitle1,ytitle1),limits=lims,legends=obs,biglab=F,fileout=paste(var,'_',lstexpid,suf,'.eps',sep=''))
CFU_plotano(CFU_smoothing(toto1$mod,runmeanlen,4),CFU_smoothing(toto1$obs,runmeanlen,4),sdates,toptitle=paste("smoothed",lstexpid,toptitle1),ytitle=c(ytitle1,ytitle1,ytitle1),limits=lims,legends=obs,biglab=F,fileout=paste(var,'_',lstexpid,suf,'smoothed.eps',sep=''))

if (plotano) {
  lims=switch(var,'sia'=c(-1.5,2),'sie'=c(-1.5,2),'tas'=c(-1,0.5),'tos'=c(-0.4,0.4),'prlr'=c(-2e-9,3e-9))
  CFU_plotano(toto3,toto4,sdates,toptitle=paste("smoothed",lstexpid,toptitle1,"anomalies"),ytitle=c(ytitle1,ytitle1,ytitle1),limits=lims,legends=obs,biglab=F,fileout=paste(var,'_',lstexpid,suf,'_ano.eps',sep=''))
  lims=switch(var,'sia'=c(0,25),'sie'=c(0,25),'tas'=c(284,292),'tos'=c(292,294),'prlr'=c(2.4e-8,3.4e-8))
  #CFU_plotclim(toto2a$clim_exp,toto2a$clim_obs,toptitle=paste(switch(pole,'N'="Arctic",'S'="Antarctic",""),toptitle2,"climatologies"),ytitle=ytitle1,monini=mon0,limits=lims,listexp=lstexpid,listobs=obs,biglab=F,fileout=paste(savename,'_clim.eps',sep=''))
  CFU_plotclim(toto2a$clim_exp,toto2a$clim_obs,toptitle=paste(switch(pole,'N'="Arctic",'S'="Antarctic",""),toptitle2,"climatologies"),ytitle=ytitle1,monini=mon0,listexp=lstexpid,listobs=obs,biglab=F,fileout=paste(savename,'_clim.eps',sep=''))
} 

if (compspread) {
  toto5=toto3-CFU_insertdim(CFU_mean1dim(toto3,2,narm=T),2,dim(toto3)[2])
  toto6=CFU_spread(toto5,c(2,3))
  CFU_plotvsltime(toto6$iqr,toptitle=paste("InterQuartile Range",toptitle1),ytitle=ytitle1,monini=mon0,listexp=lstexpid,biglab=F,fileout=paste("IQR_",savename,".eps",sep=''))
  CFU_plotvsltime(toto6$maxmin,toptitle=paste("Maximum-Minimum for",toptitle1),ytitle=ytitle1,monini=mon0,listexp=lstexpid,biglab=F,fileout=paste("MaxMin_",savename,".eps",sep=''))
  CFU_plotvsltime(toto6$sd,toptitle=paste("Standard Deviation for",toptitle1),ytitle=ytitle1,monini=mon0,listexp=lstexpid,biglab=F,fileout=paste("SD_",savename,".eps",sep=''))
  CFU_plotvsltime(toto6$mad,toptitle=paste("Median Absolute Deviation for",toptitle1),ytitle=ytitle1,monini=mon0,listexp=lstexpid,biglab=F,fileout=paste("Mad_",savename,".eps",sep=''))
}

if (compcor) {
  cor=CFU_corr(CFU_mean1dim(toto3,2),CFU_mean1dim(toto4,2),1,2,compROW=3,limits=c(ceiling((runmeanlen+1)/2),nltimeout-floor(runmeanlen/2)))
  CFU_plotvsltime(cor,toptitle=paste("Correlations for",toptitle1),ytitle="correlation",monini=mon0,limits=c(-1,2),listexp=lstexpid,listobs=obs,biglab=F,hlines=c(-1,0,1),fileout=paste("cor_",savename,".eps",sep=''))
}

if (comprms) {
  rms=CFU_RMS(CFU_mean1dim(toto3,2),CFU_mean1dim(toto4,2),1,2)
  CFU_plotvsltime(rms,toptitle=paste("RMSE for",toptitle1),ytitle=ytitle1,monini=mon0,listexp=lstexpid,listobs=obs,biglab=F,fileout=paste("rms_",savename,".eps",sep=""))
}

if (comptrend) {
  trend_exp=CFU_trend(CFU_mean1dim(toto3,2),2,intsdate/12)
  trend_obs=CFU_trend(CFU_mean1dim(toto4,2),2,intsdate/12)
  trend=array(dim=c(dim(trend_obs)[1]+dim(trend_exp)[1],dim(trend_obs)[2:length(dim(trend_obs))]))
  trend[(dim(trend_exp)[1]+1):dim(trend)[1],,]=trend_obs
  trend[1:dim(trend_exp)[1],,]=trend_exp
  CFU_plotvsltime(trend,toptitle=paste("Trend for",toptitle1),ytitle=paste(ytitle1,"/ year"),monini=mon0,listexp=c(lstexpid,obs),biglab=F,fileout=paste("trend_",savename,".eps",sep=""))
}

rm(list=ls())
quit()
