Trend <- function(var, posTR = 2, interval = 1, pldegree = 1) {
  # Computes linear trend or higher order polynomial along the posTR dimension of tensor 
  # var with the method of least squares, and estimates the associated error interval.
  # Provides also the detrended or residual (after removing fitted polynomial) data.
  # The confidence interval relies on a student-T distribution.
  #
  # Args:
  #   var: Matrix of any number of dimensions up to 10.
  #   posTR: Position along which to compute trends.
  #   interval: Number of months between 2 points along posTR dimension.
  #             Default = 1 (assumes monthly data).
  #   pldegree: The degree/order of the polynomial to be fitted and removed
  #             (keep in mind that the degree must be smaller than the number 
  #             of points along posTR dimension). Default = 1 (linear fit).
  #
  # Returns:
  #   $trend: Same dimensions as var except along posTR dimension which is replaced
  #           by a dimension with length 3*(pldegree + 1) showing for
  #           i) pldegree=1: a^(lo)_1, a_1 (slope or trend), a^(hi)_1, a_0 (intercept), 
  #              a^(lo)_0, and a^(hi)_0 due to backward compatiliblity requirement, 
  #           ii) pldegree>1: a^(lo)_pldegree, a_pldegree, a^(hi)_pldegree, 
  #               a^(lo)_(pldegree-1), a_(pldegree-1), a^(hi)_(pldegree-1), ...
  #               a^(lo)_0, a_0, and a^(hi)_0, where (lo) is the lower limit of the 
  #           95% confidence interval and (hi) is the upper limit of the 95% confidence
  #           interval for each point of the tensor var along all other dimensions.    
  #   $detrended: Same dimensions as var with residual values (after removing polynomial
  #               fit of pldegree order) along the posTR dimension.
  # 
  # History:
  # 0.1  -  2011-05  (V. Guemas, \email{virginie.guemas@ic3.cat})    -  Original code
  # 1.0  -  2013-09  (N. Manubens, \email{nicolau.manubens@ic3.cat}) -  Formatting to CRAN
  # 1.1  -  2015-01  (N.S. Fuckar, \email{neven.fuckar@ic3.cat})     -  Upgrade to polynomial fit
  #         i.e., modified to include fit of a raw polynomial with an arbitrary 
  #         (but constrained) degree/order and a more complete $trend output.

  # 
  #  Enlarge the size of var to 10 and move posTR to first position 
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #  
  dimsvar <- dim(var)
  if (is.null(dimsvar)) { 
    dimsvar <- length(var) 
  }
  enlvar <- Enlarge(var, 10)
  outdim <- c(dimsvar, array(1, dim = (10 - length(dimsvar))))
  outdim[posTR] <- 3*(pldegree + 1)
  posaperm <- 1:10
  posaperm[posTR] <- 1
  posaperm[1] <- posTR
  enlvar <- aperm(enlvar, posaperm)
  dimsaperm <- outdim[posaperm]
  if ( dim(enlvar)[1]<(pldegree + 1) ) { 
    stop("selected polynomial degree (pldegree) is too high")
  }
  # 
  #  Loop on all dimensions to compute trends 
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # 
  enltrend <- array(dim = dimsaperm)
  enldetrend <- array(dim = dim(enlvar))
  for (j2 in 1:dimsaperm[2]) {
    for (j3 in 1:dimsaperm[3]) {
      for (j4 in 1:dimsaperm[4]) {
        for (j5 in 1:dimsaperm[5]) {
          for (j6 in 1:dimsaperm[6]) {
            for (j7 in 1:dimsaperm[7]) {
              for (j8 in 1:dimsaperm[8]) {
                for (j9 in 1:dimsaperm[9]) {
                  for (j10 in 1:dimsaperm[10]) {
                    tmp <- enlvar[, j2, j3, j4, j5, j6, j7, j8, j9, j10]
                    if (length(sort(tmp)) > 0) {
                      mon <- seq(tmp) * interval
                      lm.out <- lm(tmp ~ poly(mon, degree=pldegree, raw=TRUE), na.action = na.omit)
                      for (jj in (pldegree + 1):1) {
                        jj1 <- 1 + (pldegree + 1) - jj
                        if ( (jj==1) & (pldegree==1) ) {
                          enltrend[3*jj1-2, j2, j3, j4, j5, j6, j7, j8, j9, j10] <- lm.out$coefficients[jj]
                          enltrend[3*jj1-1, j2, j3, j4, j5, j6, j7, j8, j9, j10] <- confint(lm.out)[jj, 1]
                          enltrend[3*jj1,   j2, j3, j4, j5, j6, j7, j8, j9, j10] <- confint(lm.out)[jj, 2]
                        } else {
                          enltrend[3*jj1-2, j2, j3, j4, j5, j6, j7, j8, j9, j10] <- confint(lm.out)[jj, 1]
                          enltrend[3*jj1-1, j2, j3, j4, j5, j6, j7, j8, j9, j10] <- lm.out$coefficients[jj]
                          enltrend[3*jj1,   j2, j3, j4, j5, j6, j7, j8, j9, j10] <- confint(lm.out)[jj, 2]
                        }
                      }
                      enldetrend[is.na(tmp) == FALSE, j2, j3, j4, j5, j6, j7, j8, j9, j10] <- tmp[is.na(tmp) == FALSE] - lm.out$fitted.values
                    }
                  } 
                }
              }
            }
          }
        }
      }
    }
  }
  # 
  #  Back to the original dimensions
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # 
  detrended <- array(dim = dimsvar)
  dimsvar[posTR] <- 3*(pldegree + 1)
  trend <- array(dim = dimsvar)
  trend[] <- aperm(enltrend, posaperm)
  detrended[] <- aperm(enldetrend, posaperm)
  # 
  #  Outputs
  # ~~~~~~~~~
  # 
  invisible(list(trend = trend, detrended = detrended))
}
