source("tools/libs.R")

Loading <- function(recipe) {
  ## TODO: remove with new release of startR
  path <- "modules/Loading/tmp/startR/R/"
  ff <- lapply(list.files(path), function(x) paste0(path, x))
  invisible(lapply(ff, source))
  # Source correct function depending on filesystem and time horizon
  # Case: CERISE (Mars)
  if (tolower(recipe$Run$filesystem) == "mars") {
    source("modules/Loading/R/load_GRIB.R")
    data <- load_GRIB(recipe)
  } else if (tolower(recipe$Run$filesystem) == "sample") {
    source("modules/Loading/R/load_sample.R")
    data <- load_sample(recipe)
  } else {
    # Case: esarchive
    time_horizon <- tolower(recipe$Analysis$Horizon)
    if (time_horizon == "seasonal") {
      if(recipe$Analysis$Variables$name == 'tas-tos') {
        source("modules/Loading/R/load_tas_tos.R")
        data <- load_tas_tos(recipe) 
      } else {
        source("modules/Loading/R/load_seasonal.R")
        data <- load_seasonal(recipe)
      }
    } else if (time_horizon == "decadal") {
      source("modules/Loading/R/load_decadal.R")
      data <- load_decadal(recipe)
    } else if (time_horizon == "subseasonal") {
      source("modules/Loading/R/load_subseasonal.R")
      data <- load_subseasonal(recipe)
    } else {
      stop("Incorrect time horizon.")
    }
  }
  # Display data summary
  if (recipe$Run$logger$threshold <= 2) {
    data_summary(data$hcst, recipe)
    data_summary(data$obs, recipe)
    if (!is.null(data$fcst)) {
      data_summary(data$fcst, recipe)
    }
  }
  return(data)
}
