#!/usr/bin/env Rscript
# This script will be used to perform data analysis and create display items from qBiCo indices.
#Raw qPCR data to qBiCo indices####
{#dependencies####
  # install.packages("xlsx")
  library(xlsx)
  library(plyr)
  library(dplyr)
  library(hash)
  library(zeallot)
  library(gtable)
  library(gridExtra)
  library(grid)
  library(gridtext)
  library(rio)
  library(tidyr)
  library(ggplot2)
  library(fANCOVA)
  library(ggpubr)
  library(naniar)
  library(writexl)
}
#From Excel file values to create a standard curve and obtain the amount of copy numbers and Cq standard deviations.
raw_to_parameters <- function(raw_data, manual_exlusion=FALSE,standards_list) {
  
  #if manual exlusion is TRUE, then ONLY exclude the ones that were manually provided.
  if(isTRUE(manual_exlusion)){
    raw_data$Cq[raw_data$excluded == 1] <- NA
  }
  
  #Create Standards and Samples Cq data frames
  df_Cq_avg <- raw_data  %>% spread(Target, Cq)
  df_Cq_avg <- subset(df_Cq_avg, !grepl('NA',df_Cq_avg$Sample) & !grepl('NTC',df_Cq_avg$Sample))
  df_Cq_avg <- subset(df_Cq_avg, select = -c(Fluor,DNA_input_ng,Elution_volume_ul,excluded))
  
  if ('NA' %in% colnames(df_Cq_avg)){
    colnames1 <- c('Well','Sample','Cq_Converted','Cq_Genomic', 'Cq_Long', 'Cq_IPC','Cq_Short')
    colnames2 <- c('Well','Sample','Cq_Converted','Cq_Genomic','Cq_Long', 'Cq_IPC','Cq_Short','SQ_Converted','SQ_Genomic','SQ_IPC','SQ_Long','SQ_Short')
    fit_IPC_bool <- FALSE
    
  } else {
    colnames1 <- c('Well','Sample','Cq_Converted','Cq_Genomic', 'Cq_IPC','Cq_Long','Cq_Short')
    colnames2 <- c('Well','Sample','Cq_Converted','Cq_Genomic', 'Cq_IPC','Cq_Long','Cq_Short','SQ_Converted','SQ_Genomic','SQ_IPC','SQ_Long','SQ_Short')
    fit_IPC_bool <- TRUE
  }
  
  
  df_Cq_avg <- df_Cq_avg %>% group_by(Well) %>% dplyr::summarize(across(everything(), ~.x[!is.na(.x)][1])) %>% relocate(colnames(df_Cq_avg))
  df_std_Cq_avg <- subset(df_Cq_avg, grepl('Std',df_Cq_avg$Sample))
  df_std_samples <- subset(df_Cq_avg, !grepl('Std',df_Cq_avg$Sample))
  Sample_list <- df_std_samples$Sample
  Well_list <- df_std_samples$Well
  df_std_samples <- round(data.frame(lapply(df_std_samples,as.numeric)),2)
  df_std_samples$Sample <- Sample_list
  df_std_samples$Well <- Well_list
  colnames(df_std_samples) <- colnames1
  
  #Add Copy numbers to Cq data frames
  
  standards_df <- Create_3x_standards_df(standards_list)
  df_std_Cq_avg <- subset(df_std_Cq_avg,!grepl('F',df_std_Cq_avg$Sample) & !grepl('G',df_std_Cq_avg$Sample) & !grepl('H',df_std_Cq_avg$Sample)) #only keep top 5 standards
  
  for (i in c(1,2,3,4,5)){
    standard <- distinct(data.frame(df_std_Cq_avg$Sample))[i,1]
    df_std_Cq_avg$SQ_Converted[df_std_Cq_avg$Sample==standard] <-t(standards_df[c(3),])[i]
    df_std_Cq_avg$SQ_Genomic[df_std_Cq_avg$Sample==standard] <-t(standards_df[c(4),])[i]
    df_std_Cq_avg$SQ_IPC[df_std_Cq_avg$Sample==standard] <-t(standards_df[c(5),])[i]
    df_std_Cq_avg$SQ_Long[df_std_Cq_avg$Sample==standard] <-t(standards_df[c(1),])[i]
    df_std_Cq_avg$SQ_Short[df_std_Cq_avg$Sample==standard] <-t(standards_df[c(2),])[i]
  }
  
  colnames(df_std_Cq_avg) <- colnames2
  Sample_list <- df_std_Cq_avg$Sample
  Well_list <- df_std_Cq_avg$Well
  df_std_Cq_avg <- round(data.frame(lapply(df_std_Cq_avg,as.numeric)),2)
  df_std_Cq_avg$Sample <- Sample_list
  df_std_Cq_avg$Well <- Well_list
  
  #Automatically exlude a well from the standards which is an outlier based on standard deviation.
  #subset only wells with standards
  df_std_Cq <- df_std_Cq_avg
  
  #Create standard curves.
  
  #Average the Cq values per standard, calculate the log10 values and perform linear regression.
  df_std_Cq_avg_Converted <- df_std_Cq %>% group_by(Sample) %>% dplyr::summarise(Avg = mean(head(Cq_Converted), na.rm = TRUE))
  colnames(df_std_Cq_avg_Converted) <- c('Std','Cq_Converted')
  df_std_Cq_avg_Genomic <- df_std_Cq %>% group_by(Sample) %>% dplyr::summarise(Avg = mean(head(Cq_Genomic), na.rm = TRUE))
  colnames(df_std_Cq_avg_Genomic) <- c('Std','Cq_Genomic')
  df_std_Cq_avg_IPC <- df_std_Cq %>% group_by(Sample) %>% dplyr::summarise(Avg = mean(head(Cq_IPC), na.rm = TRUE))
  colnames(df_std_Cq_avg_IPC) <- c('Std','Cq_IPC')
  df_std_Cq_avg_Long <- df_std_Cq %>% group_by(Sample) %>% dplyr::summarise(Avg = mean(head(Cq_Long), na.rm = TRUE))
  colnames(df_std_Cq_avg_Long) <- c('Std','Cq_Long')
  df_std_Cq_avg_Short <- df_std_Cq %>% group_by(Sample) %>% dplyr::summarise(Avg = mean(head(Cq_Short), na.rm = TRUE))
  colnames(df_std_Cq_avg_Short) <- c('Std','Cq_Short')
  df_std_Cq_avg <- merge(merge(merge(merge(df_std_Cq_avg_Converted,df_std_Cq_avg_Genomic),df_std_Cq_avg_IPC),df_std_Cq_avg_Long),df_std_Cq_avg_Short)
  
  amount_of_standards <- 5
  
  new_col <- t(log10(standards_df[rownames(standards_df)[3],][1:amount_of_standards]))
  colnames(new_col) = 'SQ_Converted_log'
  df_std_Cq_avg$SQ_Converted_log <- new_col
  new_col <- t(log10(standards_df[rownames(standards_df)[4],][1:amount_of_standards]))
  colnames(new_col) = 'SQ_Genomic_log'
  df_std_Cq_avg$SQ_Genomic_log <- new_col
  new_col <-t(log10(standards_df[rownames(standards_df)[5],][1:amount_of_standards]))
  colnames(new_col) <- 'SQ_IPC_log'
  df_std_Cq_avg$SQ_IPC_log <- new_col
  new_col <- t(log10(standards_df[rownames(standards_df)[1],][1:amount_of_standards]))
  colnames(new_col) <- 'SQ_Long_log'
  df_std_Cq_avg$SQ_Long_log <- new_col
  new_col <- t(log10(standards_df[rownames(standards_df)[2],][1:amount_of_standards]))
  colnames(new_col) <- 'SQ_Short_log'
  df_std_Cq_avg$SQ_Short_log <- new_col
  
  df_std_Cq$SQ_Converted_log <- log10(df_std_Cq$SQ_Converted)
  df_std_Cq$SQ_Genomic_log <- log10(df_std_Cq$SQ_Genomic)
  df_std_Cq$SQ_IPC_log <- log10(df_std_Cq$SQ_IPC)
  df_std_Cq$SQ_Long_log <- log10(df_std_Cq$SQ_Long)
  df_std_Cq$SQ_Short_log <- log10(df_std_Cq$SQ_Short)
  
  Converted.lm <- lm(Cq_Converted ~ SQ_Converted_log, data = df_std_Cq_avg)
  Genomic.lm <- lm(Cq_Genomic ~ SQ_Genomic_log, data = df_std_Cq_avg)
  if (fit_IPC_bool){
    IPC.lm <- lm(Cq_IPC ~ SQ_IPC_log, data = df_std_Cq_avg)
  }
  Long.lm <- lm(Cq_Short ~ SQ_Long_log, data = df_std_Cq_avg)
  Short.lm <- lm(Cq_Short ~ SQ_Short_log, data = df_std_Cq_avg)
  
  Converted_efficiency <- (-1 + 10^(-1/Converted.lm$coefficients[2]))*100
  Genomic_efficiency <- (-1 + 10^(-1/Genomic.lm$coefficients[2]))*100
  if (fit_IPC_bool){
    IPC_efficiency <- (-1 + 10^(-1/IPC.lm$coefficients[2]))*100}
  Long_efficiency <- (-1 + 10^(-1/Long.lm$coefficients[2]))*100
  Short_efficiency <- (-1 + 10^(-1/Short.lm$coefficients[2]))*100
  
  if (fit_IPC_bool){
    intercepts <- c(Converted.lm$coefficients[1],Genomic.lm$coefficients[1],IPC.lm$coefficients[1],Long.lm$coefficients[1],Short.lm$coefficients[1])
    slopes <- c(Converted.lm$coefficients[2],Genomic.lm$coefficients[2],IPC.lm$coefficients[2],Long.lm$coefficients[2],Short.lm$coefficients[2])
    df_std <- data.frame(c(Converted_efficiency,Genomic_efficiency,IPC_efficiency,Long_efficiency,Short_efficiency),c(summary(Converted.lm)$r.squared,summary(Genomic.lm)$r.squared,summary(IPC.lm)$r.squared,summary(Long.lm)$r.squared,summary(Short.lm)$r.squared),intercepts,slopes)
    colnames(df_std) <- c('PCR efficiency (%)','r_squared','intercept','slope')} else {
      intercepts <- c(Converted.lm$coefficients[1],Genomic.lm$coefficients[1],Long.lm$coefficients[1],Short.lm$coefficients[1])
      slopes <- c(Converted.lm$coefficients[2],Genomic.lm$coefficients[2],Long.lm$coefficients[2],Short.lm$coefficients[2])
      df_std <- data.frame(c(Converted_efficiency,Genomic_efficiency,Long_efficiency,Short_efficiency),c(summary(Converted.lm)$r.squared,summary(Genomic.lm)$r.squared,summary(Long.lm)$r.squared,summary(Short.lm)$r.squared),intercepts,slopes)
      
    }
  if (fit_IPC_bool){
    df_std_samples$SQ_IPC <- 10^((df_std_samples$Cq_IPC - IPC.lm$coefficients[1])/IPC.lm$coefficients[2]) }
  df_std_samples$SQ_Genomic <- 10^((df_std_samples$Cq_Genomic - Genomic.lm$coefficients[1])/Genomic.lm$coefficients[2])
  df_std_samples$SQ_Long <- 10^((df_std_samples$Cq_Long - Long.lm$coefficients[1])/Long.lm$coefficients[2])
  df_std_samples$SQ_Short <- 10^((df_std_samples$Cq_Short - Short.lm$coefficients[1])/Short.lm$coefficients[2])
  df_std_samples$SQ_Converted <- 10^((df_std_samples$Cq_Converted - Converted.lm$coefficients[1])/Converted.lm$coefficients[2])
  
  
  #Calculate the Standard deviation per Sample per fluorophore
  for (fluor in c('Converted','Genomic','Long','Short')){
    Cq_fluor = paste('Cq_',fluor,sep = '')
    Sd_fluor = paste('SD_',fluor,sep = '')
    for (level in levels(factor(df_std_samples$Sample)))
    {
      level_ind = df_std_samples$Sample==level
      standard_dev <- sd(df_std_samples[[Cq_fluor]][df_std_samples$Sample==level][!is.na(df_std_samples[[Cq_fluor]][df_std_samples$Sample==level])])
      df_std_samples[[Sd_fluor]][df_std_samples$Sample==level] <- standard_dev
      #When calculating the standard deviation, only the values that are not NA are taken into account. 
      #This means however that the standard deviation will be NA when there is either only one Cq-value left (because there is no standard deviation when you only have one value) or all Cq-values are NA.
    }}
  return(p=df_std_samples)
}

