save_percentiles <- function(recipe,
                             percentiles,
                             data_cube,
                             agg = "global",
                             outdir = NULL) {
  # This function adds metadata to the percentiles
  # and exports them to a netCDF file inside 'outdir'.

  # percentiles <- lapply(percentiles,
  #                       function(x) {
  #                         .drop_dims(x)
  #                       })
  archive <- get_archive(recipe)
  # Define grid dimensions and names
  lalo <- c("latitude", "longitude")
  # Add global and variable attributes
  global_attributes <- .get_global_attributes(recipe, archive)
  ## TODO: Sort out the logic once default behavior is decided
  if ((!is.null(recipe$Analysis$Workflow$Anomalies$compute)) && 
      (recipe$Analysis$Workflow$Anomalies$compute)) {
    global_attributes <- c(list(from_anomalies = "Yes"),
                           global_attributes)
  } else {
    global_attributes <- c(list(from_anomalies = "No"),
                           global_attributes)
  }

  # Time indices and metadata
  fcst.horizon <- tolower(recipe$Analysis$Horizon)
  store.freq <- recipe$Analysis$Variables$freq
  if (global_attributes$system == 'Multimodel') {
    if (fcst.horizon == 'decadal') {
      calendar <- archive$System[[recipe$Analysis$Datasets$System$models[[1]]$name]]$calendar
    } else {
      calendar <- archive$System[[recipe$Analysis$Datasets$System$models[[1]]]]$calendar
    }
  } else {
    calendar <- archive$System[[global_attributes$system]]$calendar
  }
  
  # Generate vector containing leadtimes
  if (fcst.horizon == 'decadal') {
    init_date <- as.PCICt(paste0(as.numeric(recipe$Analysis$Time$hcst_start) + 1, 
                                 '-01-01'), cal = calendar)
  } else if (fcst.horizon == 'subseasonal') {
    init_date <- as.PCICt(paste0(recipe$Analysis$Time$hcst_start,
                                 substr(recipe$Analysis$Time$sdate, 5, 8)),
                          format = '%Y%m%d', cal = calendar)
  } else {
    init_date <- as.PCICt(paste0(recipe$Analysis$Time$hcst_start,
                          recipe$Analysis$Time$sdate),
                          format = '%Y%m%d', cal = calendar)
  }

  # Select start date
  # If a fcst is provided, use that as the ref. year. Otherwise use 1970.
  if (fcst.horizon == 'decadal') {
    if (!is.null(recipe$Analysis$Time$fcst_year)) {
      #PROBLEM: May be more than one fcst_year
      # fcst.sdate <- paste0(recipe$Analysis$Time$fcst_year[1],
      #                      sprintf('%02d', init_month), '01')
      fcst.sdate <- paste0(recipe$Analysis$Time$fcst_year[1])
    } else {
      fcst.sdate <- paste0("1970", sprintf('%02d', init_month), '01')
    }
  } else if (fcst.horizon == 'subseasonal') {
    fcst.sdate <- as.character(recipe$Analysis$Time$sdate)
  } else {
    if (!is.null(recipe$Analysis$Time$fcst_year)) {
      fcst.sdate <- paste0(recipe$Analysis$Time$fcst_year,
                           recipe$Analysis$Time$sdate)
    } else {
      fcst.sdate <- paste0("1970", recipe$Analysis$Time$sdate)
    }
  }
  times <- .get_times(recipe, data_cube, fcst.sdate, calendar, init_date)
  
  for (var in 1:data_cube$dims[['var']]) {
    # Subset arrays
    subset_percentiles <- lapply(percentiles, function(x) {
                                 ClimProjDiags::Subset(x, along = 'var',
                                                       indices = var,
                                                       drop = 'selected')})
    # Generate name of output file
    variable <- data_cube$attrs$Variable$varName[[var]]
    outdir <- get_dir(recipe = recipe, variable = variable)
    if (!dir.exists(outdir)) {
      dir.create(outdir, recursive = T)
    }
    outfile <- get_filename(outdir, recipe, variable,
                            fcst.sdate, agg, "percentiles")

    # Remove singleton dimensions and rearrange lon, lat and time dims 
    if (tolower(agg) == "global") {
      subset_percentiles <- lapply(subset_percentiles, function(x) {
                                   Reorder(x, c(lalo, 'time'))})
    }
    
    attr(subset_percentiles[[1]], 'global_attrs') <- global_attributes

    for (i in 1:length(subset_percentiles)) {
      ## TODO: replace with proper standard names
      percentile <- names(subset_percentiles[i])
      long_name <- paste0(gsub("^.*_", "", percentile), "th percentile")
      if (tolower(agg) == "country") {
        dims <- c('Country', 'time')
      } else {
        dims <- c(lalo, 'time')
      }
      metadata <- list(metric = list(name = percentile, long_name = long_name))
      attr(subset_percentiles[[i]], 'variables') <- metadata
      names(dim(subset_percentiles[[i]])) <- dims
    }

    # Get grid data and metadata and export to netCDF
    if (tolower(agg) == "country") { 
      country <- get_countries(grid)
      ArrayToNc(append(country, time, subset_percentiles), outfile)
    } else {
      latitude <- data_cube$coords$lat[1:length(data_cube$coords$lat)]
      longitude <- data_cube$coords$lon[1:length(data_cube$coords$lon)]
      latlon <- .get_latlon(latitude, longitude)
      # Compile variables into a list and export to netCDF
      vars <- c(times, latlon, subset_percentiles)
      ArrayToNc(vars, outfile)
    }
  }
  info(recipe$Run$logger, "##### PERCENTILES SAVED TO NETCDF FILE #####")
}

