rm(list=ls())
gc()
setwd("/esarchive/scratch/nperez/git/auto-s2s")

source("modules/Loading/Loading.R")
source("modules/Calibration/Calibration.R")
source("modules/Anomalies/Anomalies.R")
source("modules/Skill/Skill.R")
source("modules/Saving/Saving.R")
source("modules/Visualization/Visualization.R")
source("tools/prepare_outputs.R")
source("modules/Units/Units.R")

# Read recipe
args = commandArgs(trailingOnly = TRUE)
recipe_file <- args[1]
recipe <- read_atomic_recipe(recipe_file)
## to test a single recipe:
#recipe_file <- "recipe_ecvs_seasonal_oper.yml"
#recipe <- prepare_outputs(recipe_file)

# Load datasets
data <- load_datasets(recipe)
# Change units
data <- Units(recipe, data)
# Calibrate datasets
data <- calibrate_datasets(recipe, data)
# Compute skill metrics 
skill_metrics <- compute_skill_metrics(recipe, data)
# Compute percentiles and probability bins
probabilities <- compute_probabilities(recipe, data)
# Export all data to netCDF
# save_data(recipe, data, skill_metrics, probabilities)
# Plot data
plot_data(recipe, data, skill_metrics, probabilities, significance = T)

## Add BSC logo
logo <- "tools/BSC_logo_95.jpg"
system <- list.files(paste0(recipe$Run$output_dir, "/plots"))
variable <- strsplit(recipe$Analysis$Variable$name, ", | |,")[[1]]
files <- lapply(variable, function(x) {
           f <- list.files(paste0(recipe$Run$output_dir, "/plots/",
                                   system, "/", x))
           full_path <- paste0(recipe$Run$output_dir, "/plots/",
                                   system, "/", x,"/", f)})[[1]]
dim(files) <- c(file = length(files))
Apply(list(files), target_dims = NULL, function(x) {
  system(paste("composite -gravity southeast -geometry +10+10",
               logo, x, x))}, ncores = recipe$Analysis$ncores)