#Exclude sample wells based on the standard deviation by a range around the mean and a standard deviation threshold.
exclude_on_SD <- function(df_std_samples,sd_threshold,sd_range){
  #First exclude the assay of the samples with a Standard deviation above the set sd_threshold
  for (fluor in c('Converted','Genomic','Long','Short')){
    Cq_fluor = paste('Cq_',fluor,sep = '')
    Sd_fluor = paste('SD_',fluor,sep = '')
    Sq_fluor = paste('SQ_',fluor,sep = '')
    df_std_samples[[Cq_fluor]][df_std_samples[[Sd_fluor]]>sd_threshold] <- NA #set Cq to NA to exclude for qBiCo
    df_std_samples[[Sq_fluor]][df_std_samples[[Sd_fluor]]>sd_threshold] <- NA #set copy number to NA to exclude for qBiCo
  }
  
  #Next exclude the assay of the wells with a Cq value which is outside the range of sd_range (e.g. 2) times the SD from the average.
  for (Sample in levels(factor(df_std_samples$Sample))){
    for (fluor in c('Converted','Genomic','Long','Short')){
      Cq_fluor = paste('Cq_',fluor,sep = '')
      Sd_fluor = paste('SD_',fluor,sep = '')
      Sq_fluor = paste('SQ_',fluor,sep = '')
      Cq_values = df_std_samples[[Cq_fluor]][df_std_samples$Sample==Sample]
      Mean = mean(Cq_values)
      Standard_deviation = df_std_samples[[Sd_fluor]][df_std_samples$Sample==Sample][1]
      
      #Set Cq-values which are above the range to NA
      df_std_samples[[Cq_fluor]][df_std_samples$Sample==Sample][Cq_values > (Mean + sd_range*Standard_deviation)] <- NA
      df_std_samples[[Sq_fluor]][df_std_samples$Sample==Sample][Cq_values > (Mean + sd_range*Standard_deviation)] <- NA
      
      #Set Cq-values which are below the range to NA
      df_std_samples[[Cq_fluor]][df_std_samples$Sample==Sample][Cq_values < (Mean - sd_range*Standard_deviation)] <- NA
      df_std_samples[[Sq_fluor]][df_std_samples$Sample==Sample][Cq_values < (Mean - sd_range*Standard_deviation)] <- NA
      
    }}
  return(p=df_std_samples)
}

#Compute the qBiCo indices from the obtained copy numbers per well.
parameters_to_indices <- function(raw_data, df_std_samples,experiment_label){
  ## CALCULATE QTAP indices from copy numbers  ##
  
  #Add amounts
  labels <- subset(raw_data,select = c(Well,DNA_input_ng))
  Well_list <- labels$Well
  labels <- data.frame(lapply(labels,as.numeric))
  labels$Well <- Well_list
  df_std_samples$DNA_input_ng <- with(labels, DNA_input_ng[match(df_std_samples$Well, labels$Well)])
  #Add volumes
  labels <- subset(raw_data,select = c(Well, Elution_volume_ul))
  Well_list <- labels$Well
  labels <- data.frame(lapply(labels,as.numeric))
  labels$Well <- Well_list
  df_std_samples$Elution_volume_ul <- with(labels, Elution_volume_ul[match(df_std_samples$Well, labels$Well)])
  
  #Average the copy numbers for duplicate or triplicate wells.
  #df_std_samples <- data.frame(df_std_samples %>% group_by(Sample) %>% summarise(mean(SQ_IPC),mean(SQ_Genomic),mean(SQ_Long),mean(SQ_Short),mean(SQ_Converted),mean(DNA_input_ng), mean(Elution_volume_ul)))
  #colnames(df_std_samples) <- c('Sample', 'SQ_IPC','SQ_Genomic','SQ_Long','SQ_Short','SQ_Converted','DNA_input_ng','Elution_volume_ul')
  #Short: Short
  #Long: Long
  #Converted: Converted
  #Genomic: Genomic
  #IPC: Genomic
  
  #Calculate conversion efficiency: Converted/(Converted+Genomic) --> Converted*100/(Converted+Genomic/2)
  
  df_std_samples$Conversion_efficiency <- df_std_samples$SQ_Converted *100 / (df_std_samples$SQ_Converted + df_std_samples$SQ_Genomic/2) #divide the amount of genomic copies by two as the assay targets both strands of the genomic target, but only 1 of the others.
  
  #Calculate recovery: Short / input --> Short / input
  Avogadro = 6.022E+23
  #print('check the size')
  genome_length = 3200000000 #bp
  df_std_samples$DNA_conc <- ((df_std_samples$SQ_Short) * genome_length * 10^9 * 617.96 ) / Avogadro #average mass of 1 bp dsDNA is 617.96 g/mole
  
  #Calculate fragmentation: (Long / Short)*100 --> (1- Long / Short)*100
  
  df_std_samples$Fragmentation <- (df_std_samples$SQ_Short/ df_std_samples$SQ_Long)
  #df_qBiCo_indices <- data.frame(df_std_samples %>% group_by(Sample) %>% summarise(mean(Conversion_efficiency,na.rm=TRUE), sd(Conversion_efficiency,na.rm=TRUE), mean(DNA_conc,na.rm=TRUE),sd(DNA_conc,na.rm=TRUE),mean(Fragmentation,na.rm=TRUE),sd(Fragmentation,na.rm=TRUE),mean(DNA_input_ng,na.rm=TRUE), mean(Elution_volume_ul,na.rm=TRUE)))
  #colnames(df_qBiCo_indices) <- c('Sample','Conversion_efficiency (%)','SD_conversion_efficiency','DNA concentration (ng/µl)','SD_concentration','Fragmentation (%)','SD_fragmentation','Amount (ng)','Elution volume (µl)')
  
  df_std_samples$experiment <- experiment_label
  df_qBiCo_indices <- subset(df_std_samples,select=c(Sample,Well,Conversion_efficiency,DNA_conc,Fragmentation,experiment,DNA_input_ng,Elution_volume_ul))
  return(p=df_qBiCo_indices)
}

#All in one function
raw_to_indices <- function(raw_data, experiment_label, sd_threshold, sd_range, manual_exlusion=FALSE,standards_list){
  df_std_samples <- raw_to_parameters(raw_data,manual_exlusion,standards_list) #compute the copy numbers and Cq standard deviation.
  df_std_samples_excluded <- exclude_on_SD(df_std_samples,sd_threshold,sd_range) #exclude samples based on standard deviation.
  df_qBiCo_indices <- parameters_to_indices(raw_data,df_std_samples_excluded,experiment_label) #obtain qBiCo indices per well.
  return (p=df_qBiCo_indices)
}

#Average the qBiCo indices for all wells per sample.
Average_indices <- function(df_qBiCo_indices){
  df_qBiCo_indices <- data.frame(df_qBiCo_indices %>% group_by(Sample,experiment) %>% dplyr::summarise(mean(Conversion_efficiency,na.rm=TRUE), sd(Conversion_efficiency,na.rm=TRUE), mean(DNA_conc,na.rm=TRUE),sd(DNA_conc,na.rm=TRUE),mean(Fragmentation,na.rm=TRUE),sd(Fragmentation,na.rm=TRUE),mean(DNA_input_ng,na.rm=TRUE), mean(Elution_volume_ul,na.rm=TRUE), ))
  colnames(df_qBiCo_indices) <- c('Sample','experiment','Conversion_efficiency (%)','SD_conversion_efficiency','DNA concentration (ng/µl)','SD_concentration','Fragmentation','SD_fragmentation','Amount (ng)','Elution volume (µl)')
  #When only one of the replicates is not exluded, also exclude this replicate as we need 2 for qPCR results. This could happen when for 1 fo the 3 replicates the Cq value for converted assay is excluded and for another replicate the Cq value for the genomic assay. When those are excluded we can only calculate the conversion efficiency for 1 of the 3 replicates.
  df_qBiCo_indices$Conversion_efficiency[is.na(df_qBiCo_indices$SD_conversion_efficiency)] <- NA
  df_qBiCo_indices$`DNA concentration (ng/µl)`[is.na(df_qBiCo_indices$SD_concentration)] <- NA
  df_qBiCo_indices$Fragmentation[is.na(df_qBiCo_indices$SD_fragmentation)] <- NA
  return(p=df_qBiCo_indices)
}

Create_3x_standards_df = function(x){
  standards_df <- data.frame(x)
  colnames(standards_df) <- 'StdA'
  rownames(standards_df) <- c('hTERT_long','hTERT_short','LINE1_converted','LINE1_genomic','IPC')
  standards_df$StdB <- as.integer(round(standards_df$StdA/3))
  standards_df$StdC <- as.integer(round(standards_df$StdB/3))
  standards_df$StdD <- as.integer(round(standards_df$StdC/3))
  standards_df$StdE <- as.integer(round(standards_df$StdD/3))
  standards_df$StdF <- as.integer(round(standards_df$StdE/3))
  standards_df$StdG <- as.integer(round(standards_df$StdF/3))
  standards_df$StdH <- as.integer(round(standards_df$StdG/3))
  return(p = standards_df)
}

#Double colours
double_colour_list <- function(colour_list){
  double_colour_list = c()
  for (colour_code in colour_list){
    double_colour_list <- c(double_colour_list,colour_code)
    double_colour_list <- c(double_colour_list,colour_code)
  }
  return(p=double_colour_list)
}


data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm=TRUE))
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- plyr::rename(data_sum, c("mean" = varname))
  return(data_sum)
}
#Import CQ data####
## SET THESE INPUT PARAMETERS  ##
foldername <- "/media/nw_disk1/roy/comparative_study/data"
filename <-  paste0(foldername, '/20230206_Comparative_study_Cq_values.xlsx')
data <- import_list(filename)
BC_1 <- data.frame(data$`BC_1`)
BC_2 <- data.frame(data$`BC_2`)
BC_3 <- data.frame(data$`BC_3`)
BC_4 <- data.frame(data$`BC_4`)
BC_5 <- data.frame(data$`BC_5`)
BC_6 <- data.frame(data$`BC_6`)
BC_7 <- data.frame(data$`BC_7`)
EC_1 <- data.frame(data$`EC_1`)
EC_2 <- data.frame(data$`EC_2`)
EC_3 <- data.frame(data$`EC_3`)
EC_5 <- data.frame(data$`EC_5`)
EC_6 <- data.frame(data$`EC_6`)
EC_7 <- data.frame(data$`EC_7`)
EC_8 <- data.frame(data$`EC_8`)
BCEC_set1 <- data.frame(data$`gDNA_set1`)
BCEC_set2 <- data.frame(data$`gDNA_set2`)
graph_info <- data.frame(data$graphs_sample_list)

#Get qBiCo indices####
#separately
#df_qBiCo_CFX_96_1 <- raw_to_indices(CFX96_1,'CFX96_1',sd_threshold = 1, sd_range = 2)


#all experiments in one go
sd_threshold = 1000000
sd_range = 2
for (experiment_label in c('BC_1','BC_2','BC_3','BC_4','BC_5','BC_6','BC_7','EC_1','EC_2','EC_3','EC_5','EC_6','EC_7','EC_8','BCEC_set1','BCEC_set2')){
  raw_data = get(experiment_label)
  raw_data <- subset(raw_data ,!is.na(raw_data$Sample))
  raw_data <- subset(raw_data,!grepl(1,raw_data$excluded) | grepl('Std',raw_data$Sample))
  #raw_data <- subset(raw_data,!raw_data$excluded == 1)
  output_variable_name <- paste('df_qBiCo_',experiment_label,sep = '')
  averaged_output_variable_name <- paste('df_averaged_qBiCo_',experiment_label,sep = '')
  if (experiment_label %in% c('BC_1','EC_1','EC_2','EC_3')){
    standards_list <- c(6000,6000,384000,11400,3000)
    } else {standards_list <- c(6000,12000,768000,22800,3000)}
  output <- raw_to_indices(raw_data,experiment_label, sd_threshold = sd_threshold, sd_range = sd_range, manual_exlusion=FALSE,standards_list = standards_list)
  output <- subset(output,output$Sample %in% raw_data$Sample[raw_data$excluded==0])
  averaged_output <- Average_indices(output) #average qBiCo indices per sample.
  assign(output_variable_name, output)
  assign(averaged_output_variable_name,averaged_output)
}

# group Sample data
df_qBiCo_validation_averaged <- rbind(df_averaged_qBiCo_BC_1,df_averaged_qBiCo_BC_2,df_averaged_qBiCo_BC_3,df_averaged_qBiCo_BC_4,df_averaged_qBiCo_BC_5,df_averaged_qBiCo_BC_6,df_averaged_qBiCo_BC_7,df_averaged_qBiCo_EC_1,df_averaged_qBiCo_EC_2,df_averaged_qBiCo_EC_3,df_averaged_qBiCo_EC_5,df_averaged_qBiCo_EC_6,df_averaged_qBiCo_EC_7,df_averaged_qBiCo_EC_8)
df_qBiCo_validation_averaged$Expected_concentration <- df_qBiCo_validation_averaged$`Amount (ng)`/df_qBiCo_validation_averaged$`Elution volume (µl)`

# group well data
df_qBiCo_validation <- rbind(df_qBiCo_BC_1,df_qBiCo_BC_2,df_qBiCo_BC_3,df_qBiCo_BC_4,df_qBiCo_BC_5,df_qBiCo_BC_6,df_qBiCo_BC_7,df_qBiCo_EC_1,df_qBiCo_EC_2,df_qBiCo_EC_3,df_qBiCo_EC_5,df_qBiCo_EC_6,df_qBiCo_EC_7,df_qBiCo_EC_8)
df_qBiCo_validation$Expected_concentration <- df_qBiCo_validation$DNA_input_ng/df_qBiCo_validation$Elution_volume_ul
#add conversion_method label
df_qBiCo_validation_averaged$conversion_method[df_qBiCo_validation_averaged$experiment %in% c('BC_1','BC_2','BC_3','BC_4','BC_5','BC_6','BC_7','BC_8')] <- 'BC'
df_qBiCo_validation_averaged$conversion_method[df_qBiCo_validation_averaged$experiment %in% c('EC_1','EC_2','EC_3','EC_4','EC_5','EC_6','EC_7','EC_8')] <- 'EC'
df_qBiCo_validation$conversion_method[df_qBiCo_validation$experiment %in% c('BC_1','BC_2','BC_3','BC_4','BC_5','BC_6','BC_7','BC_8')] <- 'BC'
df_qBiCo_validation$conversion_method[df_qBiCo_validation$experiment %in% c('EC_1','EC_2','EC_3','EC_4','EC_5','EC_6','EC_7','EC_8')] <- 'EC'

