#'DEM Manager
#' 
#'@author Paola Marson, \email{paola.marson@cmcc.it} \email{paola.marson@gmail.com}
#'
#'@description Given a gridded dataset of elevations it computes the zonal and meridional terrain slopes. The zonal distance between two consecutive points is calculated for the baricenter of the geographical domain
#'
#'@param dem list of length 3 containing 1) numeric array of altitudes (m) with expected dimensions 'latitudes' (north to south) and 'longitudes' (west to east); 2) numeric array with expected dimension
         'longitudes' (deg) (west to east); 3) numeric array with expected dimensions
         'latitudes' (deg) (north to south)
#'
#'@import s2dverification, geosphere
#'
#'@return a list of length 3: 
#'        1) \code{demslope} : a list of 2 numeric arrays of dimensions 'lon','lat' containing the zonal (\code{demslope$zonal}) and meridional (\code{demslope$meridional}) terrain gradients
#'        2) \code{demlon} : a numeric array with same longitudes as in input;
#'        3) \code{demlat} : a numeric array with same latitudes as in input  
#'
#'@example

DemManager <- function(dem,lons,lats){

requires(geosphere)
names(dem)<-c("dem","lons","lats")
dx <- abs(dem$lons[2] - dem$lons[1])
dy <- abs(dem$lats[ceiling(length(dem$lats)/2)]-dem$lats[floor(length(dem$lats)/2)])
d <- distHaversine(cbind(c(dem$lons[1],dem$lons[2]),
                   rep(dem$lats[ceiling(length(dem$lats)/2)],2)))  

incrlon <- d*dx  #it changes with latitude
incrlat <- 110978.29*dy 

demslope<-array(dim=c(dim(dem$dem),2))
nlons <- length(dem$lons)
nlats <- length(dem$lats)
demslope[,-nlons,1]<-(dem$dem[,2:nlons]-dem$dem[,1:(nlons-1)])/incrlon
demslope[,nlons,1]<-demslope[,(nlons - 1),1]
demslope[-nlats,,2]<-(dem$dem[2:nlats,]-dem$dem[1:(nlats-1),])/incrlat
demslope[nlats,,2]<-demslope[nlats-1,,2]

return(demslope = list(demslope=list(zonal=demslope[,,1],meridional=demslope[,,2]), demlon=dem$lons, demlat=dem$lats))
}