#!/usr/bin/env Rscript             
#########################################################
# TASK: formatting data that will be used for various plots
#########################################################
# load libraries and functions
library(data.table)
library(dplyr)
#========================================================
# plotting_data(): formatting data for plots
# input args: 
 ## input csv file
 ## lig cut off dist, default = 10 Ang
# output: list of 4 dfs, that need to be decompressed
  ## my_df
  ## my_df_u
  ## my_df_u_lig
  ## dup_muts
#========================================================
#lig_dist_colname = 'ligand_distance' or global var LigDist_colname
#lig_dist_cutoff  =  10 or global var LigDist_cutoff

plotting_data <- function(df
                          , lig_dist_colname 
                          , lig_dist_cutoff) {
my_df       = data.frame()
my_df_u     = data.frame()
my_df_u_lig = data.frame()
dup_muts    = data.frame()
  
#===========================
# Read file: struct params 
#===========================
#df = read.csv(infile_params, header = T)

cat("\nInput dimensions:", dim(df)) 

#==================================
# extract unique mutation entries
#==================================

# check for duplicate mutations
if ( length(unique(df$mutationinformation)) != length(df$mutationinformation)){
  cat(paste0("\nCAUTION:", " Duplicate mutations identified"
             , "\nExtracting these...\n"))
  #cat(my_df[duplicated(my_df$mutationinformation),])
  dup_muts = df[duplicated(df$mutationinformation),]
  dup_muts_nu = length(unique(dup_muts$mutationinformation))
  cat(paste0("\nDim of duplicate mutation df:", nrow(dup_muts)
             , "\nNo. of unique duplicate mutations:", dup_muts_nu
             , "\n\nExtracting df with unique mutations only\n"))
  my_df_u = df[!duplicated(df$mutationinformation),]
}else{
  cat(paste0("\nNo duplicate mutations detected\n"))
  my_df_u = df
}

upos = unique(my_df_u$position)
cat("\nDim of clean df:"); cat(dim(my_df_u), "\n")
cat("\nNo. of unique mutational positions:"); cat(length(upos), "\n")
  
#===============================================
# extract mutations <10 Angstroms and symbol
#===============================================
table(my_df_u[[lig_dist_colname]] < lig_dist_cutoff)

my_df_u_lig = my_df_u[my_df_u[[lig_dist_colname]] < lig_dist_cutoff,]

cat(paste0("There are ", nrow(my_df_u_lig), " sites lying within 10\u212b of the ligand\n"))

# return list of DFs
my_df = df
#df_names = c("my_df", "my_df_u", "my_df_u_lig", "dup_muts")
all_df = list(my_df, my_df_u, my_df_u_lig, dup_muts)
#all_df = Map(setNames, all_df, df_names)

return(all_df)
}
########################################################################
#               end of data extraction and cleaning for plots          #
########################################################################
