library(pryr)
source("modules/Loading/Loading.R")
source("modules/Saving/Saving.R")
source("modules/Units/Units.R")
source("modules/Visualization/Visualization.R")
#args = commandArgs(trailingOnly = TRUE)
#recipe_file <- args[1]
recipe_file <- "recipe_tas.yml"
# recipe_file <- "recipe_tas_decadal.yml"
# Will it work with a single job?
#recipe <- read_atomic_recipe(recipe_file)
original_recipe <- prepare_outputs(recipe_file, disable_checks = TRUE)
# Load datasets
models <- unlist(original_recipe$Analysis$Datasets$System)


recipe_aux <- original_recipe
datos <- list()
datos$hcst <- list()
datos$fcst <- list()
source("modules/Crossval/Crossval_metrics.R")
source("modules/Crossval/Crossval_anomalies.R")
source("modules/Aggregation/Aggregation.R")
# sys <- models[1]
for (sys in models) {
  recipe_aux$Analysis$Datasets$System <- NULL
  recipe_aux$Analysis$Datasets$System$name <- as.vector(sys)
  # recipe_aux$Analysis$Datasets$System$member <-  read_yaml("conf/archive_decadal.yml")$esarchive$System[[sys]]$member
  data <- Loading(recipe = recipe_aux)
  data <- Units(recipe = recipe_aux, data = data)
  # data <- Aggregation(recipe = recipe_aux, data = data)
  # verification individual models
  product <- Crossval_anomalies(recipe = recipe_aux, data = data)
  skill_model <- Crossval_metrics(recipe = recipe_aux, data_crossval = product,
                                fair = FALSE, nmemb = NULL, nmemb_ref = NULL) 
  Visualization(recipe = recipe_aux, data = data,
		skill_metrics = skill_model, significance = TRUE)
  ## end ver
  datos$hcst <- append(datos$hcst, list(data$hcst))
  datos$fcst <- append(datos$fcst, list(data$fcst))
  names(datos$hcst)[length(datos$hcst)] <- gsub('\\.','', sys)
  names(datos$fcst)[length(datos$fcst)] <- gsub('\\.','', sys)
  gc()
  print(mem_used())
}
data_aux <- data
datos$obs <- data$obs
data <- datos
rm(list = 'datos')

source("modules/Crossval/Crossval_multimodel_anomalies.R")
res <- Crossval_multimodel_anomalies(recipe = original_recipe, data = data)

source("modules/Crossval/Crossval_multimodel_metrics.R")
skill_metrics <- Crossval_multimodel_metrics(recipe = original_recipe,
                                    data = res, Fair = FALSE)

recipe_aux$Analysis$Datasets$System$name <- 'Multimodel'
Visualization(recipe = recipe_aux, data = data_aux, skill_metrics = skill_metrics, significance = TRUE)


## Check logo size is appropiated for your maps:
source("tools/add_logo.R")
add_logo(recipe_aux, "rsz_rsz_bsc_logo.png")

# scorecards computation:


