Cluster <- function(var, weights, nclusters=NULL) {
  #
  # This function computes clusters by applying the k-mean method on the 
  # 2-dimensional input var (space, time). The first dimension can correspond
  # either to area-averages over a series of domains or to the grid-points 
  # from any grid (x,y), (x,z) ... re-organised in arrays for each time step
  #
  # Args:
  #  var : 2-dimensional matrice (time,space); the spatial dimension can 
  #        correspond either to area-averages over a series of domains or 
  #        to the grid-points from any grid (x,y), (x,z) ...
  #        re-organised in arrays for each time step
  #  weights : 1-dimensional array of weights corresponding to the areas 
  #            covered each domain or grid-cell of var; the length of 
  #            the weights array should equal the first dimension of var
  #  nclusters : number of clusters to be computed
  #
  # Returns:
  #   clusters : 2-dimensional matrice (spatial, nclusters) containing the
  #              centroides  
  #   pvalue   : 2-dimensional matrice (spatial, nclusters) containing the 
  #              pvalue of the centroide anomalies obtained through a t-test
  #              that accounts for the serial dependence of the data
  #   occurrences : 1-dimension matrice (time) containing 1 or 2 or ... when
  #                 a given cluster occurs
  #
  # History:
  #   
##############################################################################

# 24/08: The help needs to be corrected above in the second line (space,time)
# 24/08: -> (time,space)
# 24/08: and in the description of weights : first -> second dimension of var
# 24/08: and the behaviour of nclusters=NULL should be described
# 24/08: also in the ouputs, only the array of occurrences are useful actually
# 24/08: since you are going to use Composite to compute the clusters and their
# 24/08: pvalues.

print(' ')
print('The K-means cluster analysis')
print(' ')

# Your function should start by a security check that the length of weights 
# equals the first dimension of var
print(dim(var)[2])
print(length(weights))
# 24/08: This is not what I meant by security check. I mean a if / stop
# 24/08: in case the dimensions are not correct. 

# 24/08: A more general way of defining var1 is var1 <- array(1,dim=dim(var))
var1 <- matrix(1, nrow=dim(var)[1], ncol=dim(var)[2])
for ( i in 1:dim(var)[1] ) { var1[i,] <- var[i,]/weights }

print(dim(var1))
save(var1,file='weigthed_input_to_Cluster.sav')
print(var1)

maxtryclstr <- 20
maxnoiterat <- 300

if ( is.null(nclusters)==FALSE ) { kmeans.results <- kmeans(var1, centers=nclusters, iter.max=maxnoiterat, nstart=30) }
   else {
#        tmp1a <- array(dim = maxtryclstr)
#        tmp1b <- array(dim = maxtryclstr)
#        tmp2a <- array(dim = maxtryclstr)
#        tmp2b <- array(dim = maxtryclstr)
#
#        for ( i in 1:maxtryclstr ) {
#            tmp1a[i] <- kmeans(var, centers = i, iter.max = maxnoiterat, nstart = 30)$tot.withinss
##            tmp1a[i] <- kmeans(var, centers = i, iter.max = maxnoiterat, nstart = 30)$tot.withinss/i
#            tmp1b[i] <- kmeans(var, centers = i, iter.max = maxnoiterat, nstart = 30)$betweenss
##            tmp1b[i] <- kmeans(var, centers = i, iter.max = maxnoiterat, nstart = 30)$betweenss/i
#            }
#
#        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])
#            }
#
# If one does not want to see details of the selection process for the optiomal number of clusters otherwise comment out 10 lines below 
#        postscript('within-_and_between-cluster_analysis.eps')
#        mm <- rbind(c(1,2),c(3,4),c(5,5))
#        layout(mm)
#        plot(1:maxtryclstr,tmp1a,type="b",xlab="Number of clusters",ylab="Total within-cluster sum of squares")
#        plot(1:maxtryclstr,tmp2a,type="b",xlab="Number of clusters",ylab="Shifted derivative of .. (on left)")
#        plot(1:maxtryclstr,tmp1b,type="b",xlab="Number of clusters",ylab="Total between-cluster sum of squares")
#        plot(1:maxtryclstr,tmp2b,type="b",xlab="Number of clusters",ylab="Shifted derivative of .. (on left)")
#        plot(1:maxtryclstr,tmp1b/tmp1a,type="b",xlab="Number of clusters",ylab="...  between-cluster sum of squares")
#        dev.off()
#        cat("Press ENTER/RETURN to continue")
#        line <- readline()
#
#        ia <- 2
#        while ( tmp2a[ia] > tmp2a[ia+1] ) { ia <- ia + 1 }
##       ia <- 1
##       repeat { 
##              ia <- ia + 1
##              if ( tmp2a[ia] < tmp2a[ia+1] ) break
##              }
#
#        ib <- 2
#        while ( tmp2b[ib] > tmp2b[ib+1] ) { ib <- ib + 1}
##       ib <- 1
##      repeat { 
##              ib <- ib + 1
##              if ( tmp2b[ib] < tmp2a[ib+1] ) break
##              }
#
#        ii <- min(ia,ib)      
# 29/07 : Maybe we can workaround a combined metric instead of taking the mininum of both
# 29/07 : criteria, something like computing tmp1a/tmp1b and look for the absolute minimum

   no1 <- 15
#  listindex <- c( 'kl', 'ch', 'marriot', 'tracew', 'duda', 'pseudots2', 'beal', 'ratkowsky', 'ball', 'ptbiserial', 'gap', 'mcclain', 'tau', 'sdindex' )
# below is safer list of index methods (some of methods on the above list can produce num sigularity), but I think that I could utilize at least hurbert and dindex
   listindex <- c( 'kl', 'ch', 'duda', 'beal', 'ratkowsky', 'ball', 'ptbiserial', 'gap', 'mcclain', 'tau', 'sdindex' )
   Karray    <- rep(0, length(listindex)*no1)

   ii <- 0
   for ( index1 in listindex ) {
       for ( i in 1:no1 ) {
           ii <- ii + 1        
           nbclust.results <- NbClust(var1, distance='euclidean', min.nc=2, max.nc=20, method='kmeans', index=index1)
           print(index1)
           print(nbclust.results$Best.nc[1])
           Karray[ii] <- nbclust.results$Best.nc[1]  
       }
   }

#        print(' ')
#        print(nbclust.results$All.index)
#        print(' ')
#        print(nbclust.results$Best.nc[1])
#        print(' ')
#        print(nbclust.results$Best.partition)
#        print(' ')        
#        cat("Press ENTER/RETURN to continue")
#        line <- readline()
        
   qw <- rep(0, maxtryclstr)
   for ( i in 2:maxtryclstr ) { qw[i] <- sum(which(Karray==i)/which(Karray==i)) }
   # 24/08: I do not understand the line above : why do you divide by which(Karray==i)?
   # 24/08: I guess you want an histogram and the number of occurences for each  number
   # 24/08: of cluster and you can get it by: 
   # 24/08: qw <- hist(Karray, breaks = seq(0, maxtryclstr), plot=F)$counts

}

print(' qw distribution')
print(qw)
print(' ')
print(which(qw==max(qw)))
# 24/08: This line below should be before closing the if because kmeans.results has already been
# 24/08: computed if nclusters != NULL
kmeans.results <- kmeans(var1, centers=which(qw==max(qw)), iter.max=maxnoiterat, nstart=30) 

invisible(kmeans.results)

# 24/08: What is sent back here? The array of occurrences only ?

}
