#humann_analysis <- function(humann_unstratified, metadata_file, output_dir, meta_col_selected) {
library(microeco)
library(file2meco)
library(ggplot2)
library(aplot)
library(magrittr)
library(paletteer)
library(patchwork)
library(gridExtra)
library(igraph)
library(meconetcomp)
library(ggnested)
library(Cairo)
library(cowplot)
library(grid)
# library(extrafont)
# font_import()
# loadfonts(device = "win")
args <- commandArgs(trailingOnly = TRUE)

if (length(args) == 0) {
    cat("No arguments provided. Exiting script.\n -i : Input is CARD csv result generated by add_rgi_togenePA.py, -m metadata CSV file, -out output heatmap file, -meta_cols : metadata column numbers like 2,3,4\n")
  quit(save = "no", status = 1)
}
arg_list <- list()
for (i in seq(1, length(args), 2)) {
  arg_list[[args[i]]] <- args[i + 1]
}

#######################################################################
############# custom script is written based on humann2meco ###########
process_feature_table <- function(feature_table, db = c("MetaCyc", "KEGG", "gene")[1],
                                   sample_table = NULL, match_table = NULL, ...) {
  db <- match.arg(db, c("MetaCyc", "KEGG", "gene"))
  abund_raw <- read.delim(feature_table, check.names = FALSE, row.names = 1, stringsAsFactors = FALSE)
  abund_rawname <- rownames(abund_raw)
  abund_new <- abund_raw
  
  if (db == "MetaCyc") {
    data("MetaCyc_pathway_map", envir = environment())
    MetaCyc_pathway_map_use <- cbind.data.frame(rowname = rownames(MetaCyc_pathway_map), 
                                                MetaCyc_pathway_map, stringsAsFactors = FALSE)
    
    pathway_table <- data.frame(pathway = gsub(":.*$", "", abund_rawname))
    pathway_table <- merge(pathway_table, MetaCyc_pathway_map_use, by.x = "pathway", by.y = "rowname", all.x = TRUE)
    #rownames(abund_new) <- pathway_table$pathway
    
    tax_table <- data.frame(row.names = rownames(abund_raw))
    tax_table$Superclass1 <- "unclassified"
    tax_table$Superclass2 <- "unclassified"
    tax_table$pathway <- "unclassified"
    pathway_ids <- sapply(rownames(abund_raw), function(x) strsplit(x, ":")[[1]][1])

    for (pathway_full_id in rownames(tax_table)) {

      pathway_id <- strsplit(pathway_full_id, ":")[[1]][1]
      pathway_info <- MetaCyc_pathway_map_use[MetaCyc_pathway_map_use$rowname == pathway_id, ]
      if (nrow(pathway_info) > 0) {
        tax_table[pathway_full_id, "Superclass1"] <- pathway_info$Superclass1
        tax_table[pathway_full_id, "Superclass2"] <- pathway_info$Superclass2
        tax_table[pathway_full_id, "pathway"] <- pathway_info$pathway
      }}

    # Optional: Check and integrate match table and sample table if provided
    if (!is.null(match_table)) {
      abund_new <- file2meco:::check_match_table(match_table = match_table, abund_new = abund_new)
    }
    if (!is.null(sample_table)) {
      sample_table <- file2meco:::check_sample_table(sample_table = sample_table)
    }
    
    # Create the microtable object to be used in analysis
    dataset <- microtable$new(otu_table = abund_new, sample_table = sample_table,  
                              tax_table = tax_table,...)
    return(dataset)
  }}
#}

############# custom script is written based on humann2meco ###########
#######################################################################
# call humann object with metadata to create  microtable object 
humann_unstratified <- arg_list[["-i"]]
metadata_file <- arg_list[["-m"]]
output_dir <- arg_list[["-out"]]
meta_col_selected <- arg_list[["-mc"]]
meta_col_selected <- as.integer(meta_col_selected)
sample_col_selected <- as.integer(arg_list[["-sc"]])

meta_cols <- NULL


sample_modified <- read.csv(metadata_file,header=TRUE)
rownames(sample_modified) <- sample_modified[,sample_col_selected]
#rownames(sample_modified) <- sample_modified[,1]
head(sample_modified)
## ## ## ## ## ## ## ## 

