library("s2dverification")
library("future")

args <- commandArgs(TRUE) # put into variable args the list with all the optional arguments with whom the script was run from the terminal
chunk.num <- as.integer(args[1])

## just to load lat values:
data <- Load('psl', exp = NULL,
             obs = 'erainterim',
             sdates = "19901201",
             storefreq='daily',
             leadtimemin = 1, leadtimemax = 1,
             output = 'lonlat', nprocs=1)

lat <- data$lat

## load data from models y/o reanalyses:
data <- Load('psl', exp = NULL,
             obs = list(list(path='/esarchive/recon/ecmwf/erainterim/daily_mean/$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc')),
             sdates = paste0(1991:2017, '1201'),
             storefreq='daily',
             leadtimemin = 1, leadtimemax = 31,
             latmin = lat[chunk.num], latmax = lat[chunk.num], output = 'lonlat', nprocs=1)

## my.array <- array(rnorm(40*6*256*512), c(40, 6, 256, 512))
##my.array <- array(rnorm(40*6*512), c(40, 6, 512))
my.test <- drop(apply(data$obs, 6, mean))

write.table(my.test, file=paste0("/esarchive/scratch/ncortesi/Regimes/test_", chunk.num, ".txt"))

system.time(data2 <- Load('psl', exp = NULL,
             obs = list(list(path='/esarchive/recon/ecmwf/erainterim/daily_mean/$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc')),
             sdates = paste0(1991:2017, '1201'),
             storefreq='daily',
             leadtimemin = 1, leadtimemax = 31,
             output = 'lonlat', nprocs=1))

system.time(my.test2 <- drop(apply(data2$obs, c(5,6), mean)))

            

## library(future)
##if(length(args) == 0) { print("Running the script in a sequential way"); my.par <- TRUE; nmaxcores <- max(1, availableCores()) }
##if(length(args) == 1) { print("Running the script in a parallel way"); my.par <- TRUE; nmaxcores <- 1 }
##if(length(args) > 1) stop("Only one argument is required")
##my.array <- array(rnorm(10000000), c(100, 100, 1000))
##my.test <- apply(my.array, c(1,3), mean)
##system("echo script argument= job status=$?")
