atomicrainfarm <- function(pr, lon, lat, nf, fglob = FALSE,
                           fsmooth = TRUE, weights = 1., 
                           verbose = FALSE, slope = 0, kmin=1) {
  #  library(JuliaCall)
  julia_setup(useRCall = FALSE)
  julia_library("RainFARM")
  
  r <- julia_call("lon_lat_fine", lon, lat, as.integer(nf),
                  need_return = "R")
  lon_f <- r[[1]]
  lat_f <- r[[2]]
  
  if (slope == 0) {
    r <- julia_call("fft3d", pr, need_return = "R")
    fxp <- r[[1]]
    sx <- julia_call("fitslopex", fxp, kmin = as.integer(kmin),
                     need_return = "R")
  } else {
    sx <- slope
  }
  
    rd <- julia_call("rainfarm", pr, sx, as.integer(nf), weights,
                                fglob = fglob, fsmooth = fsmooth,
                                verbose = verbose, need_return = "R")
  
  return(list(lon = lon_f, lat = lat_f, data = rd))   
}

RainFarm <- function(data, nf, fglob = FALSE,
                     fsmooth = TRUE, weights = 1., 
                     verbose = FALSE, slope = 0, kmin=1) {
  
  # test inputs
  
  Apply(data = data, target_dims = list(c('lat', 'lon'), 'lon', 'lat'), 
        fun = atomicrainfarm, nf = nf, fsmooth = fsmooth, weights = weights, 
        verbose = verbose, slope = slope, kmin = kmin)
}

exp <- 1 : (2 * 3 * 12 * 8 * 8)
dim(exp) <- c(dataset = 1, member = 2, sdate = 3, ftime = 12, lat = 8, lon = 8)
lon <- seq(10, 13.5, 0.5)
dim(lon) <- c(lon = length(lon))
lat <- seq(40, 43.5, 0.5)
dim(lat) <- c(lat = length(lat))
datas2d <- list(exp = exp, lon = lon, lat = lat)
str(datas2d)

time_id <- sort(rep(1 : 4, 3))
dim(time_id) <- c(ftime = length(time_id))
result <- Apply(data = list(exp), target_dims = list(c('ftime')), 
                fun = function(x){tapply(x, INDEX = time_id, FUN = mean)})

result <- Apply(data = list(exp, time_id), target_dims = list(c('ftime'), c('ftime')), 
                fun = function(x, y){tapply(x, INDEX = y, FUN = mean)})
str(result$output1)
dim(result$output1)
result$output1[,1,1,1,1,1]

tapply(tmax - tmin, INDEX = date.factor, FUN = mean, na.rm = na.rm)


str(result)
res <- RainFarm(data = datas2d, nf =8)
str(res)
