#dadata <- 1 : (4*5*6)ta <- 1 : (4*5*6)
#dim(data) <- c(lon = 4, lat = 5, case = 6)
#occ <- c(1,1,2,2,4,4) 
#res <- Composite(data, occ)

Composite <- function(var, occ, lag = 0, eno = FALSE, K = NULL,  fileout = NULL) {

  if ( dim(var)[3] != length(occ) ) {
     stop("Temporal dimension of var is not equal to length of occ.")
  }
  if (is.null(K)) {
     K <- max(occ)
  }
  composite <- array(dim = c(dim(var)[1:2], cluster = K))
  tvalue    <- array(dim = dim(var)[1:2])
  dof       <- array(dim = dim(var)[1:2])
  pvalue    <- array(dim = c(dim(var)[1:2], cluster = K))

  if (eno == TRUE) { 
    n_tot <- Eno(var, posdim = 3)
  } else {
    n_tot <- length(occ)
  }
  mean_tot <- Mean1Dim(var, posdim = 3, narm = TRUE)
  #MeanDims(var, dims = 'case', na.rm = TRUE)
  stdv_tot <- apply(var, c(1, 2), sd, na.rm = TRUE) 

  for (k in 1 : K) {
    if (length(which(occ == k)) >= 1) {
      indices <- which(occ == k) + lag
      toberemoved <-  which(0 > indices | indices > dim(var)[3])

      if (length(toberemoved) > 0) {
          indices <- indices[-toberemoved]
      }
      if (eno == TRUE) {
          n_k <- Eno(var[, , indices], posdim = 3)
      } else {
          n_k <- length(indices)
      }
      if (length(indices) == 1) {
          composite[, , k] <- var[, , indices] 
          warning(paste("Composite", k, "has length 1 and pvalue is NA."))
      }  else {
          composite[, , k] <- Mean1Dim(var[, , indices], posdim = 3, narm = TRUE)
      }
      stdv_k <- apply(var[, , indices], c(1, 2), sd, na.rm = TRUE)
     
      tvalue <- (mean_tot - composite[, , k]) / 
                 sqrt(stdv_tot ^ 2 / n_tot + stdv_k ^ 2 / n_k)
      dof <- (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))
      pvalue[, , k] <- 2 * pt(-abs(tvalue), df = dof)
    }
  }  

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