df_qBiCo_validation$Recovery <- (df_qBiCo_validation$DNA_conc*df_qBiCo_validation$Elution_volume_ul)/df_qBiCo_validation$DNA_input_ng
#df_qBiCo_validation_averaged$Recovery <- (df_qBiCo_validation_averaged$DNA_conc*df_qBiCo_validation_averaged$Elution_volume_ul)/df_qBiCo_validation_averaged$DNA_input_ng*100
#df_qBiCo_validation$Recovery[df_qBiCo_validation$Recovery > 100] <- 100


#group and label BCEC_set1 and BCEC_set2 data (22 10 ng gDNA conversions)
df_qbico_22_averaged <- rbind(df_averaged_qBiCo_BCEC_set1,df_averaged_qBiCo_BCEC_set2)
df_qbico_22_averaged$Expected_concentration <- df_qbico_22_averaged$`Amount (ng)`/df_qbico_22_averaged$`Elution volume (µl)`
df_qbico_22 <- rbind(df_qBiCo_BCEC_set1,df_qBiCo_BCEC_set2)
df_qbico_22$Expected_concentration <- df_qbico_22$DNA_input_ng/df_qbico_22$Elution_volume_ul
df_qbico_22_averaged$conversion_method[df_qbico_22_averaged$Sample %in% c('BC','BC_neg')] <- 'BC'
df_qbico_22_averaged$conversion_method[df_qbico_22_averaged$Sample %in% c('EC','EC_neg')] <- 'EC'
df_qbico_22$conversion_method[df_qbico_22$Sample %in% c('BC','BC_neg')] <- 'BC'
df_qbico_22$conversion_method[df_qbico_22$Sample %in% c('EC','EC_neg')] <- 'EC'

df_qbico_22$Recovery <- (df_qbico_22$DNA_conc*df_qbico_22$Elution_volume_ul)/df_qbico_22$DNA_input_ng

#Plotting & Statistical analysis####
#Create plots for all parameters per index####
#c("repeatability", "sensitivity" , "reproducibility" ,"recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time","inhibition_hematin","inhibition_proteinase, "freezing"")
print_stats <- FALSE
print_stats_AB <- TRUE
perform_stats <- TRUE
point_size <- 2
hide_ns <- FALSE
#colours
colour_EC <- '#F79B80'
colour_BC <- '#00BFC4'
colours_conversion_method <- c(colour_BC,colour_EC)