humann_obj <- process_feature_table(humann_unstratified, "MetaCyc", sample_modified)
humann_obj$tidy_dataset()

theme_set(theme_bw())

humann_obj$cal_abund(select_cols = c("Superclass1","Superclass2", "pathway"), 
                       rel = TRUE)
humann_obj$cal_alphadiv(measures =c("Shannon","Simpson") ,PD = FALSE)
# alpha_diversity.csv is saved into directory 
humann_obj$save_alphadiv(dirpath = output_dir)

# set colname to be used in downstream analysis 
group_col_name <- colnames(humann_obj$sample_table)[as.integer(meta_col_selected)]


humann_obj$taxa_abund$Superclass1 %<>% .[!grepl("unclass", rownames(.)), ]
humann_obj$taxa_abund$Superclass2 %<>% .[!grepl("unclass", rownames(.)), ]
humann_obj$taxa_abund$pathway %<>% .[!grepl("unclass", rownames(.)), ]
#humann_obj$taxa_abund      
humann_ta <- trans_abund$new(humann_obj, taxrank = "pathway",high_level="Superclass2" ,
                         ntaxa = 15, delete_taxonomy_lineage = T,
                         use_percentage = FALSE)
humann_ta$ylabname <- "Copies Per Million (CPM)"

#ggnested = T
humann_group_barplot<- humann_ta$plot_bar(facet =group_col_name, high_level_add_other = T,
                   clustering = TRUE, bar_type  = "notfull",
                   xtext_keep = FALSE) +
  guides(fill = guide_legend(ncol = 1, label.theme = element_text(size = 6),
                             title = "pathway"))+
  theme(legend.key.size = unit(0.3, "cm"),
         
        strip.text = element_text(size = 7),
        axis.title.y = element_text(size = 7),
        axis.text.y = element_text(size = 6),
        legend.title = element_text(size = 7),
        legend.text = element_text(size = 6)) + 
  scale_y_continuous(limits = c(0, NA))

CairoPDF(file = file.path(output_dir, "humann_group_barplot.pdf"), 
         width = 100 / 25.4*2, 
         height = 120  / 25.4
        )
print(humann_group_barplot)
dev.off()
message("Function plot bar of HUMAnN3 is saved into humann_group_barplot.pdf")                                                

alpha_meco <- trans_alpha$new(dataset = humann_obj, 
                              group = group_col_name)
alpha_meco$cal_diff(method = "KW")
# save group difference 
write.csv(alpha_meco$res_diff, file.path(output_dir, "humann_alpha_group_diff_stat.csv"),
            row.names = FALSE)
message("Alpha diversity of function difference between group is saved into humann_alpha_group_diff_stat.csv")                                                


abdiv_fig1 <- alpha_meco$plot_alpha(color_values = paletteer_d("ggsci::default_aaas"), 
                                    point_size = 2.0, point_alpha = 0.7 ,
                                    add_sig_text_size = 3)
abdiv_fig1 <- abdiv_fig1+ theme(axis.text.x = element_text(size = 6),
                                 axis.text.y = element_text(size = 6),
                                 axis.title.y =  element_text(size = 7)) +
  ylab("Shannon diversity")  +  
  theme(plot.margin = margin(1.5, 0.3, 0.3, 0.3, "cm")) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.15)))


  #ggsave(file.path(output_dir, "humann_alpha_diversity.pdf"), 
  #        abdiv_fig1, width = 2, height= 3)

