save_probabilities <- function(recipe,
                               probs,
                               data_cube,
                               agg = "global",
                               type = "hcst",
                               outdir = NULL) {
  # Loops over the years in the s2dv_cube containing a hindcast or forecast
  # and exports the corresponding category probabilities to a netCDF file.
  # probs: array containing the probability data
  # recipe: the auto-s2s recipe
  # data_cube: s2dv_cube containing the data and metadata
  # outdir: directory where the files should be saved
  # type: 'exp' (hcst and fcst) or 'obs'
  # agg: aggregation, "global" or "country"
  # type: 'hcst' or 'fcst'

  lalo <- c('longitude', 'latitude')
  archive <- get_archive(recipe) 
  global_attributes <- .get_global_attributes(recipe, archive)
  # Add anomaly computation to global attributes
  ## 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)
  }
  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
  }

  if (fcst.horizon == 'decadal') {
    # if (global_attributes$system == 'Multimodel') {
    #   init_month <- 11 #TODO: put as if init_month is January
    # } else {
    #   init_month <- archive$System[[recipe$Analysis$Datasets$System$name]]$initial_month
    # }
    # init_date <- as.PCICt(paste0(recipe$Analysis$Time$hcst_start, '-',
    #                              sprintf('%02d', init_month), '-01'),
    #                       cal = calendar)
    init_date <- as.PCICt(paste0(as.numeric(recipe$Analysis$Time$hcst_start)+1, 
                                 '-01-01'), cal = calendar)
  } else {
    init_date <- as.PCICt(paste0(recipe$Analysis$Time$hcst_start,
                          recipe$Analysis$Time$sdate),
                          format = '%Y%m%d', cal = calendar)
  }

  syears <- seq(1:dim(data_cube$data)['syear'][[1]])
  ## expect dim = [sday = 1, sweek = 1, syear, time]
  syears_val <- lubridate::year(data_cube$attrs$Dates[1, 1, , 1])
  # Loop over variable dimension
  for (var in 1:data_cube$dims[['var']]) {
    subset_probs <- lapply(probs, function(x) {
                           ClimProjDiags::Subset(x, along = 'var',
                                                 indices = var,
                                                 drop = 'selected')})
    # Create output directory
    variable <- data_cube$attrs$Variable$varName[[var]]
    outdir <- get_dir(recipe = recipe, variable = variable)
    if (!dir.exists(outdir)) {
      dir.create(outdir, recursive = T)
    }

    # Loop over each year in the data and save independently
    for (i in syears) {
      # Select year from array and rearrange dimensions
      probs_syear <- lapply(subset_probs, ClimProjDiags::Subset, 'syear', i, drop = 'selected')
      if (tolower(agg) == "global") {
        probs_syear <- lapply(probs_syear, function(x) {
                              Reorder(x, c(lalo, 'time'))})
      } else {
        probs_syear <- lapply(probs_syear, function(x) {
                              Reorder(x, c('country', 'time'))})
      }

      for (bin in 1:length(probs_syear)) {
        prob_bin <- names(probs_syear[bin])
        long_name <- paste0(prob_bin, " probability category")
        if (tolower(agg) == "country") {
          dims <- c('Country', 'time')
        } else {
          dims <- c(lalo, 'time')
        }
        metadata <- list(metric = list(name = prob_bin, long_name = long_name))
        attr(probs_syear[[bin]], 'variables') <- metadata
        names(dim(probs_syear[[bin]])) <- dims # is this necessary?
      }

      # Add global attributes
      attr(probs_syear[[1]], 'global_attrs') <- global_attributes
      
      # Select start date
      if (fcst.horizon == 'decadal') {
        # init_date is like "1990-11-01"
        init_date <- as.POSIXct(init_date)
        fcst.sdate <- init_date + lubridate::years(syears_val[i] - lubridate::year(init_date))
        fcst.sdate <- format(fcst.sdate, '%Y%m%d')
      } else {
        fcst.sdate <- data_cube$attrs$load_parameters$dat1$file_date[[1]][i]
      }

      # Get time dimension values and metadata
      times <- .get_times(recipe, data_cube, fcst.sdate, calendar, init_date)

      # Generate name of output file
      outfile <- get_filename(outdir, recipe, variable, fcst.sdate, agg,
                              "probs")
      if (type == 'obs') {
        filename <- strsplit(outfile, "/")
        filename <- filename[[1]][length(filename[[1]])]
        outfile <- file.path(outdir,
                     sub(gsub('\\.','',
                         recipe$Analysis$Datasets$System$name), "",
                         filename))
      }
      # Get grid data and metadata and export to netCDF
      if (tolower(agg) == "country") { 
        country <- get_countries(grid)
        ArrayToNc(append(country, times, probs_syear), 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(latlon, times, probs_syear)
        ArrayToNc(vars, outfile)
      }
    }
  }
  info(recipe$Run$logger,
       paste("#####", toupper(type),
             "PROBABILITIES SAVED TO NETCDF FILE #####"))
}