#Conversion efficiency####
y_lim_conv = c(45,102)
y_lim_coord = c(50,60,70,80,90,100)
y_lim_conv_s = c(88,100.5)
y_lim_coord_s = c(90,95,100)
y_lim_conv_lin = c(0,100)
y_lim_coord_lin = c(0,25,50,75,100)
x_lim_coord_lin = c(0,25,50,75,100)
graph_info_selected <- subset(graph_info,graph_info$index=='conv_eff')
#for (instrument_name in subset(graph_info_selected$instrument,!duplicated(graph_info_selected$instrument))) {#create one grob per machine
for (parameter_name in c("repeatability" , "reproducibility" ,"recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time","inhibition_hematin","inhibition_proteinase", "freezing")) {#create one plot per parameter
  graph_data  <- subset(graph_info_selected,graph_info_selected$parameter == parameter_name)
  x_label = graph_data$x_axis[1]
  y_label = graph_data$y_axis[1]
  #select samples/wells 
  #obtain qBiCo indices per well
  qBiCo_data = df_qBiCo_validation
  #subset to select only wells that are needed for the plot
  well_list = graph_data$well
  run_list = graph_data$run
  combined_list = paste0(well_list,run_list)
  qBiCo_data$combined <- paste0(qBiCo_data$Well,qBiCo_data$experiment)
  qBiCo_data = subset(qBiCo_data,qBiCo_data$combined %in% combined_list)
  
  if (parameter_name == 'repeatability') {
    if (dim(qBiCo_data)[1] == 0){f1 <- ggplot()} #return empty plot if dataframe is empty
    else{
      number_levels1 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      f1 <- ggplot(qBiCo_data,aes(x=factor(DNA_input_ng, level = number_levels1), y=Conversion_efficiency, color = conversion_method))
      f1 <- f1 + geom_boxplot(data=qBiCo_data, outlier.shape = NA,aes(group = interaction(conversion_method,DNA_input_ng)), color = c("#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80"))
      f1 <- f1 + scale_color_manual(values = c("#00BFC4","#F79B80","#000000","#000000"))
      f1 <- f1 + geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,position = position_jitterdodge())
      f1 <- f1 + coord_cartesian(ylim=y_lim_conv) + scale_y_continuous(breaks=y_lim_coord)
      f1 <- f1 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f1 <- f1 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f1 <- f1 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f1 <- f1 + theme(plot.title = element_text(size = 12))
      f1 <- f1 + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_conv <- append(stat_list_conv, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Conversion_efficiency,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_conv = list(stat_list)
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        f1 <- f1 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
        stat_list_pairwise <- compare_means(Conversion_efficiency ~ conversion_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_conv = list(stat_list_pairwise)
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f1 <- f1 + annotate('text',x=0.5, y =y_lim_conv[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'reproducibility'){
    if (dim(qBiCo_data)[1] == 0) {f2 <- ggplot()} #return empty plot if dataframe is empty
    else {
      number_levels2 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      number_levels2 <- number_levels2[rev(order(number_levels2))]
      #number_levels2 <- number_levels2[1:minimum_signficicant_conc_index] #only use significantly non different concentrations to compare the 2 runs.
      qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng %in% number_levels2)
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('DNA_input_ng','conversion_method','experiment'))
      f2 <- ggplot(qBiCo_data_plot,aes(x=factor(DNA_input_ng, level = number_levels2), y=Conversion_efficiency, colour = conversion_method, group = experiment))
      #f2 <- f2 + facet_grid(cols = vars(factor(DNA_input_ng,level = number_levels2)), scales = 'free', switch = "both") + theme(axis.ticks.x = element_blank(), axis.text.x = element_blank())
      f2 <- f2 + geom_miss_point(aes(shape = conversion_method),size = point_size, position = position_dodge(width = 0.9))
      f2 <- f2 + coord_cartesian(ylim=y_lim_conv) + scale_y_continuous(breaks=y_lim_coord)
      f2 <- f2 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f2 <- f2 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'), legend.title=element_blank())
      f2 <- f2 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      legends <- get_legend(f2)
      f_legend <- as_ggplot(legends)
      f2 <- f2 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f2 <- f2 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd), position = position_dodge(width = 0.9))
      #f2 <- f2 + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
      
      experiments <- subset(qBiCo_data$experiment,!duplicated(qBiCo_data$experiment))
      #qBiCo_data_1 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[1])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, label.y = 101, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      #qBiCo_data_2 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[2])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, label.y = 100, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, method = 'kruskal.test', label.y = 92, label.x = 2)
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, method = 'kruskal.test', label.y = 90, label.x = 2)
      f2 <- f2 + theme(plot.title = element_text(size = 12)) 
      #We want to compare the two runs
      
      if (perform_stats == TRUE){
        f2 <- f2 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', aes(group = conversion_method), hide.ns = TRUE)
        #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_conv <- append(stat_list_conv, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Conversion_efficiency,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_conv <- append(stat_list_conv, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Conversion_efficiency ~ conversion_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f2 <- f2 + annotate('text',x=0.5, y =y_lim_conv[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
    
  } else if (parameter_name == 'recovery') {
    if (dim(qBiCo_data)[1] == 0) {f3 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$rec_method[grepl('binding5',qBiCo_data$Sample)] <- '5m' 
      qBiCo_data$rec_method[grepl('binding1',qBiCo_data$Sample)] <- '1m'
      qBiCo_data$rec_method[grepl('double',qBiCo_data$Sample)] <- '2x' 
      qBiCo_data$rec_method[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('rec_method','conversion_method'))
      number_levels3 <- c("C","1m","5m",'2x')
      f3 <- ggplot(qBiCo_data_plot,aes(x=factor(rec_method, level = number_levels3), y=Conversion_efficiency))
      f3 <- f3 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f3 <- f3 + facet_grid(.~ conversion_method, scales = 'free') + theme(
        strip.background = element_blank(),
        strip.text.x = element_blank())
      f3 <- f3 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f3 <- f3 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f3 <- f3 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f3 <- f3 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f3 <- f3 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
      f3 <- f3 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f3 <- f3 + theme(plot.title = element_text(size = 12))
      f3 <- f3 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        BC_pairwise <- compare_means(Conversion_efficiency ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
        EC_pairwise <- compare_means(Conversion_efficiency ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
        BC_pairwise$conversion_method <- 'BC'
        EC_pairwise$conversion_method <- 'EC'
        pairwise_tests <- rbind(BC_pairwise,EC_pairwise)
        stat_list_conv <- append(stat_list_conv, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
        stat_list_conv <- append(stat_list_conv, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Conversion_efficiency ~ rec_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
        stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
      }
      
      if (print_stats == TRUE){
        #f3 <- f3 + stat_compare_means( data = qBiCo_data, method = 'kruskal.test', hide.ns = hide_ns)
        data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
        colnames(data_text) <- c('label','conversion_method')
        f3 <- f3 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_conv_s[1],label = label) , vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'stability_UV') {
    if (dim(qBiCo_data)[1] == 0) {f4 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$UV[grepl('30',qBiCo_data$Sample)] <- '30' 
      qBiCo_data$UV[grepl('60',qBiCo_data$Sample)] <- '60'
      qBiCo_data$UV[grepl('120',qBiCo_data$Sample)] <- '120' 
      qBiCo_data$UV[grepl('SHS',qBiCo_data$Sample)] <- '0' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('UV','conversion_method'))
      number_levels4 <- c("0","30","60","120")
      f4 <- ggplot(qBiCo_data_plot,aes(x=factor(UV, level = number_levels4), y=Conversion_efficiency, colour = conversion_method))
      f4 <- f4 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f4 <- f4 + coord_cartesian(ylim=y_lim_conv) + scale_y_continuous(breaks=y_lim_coord)
      f4 <- f4 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f4 <- f4 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f4 <- f4 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f4 <- f4 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
      f4 <- f4 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f4 <- f4 + theme(plot.title = element_text(size = 12)) 
      f4 <- f4 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'UV')
        #stat_list_conv <- append(stat_list_conv, list(stat_list))
        #ANCOVA
        # res.aov <- qBiCo_data %>% anova_test(Conversion_efficiency ~ UV + conversion_method)
        # p_val <- paste0('p: ',res.aov$p[2])
        # f4 <- f4 + annotate('text',x=0.5, y =y_lim_conv[1], label =  p_val, vjust='bottom', hjust = 'left')
        #Non parametric ANCOVA
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$UV,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$UV,q_EC$Conversion_efficiency,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        p_val <- paste0('p: ',round(t1$p.value,5))
        stat_list <- c('p: ',t1$p.value)
        stat_list_conv <- append(stat_list_conv, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Conversion_efficiency ~ UV, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
        stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
        
        
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f4 <- f4 + annotate('text',x=0.5, y =y_lim_conv[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    }
  } else if (parameter_name == 'stability_sonication') {
    if (dim(qBiCo_data)[1] == 0) {f5 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$SON[grepl('SON150',qBiCo_data$Sample)] <- '150' 
      qBiCo_data$SON[grepl('SON500',qBiCo_data$Sample)] <- '500'
      qBiCo_data$SON[grepl('SON1000',qBiCo_data$Sample)] <- '1000' 
      qBiCo_data$SON[grepl('SON0',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('SON','conversion_method'))
      number_levels5 <- c("C","1000","500","150")
      f5 <- ggplot(qBiCo_data_plot,aes(x=factor(SON, level = number_levels5), y=Conversion_efficiency, colour = conversion_method))
      f5 <- f5 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f5 <- f5 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f5 <- f5 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f5 <- f5 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f5 <- f5 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f5 <- f5 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
      f5 <- f5 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                               position = position_dodge(width = 0.9))
      f5 <- f5 + theme(plot.title = element_text(size = 12)) 
      f5 <- f5 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_conv <- append(stat_list_conv, list(stat_list))
        qBiCo_data$SON[qBiCo_data$SON == 'C'] <- '2000'
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$SON,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$SON,q_EC$Conversion_efficiency,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p.value)
        stat_list_conv <- append(stat_list_conv, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Conversion_efficiency ~ SON, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '2000', group.by = 'conversion_method')
        stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
        
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f5 <- f5 + annotate('text',x=0.5, y =y_lim_conv_s[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    } } else if (parameter_name == 'stability_storage') {
      if (dim(qBiCo_data)[1] == 0) {f6 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$store[grepl('BC_2',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('BC_7',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data$store[grepl('EC_7',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('EC_5',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('store','conversion_method'))
        number_levels6 <- c("No storage","4 weeks")
        f6 <- ggplot(qBiCo_data_plot,aes(x=factor(store, level = number_levels6), y=Conversion_efficiency, colour = conversion_method))
        f6 <- f6 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f6 <- f6 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f6 <- f6 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f6 <- f6 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f6 <- f6 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f6 <- f6 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f6 <- f6 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                                 position = position_dodge(width = 0.9))
        f6 <- f6 + theme(plot.title = element_text(size = 12)) 
        f6 <- f6 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_conv <- append(stat_list_conv, list(stat_list))
          qBiCo_data$store[qBiCo_data$store == 'No storage'] <- '0'
          qBiCo_data$store[qBiCo_data$store == '4 weeks'] <- '4'
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$store,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$store,q_EC$Conversion_efficiency,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_conv <- append(stat_list_conv, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ store, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
          
        }
        if (print_stats == TRUE){
          #f6 <- f6 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f6 <- f6 + annotate('text',x=0.5, y =y_lim_conv_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'linearity') {
      if (dim(qBiCo_data)[1] == 0) {f7 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$Meth_perc[grepl('M0',qBiCo_data$Sample)] <- 0
        qBiCo_data$Meth_perc[grepl('M25',qBiCo_data$Sample)] <- 25
        qBiCo_data$Meth_perc[grepl('M50',qBiCo_data$Sample)] <- 50
        qBiCo_data$Meth_perc[grepl('M75',qBiCo_data$Sample)] <- 75
        qBiCo_data$Meth_perc[grepl('M100',qBiCo_data$Sample)] <- 100
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('Meth_perc','conversion_method'))
        number_levels7 <- c(0,25,50,75,100)
        f7 <- ggplot(qBiCo_data_plot,aes(x=factor(Meth_perc, level = number_levels7), y=Conversion_efficiency, colour = conversion_method))
        f7 <- f7 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f7 <- f7 + coord_cartesian(ylim=y_lim_conv) + scale_y_continuous(breaks=y_lim_coord)
        f7 <- f7 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f7 <- f7 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f7 <- f7 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f7 <- f7 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f7 <- f7 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                                 position = position_dodge(width = 0.9))
        f7 <- f7 + theme(plot.title = element_text(size = 12))
        f7 <- f7 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_conv <- append(stat_list_conv, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$Meth_perc,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$Meth_perc,q_EC$Conversion_efficiency,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_conv <- append(stat_list_conv, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ Meth_perc, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '100', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
          
        }
        if (print_stats == TRUE){
          #f7 <- f7 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f7 <- f7 + annotate('text',x=0.5, y =y_lim_conv[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'incubation_time') {
      if (dim(qBiCo_data)[1] == 0) {f8 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$incub_time <- 'C' 
        qBiCo_data$incub_time[grepl('12h',qBiCo_data$Sample)] <- '-'
        qBiCo_data$incub_time[grepl('20h',qBiCo_data$Sample)] <- '+' 
        qBiCo_data$incub_time[grepl('APOBEC',qBiCo_data$Sample)] <- '2+'
        qBiCo_data$incub_time[grepl('TET',qBiCo_data$Sample)] <- '1+'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('incub_time','conversion_method'))
        number_levels8 <- c("C",'-','+','1+', '2+')
        f8 <- ggplot(qBiCo_data_plot,aes(x=factor(incub_time, level = number_levels8), y=Conversion_efficiency))
        f8 <- f8 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f8 <- f8 + facet_grid(.~ conversion_method, scales = 'free') + theme(
          strip.background = element_blank(),
          strip.text.x = element_blank())
        f8 <- f8 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f8 <- f8 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f8 <- f8 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f8 <- f8 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f8 <- f8 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f8 <- f8 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd, colour = conversion_method),
                                 position = position_dodge(width = 0.9))
        f8 <- f8 + theme(plot.title = element_text(size = 12)) 
        f8 <- f8 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          BC_pairwise <- compare_means(Conversion_efficiency ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
          EC_pairwise <- compare_means(Conversion_efficiency ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
          stat_list_conv <- append(stat_list_conv, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
          stat_list_conv <- append(stat_list_conv, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ incub_time, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
        }
        
        if (print_stats == TRUE){
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test', hide.ns = hide_ns)
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test', hide.ns = hide_ns)
          data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
          colnames(data_text) <- c('label','conversion_method')
          f8 <- f8 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_conv_s[1],label = label) , vjust='bottom', hjust = 'left')
        }
        
      }
    } else if (parameter_name == 'inhibition_hematin') {
      if (dim(qBiCo_data)[1] == 0) {f9 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$hematin[grepl('HH',qBiCo_data$Sample)] <- '200' 
        qBiCo_data$hematin[grepl('MH',qBiCo_data$Sample)] <- '100'
        qBiCo_data$hematin[grepl('NH',qBiCo_data$Sample)] <- '0' 
        qBiCo_data$hematin[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('hematin','conversion_method'))
        number_levels9 <- c("C","0","100","200")
        f9 <- ggplot(qBiCo_data_plot,aes(x=factor(hematin, level = number_levels9), y=Conversion_efficiency, colour = conversion_method))
        f9 <- f9 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f9 <- f9 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f9 <- f9 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f9 <- f9 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f9 <- f9 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f9 <- f9 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f9 <- f9 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                                 position = position_dodge(width = 0.9))
        f9 <- f9 + theme(plot.title = element_text(size = 12)) 
        f9 <- f9 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ hematin, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
          
          #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_conv <- append(stat_list_conv, list(stat_list))
          qBiCo_data <- subset(qBiCo_data,!qBiCo_data$hematin == 'C')
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$hematin,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$hematin,q_EC$Conversion_efficiency,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_conv <- append(stat_list_conv, list(stat_list))
          
        }
        if (print_stats == TRUE){
          #f9 <- f9 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f9 <- f9 + annotate('text',x=0.5, y =y_lim_conv_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'inhibition_proteinase') {
      if (dim(qBiCo_data)[1] == 0) {f10 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$proteinase[grepl('HP',qBiCo_data$Sample)] <- '0.2' 
        qBiCo_data$proteinase[grepl('MP',qBiCo_data$Sample)] <- '0.1'
        qBiCo_data$proteinase[grepl('LP',qBiCo_data$Sample)] <- '0.05' 
        qBiCo_data$proteinase[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('proteinase','conversion_method'))
        number_levels10 <- c("C","0.05","0.1","0.2")
        f10 <- ggplot(qBiCo_data_plot,aes(x=factor(proteinase, level = number_levels10), y=Conversion_efficiency, colour = conversion_method))
        f10 <- f10 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f10 <- f10 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f10 <- f10 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f10 <- f10 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f10 <- f10 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f10 <- f10 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f10 <- f10 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                                   position = position_dodge(width = 0.9))
        f10 <- f10 + theme(plot.title = element_text(size = 12)) 
        f10 <- f10 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_conv <- append(stat_list_conv, list(stat_list))
          qBiCo_data$proteinase[qBiCo_data$proteinase == 'C'] <- '0' 
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$proteinase,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$proteinase,q_EC$Conversion_efficiency,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_conv <- append(stat_list_conv, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ proteinase, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
          
        }
        if (print_stats == TRUE){
          #f10 <- f10 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f10 <- f10 + annotate('text',x=0.5, y =y_lim_conv_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'freezing') {
      if (dim(qBiCo_data)[1] == 0) {f11 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$freezing[grepl('5ft',qBiCo_data$Sample)] <- '5'
        qBiCo_data$freezing[grepl('10ft',qBiCo_data$Sample)] <- '10' 
        qBiCo_data$freezing[grepl('SHS',qBiCo_data$Sample)] <- '0' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Conversion_efficiency', groupnames = c('freezing','conversion_method'))
        number_levels11 <- c("0","5","10")
        f11 <- ggplot(qBiCo_data_plot,aes(x=factor(freezing, level = number_levels11), y=Conversion_efficiency, colour = conversion_method))
        f11 <- f11 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f11 <- f11 + coord_cartesian(ylim=y_lim_conv_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f11 <- f11 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f11 <- f11 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f11 <- f11 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f11 <- f11 + aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd)
        f11 <- f11 + geom_errorbar(aes(ymax = Conversion_efficiency + sd, ymin = Conversion_efficiency - sd),
                                   position = position_dodge(width = 0.9))
        f11 <- f11 + theme(plot.title = element_text(size = 12)) 
        f11 <- f11 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Conversion_efficiency ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_conv <- append(stat_list_conv, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$freezing,q_BC$Conversion_efficiency,'BC'),cbind(q_EC$freezing,q_EC$Conversion_efficiency,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_conv <- append(stat_list_conv, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Conversion_efficiency ~ freezing, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_conv = append(stat_list_pairwise_conv, list(stat_list_pairwise))
          
        }
        if (print_stats == TRUE){
          #f11 <- f11 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f11 <- f11 + annotate('text',x=0.5, y =y_lim_conv_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    }
  else {TRUE}
}

foldername_tiff <- paste0(foldername, '/TIFF')
width_tiff <- 3
height_tiff <- 3
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'repeatability', ".TIFF"), f1, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'reproducibility', ".TIFF"), f2, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'recovery', ".TIFF"), f3, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'stability_UV', ".TIFF"), f4, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'stability_sonication', ".TIFF"), f5, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'stability_storage', ".TIFF"), f6, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'linearity', ".TIFF"), f7, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'incubation_time', ".TIFF"), f8, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'inhibition_hematin', ".TIFF"), f9, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'inhibition_proteinase', ".TIFF"), f10, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Conversion_efficiency/",'freezing', ".TIFF"), f11, width = width_tiff, height = height_tiff)
title_g <- 'Conversion efficiency'
y_left <- richtext_grob("**Conversion efficiency (%)**", rot=90, gp = gpar(fontsize = 16))
for (figure_lab in c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')){
  index = which(c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')==figure_lab)
  assign(figure_lab,get(figure_lab) + labs(tag = LETTERS[index]))
}
g <- grid.arrange(arrangeGrob(f1,f2,f_legend, nrow = 1, widths = c(5,5,1)), arrangeGrob(f3,f8,f7,f4,f5,f9,f10,f6,f11, nrow = 3), nrow = 2, heights = c(2,5), left = y_left)
output_g_name <- 'g_conv'
assign(output_g_name,g)
output_stat_name <- 'stat_conv'
assign(output_stat_name,stat_list_conv)

#Recovery####
y_lim_rec = c(-0.5,7.5)
y_lim_coord = c(0,1,2,3,4,5,6,7)
y_lim_rec_s = c(-0.5,5)
y_lim_coord_s = c(0,1,2,3,4,5)
y_lim_rec_lin = c(-0.5,5)
y_lim_coord_lin = c(0,1,2,3,4,5)
x_lim_coord_lin = c(0,25,50,75,100)
graph_info_selected <- subset(graph_info,graph_info$index=='recovery')
#for (instrument_name in subset(graph_info_selected$instrument,!duplicated(graph_info_selected$instrument))) {#create one grob per machine
for (parameter_name in c("repeatability" , "reproducibility" ,"recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time","inhibition_hematin","inhibition_proteinase", "freezing")) {#create one plot per parameter
  graph_data  <- subset(graph_info_selected,graph_info_selected$parameter == parameter_name)
  x_label = graph_data$x_axis[1]
  y_label = graph_data$y_axis[1]
  #select samples/wells 
  #obtain qBiCo indices per well
  qBiCo_data = df_qBiCo_validation
  #subset to select only wells that are needed for the plot
  well_list = graph_data$well
  run_list = graph_data$run
  combined_list = paste0(well_list,run_list)
  qBiCo_data$combined <- paste0(qBiCo_data$Well,qBiCo_data$experiment)
  qBiCo_data = subset(qBiCo_data,qBiCo_data$combined %in% combined_list)
  
  if (parameter_name == 'repeatability') {
    if (dim(qBiCo_data)[1] == 0){f1 <- ggplot()} #return empty plot if dataframe is empty
    else{
      number_levels1 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      f1 <- ggplot(qBiCo_data,aes(x=factor(DNA_input_ng, level = number_levels1), y=Recovery, color = conversion_method))
      f1 <- f1 + geom_boxplot(data=qBiCo_data, outlier.shape = NA,position = position_dodge(preserve = "single"),aes(group = interaction(conversion_method,DNA_input_ng)), color = c("#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80"))
      f1 <- f1 + scale_color_manual(values = c("#000000","#000000","#00BFC4","#F79B80"))
      f1 <- f1 + geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,position = position_jitterdodge())
      f1 <- f1 + coord_cartesian(ylim=y_lim_rec) + scale_y_continuous(breaks=y_lim_coord)
      f1 <- f1 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f1 <- f1 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f1 <- f1 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f1 <- f1 + theme(plot.title = element_text(size = 12)) 
      f1 <- f1 + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_rec <- append(stat_list_rec, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Recovery,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Recovery,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_rec = list(stat_list)
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        f1 <- f1 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
        stat_list_pairwise <- compare_means(Recovery ~ conversion_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_rec = list(stat_list_pairwise)
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f1 <- f1 + annotate('text',x=0.5, y =y_lim_rec[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'reproducibility'){
    if (dim(qBiCo_data)[1] == 0) {f2 <- ggplot()} #return empty plot if dataframe is empty
    else {
      number_levels2 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      number_levels2 <- number_levels2[rev(order(number_levels2))]
      #number_levels2 <- number_levels2[1:minimum_signficicant_conc_index] #only use significantly non different concentrations to compare the 2 runs.
      qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng %in% number_levels2)
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('DNA_input_ng','conversion_method','experiment'))
      f2 <- ggplot(qBiCo_data_plot,aes(x=factor(DNA_input_ng, level = number_levels2), y=Recovery, colour = conversion_method, group = experiment))
      #f2 <- f2 + facet_grid(cols = vars(factor(DNA_input_ng,level = number_levels2)), scales = 'free', switch = "both") + theme(axis.ticks.x = element_blank(), axis.text.x = element_blank())
      f2 <- f2 + geom_miss_point(aes(shape = conversion_method),size = point_size, position = position_dodge(width = 0.9))
      f2 <- f2 + coord_cartesian(ylim=y_lim_rec) + scale_y_continuous(breaks=y_lim_coord)
      f2 <- f2 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f2 <- f2 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'), legend.title=element_blank())
      f2 <- f2 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      legends <- get_legend(f2)
      f_legend <- as_ggplot(legends)
      f2 <- f2 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f2 <- f2 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd), position = position_dodge(width = 0.9))
      #f2 <- f2 + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
      
      experiments <- subset(qBiCo_data$experiment,!duplicated(qBiCo_data$experiment))
      #qBiCo_data_1 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[1])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, label.y = 101, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      #qBiCo_data_2 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[2])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, label.y = 100, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, method = 'kruskal.test', label.y = 92, label.x = 2)
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, method = 'kruskal.test', label.y = 90, label.x = 2)
      f2 <- f2 + theme(plot.title = element_text(size = 12))
      #We want to compare the two runs
      
      if (perform_stats == TRUE){
        f2 <- f2 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', aes(group = conversion_method), hide.ns = TRUE)
        #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_rec <- append(stat_list_rec, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Recovery,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Recovery,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_rec <- append(stat_list_rec, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Recovery ~ conversion_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f2 <- f2 + annotate('text',x=0.5, y =y_lim_rec[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
    
  } else if (parameter_name == 'recovery') {
    if (dim(qBiCo_data)[1] == 0) {f3 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$rec_method[grepl('binding5',qBiCo_data$Sample)] <- '5m' 
      qBiCo_data$rec_method[grepl('binding1',qBiCo_data$Sample)] <- '1m'
      qBiCo_data$rec_method[grepl('double',qBiCo_data$Sample)] <- '2x' 
      qBiCo_data$rec_method[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('rec_method','conversion_method'))
      number_levels3 <- c("C","1m","5m",'2x')
      f3 <- ggplot(qBiCo_data_plot,aes(x=factor(rec_method, level = number_levels3), y=Recovery))
      f3 <- f3 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f3 <- f3 + facet_grid(.~ conversion_method, scales = 'free') + theme(
        strip.background = element_blank(),
        strip.text.x = element_blank())
      f3 <- f3 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f3 <- f3 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f3 <- f3 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f3 <- f3 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f3 <- f3 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
      f3 <- f3 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f3 <- f3 + theme(plot.title = element_text(size = 12))
      f3 <- f3 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        BC_pairwise <- compare_means(Recovery ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
        EC_pairwise <- compare_means(Recovery ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
        BC_pairwise$conversion_method <- 'BC'
        EC_pairwise$conversion_method <- 'EC'
        pairwise_tests <- rbind(BC_pairwise,EC_pairwise)
        stat_list_rec <- append(stat_list_rec, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
        stat_list_rec <- append(stat_list_rec, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Recovery ~ rec_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
        stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))}
      
      if (print_stats == TRUE){
        #f3 <- f3 + stat_compare_means( data = qBiCo_data, method = 'kruskal.test', hide.ns = hide_ns)
        data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
        colnames(data_text) <- c('label','conversion_method')
        f3 <- f3 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_rec_s[1],label = label) , vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'stability_UV') {
    if (dim(qBiCo_data)[1] == 0) {f4 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$UV[grepl('30',qBiCo_data$Sample)] <- '30' 
      qBiCo_data$UV[grepl('60',qBiCo_data$Sample)] <- '60'
      qBiCo_data$UV[grepl('120',qBiCo_data$Sample)] <- '120' 
      qBiCo_data$UV[grepl('SHS',qBiCo_data$Sample)] <- '0' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('UV','conversion_method'))
      number_levels4 <- c("0","30","60","120")
      f4 <- ggplot(qBiCo_data_plot,aes(x=factor(UV, level = number_levels4), y=Recovery, colour = conversion_method))
      f4 <- f4 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f4 <- f4 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord)
      f4 <- f4 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f4 <- f4 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f4 <- f4 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f4 <- f4 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
      f4 <- f4 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f4 <- f4 + theme(plot.title = element_text(size = 12))
      f4 <- f4 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'UV')
        #stat_list_rec <- append(stat_list_rec, list(stat_list))
        #ANCOVA
        # res.aov <- qBiCo_data %>% anova_test(Recovery ~ UV + conversion_method)
        # p_val <- paste0('p: ',res.aov$p[2])
        # f4 <- f4 + annotate('text',x=0.5, y =y_lim_rec[1], label =  p_val, vjust='bottom', hjust = 'left')
        #Non parametric ANCOVA
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$UV,q_BC$Recovery,'BC'),cbind(q_EC$UV,q_EC$Recovery,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        p_val <- paste0('p: ',round(t1$p.value,5))
        stat_list <- c('p: ',t1$p.value)
        stat_list_rec <- append(stat_list_rec, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Recovery ~ UV, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
        stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
        
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f4 <- f4 + annotate('text',x=0.5, y =y_lim_rec[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    }
  } else if (parameter_name == 'stability_sonication') {
    if (dim(qBiCo_data)[1] == 0) {f5 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$SON[grepl('SON150',qBiCo_data$Sample)] <- '150' 
      qBiCo_data$SON[grepl('SON500',qBiCo_data$Sample)] <- '500'
      qBiCo_data$SON[grepl('SON1000',qBiCo_data$Sample)] <- '1000' 
      qBiCo_data$SON[grepl('SON0',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('SON','conversion_method'))
      number_levels5 <- c("C","1000","500","150")
      f5 <- ggplot(qBiCo_data_plot,aes(x=factor(SON, level = number_levels5), y=Recovery, colour = conversion_method))
      f5 <- f5 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f5 <- f5 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f5 <- f5 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f5 <- f5 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f5 <- f5 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f5 <- f5 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
      f5 <- f5 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                               position = position_dodge(width = 0.9))
      f5 <- f5 + theme(plot.title = element_text(size = 12))
      f5 <- f5 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_rec <- append(stat_list_rec, list(stat_list))
        qBiCo_data$SON[qBiCo_data$SON == 'C'] <- '2000'
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$SON,q_BC$Recovery,'BC'),cbind(q_EC$SON,q_EC$Recovery,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p.value)
        stat_list_rec <- append(stat_list_rec, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Recovery ~ SON, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '2000', group.by = 'conversion_method')
        stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f5 <- f5 + annotate('text',x=0.5, y =y_lim_rec_s[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    } } else if (parameter_name == 'stability_storage') {
      if (dim(qBiCo_data)[1] == 0) {f6 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$store[grepl('BC_2',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('BC_7',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data$store[grepl('EC_7',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('EC_5',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('store','conversion_method'))
        number_levels6 <- c("No storage","4 weeks")
        f6 <- ggplot(qBiCo_data_plot,aes(x=factor(store, level = number_levels6), y=Recovery, colour = conversion_method))
        f6 <- f6 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f6 <- f6 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f6 <- f6 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f6 <- f6 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f6 <- f6 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f6 <- f6 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f6 <- f6 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                                 position = position_dodge(width = 0.9))
        f6 <- f6 + theme(plot.title = element_text(size = 12)) 
        f6 <- f6 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_rec <- append(stat_list_rec, list(stat_list))
          qBiCo_data$store[qBiCo_data$store == 'No storage'] <- '0'
          qBiCo_data$store[qBiCo_data$store == '4 weeks'] <- '4'
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$store,q_BC$Recovery,'BC'),cbind(q_EC$store,q_EC$Recovery,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_rec <- append(stat_list_rec, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ store, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f6 <- f6 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f6 <- f6 + annotate('text',x=0.5, y =y_lim_rec_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'linearity') {
      if (dim(qBiCo_data)[1] == 0) {f7 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$Meth_perc[grepl('M0',qBiCo_data$Sample)] <- 0
        qBiCo_data$Meth_perc[grepl('M25',qBiCo_data$Sample)] <- 25
        qBiCo_data$Meth_perc[grepl('M50',qBiCo_data$Sample)] <- 50
        qBiCo_data$Meth_perc[grepl('M75',qBiCo_data$Sample)] <- 75
        qBiCo_data$Meth_perc[grepl('M100',qBiCo_data$Sample)] <- 100
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('Meth_perc','conversion_method'))
        number_levels7 <- c(0,25,50,75,100)
        f7 <- ggplot(qBiCo_data_plot,aes(x=factor(Meth_perc, level = number_levels7), y=Recovery, colour = conversion_method))
        f7 <- f7 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f7 <- f7 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord)
        f7 <- f7 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f7 <- f7 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f7 <- f7 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f7 <- f7 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f7 <- f7 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                                 position = position_dodge(width = 0.9))
        f7 <- f7 + theme(plot.title = element_text(size = 12))
        f7 <- f7 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_rec <- append(stat_list_rec, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$Meth_perc,q_BC$Recovery,'BC'),cbind(q_EC$Meth_perc,q_EC$Recovery,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_rec <- append(stat_list_rec, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ Meth_perc, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '100', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f7 <- f7 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f7 <- f7 + annotate('text',x=0.5, y =y_lim_rec[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'incubation_time') {
      if (dim(qBiCo_data)[1] == 0) {f8 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$incub_time<- 'C' 
        qBiCo_data$incub_time[grepl('12h',qBiCo_data$Sample)] <- '-'
        qBiCo_data$incub_time[grepl('20h',qBiCo_data$Sample)] <- '+' 
        qBiCo_data$incub_time[grepl('APOBEC',qBiCo_data$Sample)] <- '2+'
        qBiCo_data$incub_time[grepl('TET',qBiCo_data$Sample)] <- '1+'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('incub_time','conversion_method'))
        number_levels8 <- c("C",'-','+','1+', '2+')
        f8 <- ggplot(qBiCo_data_plot,aes(x=factor(incub_time, level = number_levels8), y=Recovery))
        f8 <- f8 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f8 <- f8 + facet_grid(.~ conversion_method, scales = 'free') + theme(
          strip.background = element_blank(),
          strip.text.x = element_blank())
        f8 <- f8 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f8 <- f8 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f8 <- f8 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f8 <- f8 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f8 <- f8 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f8 <- f8 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd, colour = conversion_method),
                                 position = position_dodge(width = 0.9))
        f8 <- f8 + theme(plot.title = element_text(size = 12)) 
        f8 <- f8 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          BC_pairwise <- compare_means(Recovery ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
          EC_pairwise <- compare_means(Recovery ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
          stat_list_rec <- append(stat_list_rec, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
          stat_list_rec <- append(stat_list_rec, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ incub_time, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))}
        
        if (print_stats == TRUE){
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test', hide.ns = hide_ns)
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test', hide.ns = hide_ns)
          data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
          colnames(data_text) <- c('label','conversion_method')
          f8 <- f8 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_rec_s[1],label = label) , vjust='bottom', hjust = 'left')
        }
        
      }
    } else if (parameter_name == 'inhibition_hematin') {
      if (dim(qBiCo_data)[1] == 0) {f9 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$hematin[grepl('HH',qBiCo_data$Sample)] <- '200' 
        qBiCo_data$hematin[grepl('MH',qBiCo_data$Sample)] <- '100'
        qBiCo_data$hematin[grepl('NH',qBiCo_data$Sample)] <- '0' 
        qBiCo_data$hematin[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('hematin','conversion_method'))
        number_levels9 <- c("C","0","100","200")
        f9 <- ggplot(qBiCo_data_plot,aes(x=factor(hematin, level = number_levels9), y=Recovery, colour = conversion_method))
        f9 <- f9 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f9 <- f9 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f9 <- f9 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f9 <- f9 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f9 <- f9 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f9 <- f9 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f9 <- f9 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                                 position = position_dodge(width = 0.9))
        f9 <- f9 + theme(plot.title = element_text(size = 12)) 
        f9 <- f9 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ hematin, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
          
          #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_rec <- append(stat_list_rec, list(stat_list))
          qBiCo_data <- subset(qBiCo_data,!qBiCo_data$hematin == 'C')
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$hematin,q_BC$Recovery,'BC'),cbind(q_EC$hematin,q_EC$Recovery,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_rec <- append(stat_list_rec, list(stat_list))
        }
        if (print_stats == TRUE){
          #f9 <- f9 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f9 <- f9 + annotate('text',x=0.5, y =y_lim_rec_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'inhibition_proteinase') {
      if (dim(qBiCo_data)[1] == 0) {f10 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$proteinase[grepl('HP',qBiCo_data$Sample)] <- '0.2' 
        qBiCo_data$proteinase[grepl('MP',qBiCo_data$Sample)] <- '0.1'
        qBiCo_data$proteinase[grepl('LP',qBiCo_data$Sample)] <- '0.05' 
        qBiCo_data$proteinase[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('proteinase','conversion_method'))
        number_levels10 <- c("C","0.05","0.1","0.2")
        f10 <- ggplot(qBiCo_data_plot,aes(x=factor(proteinase, level = number_levels10), y=Recovery, colour = conversion_method))
        f10 <- f10 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f10 <- f10 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f10 <- f10 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f10 <- f10 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f10 <- f10 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f10 <- f10 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f10 <- f10 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                                   position = position_dodge(width = 0.9))
        f10 <- f10 + theme(plot.title = element_text(size = 12)) 
        f10 <- f10 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_rec <- append(stat_list_rec, list(stat_list))
          qBiCo_data$proteinase[qBiCo_data$proteinase == 'C'] <- '0' 
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$proteinase,q_BC$Recovery,'BC'),cbind(q_EC$proteinase,q_EC$Recovery,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_rec <- append(stat_list_rec, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ proteinase, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f10 <- f10 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f10 <- f10 + annotate('text',x=0.5, y =y_lim_rec_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'freezing') {
      if (dim(qBiCo_data)[1] == 0) {f11 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$freezing[grepl('5ft',qBiCo_data$Sample)] <- '5'
        qBiCo_data$freezing[grepl('10ft',qBiCo_data$Sample)] <- '10' 
        qBiCo_data$freezing[grepl('SHS',qBiCo_data$Sample)] <- '0' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Recovery', groupnames = c('freezing','conversion_method'))
        number_levels11 <- c("0","5","10")
        f11 <- ggplot(qBiCo_data_plot,aes(x=factor(freezing, level = number_levels11), y=Recovery, colour = conversion_method))
        f11 <- f11 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f11 <- f11 + coord_cartesian(ylim=y_lim_rec_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f11 <- f11 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f11 <- f11 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f11 <- f11 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f11 <- f11 + aes(ymax = Recovery + sd, ymin = Recovery - sd)
        f11 <- f11 + geom_errorbar(aes(ymax = Recovery + sd, ymin = Recovery - sd),
                                   position = position_dodge(width = 0.9))
        f11 <- f11 + theme(plot.title = element_text(size = 12)) 
        f11 <- f11 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Recovery ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_rec <- append(stat_list_rec, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$freezing,q_BC$Recovery,'BC'),cbind(q_EC$freezing,q_EC$Recovery,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_rec <- append(stat_list_rec, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Recovery ~ freezing, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_rec = append(stat_list_pairwise_rec, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f11 <- f11 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f11 <- f11 + annotate('text',x=0.5, y =y_lim_rec_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    }
  else {TRUE}
}

foldername_tiff <- paste0(foldername, '/TIFF')
width_tiff <- 3
height_tiff <- 3
ggsave(file = paste0(foldername_tiff,"/Recovery/",'repeatability', ".TIFF"), f1, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'reproducibility', ".TIFF"), f2, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'recovery', ".TIFF"), f3, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'stability_UV', ".TIFF"), f4, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'stability_sonication', ".TIFF"), f5, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'stability_storage', ".TIFF"), f6, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'linearity', ".TIFF"), f7, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'incubation_time', ".TIFF"), f8, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'inhibition_hematin', ".TIFF"), f9, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'inhibition_proteinase', ".TIFF"), f10, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Recovery/",'freezing', ".TIFF"), f11, width = width_tiff, height = height_tiff)
title_g <- 'Recovery'
y_left <- richtext_grob("**Detected/Expected concentration**", rot=90, gp = gpar(fontsize = 16))
for (figure_lab in c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')){
  index = which(c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')==figure_lab)
  assign(figure_lab,get(figure_lab) + labs(tag = LETTERS[index]))
}
g <- grid.arrange(arrangeGrob(f1,f2,f_legend, nrow = 1, widths = c(5,5,1)), arrangeGrob(f3,f8,f7,f4,f5,f9,f10,f6,f11, nrow = 3), nrow = 2, heights = c(2,5), left = y_left)
output_g_name <- 'g_rec'
assign(output_g_name,g)
output_stat_name <- 'stat_rec'
assign(output_stat_name,stat_list_rec)

#Fragmentation####
y_lim_frag = c(-5,60)
y_lim_coord = c(0,10,20,30,40,50,60)
y_lim_frag_s = c(-1,15)
y_lim_coord_s = c(0,5,10,15)
y_lim_frag_lin = c(-1,20)
y_lim_coord_lin = c(0,5,10,15,20)
x_lim_coord_lin = c(0,25,50,75,100)
graph_info_selected <- subset(graph_info,graph_info$index=='fragmentation')
#for (instrument_name in subset(graph_info_selected$instrument,!duplicated(graph_info_selected$instrument))) {#create one grob per machine
for (parameter_name in c("repeatability" , "reproducibility" ,"recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time","inhibition_hematin","inhibition_proteinase", "freezing")) {#create one plot per parameter
  graph_data  <- subset(graph_info_selected,graph_info_selected$parameter == parameter_name)
  x_label = graph_data$x_axis[1]
  y_label = graph_data$y_axis[1]
  #select samples/wells 
  #obtain qBiCo indices per well
  qBiCo_data = df_qBiCo_validation
  #subset to select only wells that are needed for the plot
  well_list = graph_data$well
  run_list = graph_data$run
  combined_list = paste0(well_list,run_list)
  qBiCo_data$combined <- paste0(qBiCo_data$Well,qBiCo_data$experiment)
  qBiCo_data = subset(qBiCo_data,qBiCo_data$combined %in% combined_list)
  
  if (parameter_name == 'repeatability') {
    if (dim(qBiCo_data)[1] == 0){f1 <- ggplot()} #return empty plot if dataframe is empty
    else{
      number_levels1 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      f1 <- ggplot(qBiCo_data,aes(x=factor(DNA_input_ng, level = number_levels1), y=Fragmentation, color = conversion_method))
      f1 <- f1 + geom_boxplot(data=qBiCo_data, outlier.shape = NA,position = position_dodge(preserve = "single"),aes(group = interaction(conversion_method,DNA_input_ng)), color = c("#00BFC4","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80","#00BFC4","#F79B80"))
      f1 <- f1 + scale_color_manual(values = c("#000000","#000000","#00BFC4","#F79B80"))
      f1 <- f1 + geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,position = position_jitterdodge())
      f1 <- f1 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f1 <- f1 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f1 <- f1 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f1 <- f1 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f1 <- f1 + theme(plot.title = element_text(size = 12))
      f1 <- f1 + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_frag <- append(stat_list_frag, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Fragmentation,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Fragmentation,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_frag = list(stat_list)
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        f1 <- f1 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
        qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng != '1')
        qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng != '5')
        stat_list_pairwise <- compare_means(Fragmentation ~ conversion_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_frag = list(stat_list_pairwise)
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f1 <- f1 + annotate('text',x=0.5, y =-1, label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'reproducibility'){
    if (dim(qBiCo_data)[1] == 0) {f2 <- ggplot()} #return empty plot if dataframe is empty
    else {
      number_levels2 <- subset(qBiCo_data$DNA_input_ng,!duplicated(qBiCo_data$DNA_input_ng)) #pick amounts for x-axis
      number_levels2 <- number_levels2[rev(order(number_levels2))]
      #number_levels2 <- number_levels2[1:minimum_signficicant_conc_index] #only use significantly non different concentrations to compare the 2 runs.
      qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng %in% number_levels2)
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('DNA_input_ng','conversion_method','experiment'))
      f2 <- ggplot(qBiCo_data_plot,aes(x=factor(DNA_input_ng, level = number_levels2), y=Fragmentation, colour = conversion_method, group = experiment))
      #f2 <- f2 + facet_grid(cols = vars(factor(DNA_input_ng,level = number_levels2)), scales = 'free', switch = "both") + theme(axis.ticks.x = element_blank(), axis.text.x = element_blank())
      f2 <- f2 + geom_miss_point(aes(shape = conversion_method),size = point_size, position = position_dodge(width = 0.9))
      f2 <- f2 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f2 <- f2 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f2 <- f2 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'), legend.title=element_blank())
      f2 <- f2 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      legends <- get_legend(f2)
      f_legend <- as_ggplot(legends)
      f2 <- f2 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      f2 <- f2 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd), position = position_dodge(width = 0.9))
      #f2 <- f2 + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
      
      experiments <- subset(qBiCo_data$experiment,!duplicated(qBiCo_data$experiment))
      #qBiCo_data_1 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[1])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, label.y = 101, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      #qBiCo_data_2 <- subset(qBiCo_data,qBiCo_data$experiment == experiments[2])
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, label.y = 100, label = 'p.signif', method = 't.test', paired = FALSE, ref.group = '5', hide.ns = hide_ns)
      
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_1, method = 'kruskal.test', label.y = 92, label.x = 2)
      #f2 <- f2 + stat_compare_means(data = qBiCo_data_2, method = 'kruskal.test', label.y = 90, label.x = 2)
      f2 <- f2 + theme(plot.title = element_text(size = 12)) 
      #We want to compare the two runs
      
      if (perform_stats == TRUE){
        f2 <- f2 + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', aes(group = conversion_method), hide.ns = TRUE)
        #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_frag <- append(stat_list_frag, list(stat_list))
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$DNA_input_ng,q_BC$Fragmentation,'BC'),cbind(q_EC$DNA_input_ng,q_EC$Fragmentation,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- anova_test(data = data.bind, formula = y ~ group, covariate = x)#T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p)
        stat_list_frag <- append(stat_list_frag, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng != '1')
        qBiCo_data <- subset(qBiCo_data,qBiCo_data$DNA_input_ng != '5')
        stat_list_pairwise <- compare_means(Fragmentation ~ conversion_method, data= qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'DNA_input_ng')
        stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
      }
      if (print_stats_AB == TRUE){
        p_val <- paste0('p: ',t1$p)
        f2 <- f2 + annotate('text',x=0.5, y =-1, label =  p_val, vjust='bottom', hjust = 'left')
      }
      
    }
    
  } else if (parameter_name == 'recovery') {
    if (dim(qBiCo_data)[1] == 0) {f3 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$rec_method[grepl('binding5',qBiCo_data$Sample)] <- '5m' 
      qBiCo_data$rec_method[grepl('binding1',qBiCo_data$Sample)] <- '1m'
      qBiCo_data$rec_method[grepl('double',qBiCo_data$Sample)] <- '2x' 
      qBiCo_data$rec_method[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('rec_method','conversion_method'))
      number_levels3 <- c("C","1m","5m",'2x')
      f3 <- ggplot(qBiCo_data_plot,aes(x=factor(rec_method, level = number_levels3), y=Fragmentation))
      f3 <- f3 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f3 <- f3 + facet_grid(.~ conversion_method, scales = 'free') + theme(
        strip.background = element_blank(),
        strip.text.x = element_blank())
      f3 <- f3 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
      f3 <- f3 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f3 <- f3 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f3 <- f3 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f3 <- f3 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
      f3 <- f3 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f3 <- f3 + theme(plot.title = element_text(size = 12))
      f3 <- f3 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        BC_pairwise <- compare_means(Fragmentation ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
        EC_pairwise <- compare_means(Fragmentation ~ rec_method, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
        BC_pairwise$conversion_method <- 'BC'
        EC_pairwise$conversion_method <- 'EC'
        pairwise_tests <- rbind(BC_pairwise,EC_pairwise)
        stat_list_frag <- append(stat_list_frag, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
        stat_list_frag <- append(stat_list_frag, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Fragmentation ~ rec_method, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
        stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))}
      
      if (print_stats == TRUE){
        #f3 <- f3 + stat_compare_means( data = qBiCo_data, method = 'kruskal.test', hide.ns = hide_ns)
        data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
        colnames(data_text) <- c('label','conversion_method')
        f3 <- f3 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_frag_s[1],label = label) , vjust='bottom', hjust = 'left')
      }
      
    }
  } else if (parameter_name == 'stability_UV') {
    if (dim(qBiCo_data)[1] == 0) {f4 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$UV[grepl('30',qBiCo_data$Sample)] <- '30' 
      qBiCo_data$UV[grepl('60',qBiCo_data$Sample)] <- '60'
      qBiCo_data$UV[grepl('120',qBiCo_data$Sample)] <- '120' 
      qBiCo_data$UV[grepl('SHS',qBiCo_data$Sample)] <- '0' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('UV','conversion_method'))
      number_levels4 <- c("0","30","60","120")
      f4 <- ggplot(qBiCo_data_plot,aes(x=factor(UV, level = number_levels4), y=Fragmentation, colour = conversion_method))
      f4 <- f4 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f4 <- f4 + coord_cartesian(ylim=y_lim_frag) + scale_y_continuous(breaks=y_lim_coord)
      f4 <- f4 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f4 <- f4 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f4 <- f4 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f4 <- f4 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
      f4 <- f4 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd, colour = conversion_method),
                               position = position_dodge(width = 0.9))
      f4 <- f4 + theme(plot.title = element_text(size = 12)) 
      f4 <- f4 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'UV')
        #stat_list_frag <- append(stat_list_frag, list(stat_list))
        #ANCOVA
        # res.aov <- qBiCo_data %>% anova_test(Fragmentation ~ UV + conversion_method)
        # p_val <- paste0('p: ',res.aov$p[2])
        # f4 <- f4 + annotate('text',x=0.5, y =y_lim_frag[1], label =  p_val, vjust='bottom', hjust = 'left')
        #Non parametric ANCOVA
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$UV,q_BC$Fragmentation,'BC'),cbind(q_EC$UV,q_EC$Fragmentation,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        p_val <- paste0('p: ',round(t1$p.value,5))
        stat_list <- c('p: ',t1$p.value)
        stat_list_frag <- append(stat_list_frag, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Fragmentation ~ UV, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
        stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
        
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f4 <- f4 + annotate('text',x=0.5, y =y_lim_frag[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    }
  } else if (parameter_name == 'stability_sonication') {
    if (dim(qBiCo_data)[1] == 0) {f5 <- ggplot()} #return empty plot if dataframe is empty
    else {
      qBiCo_data$SON[grepl('SON150',qBiCo_data$Sample)] <- '150' 
      qBiCo_data$SON[grepl('SON500',qBiCo_data$Sample)] <- '500'
      qBiCo_data$SON[grepl('SON1000',qBiCo_data$Sample)] <- '1000' 
      qBiCo_data$SON[grepl('SON0',qBiCo_data$Sample)] <- 'C' 
      qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('SON','conversion_method'))
      number_levels5 <- c("C","1000","500","150")
      f5 <- ggplot(qBiCo_data_plot,aes(x=factor(SON, level = number_levels5), y=Fragmentation, colour = conversion_method))
      f5 <- f5 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                            position = position_dodge(width = 0.9))
      f5 <- f5 + coord_cartesian(ylim=y_lim_frag) + scale_y_continuous(breaks=y_lim_coord)
      f5 <- f5 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
      f5 <- f5 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
      f5 <- f5 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
      #f5 <- f5 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
      f5 <- f5 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                               position = position_dodge(width = 0.9))
      f5 <- f5 + theme(plot.title = element_text(size = 12)) 
      f5 <- f5 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
      if (perform_stats == TRUE){
        #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
        #stat_list_frag <- append(stat_list_frag, list(stat_list))
        qBiCo_data$SON[qBiCo_data$SON == 'C'] <- '2000'
        q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
        q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
        data.bind <- rbind(cbind(q_BC$SON,q_BC$Fragmentation,'BC'),cbind(q_EC$SON,q_EC$Fragmentation,'EC'))
        data.bind <- data.frame(data.bind)
        colnames(data.bind)=c('x','y','group')
        data.bind$x <- as.numeric(paste(data.bind$x))
        data.bind$y <- as.numeric(paste(data.bind$y))
        data.bind$group <- as.numeric(data.bind$group)
        data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
        t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
        stat_list <- c('p: ',t1$p.value)
        stat_list_frag <- append(stat_list_frag, list(stat_list))
        
        #pairwise wilcoxon ranksum test (separate per conversion method)
        stat_list_pairwise <- compare_means(Fragmentation ~ SON, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '2000', group.by = 'conversion_method')
        stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
      }
      if (print_stats == TRUE){
        #f5 <- f5 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
        p_val <- paste0('p: ',round(t1$p.value,5))
        f5 <- f5 + annotate('text',x=0.5, y =y_lim_frag[1], label =  p_val, vjust='bottom', hjust = 'left')
      }
    } } else if (parameter_name == 'stability_storage') {
      if (dim(qBiCo_data)[1] == 0) {f6 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$store[grepl('BC_2',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('BC_7',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data$store[grepl('EC_7',qBiCo_data$experiment)] <- 'No storage' 
        qBiCo_data$store[grepl('EC_5',qBiCo_data$experiment)] <- '4 weeks'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('store','conversion_method'))
        number_levels6 <- c("No storage","4 weeks")
        f6 <- ggplot(qBiCo_data_plot,aes(x=factor(store, level = number_levels6), y=Fragmentation, colour = conversion_method))
        f6 <- f6 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f6 <- f6 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f6 <- f6 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f6 <- f6 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f6 <- f6 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f6 <- f6 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f6 <- f6 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                                 position = position_dodge(width = 0.9))
        f6 <- f6 + theme(plot.title = element_text(size = 12)) 
        f6 <- f6 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_frag <- append(stat_list_frag, list(stat_list))
          qBiCo_data$store[qBiCo_data$store == 'No storage'] <- '0'
          qBiCo_data$store[qBiCo_data$store == '4 weeks'] <- '4'
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$store,q_BC$Fragmentation,'BC'),cbind(q_EC$store,q_EC$Fragmentation,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_frag <- append(stat_list_frag, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ store, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f6 <- f6 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f6 <- f6 + annotate('text',x=0.5, y =y_lim_frag_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'linearity') {
      if (dim(qBiCo_data)[1] == 0) {f7 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$Meth_perc[grepl('M0',qBiCo_data$Sample)] <- 0
        qBiCo_data$Meth_perc[grepl('M25',qBiCo_data$Sample)] <- 25
        qBiCo_data$Meth_perc[grepl('M50',qBiCo_data$Sample)] <- 50
        qBiCo_data$Meth_perc[grepl('M75',qBiCo_data$Sample)] <- 75
        qBiCo_data$Meth_perc[grepl('M100',qBiCo_data$Sample)] <- 100
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('Meth_perc','conversion_method'))
        number_levels7 <- c(0,25,50,75,100)
        f7 <- ggplot(qBiCo_data_plot,aes(x=factor(Meth_perc, level = number_levels7), y=Fragmentation, colour = conversion_method))
        f7 <- f7 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f7 <- f7 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f7 <- f7 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f7 <- f7 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f7 <- f7 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f7 <- f7 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f7 <- f7 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                                 position = position_dodge(width = 0.9))
        f7 <- f7 + theme(plot.title = element_text(size = 12))
        f7 <- f7 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_frag <- append(stat_list_frag, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$Meth_perc,q_BC$Fragmentation,'BC'),cbind(q_EC$Meth_perc,q_EC$Fragmentation,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_frag <- append(stat_list_frag, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ Meth_perc, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '100', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f7 <- f7 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f7 <- f7 + annotate('text',x=0.5, y =-1, label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'incubation_time') {
      if (dim(qBiCo_data)[1] == 0) {f8 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$incub_time <- 'C' 
        qBiCo_data$incub_time[grepl('12h',qBiCo_data$Sample)] <- '-'
        qBiCo_data$incub_time[grepl('20h',qBiCo_data$Sample)] <- '+' 
        qBiCo_data$incub_time[grepl('APOBEC',qBiCo_data$Sample)] <- '2+'
        qBiCo_data$incub_time[grepl('TET',qBiCo_data$Sample)] <- '1+'
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('incub_time','conversion_method'))
        number_levels8 <- c("C",'-','+','1+', '2+')
        f8 <- ggplot(qBiCo_data_plot,aes(x=factor(incub_time, level = number_levels8), y=Fragmentation))
        f8 <- f8 + geom_miss_point(aes(shape = conversion_method, colour = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f8 <- f8 + facet_grid(.~ conversion_method, scales = 'free') + theme(
          strip.background = element_blank(),
          strip.text.x = element_blank())
        f8 <- f8 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f8 <- f8 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f8 <- f8 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f8 <- f8 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f8 <- f8 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f8 <- f8 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd, colour = conversion_method),
                                 position = position_dodge(width = 0.9))
        f8 <- f8 + theme(plot.title = element_text(size = 12)) 
        f8 <- f8 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          BC_pairwise <- compare_means(Fragmentation ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test')
          EC_pairwise <- compare_means(Fragmentation ~ incub_time, data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test')
          stat_list_frag <- append(stat_list_frag, list(c('Kruskal-Wallis',BC_pairwise$p,'BC')))
          stat_list_frag <- append(stat_list_frag, list(c('Kruskal-Wallis',EC_pairwise$p,'EC')))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ incub_time, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))}
        
        if (print_stats == TRUE){
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'BC'), method = 'kruskal.test', hide.ns = hide_ns)
          #f8 <- f8 + stat_compare_means(aes(colour = experiment),data = subset(qBiCo_data,qBiCo_data$conversion_method == 'EC'), method = 'kruskal.test', hide.ns = hide_ns)
          data_text <- data.frame(label <- paste('p: ',round(pairwise_tests$p,5)), conversion_method <- c('BC','EC'))
          colnames(data_text) <- c('label','conversion_method')
          f8 <- f8 + geom_text(data =  data_text,mapping = aes(x=0.5, y =y_lim_frag_s[1],label = label) , vjust='bottom', hjust = 'left')
        }
        
      }
    } else if (parameter_name == 'inhibition_hematin') {
      if (dim(qBiCo_data)[1] == 0) {f9 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$hematin[grepl('HH',qBiCo_data$Sample)] <- '200' 
        qBiCo_data$hematin[grepl('MH',qBiCo_data$Sample)] <- '100'
        qBiCo_data$hematin[grepl('NH',qBiCo_data$Sample)] <- '0' 
        qBiCo_data$hematin[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('hematin','conversion_method'))
        number_levels9 <- c("C","0","100","200")
        f9 <- ggplot(qBiCo_data_plot,aes(x=factor(hematin, level = number_levels9), y=Fragmentation, colour = conversion_method))
        f9 <- f9 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                              position = position_dodge(width = 0.9))
        f9 <- f9 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f9 <- f9 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f9 <- f9 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f9 <- f9 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f9 <- f9 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f9 <- f9 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                                 position = position_dodge(width = 0.9))
        f9 <- f9 + theme(plot.title = element_text(size = 12)) 
        f9 <- f9 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ hematin, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = 'C', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
          
          #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_frag <- append(stat_list_frag, list(stat_list))
          qBiCo_data <- subset(qBiCo_data,!qBiCo_data$hematin == 'C')
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$hematin,q_BC$Fragmentation,'BC'),cbind(q_EC$hematin,q_EC$Fragmentation,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_frag <- append(stat_list_frag, list(stat_list))
        }
        if (print_stats == TRUE){
          #f9 <- f9 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f9 <- f9 + annotate('text',x=0.5, y =y_lim_frag_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'inhibition_proteinase') {
      if (dim(qBiCo_data)[1] == 0) {f10 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$proteinase[grepl('HP',qBiCo_data$Sample)] <- '0.2' 
        qBiCo_data$proteinase[grepl('MP',qBiCo_data$Sample)] <- '0.1'
        qBiCo_data$proteinase[grepl('LP',qBiCo_data$Sample)] <- '0.05' 
        qBiCo_data$proteinase[grepl('SHS',qBiCo_data$Sample)] <- 'C' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('proteinase','conversion_method'))
        number_levels10 <- c("C","0.05","0.1","0.2")
        f10 <- ggplot(qBiCo_data_plot,aes(x=factor(proteinase, level = number_levels10), y=Fragmentation, colour = conversion_method))
        f10 <- f10 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f10 <- f10 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f10 <- f10 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f10 <- f10 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f10 <- f10 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f10 <- f10 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f10 <- f10 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                                   position = position_dodge(width = 0.9))
        f10 <- f10 + theme(plot.title = element_text(size = 12)) 
        f10 <- f10 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_frag <- append(stat_list_frag, list(stat_list))
          qBiCo_data$proteinase[qBiCo_data$proteinase == 'C'] <- '0' 
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$proteinase,q_BC$Fragmentation,'BC'),cbind(q_EC$proteinase,q_EC$Fragmentation,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_frag <- append(stat_list_frag, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ proteinase, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f10 <- f10 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f10 <- f10 + annotate('text',x=0.5, y =y_lim_frag_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    } else if (parameter_name == 'freezing') {
      if (dim(qBiCo_data)[1] == 0) {f11 <- ggplot()} #return empty plot if dataframe is empty
      else {
        qBiCo_data$freezing[grepl('5ft',qBiCo_data$Sample)] <- '5'
        qBiCo_data$freezing[grepl('10ft',qBiCo_data$Sample)] <- '10' 
        qBiCo_data$freezing[grepl('SHS',qBiCo_data$Sample)] <- '0' 
        qBiCo_data_plot <- data_summary(qBiCo_data, varname = 'Fragmentation', groupnames = c('freezing','conversion_method'))
        number_levels11 <- c("0","5","10")
        f11 <- ggplot(qBiCo_data_plot,aes(x=factor(freezing, level = number_levels11), y=Fragmentation, colour = conversion_method))
        f11 <- f11 + geom_miss_point(aes(shape = conversion_method),size = point_size,
                                position = position_dodge(width = 0.9))
        f11 <- f11 + coord_cartesian(ylim=y_lim_frag_s) + scale_y_continuous(breaks=y_lim_coord_s)
        f11 <- f11 + theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold"))
        f11 <- f11 + labs(x = x_label, y = element_blank()) + theme(text = element_text(face = 'bold'))
        f11 <- f11 + theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1))
        #f11 <- f11 + aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd)
        f11 <- f11 + geom_errorbar(aes(ymax = Fragmentation + sd, ymin = Fragmentation - sd),
                                   position = position_dodge(width = 0.9))
        f11 <- f11 + theme(plot.title = element_text(size = 12)) 
        f11 <- f11 + scale_color_manual(values = colours_conversion_method) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1))
        if (perform_stats == TRUE){
          #stat_list <- compare_means(Fragmentation ~ conversion_method ,data = qBiCo_data, conversion_method = 'wilcox.test', paired = FALSE, group.by = 'SON')
          #stat_list_frag <- append(stat_list_frag, list(stat_list))
          q_BC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'BC')
          q_EC <- subset(qBiCo_data,qBiCo_data$conversion_method == 'EC')
          data.bind <- rbind(cbind(q_BC$freezing,q_BC$Fragmentation,'BC'),cbind(q_EC$freezing,q_EC$Fragmentation,'EC'))
          data.bind <- data.frame(data.bind)
          colnames(data.bind)=c('x','y','group')
          data.bind$x <- as.numeric(paste(data.bind$x))
          data.bind$y <- as.numeric(paste(data.bind$y))
          data.bind$group <- as.numeric(data.bind$group)
          data.bind <- subset(data.bind,rowSums(is.na(data.bind)) == 0)
          t1 <- T.aov(data.bind$x, data.bind$y, data.bind$group)
          stat_list <- c('p: ',t1$p.value)
          stat_list_frag <- append(stat_list_frag, list(stat_list))
          
          #pairwise wilcoxon ranksum test (separate per conversion method)
          stat_list_pairwise <- compare_means(Fragmentation ~ freezing, data = qBiCo_data, method = 'wilcox.test', paired = FALSE, ref.group = '0', group.by = 'conversion_method')
          stat_list_pairwise_frag = append(stat_list_pairwise_frag, list(stat_list_pairwise))
        }
        if (print_stats == TRUE){
          #f11 <- f11 + stat_compare_means(data = qBiCo_data,label.y = 100, method = 'wilcox.test', paired = FALSE, hide.ns = hide_ns, label = "p.signif")
          p_val <- paste0('p: ',round(t1$p.value,5))
          f11 <- f11 + annotate('text',x=0.5, y =y_lim_frag_s[1], label =  p_val, vjust='bottom', hjust = 'left')}
        
      }
    }
  else {TRUE}
}

foldername_tiff <- paste0(foldername, '/TIFF')
width_tiff <- 3
height_tiff <- 3
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'repeatability', ".TIFF"), f1, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'reproducibility', ".TIFF"), f2, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'recovery', ".TIFF"), f3, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'stability_UV', ".TIFF"), f4, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'stability_sonication', ".TIFF"), f5, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'stability_storage', ".TIFF"), f6, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'linearity', ".TIFF"), f7, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'incubation_time', ".TIFF"), f8, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'inhibition_hematin', ".TIFF"), f9, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'inhibition_proteinase', ".TIFF"), f10, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/Fragmentation/",'freezing', ".TIFF"), f11, width = width_tiff, height = height_tiff)
title_g <- 'Fragmentation'
y_left <- richtext_grob("**Fragmentation index**", rot=90, gp = gpar(fontsize = 16))
for (figure_lab in c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')){
  index = which(c('f1','f2','f3','f8','f7','f4','f5','f9','f10','f6','f11')==figure_lab)
  assign(figure_lab,get(figure_lab) + labs(tag = LETTERS[index]))
}
g <- grid.arrange(arrangeGrob(f1,f2,f_legend, nrow = 1, widths = c(5,5,1)), arrangeGrob(f3,f8,f7,f4,f5,f9,f10,f6,f11, nrow = 3), nrow = 2, heights = c(2,5), left = y_left)
output_g_name <- 'g_frag'
assign(output_g_name,g)
output_stat_name <- 'stat_frag'
assign(output_stat_name,stat_list_frag)



