
rm(list = ls()); gc()

args <- commandArgs(trailingOnly = TRUE)

setwd("/esarchive/scratch/nmilders/gitlab/git_clones/s2s-suite/")

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

recipe_file <- "recipes/atomic_recipes/recipe_test_multivar_nadia.yml"
recipe <- prepare_outputs(recipe_file)

## Run job for each start month
recipe$Analysis$Time$sdate <- paste0(sprintf("%02d", as.numeric(args)), '01')

## Load datasets
data <- load_datasets(recipe)


################################################################################

### For Testing ###
# 
# lon <- attributes(data$hcst$coords$longitude)
# lat <- attributes(data$hcst$coords$latitude)
# 
# 
# source('/esarchive/scratch/nmilders/gitlab/git_clones/s2s-suite/modules/Loading/R/mask_tas_tos.R')
# tas_tos_hcst <- mask_tas_tos(input_data = data$hcst, region = c(20, 40, 30, 50),
#                              grid = 'r360x181', lon = lon, lat = lat,
#                              lon_dim = 'longitude', lat_dim = 'latitude', ncores = NULL)
# 
# tas_tos_obs <- mask_tas_tos(input_data = data$obs, region = c(0.1, 359.95, -90, 90),
#                             grid = 'r360x181', lon = lon, lat = lat,
#                             lon_dim = 'longitude', lat_dim = 'latitude', ncores = NULL)
# 
# 
# source('/esarchive/scratch/nmilders/gitlab/git_clones/s2s-suite/modules/Loading/R/mask_tas_tos.R')
# mask <- .load_mask(grid = 'r360x181', mask_path = NULL,
#                    land_value = 0, sea_value = 1,
#                    lon_dim = 'lon', lat_dim = 'lat', region = NULL)

################################################################################

## compute anomalies
anomalies <- compute_anomalies(recipe, data)

## Compute skill metrics of data
skill_metrics <- compute_skill_metrics(recipe, anomalies)

## save data
save_data(recipe, data, skill_metrics = skill_metrics)
gc()

## plot metrics maps
## plot_data(recipe, anomalies, skill_metrics, significance = T)
