
#' Downscaling (Significant predictors) 
#'@param  
#'@return downscaling_analog 
#'@useDynLib CSTools
#'@export 

library(data.table)

downscaling_analogs <- function(um,
                                vm,
                                nger,
                                gu92,
                                gv92,
                                gu52,
                                gv52,
                                neni,
                                vdmin,
                                vref,
                                ccm,
                                lab_pred,
                                cor_pred) {


#! REANALYSIS GRID PARAMETERS
ngridd <- 14076
nlat <- 18
nlon <- 30
ic <- nlat*nlon
nlatt <- 25
nlont <- 37
id <- nlatt*nlont
slat <- 55.5
slon <- "-28.5"
rlat <- "-1.5"
rlon <- 1.5
slatt <- 63.
slont <- "-36."
#ngridd <- ((2*nlat)-1)*((2*nlon)-1)

#! OTHER PARAMETERS
#! nd: number of training days
#! nm: number of estimated days
#! f.i, nm = 36600 -> regionalization of 100 years daily data 
#nd <- 5844
#nm <- 7305
nd <- 200
nm <- 50
#! Number of analog situations to consider
nanx <- 155
#nanx <- 20
npx <- 11


#! INPUT DATA PATHS
pathSI <- "/home/sclim/cle/regionalizacion/asun/eraint/datosAscii_SI/"
pathSI_estim <- "/home/sclim/cle/regionalizacion/asun/eraint/datosAscii_SI_estim/1997-2016/"
pathLR_estim <- "/home/sclim/cle/regionalizacion/asun/eraint/datosAscii_LR_estim/1997-2016/"
obspath <- "/MASIVO/cle/datos/REJ5/"

#! TRAINING REANALYSIS FILES
u500_file <- paste(pathSI,'u500.dat',sep="")
v500_file <- paste(pathSI,'v500.dat',sep="")
t500_file <- paste(pathSI,'t500.dat',sep="")
t850_file <- paste(pathSI,'t850.dat',sep="")
msl_file_si <- paste(pathSI,'msl.dat',sep="")
q700_file <- paste(pathSI,'q700.dat',sep="")

#! 6 predictors in 2D format
preu500 <- matrix(scan(u500_file), nrow=5844, ncol=ic+4, byrow=TRUE)
prev500 <- matrix(scan(v500_file), nrow=5844, ncol=ic+4, byrow=TRUE)
pret500 <- matrix(scan(t500_file), nrow=5844, ncol=ic+4, byrow=TRUE)
pret850 <- matrix(scan(t850_file), nrow=5844, ncol=ic+4, byrow=TRUE)
premslsi <- matrix(scan(msl_file_si), nrow=5844, ncol=ic+4, byrow=TRUE)
preq700 <- matrix(scan(q700_file), nrow=5844, ncol=ic+4, byrow=TRUE)

u500 <- preu500[,-c(1:4)]
v500 <- prev500[,-c(1:4)]
t500 <- pret500[,-c(1:4)]
t850 <- pret850[,-c(1:4)]
msl_si <- premslsi[,-c(1:4)]
q700 <- preq700[,-c(1:4)]

#! ESTIMATED REANALYSIS VARIABLES
u500_efile <- paste(pathSI_estim,'u500.dat',sep="")
v500_efile <- paste(pathSI_estim,'v500.dat',sep="")
t500_efile <- paste(pathSI_estim,'t500.dat',sep="")
t850_efile <- paste(pathSI_estim,'t850.dat',sep="")
msl_efile_lr <- paste(pathLR_estim,'msl.dat',sep="")
q700_efile <- paste(pathSI_estim,'q700.dat',sep="")

#! 6 predictors in 2D format
preu500_estim <- matrix(scan(u500_efile), nrow=7305, ncol=ic+4, byrow=TRUE)
prev500_estim <- matrix(scan(v500_efile), nrow=7305, ncol=ic+4, byrow=TRUE)
pret500_estim <- matrix(scan(t500_efile), nrow=7305, ncol=ic+4, byrow=TRUE)
pret850_estim <- matrix(scan(t850_efile), nrow=7305, ncol=ic+4, byrow=TRUE)
premsllr_estim <- matrix(scan(msl_efile_lr), nrow=7305, ncol=id+4, byrow=TRUE)
preq700_estim <- matrix(scan(q700_efile), nrow=7305, ncol=ic+4, byrow=TRUE)

u500_estim <- preu500_estim[,-c(1:4)]
v500_estim <- prev500_estim[,-c(1:4)]
t500_estim <- pret500_estim[,-c(1:4)]
t850_estim <- pret850_estim[,-c(1:4)]
msl_lr_estim <- premsllr_estim[,-c(1:4)]
q700_estim <- preq700_estim[,-c(1:4)]

#! HIGH-RESOLUTION OBSERVATIONAL DATASET
#! maestro file has "est", "lon", "lat" and "alt" in columns (vector structure)
maestro_hr_file <- paste(obspath, "maestro_red_hr",sep="")
assign("prec_hr_file",paste(obspath, "pcp_red_1981-1996.geo",sep=""))
maestro <- read.table(maestro_hr_file)
lon_hr <- unlist(maestro[2])
lat_hr <- unlist(maestro[3])
nptos <- 20945
preprec_hr <- matrix(scan(prec_hr_file), nrow=5844 ,ncol= nptos+1, byrow=TRUE)
prec_hr <- preprec_hr[,-c(1:2)]

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

     downs <- .Fortran("down_prec",
                      ic = as.integer(ic),
                      id = as.integer(id),
                      nd = as.integer(nd),
                      nm = as.integer(nm),
                      nlat = as.integer(nlat),
                      nlon = as.integer(nlon),
                      nlatt = as.integer(nlatt),
                      nlont = as.integer(nlont),
                      slat = as.numeric(slat),
                      slon = as.numeric(slon),
                      rlat = as.numeric(rlat),
                      rlon = as.numeric(rlon),
                      slatt = as.numeric(slatt),
                      slont = as.numeric(slont),
                      ngridd = as.integer(ngridd),
                      u500 = as.numeric(u500[1:nd,]),
                      v500 = as.numeric(v500[1:nd,]),
                      t500 = as.numeric(t500[1:nd,]),
                      t850 = as.numeric(t850[1:nd,]),
                      msl_si = as.numeric(msl_si[1:nd,]),
                      q700 = as.numeric(q700[1:nd,]),
                      lon_hr = as.numeric(lon_hr),
                      lat_hr = as.numeric(lat_hr),
                      prec_hr = as.numeric(prec_hr[1:nd,]),
                      nanx = as.integer(nanx),
                      um = as.double(um),
                      vm = as.double(vm),
                      nger = as.integer(nger),
                      gu92 = as.double(gu92),
                      gv92 = as.double(gv92),
                      gu52 = as.double(gu52),
                      gv52 = as.double(gv52),
                      neni = as.integer(neni),
                      vdmin = as.double(vdmin),
                      vref = as.integer(vref),  
                      ccm = as.double(ccm),
                      lab_pred = as.integer(lab_pred),
                      cor_pred = as.double(cor_pred), 
                      u500_estim = as.numeric(u500_estim[1:nm,]),
                      v500_estim = as.numeric(v500_estim[1:nm,]),
                      t500_estim = as.numeric(t500_estim[1:nm,]),
                      t850_estim = as.numeric(t850_estim[1:nm,]),
                      msl_lr_estim = as.numeric(msl_lr_estim[1:nm,]),
                      q700_estim = as.numeric(q700_estim[1:nm,]),
                      pp=matrix(as.double(seq(1,nm*nptos)),c(nm,nptos)),
                      PACKAGE = 'CSTools')

             output <- downs$pp

             return(output)

}
                                 