#BC_EC_22_gDNA####
df_qbico_22 <- subset(df_qbico_22,!df_qbico_22$Sample %in% c('BC_neg','EC_neg')) #remove negative controls as they only have NA values as expected.

y_lim_conv = c(90,102)
y_lim_coord_conv = c(90,95,100)
f_conv <- ggplot(df_qbico_22,aes(x=conversion_method,y=Conversion_efficiency)) +
  geom_boxplot(outlier.shape = NA, color = colours_conversion_method) +
  scale_color_manual(values = c("#000000","#000000","#00BFC4","#F79B80")) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,
                  position = position_jitterdodge()) +
  coord_cartesian(ylim=y_lim_conv) + scale_y_continuous(breaks=y_lim_coord_conv) + 
  theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold")) + 
  labs(x = element_blank(), y = 'Conversion efficiency (%)') + theme(text = element_text(face = 'bold')) + 
  theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1)) + 
  theme(plot.title = element_text(size = 12))
if (perform_stats == TRUE){
  #pairwise wilcoxon ranksum test (separate per conversion method)
  f_conv <- f_conv + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
  stat_list_pairwise <- compare_means(Conversion_efficiency ~ conversion_method, data = df_qbico_22, method = 'wilcox.test', paired = FALSE)
  stat_list_pairwise_gDNA10ng = data.frame(stat_list_pairwise)
}
 
