SeaIceModes <- function(var, exp, obs, sdates, seasoninf, seasonsup, nclusters=NULL, nleadtime=NULL, nmember=NULL, leadtimemin=1, leadtimemax=NULL, storefreq="monthly", sampleperiod=1, detrended=FALSE, datagrid=N3.2_O1L42 ) {
  #
  # This function computes sea ice modes of variability based on the k-mean
  # method applied to sea ice area or extent averages over the Arctic Seas.
  #
  # Args:
  #   var can be sia, sie, siv, and sit (sea ice area, extent, volume and thickness)
  #   exp, obs, sdates, nleadtime, nmember, leadtimemin, leadtimemax, 
  #            storefreq are sampleperiod are the same as in Load;
  #            only exp, obs and sdates are compulsory, and 
  #            only 1 experiment or only 1 observational dataset can be loaded
  #   seasoninf is the month of the year month when to start computing the 
  #            extended seasonal means: 1 to 12.
  #   seasonsup is the month of the year when to stop computing the extended
  #            seasonal means: 1 to 12. The extended seasonal means can overlap
  #            the 31s December: DJF average for example.
  #   nclusters is number of clusters to be computed, default is NULL and then
  #             Cluster.R  will determine the optimal number of clusters 
  #   detrended can request linear detrending before clustering, default is FALSE
  #   datagrid specify what NEMO or EC-Earth version of obs dataset is being used
  #
  # Return:
  #   clusters : 3-dimensional tensor (x, y, nclusters) containing the
  #              centroides  
  #   pvalue   : 3-dimensional tensor (x, y, 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 array (time) containing 1 or 2 or ... when
  #                 a given cluster occurs
  #
  # History:
  #
###############################################################################
#

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

listseas=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' )

# 24/08 : Why are there both regions and ArcticSeas? Could you make that uniform please? 
#         -> we should use name "regions" because these files contain regions way outside of the Arctice, e.g., Weddel Sea, ...
#         -> when you give me permission I will modify mask.ArcticSeas.HadISST.nc and mask.ArcticSeas.NSIDC.nc (they have space in names, etc.)

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

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

    if ( is.null(obs) ) { data1 <- tmp$mod } else { data1 <- tmp$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(listseas))) }
    tmp3[,i] <- tmp2[1,1,]
}

if ( detrended == FALSE ) { output1 <- Cluster(tmp3, weights, nclusters) }
else { output1 <- Cluster(Trend(tmp3,1)$detrended, weights, nclusters) } 

# 4 lines below are only temporary used in testing phase
print(' ')
print('The time series of clusters occurances is')
print(' ')
print(output1$cluster)

# You obtain the array of occurrences that you can use to composite the sea ice
# concentration to obtain clusters with dimensions (x, y, time). To do so,
# you need to call Load('sic', wil all the arguments used when loading the area
# averages)
#
# Then you call the function Composite to obtain the clusters on the (x,y,time)
# grid and their pvalue
#

# this is not the complete output of SeaIceModes, but current version used in testing phase
invisible(output1)

# 24/08 : We would need some figures of the clusters now and this requires the
# 24/08 : loading and compositing steps described above
#         -> will work on this on Tuesday (26th)

}
