SeaIceModes <- function(var, exp, obs, sdates, seasoninf, seasonsup, nclusters=NULL, nleadtime=NULL, nmember=NULL, leadtimemin=1, leadtimemax=NULL, storefreq="monthly", sampleperiod=1, pldgr=0, listregs=NULL, weights=NULL, listindx=NULL) {
  
  if ( is.null(listregs) ) { stop('list of sea ice regions/zones/points is not specified') }
  
  if ( is.null(weights) ) { weights <- rep(1, length(listregs)) }
  
  for ( i in 1:length(listregs) ) {
    tmp1 <- Load(paste(var, listregs[i], sep='_'), exp, obs, sdates, nleadtime=nleadtime, nmember=NULL, leadtimemin=leadtimemin, leadtimemax=leadtimemax, storefreq=storefreq, sampleperiod=sampleperiod)  
    
    if ( is.null(obs) ) {
      tmp2 <- Season(tmp1$mod, posdim = 4, monini = as.integer(substr(sdates,5,6)), moninf = seasoninf, monsup = seasonsup)
      #tmp2 <- tmp1$mod
    } else {
      tmp2 <- Season(tmp1$obs, posdim = 4, monini = as.integer(substr(sdates,5,6)), moninf = seasoninf, monsup = seasonsup)
      #tmp2 <- tmp1$obs
    }
    
    ti2 <- ti1 <- seq(seasoninf, seasonsup)
    while ( max(ti2) < dim(tmp2)[4] ) { ti1 <- ti1 + 12; ti2 <- append(ti2, ti1) }
    tif <- dim(tmp2)[4]
    ti2[ti2 > tif] <- ti2[ti2 > tif] - tif
    ti2 <- unique(ti2)
    
    tmp2a <- drop(tmp2)
    tii <- min(ti2)
    tmp2b <- matrix(0, nrow = dim(tmp2a)[1], ncol = 1)
    tmp2b[, 1] <- tmp2a[, tii]
    for (i1 in (tii+1):tif) {
      if (i1 %in% ti2) { tmp2b <- cbind(tmp2b, tmp2a[,i1]) }
    }
    
    tmp2 <- InsertDim(var=InsertDim(var=tmp2b, posdim=2, lendim=1), posdim=1, lendim=1)
    
#     if ( is.null(nmember) ) {
#       tmp3 <- Mean1Dim(tmp2, posdim=2)
#     } else {
#       if ( length(nmember)== 1) {
#         if ( nmember > length(tmp2[1,,1,1]) ) stop('selected ensemble member is not available')
#         tmp3 <- InsertDim(var=InsertDim(var=tmp2[1,nmember,1,], posdim=1, lendim=1), posdim=1, lendim=1)
#       } else {
#         if ( length(nmember)==2 ) {
#           if ( max(nmember) > length(tmp2[1,,1,1]) ) stop('selected ensemble member is not available')
#           tmp3 <- Mean1Dim(tmp2, posdim=2, limits=nmember)
#         } else {
#           stop('incorrect selection of ensemble members')
#         }
#       }
#     }
    tmp4 <- tmp3
    if ( i==1 ) { tmp4 <- array(dim=c(length(tmp3[1,1,]), length(listregs))) }
    tmp4[,i] <- tmp3[1,1,]
  }
  if (detrend == TRUE) {
    var <- Trend(var = tmp4, posTR=1, pldegree = pldgr)$detrended
  }
  if (!is.null(weights)) {
    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
      }
  } 
  
  output <- kmeans(var, centers = nclusters, iter.max = maxnoiterat, nstart = 30)
  
  invisible(output1)
  
}