y_lim_rec = c(-0.5,5)
y_lim_coord_rec = c(0,1,2,3,4,5)
f_rec <- ggplot(df_qbico_22,aes(x=conversion_method,y=Recovery)) +
  geom_boxplot(outlier.shape = NA, color = colours_conversion_method) +
  scale_color_manual(values = c("#000000","#000000","#00BFC4","#F79B80")) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,
                  position = position_jitterdodge()) +
  coord_cartesian(ylim=y_lim_rec) + scale_y_continuous(breaks=y_lim_coord_rec) + 
  theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold")) + 
  labs(x = element_blank(), y = 'Detected/Expected concentration') + theme(text = element_text(face = 'bold')) + 
  theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1)) + 
  theme(plot.title = element_text(size = 12))
if (perform_stats == TRUE){
  #pairwise wilcoxon ranksum test (separate per conversion method)
  f_rec <- f_rec + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
  stat_list_pairwise <- compare_means(Recovery ~ conversion_method, data = df_qbico_22, method = 'wilcox.test', paired = FALSE)
  stat_list_pairwise_gDNA10ng <- rbind(stat_list_pairwise_gDNA10ng,data.frame(stat_list_pairwise))
}

y_lim_frag = c(-1,15)
y_lim_coord_frag = c(0,5,10,15)
f_frag <- ggplot(df_qbico_22,aes(x=conversion_method,y=Fragmentation)) +
  geom_boxplot(outlier.shape = NA, color = colours_conversion_method) +
  scale_color_manual(values = c("#000000","#000000","#00BFC4","#F79B80")) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  geom_miss_point(aes(shape = conversion_method,group = conversion_method,colour = interaction(..group..,..missing..)),size = point_size/2,
                  position = position_jitterdodge()) +
  coord_cartesian(ylim=y_lim_frag) + scale_y_continuous(breaks=y_lim_coord_frag) + 
  theme(axis.text=element_text(size=10, face = "bold"),axis.title=element_text(size=10,face="bold")) + 
  labs(x = element_blank(), y = 'Fragmentation index') + theme(text = element_text(face = 'bold')) + 
  theme(legend.position = "none") + theme(axis.line = element_line(size = 0.5, colour = "black", linetype=1)) + 
  theme(plot.title = element_text(size = 12))
