################################################################################
##                          Mukherjee et al. (2022)                           ##
##                                                                            ##
################################################################################
MMCM <- function(X1, X2, ..., dist.fun = stats::dist, dist.args = NULL, seed = NULL, shuffle = FALSE) {
  if(!is.null(seed)) {
    set.seed(seed)
  }
  data.list <- c(list(X1, X2), list(...))
  if(any(!sapply(data.list, function(x) inherits(x, "matrix") | inherits(x, "data.frame")))) {
    stop("All datasets must be provided as data.frames or matrices.")
  }
  mc <- as.list(match.call())
  mc <- mc[!names(mc) %in% c("dist.fun", "dist.args", "seed", "shuffle")]
  dname <- sapply(mc[-1], deparse)
  NAs <- sapply(data.list, anyNA)
  if(sum(NAs) > 1) {
    warning(paste0("Missing values in ", paste0(dname[NAs], collapse = ", "), 
                   " were omitted from the calculation."))
    data.list <- lapply(data.list, na.omit)
  }
  dname <- paste0(dname, collapse = ifelse(length(data.list) > 2, ", ", " and "))
  p <- sapply(data.list, ncol)
  if(length(unique(p)) > 1) 
    stop("all datasets must have the same number of variables")
  K <- length(data.list)
  n.vec <- sapply(data.list, nrow)
  data.list <- lapply(data.list, function(X) {
    colnames(X) <- paste0("X", 1:p[1])
    X
  })
  
  a_N <- nbmatch(data.list, n.vec, dist.fun, dist.args, shuffle)
  MMCM_stat <- MMCMStatistic(a_N, n.vec)
  
  stat <- MMCM_stat$S_KN
  names(stat) <- "chisq"
  param <- MMCM_stat$df
  names(param) <- "df"
  
  pval <- 1 - stats::pchisq(stat, param)
  
  res <- list(statistic = stat, parameter = param,
              p.value = pval, estimate = NULL,
              alternative = ifelse(K > 2, "At least one pair of distributions are unequal.", 
                                   paste0("The distributions of ", dname, " are unequal.")), 
              method = "Approximative MMCM test",  
              data.name = dname)
  class(res) <- "htest"
  return(res)
}
