Clusters <- function(var, weights, nclusters=NULL, listindex=NULL) {

if ( dim(var)[2]!=length(weights) ) stop('spatial dimension of var is not equal to length of weights')

var1 <- array(1, dim=dim(var))
for ( i in 1:dim(var)[1] ) { var1[i,] <- var[i,]/weights }

maxtryclstr <- 20
maxnoiterat <- 300
noatnbclust <- 10

if ( is.null(nclusters)==FALSE ) { 
  kmeans.results <- kmeans(var1, centers=nclusters, iter.max=maxnoiterat, nstart=30) 
} else {
  if ( is.null(listindex)==TRUE ) { listindex <- c('kl', 'ch', 'duda', 'ratkowsky', 'ball', 'ptbiserial', 'gap', 'mcclain', 'tau', 'sdindex') }

  Karray <- rep(0, length(listindex)*noatnbclust)

  ii <- 0
  for ( index1 in listindex ) {
    for ( i in 1:noatnbclust ) {
      ii <- ii + 1

      if ( index1!='first' ) {
        nbclust.results <- NbClust::NbClust(var1, distance='euclidean', min.nc=2, max.nc=20, method='kmeans', index=index1)
        Karray[ii] <- nbclust.results$Best.nc[1]  
      } else {
        Karray <- c(Karray, rep(0, noatnbclust))

        tmp1a <- array(dim = maxtryclstr)
        tmp1b <- array(dim = maxtryclstr)
        tmp2a <- array(dim = maxtryclstr)
        tmp2b <- array(dim = maxtryclstr)

        for ( i in 1:maxtryclstr ) {
          tmp1a[i] <- kmeans(var1, centers = i, iter.max = maxnoiterat, nstart = 30)$tot.withinss
          tmp1b[i] <- kmeans(var1, centers = i, iter.max = maxnoiterat, nstart = 30)$betweenss
        }
        for ( i in 2:(maxtryclstr-1) ) {
          tmp2a[i] <- (tmp1a[i] - tmp1a[i+1])/(tmp1a[i-1] - tmp1a[i])
          tmp2b[i] <- (tmp1b[i] - tmp1b[i+1])/(tmp1b[i-1] - tmp1b[i])
        }

        ia <- 2
        while ( tmp2a[ia] > tmp2a[ia+1] ) { ia <- ia + 1 }
        Karray[ii] <- ia      
        for (j in 1:(noatnbclust-1)) { Karray[ii+j] <- ia }
        ii <- ii + noatnbclust

        ib <- 2
        while ( tmp2b[ib] > tmp2b[ib+1] ) { ib <- ib + 1 }
        Karray[ii] <- ib      
        for (j in 1:(noatnbclust-1)) { Karray[ii+j] <- ib }
        ii <- ii + noatnbclust - 1
        break
      }
    }
  }

  qw <- hist(Karray, breaks = seq(0, maxtryclstr), plot=F)$counts

  kmeans.results <- kmeans(var1, centers=which(qw==max(qw)), iter.max=maxnoiterat, nstart=30) 
}

invisible(kmeans.results)

}