# save beta and jaccard
humann_obj$cal_betadiv(unifrac = FALSE)
humann_obj$save_betadiv(dirpath = output_dir)
message("Beta diversity of function csv files were saved")                                                

  beta_meco <- trans_beta$new(dataset = humann_obj, 
                              group = group_col_name,
                              measure="bray")
  sample_counts <- table(humann_obj$sample_table[[group_col_name]])
  
  has_enough_samples <- any(sample_counts >= 2)
  

  bcd_plot <- ggplot() + 
    annotate("text", x = 0.5, y = 0.5, label = "Not enough samples per group\nfor within-group distance analysis", 
             size = 3, hjust = 0.5) +
    theme_void() +
    theme(plot.margin = margin(0.5, 0.3, 0.3, 0.3, "cm"))
  
  # 빈 beta_fig_grob 및 legend 객체 초기화
  beta_fig_grob <- ggplot() + 
    annotate("text", x = 0.5, y = 0.5, label = "Ordination not available\nwith limited samples", 
             size = 4, hjust = 0.5) +
    theme_void()
  
  legend <- ggplot() + theme_void()


  if (has_enough_samples) {
    tryCatch({


  beta_meco$cal_group_distance(within_group = TRUE)
  #beta_meco$res_group_distance
  write.csv(beta_meco$res_group_distance,
            file.path(output_dir, "humann_beta_group_distance_raw.csv"))
    message("Group distance difference of beta diversity function was saved : humann_beta_group_distance_diff_stat.csv")


#message("(Intra) Beta diversity of function csv file was saved : humann_beta_group_distance_raw.csv")                                                

  beta_meco$cal_group_distance_diff(method = "wilcox")
  write.csv(beta_meco$res_group_distance_diff,
            file.path(output_dir, "humann_beta_group_distance_diff_stat.csv"))
message("Group distance difference of beta diversity function was saved : humann_beta_group_distance_diff_stat.csv")                                                
  
  beta_meco$cal_ordination(ordination = "PCoA")
  
bcd_plot<- beta_meco$plot_group_distance(boxplot_add = "mean",
                               color_values = paletteer_d("ggsci::default_aaas"),
                               add_sig_text_size = 3) + 
  theme(plot.margin = margin(0.5, 0.3, 0.3, 0.3, "cm")) 
bcd_plot <-  bcd_plot+ theme(axis.text.x = element_text(size = 6),
                             axis.text.y = element_text(size = 6),
                             axis.title.y =  element_text(size = 7)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.15)))
    }, error = function(e) {
      message("Error in group distance calculations: ", e$message)

    })
  } else {
    message("Skipping within-group distance calculations as there are not enough samples per group (need at least 2)")
  }
  message("beta diversity group differece figure step executed")


 
  tryCatch({

  beta_meco$cal_manova(manova_all = TRUE,p_adjust_method = "fdr")
  write.csv(beta_meco$res_manova,
            file.path(output_dir, "beta_group_perMANOVA_stat.csv"))

if (nrow(beta_meco$res_manova) > 0) {
  R2_value <- beta_meco$res_manova$R2[1]
  Pseudo_F <- beta_meco$res_manova$F[1]
  PrF_value <- beta_meco$res_manova$'Pr(>F)'[1]
  R2_text <- paste("R² =", format(R2_value, digits = 4))
  Pseudo_F_text <- paste("Pseudo-F statistic =", format(Pseudo_F,digits=4))
  PrF_text <- paste("Pr(>F) =", format(PrF_value, digits = 4))
    } else {
      R2_text <- "R² = NA"
      Pseudo_F_text <- "Pseudo-F statistic = NA"
      PrF_text <- "Pr(>F) = NA"
    }


  beta_meco$cal_ordination(ordination ="PCoA")
    
  message("PERMANOVA statistical analysis done ")

  beta_p1 <- beta_meco$plot_ordination(plot_color = group_col_name,
                                      point_size = 1.0,point_alpha = 0.7, 
                                      plot_shape = group_col_name,
                                      plot_type = c("point", "ellipse"),
                                      color_values = paletteer_d("ggsci::default_aaas"))
beta_p1 <- beta_p1 + 
  annotate("text", x = Inf, y = Inf, label = R2_text, hjust = 1.1, vjust = 5.5, size =  1.7) +
  annotate("text", x = Inf, y = Inf, label = Pseudo_F_text, hjust = 1.1, vjust = 3.5, size =  1.7) +
  annotate("text", x = Inf, y = Inf, label = PrF_text, hjust = 1.1, vjust = 1.5, size =  1.7) +
   theme(legend.position = "none", 
        axis.text.x = element_text(size = 6),
        axis.text.y = element_text(size = 6),
        axis.title.y =  element_text(size = 7),
        axis.title.x =  element_text(size = 7)) 


  if (!is.null(beta_meco$res_ordination$scores) && ncol(beta_meco$res_ordination$scores) >= 2) {



pcoa_axis <-  beta_meco$res_ordination$scores
pcoa_te1 <- trans_env$new(dataset = humann_obj, add_data = pcoa_axis[, 1:2])
pcoa_te1$cal_diff(group =  group_col_name,
                  method = "KW")
beta_p2 <- pcoa_te1$plot_diff(measure = "PCo1", add_sig = T,
                              point_size = 2,point_alpha = 0.7,
                              color_values = paletteer_d("ggsci::default_aaas")) + 
  theme_bw() + coord_flip() + theme(legend.position = "none", 
                                    axis.title.x = element_blank(), 
                                    axis.title.y = element_blank(),                                    
                                    axis.text.x  = element_blank(), 
                                    axis.text.y = element_blank(),
                                    axis.ticks.y = element_blank())
  message("beta_p2 done ")

beta_p3 <- pcoa_te1$plot_diff(measure = "PCo2", add_sig = T,
                              color_values = paletteer_d("ggsci::default_aaas"),
                              point_size = 1.0,point_alpha = 0.7) +
  theme_bw() + theme(legend.position = "none", 
                     axis.title.x = element_blank(),
                     axis.title.y = element_blank(),
                     axis.text.x = element_blank(), 
                     axis.text.y  = element_blank(), 
                     axis.ticks.x = element_blank())
beta_fig <- beta_p1 %>% insert_top(beta_p2, height = 0.2) %>% 
  insert_right(beta_p3, width = 0.2) 
message("beta_p3 done ")

legend <- cowplot::get_legend(beta_p1 + theme(legend.position = "bottom",
                                              strip.text = element_text(size = 7),
                                              legend.title = element_text(size = 7),
                                              legend.text = element_text(size = 6),
                                              legend.key.size = unit(0.3, "cm")))

beta_fig_grob <- grid::grid.draw(beta_fig)
beta_fig_grob <- grid::grid.grab()
message("beta fig done ")
    } else {
      message("Not enough ordination components for PCo1/PCo2 plots")
    }

  }, error = function(e) {
    message("Error in MANOVA or ordination: ", e$message)
    # 에러 발생 시 빈 플롯 생성

  })

