#'Multivariate Root Mean Square Error (RMSE) 
#'
#'@author Deborah Verfaillie, \email{deborah.verfaillie@bsc.es}
#'@description This function calculates the RMSE from multiple variables, as the mean of each variable's RMSE scaled by its observed standard deviation. Variables can be weighted based on their relative importance (defined by the user).
#'
#'@param data a list of s2dverification objects (lists) as output by the \code{Load} function from the s2dverification package, one for each variable.
#'
#'@param weight (optional) a vector of weight values to assign to each variable. If no weights are defined, a value of 1 is assigned to every variable.
#'
#'@return \code{$mvrmse} {An array with dimensions: c(number of exp, number of obs, 1 (the multivariate RMSE value), number of lat, number of lon)}
#'
#'@import s2dverification
#'@examples
#'# Creation of sample s2dverification objects. These are not complete
#'# s2dverification objects though. The Load function returns complete objects.
#'
#'# Example with 2 variables
#'mod1 <- 1 : (1 * 3 * 4 * 5 * 6 * 7)
#'mod2 <- 1 : (1 * 3 * 4 * 5 * 6 * 7)
#'dim(mod1) <- c(dataset = 1, member = 3, sdate = 4, ftime = 5, lat = 6, lon = 7)
#'dim(mod2) <- c(dataset = 1, member = 3, sdate = 4, ftime = 5, lat = 6, lon = 7)
#'obs1 <- 1 : (1 * 1 * 4 * 5 * 6 * 7)
#'obs2 <- 1 : (1 * 1 * 4 * 5 * 6 * 7)
#'dim(obs1) <- c(dataset = 1, member = 1, sdate = 4, ftime = 5, lat = 6, lon = 7)
#'dim(obs2) <- c(dataset = 1, member = 1, sdate = 4, ftime = 5, lat = 6, lon = 7)
#'lon <- seq(0, 25, 5)
#'lat <- seq(0, 30, 5)
#'data1 <- list(mod = mod1, obs = obs1, lat = lat, lon = lon)
#'data2 <- list(mod = mod2, obs = obs2, lat = lat, lon = lon)
#'data <- list(data1, data2)
#'weight <- c(1, 2)
#'a <- CST_MultivarRMSE(data, weight)
#'str(a)
#'@export
CST_MultivarRMSE <- function(data, weight = NULL) {
  is_s2dv_object <- function(x) {
    if (all(c('mod', 'obs', 'lon', 'lat') %in% names(x))) { #&& length(x) == 11) {
      TRUE
    } else {
      FALSE
    }
  }

  wrong_input <- FALSE
  if (!is.list(data)) {
    wrong_input <- TRUE
  }

  if (!(all(sapply(data, is_s2dv_object)))) {
    wrong_input <- TRUE
  }

  if (wrong_input) {
    stop("Parameter 'data' must be a list of s2dverification objects as returned by ",
         "the s2dverification::Load function.")
  }

  nvar <- length(data)
  
  if (nvar < 2) {
    stop("Parameter 'data' must contain at least two s2dverification objects for two ",
         "different variables.")
  }
  
  if (is.null(weight)) {
    weight <- c(rep(1, nvar))
  } else if (length(weight) != nvar) {
    stop("Parameter 'weight' must have a length equal to the number of variables.")
  }
  
  mvrmse <- 0
  sumweights <- 0
  for (j in 1:nvar) {
    ano <- Ano_CrossValid(data[[j]]$mod, data[[j]]$obs)
    # seasonal average of anomalies
    AvgExp <- MeanListDim(ano$ano_exp, narm = TRUE, c(2, 4))
    AvgObs <- MeanListDim(ano$ano_obs, narm = TRUE, c(2, 4))
    # multivariate RMSE (weighted) 
    rmse <- s2dverification::RMS(AvgExp, AvgObs, posloop = 1, posRMS = 2, conf = FALSE)
    stdev <- sd(AvgObs)
    mvrmse <- mvrmse + (rmse / stdev * as.numeric(weight[j]))
    sumweights <- sumweights + as.numeric(weight[j])
  }
  mvrmse <- mvrmse / sumweights 
  data <- data[[1]]
  data$mvrmse <- mvrmse
  data$obs <- NULL
  data$mod <- NULL
  data <- data[c("mvrmse", names(data)[-which(names(data) == "mvrmse")])]
  return(data)
}