if (perform_stats == TRUE){
  #pairwise wilcoxon ranksum test (separate per conversion method)
  f_frag <- f_frag + stat_compare_means(method = 'wilcox.test', paired = FALSE, label = 'p.signif', hide.ns = TRUE)
  stat_list_pairwise <- compare_means(Fragmentation ~ conversion_method, data = df_qbico_22, method = 'wilcox.test', paired = FALSE)
  stat_list_pairwise_gDNA10ng <- rbind(stat_list_pairwise_gDNA10ng,data.frame(stat_list_pairwise))
}




#Manova to compare BC set with EC set combining all three qBiCo indices.
res.man <- manova(cbind(Conversion_efficiency,Recovery,Fragmentation) ~ conversion_method, data = df_qbico_22)
p_val_manova <- summary(res.man)$stats['conversion_method',"Pr(>F)"]
summary.aov(res.man) #Shows which indices differ between the two conversion methods

foldername_tiff <- paste0(foldername, '/TIFF')
width_tiff <- 3
height_tiff <- 3
ggsave(file = paste0(foldername_tiff,"/BC_EC_22_gDNA/",'Conversion_efficiency', ".TIFF"), f_conv, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/BC_EC_22_gDNA/",'Recovery', ".TIFF"), f_rec, width = width_tiff, height = height_tiff)
ggsave(file = paste0(foldername_tiff,"/BC_EC_22_gDNA/",'Fragmentation', ".TIFF"), f_frag, width = width_tiff, height = height_tiff)

for (figure_lab in c('f_conv','f_rec','f_frag')){
  index = which(c('f_conv','f_rec','f_frag')==figure_lab)
  assign(figure_lab,get(figure_lab) + labs(tag = LETTERS[index]))
}
g <- grid.arrange(arrangeGrob(f_conv,f_rec,f_frag, nrow = 1), nrow = 1)
output_g_name <- 'g_22gDNA'
assign(output_g_name,g)



#png_Export####
width_png <- 9
height_png <- 12
foldername_png <- paste0(foldername, '/TIFF')
#Export Conversion efficiency
ggsave(file = paste0(foldername_png,"/Conversion_efficiency.png"), get('g_conv'), width = width_png, height = height_png, limitsize = FALSE)
#Export Recovery
ggsave(file = paste0(foldername_png,"/Recovery.png"), get('g_rec'), width = width_png, height = height_png, limitsize = FALSE)
#Export Fragmentation
ggsave(file = paste0(foldername_png,"/Fragmentation.png"), get('g_frag'), width = width_png, height = height_png, limitsize = FALSE)
#Export 22gDNA
ggsave(file = paste0(foldername_png,"/22gDNA.png"), get('g_22gDNA'), width = width_png, height = 3, limitsize = FALSE)



#Export_qbico_output####
df_qBiCo_validation <- rbind(df_qBiCo_validation,df_qbico_22)
df_qBiCo_validation_averaged <- rbind(df_qBiCo_validation_averaged,df_qbico_22_averaged)
{write_xlsx(df_qBiCo_validation,paste0(foldername,'/20221230_qBiCo_indices_per_well.xlsx'))
  write_xlsx(df_qBiCo_validation_averaged,paste0(foldername,'/20221230_qBiCo_indices_per_sample.xlsx'))
}

#Export_stats####
#pairwise
parameter_list <- c("repeatability" , "reproducibility" ,"recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time","inhibition_hematin","inhibition_proteinase", "freezing")
index_list <- c('conv','rec','frag')
qindex_list <- c('stat_list_pairwise_conv','stat_list_pairwise_rec','stat_list_pairwise_frag')
df_export_stat <- data.frame()
for (j in seq_along(index_list)){
  for (i in seq_along(parameter_list)){
    df_pairwise <- get(qindex_list[j])[[i]] 
    df_pairwise$parameter <- parameter_list[i]
    df_export_stat <- rbind.fill(df_export_stat,df_pairwise)
  }
}

df_export_stat <- df_export_stat[,c(2,10,1,3,4,5,6,7,8,9,11)]
df_export_stat <- rbind.fill(df_export_stat,stat_list_pairwise_gDNA10ng)
filename <- paste0(foldername, '/pairwise_tests.xlsx')
wb <- createWorkbook()
sheet_nr <- createSheet(wb)
addDataFrame(df_export_stat,sheet = sheet_nr, row.names=FALSE)
saveWorkbook(wb,file = filename)

#BC vs EC
parameter_list <- c("repeatability" , "reproducibility", "recovery", "recovery", "stability_UV", "stability_sonication", "stability_storage", "linearity", "incubation_time", "incubation_time","inhibition_hematin","inhibition_proteinase", "freezing")
index_list <- list(stat_list_conv,stat_list_rec,stat_list_frag)
index_label_list <- c('Conversion_efficiency', 'Recovery', 'Fragmentation')
df_export_stat <- data.frame()
for (j in seq_along(index_list)){
  for (i in seq_along(parameter_list)){
    if (length(index_list[[j]][[i]]) == 3){
      list_comp <- c(index_list[[j]][[i]],parameter_list[i],index_label_list[j])
      df_comp <- data.frame(list_comp[1],list_comp[2],list_comp[4],list_comp[5],list_comp[3])
      colnames(df_comp) <- c('Test','p-value','parameter','index','conversion_method')
    } else {
      list_comp <- c(index_list[[j]][[i]],parameter_list[i],index_label_list[j])
      df_comp <- data.frame(list_comp[1],list_comp[2],list_comp[3],list_comp[4])
      colnames(df_comp) <- c('Test','p-value','parameter','index')
    }
    df_export_stat <- rbind.fill(df_export_stat,df_comp)
  }
}
df_manova <- data.frame('Manova',p_val_manova,'10ng','all',NA)
colnames(df_manova) <- colnames(df_export_stat)
df_export_stat <- rbind.fill(df_export_stat,df_manova)
filename <- paste0(foldername, '/comparative_tests.xlsx')
wb <- createWorkbook()
sheet_nr <- createSheet(wb)
addDataFrame(df_export_stat,sheet = sheet_nr, row.names=FALSE)
saveWorkbook(wb,file = filename)

