source("modules/Loading/Loading.R")
source("modules/Saving/Saving.R")
source("modules/Units/Units.R")
source("modules/Visualization/Visualization.R")
source("modules/Aggregation/Aggregation.R")
args = commandArgs(trailingOnly = TRUE)
recipe_file <- args[1]
#recipe_file <- "/esarchive/scratch/ptrascas/R/dev-test_bigpredidata/sunset/sunset/recipes/recipe_bigpredidata_oper_test_tas.yml"
recipe <- read_atomic_recipe(recipe_file)
#recipe <- prepare_outputs(recipe_file)
# Load datasets
data <- Loading(recipe)
data <- Units(recipe, data)
data_summary(data$hcst, recipe)
data_summary(data$obs, recipe)
data_summary(data$fcst, recipe)

data_agg <- Aggregation(recipe = recipe, data = data)
data_summary(data_agg$hcst, recipe)
data_summary(data_agg$obs, recipe)
data_summary(data_agg$fcst, recipe)

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

# Save calibrated hindcast, forecast and probabilities

#outdir <- recipe$Run$output_dir

#hcstcal <- res$hcst.full_val

#CST_SaveExp(data = hcstcal,
#                destination = outdir,
#                dat_dim = NULL, sdate_dim = 'syear',
#                ftime_dim = 'time', var_dim = NULL,
#                memb_dim = 'ensemble')


source("modules/Crossval/Crossval_metrics.R")
skill_metrics <- Crossval_metrics(recipe = recipe, data_crossval = res,
                                fair = FALSE, nmemb = NULL, nmemb_ref = NULL) 

# Save forecast skill




# Required to plot a forecast:
data_agg$fcst <- res$fcst
tmp_probs <- list(probs_fcst = res$probs$fcst[[1]])
lats <- length(data$hcst$coords$latitude)
lons <- length(data$hcst$coords$longitude)
timesteps <- as.numeric(dim(data$hcst$data)['time'])
dim(tmp_probs$probs_fcst) <- c(bin = 3, syear = 1, var = 1, time = timesteps, 
								latitude = lats, longitude = lons)

# Try transforming forecast probabilities into a list instead of s2dvcube

#hcst <- list(data = data_agg$hcst$data, dims = data_agg$hcst$data, coords = data_agg$hcst$coords, attrs = data_agg$hcst$attrs)
#fcst <- list(data = data_agg$fcst$data, dims = data_agg$fcst$data, coords = data_agg$fcst$coords, attrs = data_agg$fcst$attrs)
#obs <- list(data = data_agg$obs$data, dims = data_agg$obs$data, coords = data_agg$obs$coords, attrs = data_agg$obs$attrs)

#data_agg <- list(hcst = hcst, fcst = fcst, obs = obs)

Visualization(recipe = recipe, data = data_agg, skill_metrics = skill_metrics, significance = TRUE, probabilities = tmp_probs)

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

# scorecards computation:



