# This is a wrapper main function that will process the fRMI data
# Author: Lukasz Piszczek
# Email: lukasz.piszczek@imp.ac.at

process_fMRI_data <- function(iteration = 0, config.file = './R/config_selected.R'){
  tryCatch({
    
    # Initilialize ----------------------------------------------------------------------------------------------------
    
    # Load libraries
    suppressWarnings(library(futile.logger))
    suppressWarnings(library(R.matlab))
    suppressWarnings(library(psych))
    suppressWarnings(library(multtest))
    suppressWarnings(library(Hmisc))
    suppressWarnings(library(pheatmap))
    suppressWarnings(library(ggnetwork))
    suppressWarnings(library(network))
    suppressWarnings(library(sna))
    suppressWarnings(library(igraph))
    suppressWarnings(library(intergraph))
    suppressWarnings(library(scales))
    suppressWarnings(library(RColorBrewer))
    suppressWarnings(library(broom))
    suppressWarnings(library(tidyverse))
    suppressWarnings(library(furrr))
    
    plan(multiprocess) #multiprocess
    
    # Load config file
    # Load configuration file (folder location, data filtering, statistics settings, plot variables, etc).
    source(config.file)
    source('./R/data_functions.R')
    source('./R/plot_functions.R')
    source('./R/process_inputs_functions.R')
    source('./R/grouped_data_functions.R')
    source('./R/HvsL_data_functions.R')
    source('./R/interaction_data_functions.R')
    source('./R/make_paper_figures_functions.R')
    
    # Set up logger
    flog.logger(name = log.name, threshold = threshold, 
                appender = appender.tee(paste0(output.folder, log.name, ".log")))
    flog.threshold(threshold, name = log.name)
    
    flog.info(paste0("Initializing: ", format(Sys.Date(), "%d %B, %Y")), name = log.name)
    
    flog.info(paste0("starting iteration: ", iteration), name = log.name)
    
    # if iteration > 0 add iterator to file names 
    if (iteration > 0) {
      flog.info("Renaming files", name = log.name)
      for (n in c("PI_single.data","PI_grouped_data",
                  "GD_network", "GD_heatmap", "GD_delta_heatmap", 
                  "HvsL_heatmap", "HvsL_mean_FisherZ_box", "HvsL_mean_Regionwise_tTest", 
                  "HvsL_mean_Regionwise_KS", "HvsL_meanDelta_Regionwise_oneSample",
                  "Interaction_heatmap")) {
        v <- get(n)
        v = paste(iteration, v, sep = "_")
        assign(n, v)
      }
      v <- NULL
    }
    
    # filter color list --------------------------------------------------------------------------------------------------
    flog.info("Processing brain labels", name = log.name)
    Labels.data <- filter_heatmap_colors(Labels.data.file, remove.areas)
    Heatmap.brains.sorted <- process_heatmap_colors(Labels.data, Heatmap.Level.color)
    
    # Process Inputs --------------------------------------------------------------------------------------------------
    flog.info("Processing inputs start", name = log.name)
    # 1) process_correlations processing single files (with option to permute), returning data frame
    Data.single <- process_inputs_raw(raw.data.folder, 
                                    Treatments.groups, Impulsivity.groups, 
                                    Labels.data, Matlab.labels.file, permute = permute, remove.areas)
    
    # 2) One-sample t-test running one sample t-test on each edge and returning grouped data frame
    Data.grouped <- process_inputs_onesample(Data.single, PI_mu.set, PI_TSBH, PI_varEqual)
    
    # 3) saving both data frames to file
    process_inputs_savefile(Data.single, Data.grouped, output.folder, PI_single.data, PI_grouped_data)
    
    flog.info("Processing inputs complete", name = log.name)
    
    # Grouped data analysis --------------------------------------------------------------------------------------------
    # Here several function should be made, with optonal to make figures (as specified in config file)
    
    if (GD_make.heatmap) {
      flog.info("Making grouped heatmap plots", name = log.name)
      GD_make_heatmap(Data.grouped, Heatmap.brains.sorted,
                      GD_heatmap, GD_delta_heatmap, GD.p.filter)
      
    }
    
    if (GD_make.network) {
      flog.info("Making grouped network plots", name = log.name)
      GD_make_network_graphs(Data.grouped, Brain.coordinates.file, GD_network)
      
    }
    
    # High vs Low data analysis ----------------------------------------------------------------------------------------
    # Here several function should be made, with optonal to make figures (as specified in config file)
    flog.info("Making High vs Low stats", name = log.name)
    HvsL_edge_stats(Data.single, Data.grouped,
                    Heatmap.brains.sorted,
                    HvsL_p.correction, HvsL_p.alpha, HvsL_heatmap.p.filter, 
                    HvsL_heatmap, 
                    HvsL_edgewise.columns, HvsL_single.hemisphere,
                    HvsL_mean_FisherZ_box, HvsL_mean_Regionwise_tTest,
                    HvsL_mean_Regionwise_KS, HvsL_edgeTtest_make.plots)
    
    flog.info("Making Delta High vs Low stats", name = log.name)
    Delta.OneSample <- HvsL_delta_stats(Data.grouped, HvsL_meanDelta_Regionwise_oneSample)
    
    # Interaction analysis  --------------------------------------------------------------------------------------------
    # Here several function should be made, with optonal to make figures (as specified in config file)
    flog.info("Making edge wise interaction ANOVA", name = log.name)
    Interaction.edge <- Interaction_edgewise(Data.single, Heatmap.brains.sorted, 
                                             Interaction_p.correction, 
                                             Interaction_heatmap.p.filter,
                                             Interaction_heatmap,
                                             Interaction_make.heatmap) 
    
    flog.info("Making nodewise interaction ANOVA", name = log.name)
    Interaction.node <- Interaction_nodewise(Data.single,
                                             Interaction_p.correction, 
                                             Interaction_heatmap.p.filter,
                                             Interaction_heatmap,
                                             Interaction_make.heatmap)

    # Make figures  ----------------------------------------------------------------------------------------------------
    # Here several function should be made, with optonal to make figures (as specified in config file)
    
    if (make.paper.figures) {
      flog.info("Making paper figures", name = log.name)
      
      make_paper_figures(Data.single, Data.grouped, 
                         Interaction.node, Delta.OneSample,
                         Impulsivity.groups, Treatments.groups,
                         Heatmap.brains.sorted,
                         make_paper_p.adjust.method = make_paper_p.adjust.method)
      
    }
    
    flog.info(paste0("Done iteration: ", iteration), name = log.name)
  }, error = function(e) {
    flog.error("ERROR!", name = log.name)
    flog.error(e, name = log.name)
  })
}









