
  #-------------------------------------------------------------------
  # Init 
  #-------------------------------------------------------------------
  
  
  fcst.month <- substr(fcst.sdate,5,6) 
  fcst.year <- substr(fcst.sdate,1,4) 

  file_dates.fcst <- paste(fcst.year, fcst.month, sep = "")
  file_dates <- paste(strtoi(hcst.inityear):strtoi(hcst.endyear),
                         fcst.month, sep = "")
                         
  add_dims <- function(data){
    default_dims <- c(sweek = 1, sday = 1, syear = length(data))
    default_dims[names(dim(data))] <- dim(data)
    dim(data) <- default_dims
    return(data)
  }

  file_dates <- add_dims(file_dates)
  file_dates.fcst <- add_dims(file_dates.fcst)

# REPLACED                      
#  accum <- FALSE
#  switch (tolower(variable),
#      "tas"     = {freq.hcst <- 'f6h';    freq.obs <- 'f1h'},
#      "tasmin"  = {freq.hcst <- 'f24h';   freq.obs <- 'f24h'},
#      "tasmax"  = {freq.hcst <- 'f24h';   freq.obs <- 'f24h'},
#      "psl"     = {freq.hcst <- 'f6h';   freq.obs <- 'f1h'},
#      "prlr"    = {freq.hcst <- 's0-24h';  freq.obs <- 's0-24h'; accum <- TRUE},
#      "rsds"    = {freq.hcst <- 's0-24h'; freq.obs <- 's0-24h'; accum <- TRUE},
#      "sfcwind" = {freq.hcst <- 'f6h';   freq.obs <- 'f1h'}
#  ) 
#-------------
table <- read_yaml(paste0(conf$code_dir, "data_analysis/data_table.yml"))
dataset_descrip <- table[which(names(table) == fcst.name)][[1]]
store_freq <- which(names(unlist(dataset_descrip$store_freq)) == variable)
freq.hcst <- unlist(dataset_descrip$store_freq[store_freq])
refere_descrip <- table[which(names(table) == ref.name)][[1]]
freq.obs <- unlist(refere_descrip$store_freq[store_freq])
obs.dir <- refere_descrip$path
fcst.dir <- dataset_descrip$path 
hcst.dir <- dataset_descrip$path
fcst.nmember <- dataset_descrip$nmember$fcst
hcst.nmember <- dataset_descrip$nmember$hcst

