#'#This auxiliar function looks for replecated dimension names between two vectors.
#'# The repeated dimensions (different than 'lon' and 'lat') will be replaced in the first 
#'# vector with the same name and extra label '_exp'.
#'# Example for 'time' and member' repeated dim in the same order of names 
#'# dimension for 'expL' and 'obsL'
#'expL <- 1 : (8*10*2*6*7)
#'expL <- 1 :c(8*10*2*6*7)
#'dim(expL) <- c(lat = 8, lon = 10, time = 2, member = 6, sdate = 7)
#'obsL <- 1 : (8*10*5*3)
#'dim(obsL) <- c(lat = 8, time = 5, member = 3, lon = 10)
#'names_exp <- names(dim(expL))
#'names_obs <- names(dim(obsL))
#'replace_repeat_dimnames(names_exp, names_obs)
#'#[1] "lat"        "lon"        "time_exp"   "member_exp" "sdate" 
#'
#' Example for time and memeber repeated with different order
#'dim(obsL) <- c(lon = 10, member = 3, time = 5, lat = 8)
#'names_obs <- names(dim(obsL))
#'replace_repeat_dimnames(names_exp, names_obs)
#'#[1] "lat"        "lon"        "time_exp"   "member_exp" "sdate"     
#'
#'# Example for no repeated names:
#'dim(obsL) <- c(lon = 10, time_obs = 5, member_obs = 3, lat = 8)
#'names_obs <- names(dim(obsL))
#'replace_repeat_dimnames(names_exp, names_obs)
#'#[1] "lat"    "lon"    "time"   "member" "sdate" 
replace_repeat_dimnames <- function(names_exp, names_obs, lat_name = 'lat', lon_name = 'lon') {
  if (!is.character(names_exp)) {
     stop("Parameter 'names_exp' must be a vector of characters.")
  }
  if (!is.character(names_obs)) {
     stop("Parameter 'names_obs' must be a vector of characters.")
  }

  latlon_dim_exp <- which(names_exp == lat_name | names_exp == lon_name)
  latlon_dim_obs <- which(names_obs == lat_name | names_obs == lon_name)
  if (any(unlist(lapply(names_exp[-latlon_dim_exp],
                          function(x){x == names_obs[-latlon_dim_obs]})))) {
    original_pos <- lapply(names_exp, function(x) which(x == names_obs[-latlon_dim_obs]))
    original_pos <- lapply(original_pos,length) > 0
     names_exp[original_pos] <- paste0(names_exp[original_pos], "_exp")
  }
  return(names_exp)
## Improvements: other dimensions to avoid replacement for more flexibility.
}

