Trend <- function(var, posTR = 2, interval = 1, conf = TRUE, siglev = 0.95,
                  parallel = FALSE, ncores = NULL) {
  if (!is.null(dim(var))) {
    margins <- c(1:length(dim(var)))[-posTR]
    output <- Apply(list(var), margins = list(margins), AtomicFun = ".Trend",
                    interval = interval, conf = conf, siglev = siglev,
                    parallel = parallel, ncores = ncores)
    new_margins <- append(1: length(dim(output)), 1, posTR)[-1]
    output <- aperm(output, new_margins)
    result <- list()
    if (conf) {
      result$trend <- Subset(output, along = posTR, 1 : 4)
      result$detrend <- Subset(output, along = posTR, 5 : dim(output)[posTR])
    } else {
      result$trend <- Subset(output, along = posTR, 1 : 2)
      result$detrend <- Subset(output, along = posTR, 3 : dim(output)[posTR])
    }
  } else {
    output <- .Trend(var, interval = interval, conf = conf, siglev = siglev)
    result <- list(trend = output[c(1 : (length(output) - length(var)))],
                   detrended = output[(length(output) - length(var) + 1) : length(output)])
  }
  return(result)
}

.Trend <- function(data, interval = interval, conf = conf, siglev = siglev) {
  if (conf) {
    nvals <- 4
    poscoef2 <- 2
    poscoef1 <- 4
  } else {
    nvals <- 2
    poscoef2 <- 1
    poscoef1 <- 2
  }
  if (any(!is.na(data))) {
    mon <- seq(data) * interval
    lm.out <- lm(data ~ poly(mon, raw = TRUE), na.action = na.omit)
    trend <- detrended <- c()
    trend[poscoef2] <- lm.out$coefficients[2]
    trend[poscoef1] <- lm.out$coefficients[1]
    if (conf) {
    trend[c(1, 3)] <- confint(lm.out, level = siglev)[2, 1:2]
    }
    names(trend) <- NULL
    detrended[is.na(data) == FALSE] <- data[is.na(data) == FALSE] - lm.out$fitted.values
  }
  return(c(trend, detrended))
}