layout <- rbind(c(1, 2),
                c(3),
                c(3),
                c(4))
abdiv_fig1 <- abdiv_fig1 + theme(plot.margin = margin(t = 1, r = 0.1, b = 0.1, l = 0.1, unit = "cm"))
bcd_plot <- bcd_plot + theme(plot.margin = margin(t = 1, r = 0.1, b = 0.1, l = 0.1, unit = "cm"))
combined_diversity <- gridExtra::grid.arrange(abdiv_fig1,bcd_plot, beta_fig_grob,
                                              legend,
                                              layout_matrix = layout,
                                              heights = unit(c(1.2, 1.2, 2, 0.1), "null"),
                                              widths = unit(c(1, 1),"null"))

library(Cairo)
CairoPDF(file = file.path(output_dir, "humann_alpha_beta_diversity.pdf"), 
         width = 100 / 25.4, 
         height = 130  / 25.4
)
grid.draw(combined_diversity)
dev.off()
message("Alpha and beta diversity figure was saved.")            

# differential analysis 
lefse_plot <- NULL
glefse_3 <- NULL


tryCatch({

humann_obj$filter_taxa(rel_abund = 0.00001, freq=2) 
lefse_t1<- trans_diff$new(humann_obj, method = "lefse", group = group_col_name,
                          taxa_level = "pathway", alpha = 0.01,
                          p_adjust_method = "none")

  if (nrow(lefse_t1$res_diff) > 0 && any(!is.na(lefse_t1$res_diff$LDA))) {

glefse_1 <- lefse_t1$plot_diff_bar(use_number = 1:20,
  color_values = paletteer_d("ggsci::default_aaas"))

glefse_1 <- glefse_1 +  theme(legend.position = "none", 
        axis.text.y = element_text(size = 7),
        axis.text.x =element_text(size = 6) ,
        axis.title.x = element_text(size = 7))  


  glefse_2 <- lefse_t1$plot_diff_abund(use_number = 1:20,
    color_values = paletteer_d("ggsci::default_aaas"), 
              add_sig = TRUE,select_taxa = lefse_t1$plot_diff_bar_taxa)
glefse_2 <- glefse_2 +  theme(axis.text.y = element_blank(), 
                            axis.ticks.y = element_blank(),
                            axis.text.x =element_text(size = 6) ,
                            axis.title.x = element_text(size = 7),
                            legend.key.size = unit(0.3, "cm"),
                            legend.title = element_text(size = 7),
                            legend.text = element_text(size = 6.5),
                            strip.text = element_text(size = 6)) + 
  geom_vline(xintercept = -Inf, color = "gray", size = 0.5) + 
  scale_y_continuous(expand = expansion(mult = c(0, 0.15)))

  glefse_1 + glefse_2

  lefse_plot <- gridExtra::grid.arrange(glefse_1,glefse_2, ncol = 2 , nrow = 1 , widths = c(2,1.3)) 
  
CairoPDF(file = file.path(output_dir, "humann_lefse_result.pdf"), 
         width = 20/2.54, 
         height = (0.77*length(lefse_t1$plot_diff_bar_taxa)+1)/2.54
)
grid.draw(lefse_plot)
dev.off()
  
  message("Diefferential function analysis by lefse figure was saved. : humann_lefse_result.pdf")   


#hetamap generation
DA_function_name <- lefse_t1$plot_diff_bar_taxa
tt <- trans_abund$new(humann_obj,taxrank = "pathway" ,input_taxaname =DA_function_name )
glefse_3 <- tt$plot_heatmap(facet = group_col_name, xtext_keep = FALSE,
                            withmargin = FALSE,plot_colorscale = "log10",
                            min_abundance = 0.0001,,plot_text_size = 6,
                  ytext_size = 6,strip_text = 7) +
  ggtitle("DA function in relative abundance(%)") + 
    theme(title = element_text(size=7.5),
          legend.title = element_text(size=7),
          legend.text  = element_text(size=7),
          legend.key.height = unit(0.2, 'inches'))
  CairoPDF(file = file.path(output_dir, "humann_lefse_heatmap.pdf"),
           width = 20/2.54, 
           height = (0.35*length(lefse_t1$plot_diff_bar_taxa)+2)/2.54
  )
  grid.draw(glefse_3)
  dev.off()

    message("Differential taxa analysis heatmap figure was saved. : humann_lefse_heatmap.pdf")
    
    # 메타데이터와 차등 풍부 기능 간의 상관관계 분석
    message("Aligning lefse plot and relative abundance plot.")

      te1 <- trans_env$new(humann_obj, env_cols =c(1:ncol(humann_obj$sample_table)))
  sum(sapply(te1$data_env, is.numeric))


    DA_function_name <- lefse_t1$plot_diff_bar_taxa
    full_func <- lefse_t1$res_diff$Taxa
    matched_full_func <- vector("character", length(DA_function_name))
    
    for (i in seq_along(DA_function_name)) {
      escaped_function_name <- gsub("\\(", "\\\\(", DA_function_name[i])
      escaped_function_name <- gsub("\\)", "\\\\)", escaped_function_name)
      
      function_pattern <- paste0(".*", escaped_function_name, "$")
      matched_index <- grep(function_pattern, full_func, perl = TRUE)
      matched_full_func[i] <- ifelse(length(matched_index) > 0, full_func[matched_index], NA)
    }
    
    te1$cal_cor(by_group = group_col_name, use_data = "other", 
              p_adjust_method = "fdr", other_taxa = matched_full_func)
    
    message("Correlation between Numerical metadata variable and differentially abundant taxa.")
    
    ttt <- te1$plot_cor(xtext_size = 6) + 
      theme(plot.margin = margin(b = 0.1, l = 1.5, unit = "cm"),
            axis.text.y = element_text(size=6),
            strip.text = element_text(size=7),
            legend.title = element_text(size=7),
            legend.text = element_text(size=6))
    
    min_height <- 5  
    min_width <- 6   


    CairoPDF(file = file.path(output_dir, "humann_DAfunction_meta_correlation.pdf"),
             height = (max(min_height,(length(unique(te1$res_cor$Taxa))*0.35+3)/2.54)), 
             width = (max(min_width,(length(unique(te1$res_cor$Env))*
                      length(unique(te1$res_cor$Type))*0.35 +
                      (length(unique(te1$res_cor$Type))-1)*0.35 +
                      10)/2.54)))
    grid.draw(ttt)
    dev.off()
    
    message("DA taxa and metadata correlation was saved: humann_DAfunction_meta_correlation")
  } else {
    message("No significant features found in LEfSe analysis. Skipping LEfSe plots.")
    # 유의한 특징이 없을 때 기본 메시지가 있는 플롯 생성
    empty_plot <- ggplot() + 
      annotate("text", x = 0.5, y = 0.5, label = "No significant differential functions found", 
               size = 4, hjust = 0.5) +
      theme_void()
    
    CairoPDF(file = file.path(output_dir, "humann_lefse_result.pdf"), 
             width = 8, height = 4)
    print(empty_plot)
    dev.off()
    
    message("Empty LEfSe result was saved.")
  }
}, error = function(e) {
  message("Error in differential analysis by lefse: ", e$message)
  # 오류 발생 시 기본 메시지가 있는 플롯 생성
  empty_plot <- ggplot() + 
    annotate("text", x = 0.5, y = 0.5, label = paste("LEfSe analysis error:", e$message), 
             size = 4, hjust = 0.5) +
    theme_void()
  
  CairoPDF(file = file.path(output_dir, "humann_lefse_result.pdf"), 
           width = 8, height = 4)
  print(empty_plot)
  dev.off()
})