# ngridd=((2*nlat)-1)*((2*nlon)-1) (LR grid)

#  # check inputs
#  # check exp
#  # check exp_lat
## completar los checks (depende de lo exigente que seamos con la funcion)
#  if (!is.numeric(exp_lat)) {
#    stop("Parameter 'exp_lat' must be a numeric vector.")
#  }
#  if (length(exp_lat) < 2) {
#    stop("Parameter 'exp_lat' must be a vector with multiple values.")
#  }
## En esta parte calculamos todo lo que nuestra funcion necesite como argumento
#  exp_res <- c(exp_lat, NA) - c(NA, exp_lat)
#  exp_res <- exp_res[!is.na(exp_res)]
#  if (!all(exp_res == exp_res[1])) {
#    stop("Parameter 'exp_lat' must be in regular grid.")
#  } else {
#    exp_res <- exp_res[1]
#  }
#  nlat <- (exp_lat[length(exp_lat)] - exp_lat[1]) / exp_res
#  nlon <- (exp_lon[length(exp_lon)] - exp_lon[1]) / exp_res
#  ic <- nlat * nlon
#  extra_nw_dom <- 7.5 
#  extra_se_dom <- 3 
#  dif_grids <- extra_nw_dom+extra_se_dom
#  nlatt <- nlat + (dif_grids / exp_res)
#  nlont <- nlon + (dif_grids / exp_res)
#  id <- nlatt * nlont
#  slat <- max(exp_lat)
#  slon <- exp_lon[1] # if -180 : 180
#  slon <- min(c(exp_lon[which(exp_lon > 180)] - 360, 
#                exp_lon[which(exp_lon <= 180)])) # if lon 0 :360
#
#  if (any(names(dim(obs_psl)) == 'time')) {
#    time_dim <- which(names(dim(obs_psl)) == 'time')
#  } else if (any(names(dim(obs_psl)) == 'sdate')) {
#    if (any(names(dim(obs_psl)) == 'ftime')) {
#        obs_psl <- MergeDims(obs_psl, c('ftime', 'sdate'), rename_dim = 'time')
#        time_dim <- which(names(dim(obs_psl)) == 'time')
#  }
#  if (any(names(dim(obs_psl)) == 'gridpoint')) {
#    gp_dim <- which(names(dim(obs_psl)) == 'gridpoint')
#  } else if (any(names(dim(obs_psl)) == 'lat')) {
#    if (any(names(dim(obs_psl)) == 'lon')) {
#        obs_psl <- MergeDims(obs_psl, c('lat', 'lon'), rename_dim = 'gridpoint')
#        gp_dim <- which(names(dim(obs_psl)) == 'gridpoint')
#  }  
  
#  nm <- exp$time 
#  nd <- obs$time 
  
# completar los argumentos de la funcion training (basado en los programas de fortran)
# y ver la manera de obtenerlos de la informacion que nos pasa la funcion AnalogPredictors.
# Una vez que tenga todo claro, ir probandolo en R a ver si funciona (habria que hacerlo con el
# dyn.load como habia hecho la prueba).