if ("accum" %in% names(refere_descrip)) {
  accum <- unlist(refere_descrip$accum[store_freq][[1]])
} else {
  accum <- FALSE
}
# -----------
  obs.path <- paste0(
              obs.dir,fcst.freq,"/$var$_",
              freq.obs,"/$var$_$file_date$.nc")

  hcst.path <- paste0(
               hcst.dir,fcst.freq,"/", "/$var$_",
               freq.hcst,"/$var$_$file_date$01",
               ".nc")

  fcst.path <- paste0(
               fcst.dir,fcst.freq,"/", "/$var$_",
               freq.hcst,"/$var$_$file_date$01",
               ".nc")
  #-------------------------------------------------------------------
  # Timeseries load 
  #-------------------------------------------------------------------
  
  if (tolower(stream) == "fcst"){
    
    fcst <- Start(dat = fcst.path,
                  var = variable,
                  file_date = file_dates.fcst,
                  time = indices(ltmin:ltmax),
  	              latitude = values(list(lats.min, lats.max)),
                  latitude_reorder = Sort(decreasing = TRUE),
                  longitude = values(list(lons.min, lons.max)),
                  longitude_reorder = CircularSort(0, 361),
                  synonims = list(latitude=c('lat','latitude'),
                                  longitude=c('lon','longitude'),
                                  member=c('ensemble')), 
                  member = indices(1:fcst.nmember),
                  return_vars = list(latitude = 'dat',
                                     longitude = 'dat',
                                     time = 'file_date'),
                  split_multiselected_dims = TRUE,
                  retrieve = T)
  }

  hcst<-Start(dat = hcst.path,
              var = variable,
              file_date = file_dates,
              time = indices(ltmin:ltmax),
              latitude = values(list(lats.min, lats.max)),
              latitude_reorder = Sort(decreasing = TRUE),
              longitude = values(list(lons.min, lons.max)),
              longitude_reorder = CircularSort(0, 361),
              synonims = list(latitude=c('lat','latitude'),
                              longitude=c('lon','longitude'),
                              member=c('ensemble')), 
              member = indices(1:hcst.nmember),
              return_vars = list(latitude = 'dat',
                                 longitude = 'dat',
                                 time = 'file_date'),
              split_multiselected_dims = TRUE,
              retrieve = T)

  hcst.NA_files <- c(attributes(hcst)$NotFoundFiles)
  hcst.NA_files <- hcst.NA_files[!is.na(hcst.NA_files)]
  try(hcst.NA_files <- hcst.NA_files[order(hcst.NA_files)])

  dates <- attr(hcst, 'Variables')$common$time
  dates_file <- sapply(dates, format, '%Y%m%d')
  dates_file <- format(as.Date(dates_file, '%Y%m%d'), "%Y%m")
  dim(dates_file) <- dim(Subset(hcst, 
                                along=c('dat','var',
                                'latitude', 'longitude', 'member'), 
                                list(1,1,1,1,1), drop="selected")) 

  obs <- Start(dat = obs.path,		  
               var = variable,
  	           file_date = dates_file,
               latitude = values(list(lats.min, lats.max)),
               latitude_reorder = Sort(decreasing = TRUE),
               longitude = values(list(lons.min, lons.max)),
               longitude_reorder = CircularSort(0, 361),
               synonims = list(latitude=c('lat','latitude'),
                               longitude=c('lon','longitude')), 
               transform = CDORemapper,
		       transform_params = list(
		       grid = paste0(
		          "/esarchive/exp/ecmwf/system5c3s/",fcst.freq,
		          "/",variable,"_",freq.hcst,
		          "/",variable,"_","201805","01.nc"
		       ),
		       method = 'con',
		       crop = c(lons.min,lons.max,lats.min,lats.max)), 
		       transform_vars = c('latitude', 'longitude'),
  	           return_vars = list(latitude = 'dat',
                                  longitude = 'dat',
                                  time = 'file_date'),
  	           split_multiselected_dims = TRUE,
  	           retrieve = TRUE)

  dates_file <- paste0(dates_file, '01')
  dim(dates_file) <- dim(Subset(hcst,
                                along=c('dat','var',
                                'latitude', 'longitude', 'member'),
                                list(1,1,1,1,1), drop="selected"))

  file_dates <- paste0(file_dates, '01')
  dim(file_dates) <- dim(Subset(hcst,
                                along=c('dat','var',
                                'latitude', 'longitude', 'member', 'time'),
                                list(1,1,1,1,1,1), drop="selected"))



  obs.NA_dates.ind <- Apply(obs, 
                            fun=(function(x){ all(is.na(x))}), 
                            target_dims=c('time', 'latitude', 'longitude'))[[1]]
  obs.NA_dates <- dates_file[obs.NA_dates.ind]
  obs.NA_dates <- obs.NA_dates[order(obs.NA_dates)]
  obs.NA_files <- paste0(obs.dir,fcst.freq,"/",variable,"_",
                         freq.obs,"obs.grid","/",variable,"_",obs.NA_dates,".nc")

  if (any(is.na(hcst))){
    print(" ERROR: MISSING HCST VALUES FOUND DURING LOADING # " )
    print(" ################################################# " )
    print(" ######           MISSING FILES               #### " )
    print(" ################################################# " )
    print("hcst files:")
    print(hcst.NA_files)
    print(" ################################################# " )
    print(" ################################################# " )
    quit(status=1)
  }

  if (any(is.na(obs)) && !identical(obs.NA_dates,character(0))){
    print(" ERROR: MISSING OBS VALUES FOUND DURING  LOADING # " )
    print(" ################################################# " )
    print(" ######           MISSING FILES               #### " )
    print(" ################################################# " )
    print("obs files:")
    print(obs.NA_files)
    print(" ################################################# " )
    print(" ################################################# " )
    quit(status=1)
  }

  print("######### DATA LOADING COMPLETED SUCCESFULLY ##############")

  default_dims <- c(dat=1, var=1, sweek = 1, 
                    sday = 1, syear = 1, time=1, 
                    latitude=1, longitude = 1, member = 1)

  default_dims[names(dim(obs))] <- dim(obs)
  dim(obs) <- default_dims

  lon <- attr(obs, 'Variables')$dat1$longitude
  lat <- attr(obs, 'Variables')$dat1$latitude
  hcst.times <- attr(hcst, 'Variables')$common$time
  hcst.times <- sort(unique(sapply(as.character(hcst.times),
                     substr, 1, 10)))

  #obs<-Subset(obs,c('dat','var'),list(1,1),drop='selected')
  #hcst<-Subset(hcst,c('dat','var'),list(1,1),drop='selected')
  #if (stream == "fcst"){ 
  #  fcst<-Subset(fcst,c('dat','var'),list(1,1),drop='selected')
  #}

  #filters negative values in accum vars
  if (accum){
     obs[obs < 0 ] <- 0
     hcst[hcst < 0 ] <- 0
     if (stream == "fcst"){ fcst[fcst < 0 ] <- 0 }
  }

  sdates.hcst <- file_dates
  sdates.fcst <- file_dates.fcst
  leadtimes.hcst <- dates_file

