.get_global_attributes <- function(recipe, archive) {
  # Generates metadata of interest to add to the global attributes of the
  # netCDF files.
  parameters <- recipe$Analysis
  hcst_period <- paste0(parameters$Time$hcst_start, " to ",
                        parameters$Time$hcst_end)
  current_time <- paste0(as.character(Sys.time()), " ", Sys.timezone())
  system_name <- parameters$Datasets$System$name
  reference_name <- parameters$Datasets$Reference$name

  attrs <- list(reference_period = hcst_period,
                institution_system = archive$System[[system_name]]$institution,
                institution_reference = archive$Reference[[reference_name]]$institution,
                system = system_name,
                reference = reference_name,
                calibration_method = parameters$Workflow$Calibration$method,
                computed_on = current_time)
  
  return(attrs)
}

.get_times <- function(store.freq, fcst.horizon, leadtimes, sdate, calendar) {
  # Generates time dimensions and the corresponding metadata.
  ## TODO: Subseasonal

  switch(fcst.horizon,
         "seasonal" = {time <- leadtimes; ref <- 'hours since '; 
                       stdname <- paste(strtoi(leadtimes), collapse=", ")},
         "subseasonal" = {len <- 4; ref <- 'hours since ';
                          stdname <- ''},
         "decadal" = {time <- leadtimes; ref <- 'hours since ';
                      stdname <- paste(strtoi(leadtimes), collapse=", ")})

  dim(time) <- length(time)
  sdate <- as.Date(sdate, format = '%Y%m%d') # reformatting
  metadata <- list(time = list(units = paste0(ref, sdate, 'T00:00:00'),
                               calendar = calendar))
  attr(time, 'variables') <- metadata
  names(dim(time)) <- 'time'
  
  sdate <- 1:length(sdate)
  dim(sdate) <- length(sdate)
  metadata <- list(sdate = list(standard_name = paste(strtoi(sdate),
                                                      collapse=", "),
                                units = paste0('Init date')))
  attr(sdate, 'variables') <- metadata
  names(dim(sdate)) <- 'sdate'

  return(list(time=time))
}

.get_latlon <- function(latitude, longitude) {
  # Adds dimensions and metadata to lat and lon
  # latitude: array containing the latitude values
  # longitude: array containing the longitude values
  
  dim(longitude) <- length(longitude)
  metadata <- list(longitude = list(units = 'degrees_east'))
  attr(longitude, 'variables') <- metadata
  names(dim(longitude)) <- 'longitude'
  
  dim(latitude) <- length(latitude)
  metadata <- list(latitude = list(units = 'degrees_north'))
  attr(latitude, 'variables') <- metadata
  names(dim(latitude)) <- 'latitude'

  return(list(lon = longitude, lat = latitude))

}
