SeaIceModes <- function( var, exp, obs, sdates, seasoninf, seasonsup, nclusters=NULL, nleadtime=NULL, nmember=NULL, leadtimemin=1, leadtimemax=NULL, storefreq="monthly", sampleperiod=1, pldgr=0, datagrid=N3.2_O1L42 ) {
  #
  # This function computes sea ice variability modes based on the K-mean clustering
  # method applied to sea ice area, extent, volume or thcikness averages over the 
  # selected region in the Arctic.
  #
  # Args:
  #   var : sia, sie, siv, and sit (sea ice area, extent, volume and thickness)
  #   exp, obs, sdates, nleadtime, nmember, leadtimemin, leadtimemax, storefreq and
  #     sampleperiod are the same as in Load: only exp, obs and sdates are mandatory, 
  #     and only 1 experiment or only 1 observational dataset can be loaded
  #   seasoninf : month of the year when to start computing the extended seasonal means: 1 to 12.
  #   seasonsup : month of the year when to stop computing the extended seasonal means: 1 to 12. 
  #               The extended seasonal means can overlap the 31s December: e.g., DJF average.
  #               They go from 1 to 12, and for monthly means put the same vales for inf and sup
  #   nclusters : K number of clusters to be computed, or K initial cluster centers (default is NULL
  #               and then Cluster.R  will determine the optimal number of clusters and their centers) 
  #   pldgr : pldgr<0 for using the full values, 0 for removing the long-term mean, and 1<pldgr for
  #           using residulas after removing polynomial fit of the pldgr order/degree (deafult is 0) 
  #   datagrid : specify what NEMO or EC-Earth or obs dataset grid is being used (default is N3.2_O1L42)
  #
  # Return:
  #   clusters : 3-dimensional tensor (x, y, nclusters) containing the centroides of clusters  
  #   pvalue : 3-dimensional tensor (x, y, nclusters) containing the pvalue of the centroide 
  #            anomalies obtained through t-test that accounts for the serial dependence of data
  #   occurrences : 1-dimension array (time) containing 1 or 2 or ... when a given cluster occurs
  #
  # History:
  #   1.0  #  2014-09  (N.S. Fuckar, neven.fuckar@ic3.cat)  #  Original code
  #
###############################################################################
  #

listregs=c( 'Baffin_Bay', 'Baltic_Sea', 'Barents_Sea', 'Beaufort_Sea', 'Bering', 'CanArch', 'Chukchi_Sea', 'CntArctic', 'CntArcticRing1', 'CntArcticRing2', 'CntArcticRing3', 'CntArcticRing4', 'CntArcticRing5', 'CntArcticRing6', 'CntArcticRing7_Lincoln_Sea', 'CntArcticRing8', 'CntArcticPrf1', 'CntArcticPrf2r', 'CntArcticPrf3', 'CntArcticPrf4', 'East_Siberian_Sea1', 'Greenland_Sea', 'Hudson', 'Icelandic_Sea', 'Irminger', 'Japan1', 'Kara_Sea', 'Laptev_Sea', 'Labrador_Sea1', 'Norwegian_Sea', 'Okhotsk', 'StLawr' )

# listregs above is the list of non-overlapping regions in the NH (default of Arcticreg1) where sea ice can appear at least in 
# winter (regional masks are designed to include only grid points where sea ice appears at least once in the entire record).

if ( var!='sit' ) { weights <- AreaWeights(listregs, datagrid) } else { weights <- rep(1, length(listregs)) }

for ( i in 1:length(listregs) ) {
    tmp0 <- Load(paste(var, listregs[i], sep='_'), exp, obs, sdates, nleadtime=nleadtime, nmember=nmember, leadtimemin=leadtimemin, leadtimemax=leadtimemax, storefreq=storefreq, sampleperiod=sampleperiod)  

    if ( is.null(obs) ) { data1 <- tmp0$mod } else { data1 <- tmp0$obs }

    tmp1 <- Season(data1, posdim=4, monini=as.integer(substr(sdates,5,6)), moninf=seasoninf, monsup=seasonsup)
    tmp2 <- Mean1Dim(tmp1, 2)

    if ( i==1 ) { tmp3 <- array(dim=c(length(tmp2[1,1,]), length(listregs))) }
    tmp3[,i] <- tmp2[1,1,]
}

ifelse( pldgr<0, output1 <- Clusters(tmp3, weights, nclusters), 
                 ifelse( pldgr>0, output1 <- Clusters(Trend(var=tmp3, posTR=1, pldegree=pldgr)$detrended, weights, nclusters), 
                                  output1 <- Clusters(tmp3 - InsertDim(var=Mean1Dim(tmp3, 1), posdim=1, lendim=dim(tmp3)[1]), weights, nclusters) ) 

invisible(output1)

}
