rm(list=ls())
gc()

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")
source("modules/Aggregation/Aggregation.R")

# Read recipe
#args = commandArgs(trailingOnly = TRUE)
#recipe_file <- args[1]
#recipe <- read_atomic_recipe(recipe_file)
## to test a single recipe:
 #  recipe_file <- "recipes/examples/recipe_tas_seasonal_timeagg.yml"
 #  recipe_file <- "recipes/examples/recipe_prlr_seasonal_timeagg.yml"

recipe <- prepare_outputs(recipe_file)

# Load datasets
data <- Loading(recipe)
# Units transformation
data <- Units(recipe, data)
# Temporal aggregation
data_agg <- Aggregation(recipe = recipe, data = data)
# Calibrate datasets
data <- Calibration(recipe, data)
# Compute skill metrics 
skill_metrics <- Skill(recipe, data)
# Compute percentiles and probability bins
probabilities <- Probabilities(recipe, data)
# Export all data to netCDF
## TODO: Fix plotting
# save_data(recipe, data, skill_metrics, probabilities)
# Plot data
Visualization(recipe = recipe, data = data, skill_metrics = skill_metrics,
              probabilities = probabilities, significance = T)

