source('tools/libs.R')
source('modules/Scorecards/Scorecards_plotting.R')

args = commandArgs(trailingOnly = TRUE)
recipe_file <- args[1]
output_dir <- args[2]

# Read recipe and set outdir
recipe <- read_yaml(recipe_file)
recipe$Run$output_dir <- output_dir

## Loop over variables
datasets <- recipe$Analysis$Datasets

for (variable in 1:length(recipe$Analysis$Variables)) {
  # Create a copy of the recipe for this variable
  scorecard_recipe <- recipe 
  # Collect all system names
  scorecard_recipe$Analysis$Datasets$System <- 
    list(name = as.vector(unlist(recipe$Analysis$Datasets$System)))
  # Include multimodel in systems
  if (!isFALSE(recipe$Analysis$Datasets$Multimodel$execute)) {
    scorecard_recipe$Analysis$Datasets$System <-
      c(scorecard_recipe$Analysis$Datasets$System, 'Multimodel')
  }
  # Collect all reference names
  scorecard_recipe$Analysis$Datasets$Reference <- 
    list(name = as.vector(unlist(recipe$Analysis$Datasets$Reference)))
  # Assign variables
  scorecard_recipe$Analysis$Variables <-
    recipe$Analysis$Variables[[variable]]
  # Plot Scorecards
  Scorecards_plotting(scorecard_recipe)
}

# Add BSC logo to scorecards
source("tools/add_logo.R")
add_logo_scorecards(recipe, "bsc_logo_small.png")

print("##### SCORECARDS SAVED TO THE OUTPUT DIRECTORY #####")
