#'Read regrid parameters from recipe and returns a list for use with Start()
#'
#'The purpose of this function is to read the recipe and archive configuration
#'data for Auto-S2S workflows, retrieve the regridding parameters for hcst and
#'obs, and return an object that can be the input for 'transform' and 
#''transform_params' when the data is loaded using Start().
#'Requires CDORemapper.
#' 
#'@param recipe Auto-S2S configuration recipe as returned by read_yaml()
#'@param archive Auto-S2S exp and obs archive as returned by read_yaml()
#'
#'@return A list containing regridding parameters for fcst and obs
#' 
#'@import startR
#'@examples
#'setwd("/esarchive/scratch/vagudets/repos/auto-s2s/")
#'library(yaml)
#'library(startR)
#'recipe <- read_yaml("modules/data_load/recipe_1.yml")
#'archive <- read_yaml(paste0(recipe$Run$code_dir, "conf/archive.yml"))$archive
#'regrid_params <- get_regrid_params(recipe, archive)
#' 
#'@export
get_regrid_params <- function(recipe, archive) {

  ## TODO: Multi-model case
  ## TODO: 'NULL' entries had to be removed due to bug in Start(). Rewrite when
  ## the bug is fixed.
  exp.name <- recipe$Analysis$Datasets$System$name
  ref.name <- recipe$Analysis$Datasets$Reference$name
  exp_descrip <- archive$System[[exp.name]]
  reference_descrip <- archive$Reference[[ref.name]]

  if (tolower(recipe$Analysis$Regrid$type) == 'to_reference') {

    regrid_params <- list(fcst.gridtype = reference_descrip$reference_grid,
                          fcst.gridmethod = recipe$Analysis$Regrid$method,
                          fcst.transform = CDORemapper,
			  obs.gridtype = reference_descrip$reference_grid,
			  obs.gridmethod = recipe$Analysis$Regrid$method,
			  obs.transform = CDORemapper)

  } else if (tolower(recipe$Analysis$Regrid$type) == 'to_system') {

    regrid_params <- list(fcst.gridtype = exp_descrip$reference_grid,
                          fcst.gridmethod = recipe$Analysis$Regrid$method,
                          fcst.transform = CDORemapper,
                          obs.gridtype = exp_descrip$reference_grid,
                          obs.gridmethod = recipe$Analysis$Regrid$method,
                          obs.transform = CDORemapper)

  } else if (tolower(recipe$Analysis$Regrid$type) == 'none') {

    regrid_params <- list(fcst.gridtype = exp_descrip$reference_grid,
			  fcst.gridmethod = recipe$Analysis$Regrid$method,
			  fcst.transform = CDORemapper,
			  obs.gridtype = reference_descrip$reference_grid,
			  obs.gridmethod = recipe$Analysis$Regrid$method,
			  obs.transform = CDORemapper)

  } else {
    regrid_params <- list(fcst.gridtype = recipe$Analysis$Regrid$type,
			  fcst.gridmethod = recipe$Analysis$Regrid$method,
			  fcst.transform = CDORemapper,
			  obs.gridtype = recipe$Analysis$Regrid$type,
			  obs.gridmethod = recipe$Analysis$Regrid$method,
			  obs.transform = CDORemapper)
  }

  return(regrid_params)
}


