Clusters <- function(var, weights, nclusters=NULL, index='sdindex') {

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

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

if ( is.null(nclusters)==FALSE ) { 
  kmeans.results <- kmeans(var1, centers=nclusters, iter.max=300, nstart=30) 
} else {
  if ( is.null(index)==TRUE ) stop('an index and the associated crteria (from NbClust) to select the optimal number of clusters can not be NULL')

  nbclust.results <- NbClust::NbClust(var1, distance='euclidean', min.nc=2, max.nc=20, method='kmeans', index=index)
  if ( index=='alllong' || index=='all' ) {
    kmc  <- hist(nbclust.results$Best.nc[1,], breaks = seq(0, 20), plot=FALSE)$counts
    kmc1 <- which(kmc==max(kmc))
  } else {
    kmc1 <- nbclust.results$Best.nc[1]
  }
  
  kmeans.results <- kmeans(var1, centers=kmc1, iter.max=300, nstart=30)
}

invisible(kmeans.results)

}
