# STEP 2
library(zeallot); library(CSTools)
StartDates <- paste0(1993:2018, '1101')
exp <- list(name = 'ecmwfS5', path = "/esarchive/exp/ecmwf/system5c3s/$STORE_FREQ$_mean/$VAR_NAME$_s0-24h/$VAR_NAME$_$START_DATE$.nc")
obs <- list(name = 'era5', path = '/esarchive/scratch/nperez/ERA5/daily_total_prlr_f1h-r1440x721cds/$VAR_NAME$_$YEAR$$MONTH$.nc')

c(exp, obs) %<-% CST_Load(var = 'prlr', exp = list(exp), obs = list(obs),
                          sdates = StartDates, nmember = 25,
                          storefreq = "daily", sampleperiod = 1,
                          latmin = 42, latmax = 49, lonmin = 4, lonmax = 11,
                          output = 'lonlat', nprocs = 1)

exp <- CST_SplitDim(exp, split_dim = c('ftime'))
obs <- CST_SplitDim(obs, split_dim = c('ftime'))

exp$data <- exp$data * 24 * 3600 * 1000
obs$data <- obs$data * 1000
exp$data[which(exp$data < 0)] <- 0
range(obs$data, na.rm = TRUE)
range(exp$data, na.rm = TRUE)
exp.qm <- CST_QuantileMapping(exp, obs, method = "QUANT",
                              wet.day = FALSE,
                              sample_dims = c('member', 'sdate', 'ftime'),
                              ncores = 4)
save(obs, file = '/esarchive/scratch/nperez/CSTools_manuscript/Dataset_Section3-1-Obs.RDS', version = 2)
save(exp, file = '/esarchive/scratch/nperez/CSTools_manuscript/Dataset_Section3-1-Exp.RDS', version = 2)
save(exp.qm, file = '/esarchive/scratch/nperez/CSTools_manuscript/Dataset_Section3-1-ExpQM.RDS', version = 2)