message("Calculating numerical categories correlation.")

tryCatch({



  te1 <- trans_env$new(humann_obj, env_cols =c(1:ncol(humann_obj$sample_table)))
  sum(sapply(te1$data_env, is.numeric))

  numerical_metadata_stats <- te1$cal_autocor(group_col_name,
    color_values = paletteer_d("ggsci::default_aaas")) +
  theme(strip.text = element_text(size = 7),
        axis.text.x = element_text(size = 6),
        axis.text.y = element_text(size = 6),
        text = element_text(size = 6))

CairoPDF(file = file.path(output_dir, "humann_metadata_autocorrelation.pdf"),
         height = (sum(sapply(te1$data_env, is.numeric))+1)*4/2.54, 
         width = (sum(sapply(te1$data_env, is.numeric))+1)*4/2.54
)
grid.draw(numerical_metadata_stats)
dev.off()

message("Calcluating numerical cateogries correlation info was saved.")    
}, error = function(e) {
  message("Error in aligning LEfSe plot and relative abundance plot: ", e$message)
})

# tryCatch({

#   message("Aligning lefse plot and relative abundance plot .")    
#   DA_function_name <- lefse_t1$plot_diff_bar_taxa
#   full_func <- lefse_t1$res_diff$Taxa
#   matched_full_func <- vector("character", length(DA_function_name))

