#library(startR)
#MergeArrays <- 
library(s2dverification)
MergeArrays <- s2dverification:::.MergeArrays

shared_dir <- 

args <- commandArgs(TRUE)

chunk_files <- list.files(paste0(shared_dir, '/'), '.*\\.Rds$')
chunk_files <- gsub('\\.Rds$', '', chunk_files)
chunk_filename_parts <- strsplit(chunk_files, '__')
if (length(unique(sapply(chunk_filename_parts, length))) != 1) {
  stop("Detected chunks with more dimensions than others.")
}
dim_names <- sapply(chunk_filename_parts[[1]], 
                    function(x) strsplit(x, '_')[[1]][1])
found_chunk_indices <- sapply(chunk_filename_parts, 
                              function(x) as.numeric(strsplit(x, '_')[[1]][2]))
found_chunk_indices <- array(chunk_indices, 
                             dim = c(length(dim_names), 
                                     length(chunk_indices) / length(dim_names))
                            )

if (length(args) > 0) {
  if ((length(args) %% 2) != 0) {
    stop("Wrong number of parameters.")
  }
  expected_dim_names <- args[(1:(length(args) / 2) - 1) * 2 + 1])
  if (any(!is.character(expected_dim_names))) {
    stop("Expected dimension names in parameters at odd positions.")
  }
  dim_indices <- args[(1:(length(args) / 2) - 1) * 2 + 2])
  if (!any(dim_indices == 'all')) {
    stop("Expected one dimension index to be 'all'.")
  }
  dim_to_merge <- which(dim_indices == 'all')
  if (length(dim_indices) > 1) {
    if (!all(is.numeric(dim_indices[-dim_to_merge]))) {
      stop("Expected all dimension index but one to be numeric.")
    }
  }
  # Check expected dim names match dim names
  ## TODO
  # Merge indices that vary along dim_to_merge whereas other fixed by dim_indices
  ## TODO
  stop("Feature not implemented.")
} else {
  chunk_indices <- 1:length(dim_names)
  chunk_indices <- lapply(chunk_indices, function(x) unique(found_chunk_indices[x, ]))
  names(chunk_indices) <- dim_names
  dim_array_of_chunks <- sapply(chunk_indices, length(unique))
  names(dim_array_of_chunks) <- dim_names
  array_of_chunks <- array(1:length(found_chunk_indices), dim_array_of_chunks)
  result <- list(mod = NULL, obs = NULL)
  ## TODO
  #previous_chunk_indices <- NULL
  #for chunk
  #  .......
  #  result$mod <- MergeArrays(res_lat$mod, res_lon$mod, 'lat')
  #  resilt$obs <- MergeArrays(res_lat$obs, res_lon$obs, 'lat')
  #  previous_chunk_indices <- current_chunk_indices
  #}
}

saveRDS(result, file = paste0(shared_dir, '/result.Rds'))

