Composite <- function(var, occurrences, lag, tflag=FALSE, nameout=NULL) {
  #
  # This function composites the 3-d field var(x,y,time) according to the 
  # indices of occurrences in time and computes the pvalues (t-test). 
  # 
  # Args :
  #  var         : 3-dimensional tensor (x, y, time) containing the variable to composite
  #  occurrences : 1-dimensional array for the occurrence time series of cluster(s) 
  #                (*1) when one wants to composite all, e.g., K=3 clusters then for
  #                example occurrences = 1 1 2 3 2 3 1 3 3 2 3 2 2 3 2
  #                (*2) otherwise for compositing only the 2nd cluster of the above 
  #                example occurrences = 0 0 1 0 1 0 0 0 0 1 0 1 1 0 2
  #  lag         : lag time step (an integer), e.g., for lag=2 composite will use occurrences + 2
  #  tflag       : for using the effective sample size (TRUE) or the total sample size 
  #                (FALSE that is the default) for the number of degrees of freedom  
  #  nameout     : name of the .csv output file (NULL is the default)
  #
  # Return :
  #   Composite : 3-d tensor (x, y, k) containing the composites k=1,..,K for case (*1)
  #               or only k=1 for any specific cluster, i.e., case (*2)
  #   Pvalue    : 3-d tensor (x, y, k) containing the pvalue of the 
  #               composites obtained through a t-test that accounts for the serial
  #               dependence of the data with the same structure as Composite  
  #
  # History: to be specified ..
  #   
############################################################################################

if ( dim(var)[3]!=length(occurrences) ) stop("temporal dimension of var is not equal to length of occurrences")

K         <- max(occurrences)
composite <- array(dim = c(dim(var)[1:2], K))

# 22/07 : For tvalue and dof, you do not need to define a 3d field here. You can
# 22/07 : have a 2d field that you overwrite for each cluster
tvalue <- array(dim = c(dim(var)[1:2], K))
dof    <- array(dim = c(dim(var)[1:2], K))
pvalue <- array(dim = c(dim(var)[1:2], K))

if ( tflag==TRUE ) { n_tot <- Eno(var,3) }
   else { n_tot <- length(occurrences) }

mean_tot <- Mean1Dim(var,3,narm=TRUE)
stdv_tot <- apply(var,c(1,2),sd) 

for (k in 1:K) {
    indices <- which(occurrences==k)+lag

    toberemoved=which(0>indices|indices>dim(var)[3])
    if ( length(toberemoved) > 0 ) { indices=indices[-toberemoved] }

    composite[,,k] <- Mean1Dim(var[,,indices],3,narm=TRUE)
    
    if ( tflag==TRUE ) { n_k <- Eno(var[,,indices],3) }
       else { n_k <- length(indices) }

    # 27/07 mean_k <- composite[,,k], you do not need to compute it again
    mean_k <- Mean1Dim(var[,,indices],3,narm=TRUE)
    stdv_k <- apply(var[,,indices],c(1,2),sd)
    # 27/07 : You also need something like na.rm=T above - in apply ?

# Student's t-test of the difference of means with unequal variances is performed according to von Storch and Zwiers, 2003
#   Formula (6.19) on page 113 
    tvalue[,,k] <- (mean_tot - mean_k)/sqrt(stdv_tot^2/n_tot + stdv_k^2/n_k)
#   Formula (6.20) on page 113 
    dof[,,k]    <- (stdv_tot^2/n_tot + stdv_k^2/n_k)^2/((stdv_tot^2/n_tot)^2/(n_tot - 1) +  (stdv_k^2/n_k)^2/(n_k - 1))

# this is a parametric test of the null hypothesis that univariate random fields var[,,] and var[,,indices] have equal means in time 
    for (x in 1:dim(var)[1]) {
        for (y in 1:dim(var)[2]) {
            pvalue[x,y,k] <- 2*pt(-abs(tvalue[x,y,k]),df=dof[x,y,k])
        }
    }
}

if ( is.null(nameout)==FALSE ) { 
   output <- list(Composite = composite, Pvalue = pvalue)   
   save(output,file=paste(nameout,'.sav',sep=''))
   }

invisible(list(Composite = composite, Pvalue = pvalue)) 

}


