WeatherRegime <- function(data, EOFS = FALSE, neofs = NULL, ncenters = NULL, method = "kmeans",
                          nstart = 30, detrend = FALSE, pldegree = NULL, posTR = NULL, listindex = NULL) {
  sdate <- which(names(dim(data)) == "sdate")
  ftime <- which(names(dim(data)) == "ftime")
  lon <- which(names(dim(data)) == "lon")
  lat <- which(names(dim(data)) == "lat")
  dims <- c(1 : length(dim(data)))[-c(sdate, ftime, lon, lat)]
  data <- aperm(data, c(sdate, ftime, lat, lon, dims))
  if (is.null(ncenters)) {
    stop("nclusters must be specified")
  }
  if (detrend == TRUE) {
    if (is.null(pldegree)) {
      pldegree <- 1
    }
    data <- Trend(data, posTR = posTR, pldegree = pldegree)$detrend
  }
  if (EOFS) {
    EOFs <- EOF(data, lon = lon, lat = lat, neofs = neofs)$EOFs 
  }
  if (method == "kmeans") {
    KMeans <- function(data, ncenters) {
      data <- melt(data, varnames = c("Year", "Day", "Lat", "Lon"))
      data <- acast(data, Year + Day ~ Lat + Lon)
      kmeans(data, centers = ncenters, iter.max = 100, nstart= nstart, trace=FALSE)
    }
  }
  if (length(dim(data)) >= 5) {
    margins <- c(1 : length(dim(data)))[-c(sdate, ftime, lat, lon)]
    result <- Apply(list(data), margins = margins, AtomicFun = "Kmeans", parallel = parallel,
                    ncores = ncores)
  } else {
    data <- melt(data, varnames = c("Year", "Day", "Lat", "Lon"))
    data <- unname(acast(data, Year + Day ~ Lat + Lon))
    result <- kmeans(data, centers = ncenters, iter.max = 100, nstart= nstart, trace=FALSE)
  }
}
  

