p_load(rJava)
options(java.parameters="-Xmx5000m") # must be set initially
p_load(bartMachine)

bart_imp <- function(x, y, ...) {
  
  set_bart_machine_num_cores(1)
  
  bart_fit <- build_bart_machine(x, y, verbose = FALSE)
  pk1 <- var_selection_by_permute(bart_fit, plot=FALSE)
  
  oimp  <- pk1$var_true_props_avg[order(names(pk1$var_true_props_avg))]

  tmp_imp <- rep(0, NCOL(x))
  names(tmp_imp) <- colnames(x)
  for (xv in names(oimp)) {
    if (grepl('_', xv)) {
      tx <- strsplit(xv, '_')[[1]][1]
    } else {
      tx <- xv
    }
    tmp_imp[tx] = oimp[xv] + tmp_imp[tx]
  }
  oimp <- tmp_imp

  errRank = imp_measure(oimp)
  imp = imp_scale(oimp)

  return(list(errRank = errRank, 
              imp = imp_scale(imp),
              oimp = oimp))
  
}