#library(startR)
library(s2dverification, lib.loc = '/home/Earth/nmanuben/s2dverification/s2dverification.Rcheck')

shared_dir <- 

##################################################################
var <- 
obs <- 
##################################################################
debug <- 
params <- 
fun <- 

original_selectors <- 
#original_selectors <- list(
#  dim_name_1 = exp,
#  dim_name_2 = NULL,
#  dim_name_3 = sdates,
#  dim_name_4 = NULL,
#  dim_name_5 = NULL,
#  dim_name_6 = NULL
#)

args <- commandArgs(TRUE)[-1]

#total_specified_dims <- length(args) / 2
#chunk_indices <- args[((1:total_specified_dims) - 1) * 2 + 1]
#chunk_amounts <- args[((1:total_specified_dims) - 1) * 2 + 2]
##################################################################
total_specified_dims <- length(args) / 4

chunk_indices <- args[((1:total_specified_dims) - 1) * 4 + 1]

dim_indices <- list()
for (i in 1:total_specified_dims) {
  dim_indices <- c(dim_indices, list(args[3:4 + 4 * (i - 1)]))
}
##################################################################

#i <- 1
#dim_selectors <- lapply(original_selectors, 
#                        function(x) {
#                          chunk(chunk_indices[i], chunk_amounts[i], x)
#                          i <<- i + 1
#                        })
##################################################################
i <- 1
dim_selectors <- lapply(original_selectors,
                        function(x) {
                          indices <- dim_indices[[i]][1]:dim_indices[[i]][2]
                          if (!is.null(x)) {
                            result <- x[indices]
                          } else {
                            result <- indices
                          }
                          i <<- i + 1
                          result
                        })
##################################################################



#data <- do.call("Start",
#          c(
#            dim_selectors,
##################################################################
data <- do.call("Load", 
          c(
            list(
              var = var, 
              exp = dim_selectors[['dataset']], 
              obs = obs,
              sdates = dim_selectors[['sdate']],
              leadtimemin = head(dim_selectors[['ftime']], 1), 
              leadtimemax = tail(dim_selectors[['ftime']], 1),
              latmin = head(dim_selectors[['lat']], 1), 
              latmax = tail(dim_selectors[['lat']], 1),
              lonmin = head(dim_selectors[['lon']], 1), 
              lonmax = tail(dim_selectors[['lon']], 1),
              silent = !debug
            ),
##################################################################
            params
          )
        )

res <- fun(data)
rm(data)

filename <- ''
for (i in 1:total_specified_dims) {
  filename <- paste0(filename, names(original_selectors)[i], '_', chunk_indices[i], '__')
}
saveRDS(res, file = paste0(shared_dir, '/', filename, '.Rds'))

rm(res)
gc()

