# data format for input in CSIndicators SPEI functions
data_format_csindicators <- function(data, vars, var.list, lat, lon, dates){
    dict <- c('tas' = 'tmean', 
              'tasmax' = 'tmax', 
              'tasmin' = 'tmin', 
              'prlr' = 'pr', 
              'pet' = 'pet',
              'hurs' = 'hurs',
              'tdps' = 'tdps')
    dim.names <- names(dim(data$data))
    
    result <- list()
    for (var in vars){
        if (var %in% var.list){
           data.var <- list(data = data$data[,which(var.list == var),,,,,,,],
                            coords = list(latitude = lat, longitude = lon))
        
            # read original units
            var.metadata.pos <- which(names(data$attrs$Variable$metadata) == var)
            units <- data$attrs$Variable$metadata[[var.metadata.pos]]$units
            # to keep original dims
            for(nn in dim.names){
                if(!(nn %in% names(dim(data.var$data)))){
                    data.var$data <- s2dv::InsertDim(data.var$data, 
                                                        pos = 1, 
                                                        len = 1, 
                                                        name = nn)
                }
            }
            dim.order <- match(dim.names, names(dim(data.var$data)))
            data.var$data <- aperm(data.var$data, dim.order)

            # transform to s2dv_cube with metadata
            attr(data.var, 'class') <- 's2dv_cube'
            data.var$attrs$Dates <- dates
            data.var$attrs$Units <- units
        } else {
            data.var <- NULL
        }

        # append all variables in a list of s2dv_cubes
        result <- append(result, list(data.var))
    
    }
    
    names(result) <- dict[vars]
    
    return(result)
}
