# recipe: the recipe as returned by prepare_outputs()
divide_recipe <- function(recipe) {

  ## TODO: Implement dependent vs independent verifications?
  info(recipe$Run$logger, "Splitting recipe in single verifications.")
  beta_recipe <- list(Description = append(recipe$Description, 
                                           list(Origin = paste("Atomic recipe,",
                                                               "split from:", 
                                                               recipe$name))),
                      Analysis = list(Horizon = recipe$Analysis$Horizon,
                                      Variables = NULL,
                                      Datasets = NULL,
                                      Time = NULL,
                                      Region = NULL,
                                      Regrid = recipe$Analysis$Regrid,
                                      Workflow = recipe$Analysis$Workflow,
                                      ncores = recipe$Analysis$ncores,
                                      remove_NAs = recipe$Analysis$remove_NAs,
                                      Output_format = 
                                        recipe$Analysis$Output_format),
                      Run = recipe$Run[c("Loglevel", "output_dir", "Terminal",
                                         "code_dir", "logfile", "filesystem")])
  
  # duplicate recipe by independent variables:ç
  # If a single variable is not given inside a list, rebuild structure
  if (any(c("name", "freq", "units") %in% names(recipe$Analysis$Variables))) {
    variables <- recipe$Analysis$Variables
    recipe$Analysis$Variables <- NULL
    recipe$Analysis$Variables[[1]] <- variables
  }
  all_recipes <- rep(list(beta_recipe), length(recipe$Analysis$Variables))
  for (var in 1:length(recipe$Analysis$Variables)) {
    all_recipes[[var]]$Analysis$Variables <- recipe$Analysis$Variables[[var]]
  }

  # for (dep in verifications$dependent) {
  #   all_recipes[[i]]$Analysis$Variables <- dep
  #   i = i + 1
  #   all_recipes <- append(all_recipes, list(beta_recipe))
  # }
  # all_recipes <- all_recipes[-length(all_recipes)] # wth does this do
  
  # duplicate recipe by Datasets:
  # check Systems
  # If a single system is not given inside a list, rebuild structure
  if (any(c("name", "member") %in% names(recipe$Analysis$Datasets$System))) {
    system <- recipe$Analysis$Datasets$System
    recipe$Analysis$Datasets$System <- NULL
    recipe$Analysis$Datasets$System[[1]] <- system
  }
  
  if (recipe$Analysis$Datasets$Multimodel %in% c(TRUE, 'both')) {
    for (reci in 1:length(all_recipes)) {
      all_recipes[[reci]]$Analysis$Datasets <- 
        list(System = recipe$Analysis$Datasets$System,
             Multimodel = recipe$Analysis$Datasets$Multimodel,
             Reference = NULL)
    }
  } else {
    for (sys in 1:length(recipe$Analysis$Datasets$System)) {
      for (reci in 1:length(all_recipes)) {
        all_recipes[[reci]]$Analysis$Datasets <- 
          list(System = recipe$Analysis$Datasets$System[[sys]],
               Multimodel = recipe$Analysis$Datasets$Multimodel,
               Reference = NULL)
      }
      if (sys == 1) {
        recipes <- all_recipes
      } else {
        recipes <- append(recipes, all_recipes)
      }
    } # Rest of horizons
    all_recipes <- recipes
    rm(list = 'recipes')
  }
  # Check references
  # If a single reference is not given inside a list, rebuild structure
  if (c("name") %in% names(recipe$Analysis$Datasets$Reference)) {
    reference <- recipe$Analysis$Datasets$Reference
    recipe$Analysis$Datasets$Reference <- NULL
    recipe$Analysis$Datasets$Reference[[1]] <- reference
  }

  for (ref in 1:length(recipe$Analysis$Datasets$Reference)) {
    for (reci in 1:length(all_recipes)) {
      all_recipes[[reci]]$Analysis$Datasets$Reference <- 
        recipe$Analysis$Datasets$Reference[[ref]]
    }
    if (ref == 1) {
        recipes <- all_recipes
    } else {
        recipes <- append(recipes, all_recipes)
    }
  }
  all_recipes <- recipes
  rm(list = 'recipes')

  # Duplicate recipe by Region
  recipes <- list()
  if (any(c("latmin", "latmax", "lonmin", "lonmax") %in% 
          names(recipe$Analysis$Region))) {
    region <- recipe$Analysis$Region
    recipe$Analysis$Region <- NULL
    recipe$Analysis$Region[[1]] <- region
  }
  for (reg in 1:length(recipe$Analysis$Region)) {
    for (reci in 1:length(all_recipes)) {
      all_recipes[[reci]]$Analysis$Region <- recipe$Analysis$Region[[reg]]
    }
    if (reg == 1) {
      recipes <- all_recipes
    } else {
      recipes <- append(recipes, all_recipes)
    }
  }

  all_recipes <- recipes
  rm(list = 'recipes')
  # Duplicate recipe by start date
  if (tolower(recipe$Analysis$Horizon) == 'seasonal') {
    for (sdate in 1:length(recipe$Analysis$Time$sdate)) {
      for (reci in 1:length(all_recipes)) {
      all_recipes[[reci]]$Analysis$Time <-
        list(sdate = recipe$Analysis$Time$sdate[[sdate]],
             fcst_year = recipe$Analysis$Time$fcst_year,
             hcst_start = recipe$Analysis$Time$hcst_start,
             hcst_end = recipe$Analysis$Time$hcst_end,
             ftime_min = recipe$Analysis$Time$ftime_min,
             ftime_max = recipe$Analysis$Time$ftime_max)
      }
      if (sdate == 1) {
        recipes <- all_recipes
      } else {
        recipes <- append(recipes, all_recipes)
      } 
    }
    all_recipes <- recipes
    rm(list = 'recipes')
  } else if (tolower(recipe$Analysis$Horizon) == 'decadal') {
    for (reci in 1:length(all_recipes)) {
      all_recipes[[reci]]$Analysis$Time <-
        list(fcst_year = recipe$Analysis$Time$fcst_year,
             hcst_start = recipe$Analysis$Time$hcst_start,
             hcst_end = recipe$Analysis$Time$hcst_end,
             ftime_min = recipe$Analysis$Time$ftime_min,
             ftime_max = recipe$Analysis$Time$ftime_max)
    }
  } # Rest of horizons
  # Save all recipes in separate YAML files
  for (reci in 1:length(all_recipes)) {
    if (reci < 10) {
      recipe_number <- paste0("0", reci)
    } else {
      recipe_number <- reci
    }
    write_yaml(all_recipes[[reci]], 
               paste0(recipe$Run$output_dir, "/logs/recipes/atomic_recipe_",
                      recipe_number, ".yml"))
  }
  info(recipe$Run$logger,
       paste("The main recipe has been divided into", length(all_recipes),
             "atomic recipes."))
  text <- paste0("Check output directory ", recipe$Run$output_dir,
                 "/logs/recipes/ to see all the individual atomic recipes.")
  info(recipe$Run$logger, text)
  ## TODO: Change returns?
  return(list(n_atomic_recipes = length(all_recipes),
              outdir = recipe$Run$output_dir))
}