#   for (i in seq_along(DA_function_name)) {
#     escaped_function_name <- gsub("\\(", "\\\\(", DA_function_name[i])
#   escaped_function_name <- gsub("\\)", "\\\\)", escaped_function_name)
  
#   function_pattern <- paste0(".*", escaped_function_name, "$")  # Create the pattern
#   matched_index <- grep(function_pattern, full_func, perl = TRUE)      # Find the index of the match
#   matched_full_func[i] <- ifelse(length(matched_index) > 0, full_func[matched_index], NA)  # Store the matched full taxonomy
# }
#   te1$cal_cor(by_group = group_col_name, use_data = "other", 
#             p_adjust_method = "fdr", other_taxa = matched_full_func)
#     message("Correlation betwwen Numerical metadata variable and differentially abundant taxa.")   

# ttt<-te1$plot_cor( xtext_size = 6) + 
#   theme(plot.margin = margin(b = 0.1, l = 1.5, unit = "cm"),
#         axis.text.y = element_text(size=6),
#         strip.text = element_text(size=7),
#         legend.title = element_text(size=7),
#         legend.text = element_text(size=6))

# CairoPDF(file = file.path(output_dir, "humann_DAfunction_meta_correlation.pdf"),
#          height = (length(unique(te1$res_cor$Taxa))*0.35+3)/2.54, 
#          width = (length(unique(te1$res_cor$Env))*
#                     length(unique(te1$res_cor$Type))*0.35 +
#                     (length(unique(te1$res_cor$Type))-1)*0.35 +
#                     10)/2.54
# )
# grid.draw(ttt)
# dev.off()

#   message("DA taxa and metadata correlataion was saved  : humann_DAfunction_meta_correlation")

# }, error = function(e) {
#   message("Error in aligning LEfSe plot and relative abundance plot: ", e$message)
# })

#humann_analysis(humann_unstratified, metadata_file, output_dir, metadata_col_index)
