Mean1DimFast <- function(var, posdim, narm = TRUE, limits = NULL) {
 # Averages the matrix var along the posdim dimension between limits [1] and 
# limits [2] if limits argument is given.
#
# Args:
#   var: Matrix to average.
#   posdim: Position of the dimension to average along.
#   narm: Ignore NA values or not.
#   limits: Limits to average between.
#
# Returns:
#   Matrix with one dimension less containing the average.
# History:
#   1.0  #  2015-02  (C. Carmona, carles.carmona@ic3.cat)  #  Original code    


#Set the limit parameter
if (is.null(limits)) {
	linf<-0
	lsup<-dim(var)[posdim]
}
else{
	linf<- limits[0]
	lsup<- limits[1]
}

#NA 
#var[is.na(var)] <- 0 is too slow
b <- replace(var, var==NA , 0)

#Set the data needed by .C extension (The offset is necessary to calcule the mean without reorder data)
ndims <- length(dim(var))
nlen <- dim(var)
offset <- 1
offset2 <- 1
dim <- nlen[posdim]
dimout <- array(0,c(length(dim(var))-1))
for (i in 1:ndims){
	if(i<posdim){
		offset <- offset * nlen[i]
	}
	if(i>posdim){
		offset2 <- offset2 * nlen[i]
	}
	if(i!=posdim){
		if(i>posdim){
			dimout[i-1] <- nlen[i]
		}
		else{
			dimout[i] <- nlen[i]
		}
	}
}
#Define data types for .C Call
alen <- length(var)
b <- array(0,c(length(var)/dim))
blen <- length(b)

mode(var) <- "double"
mode(b) <- "double"
mode(offset) <- "integer"
mode(offset2) <- "integer"
mode(dim) <- "integer"
mode(linf) <- "integer"
mode(lsup) <- "integer"
mode(alen) <- "integer"
mode(blen) <- "integer"

b <- .Fortran("Mean1DimFast",a=as.vector(var),b=b,offset=offset,offset2=offset2,ndims=dim,linf=linf,lsup=lsup,alen=alen,blen=blen, NAOK=TRUE,PACKAGE = "s2dverification")$b

#Change 0 to NA
b <- replace(b, b==0 , NA)
#Define the outdimension
dim(b) = dimout
b
}
