# Usage: R --no-save --slave --args <FUNCTION_DIR> <PID> <SPECTRUM_SUMMARY_DIR> <REPEAT_THRESHOLD> <CONSECUTIVE_FLAG> <MAPQ> <PLOT_FILE_FORMAT> < plot_spectrum_summary.R
# Description: Makes a bar plot of the number of telomere reads (per million reads) in the different fractions
#               of the tumor and/or control sample.

# Copyright 2015 Lina Sieverling

# This file is part of TelomereHunter.

# TelomereHunter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# TelomereHunter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with TelomereHunter.  If not, see <http://www.gnu.org/licenses/>.



# get commandline arguments
commandArgs = commandArgs()
pipeline_dir = commandArgs[5]
pid = commandArgs[6]
spectrum_dir = paste0(commandArgs[7], "/", pid, "/")
repeat_threshold = commandArgs[8]
consecutive_flag = commandArgs[9]
mapq_threshold = commandArgs[10]
plot_reverse_complement = commandArgs[11]
plot_file_format = commandArgs[12]

source(file.path(pipeline_dir, "/functions_for_plots.R"))

if (consecutive_flag == "True"){
  count_type = "Consecutive"
}else{
  count_type = "Non-consecutive"
}

if (plot_reverse_complement == "True"){
  plot_reverse_complement = TRUE
}else{
  plot_reverse_complement = FALSE
}

if (plot_file_format=="all"){
  plot_file_format=c("pdf", "png", "svg")
}


spectrum_tumor_file = paste0(spectrum_dir, "/tumor_TelomerCnt_", pid,"/", pid, ".spectrum")
spectrum_control_file = paste0(spectrum_dir, "/control_TelomerCnt_", pid,"/", pid, ".spectrum")

samples = c()
samples_short = c()
if (file.exists(spectrum_tumor_file)){samples = c(samples, "tumor"); samples_short = c(samples_short, "T")}
if (file.exists(spectrum_control_file)){samples = c(samples, "control"); samples_short = c(samples_short, "C")}



spectrum_summary_norm_list = list()

for (sample in samples){
  read_count_file = paste0(spectrum_dir, "/",sample, "_TelomerCnt_", pid, "/", pid, "_readcount.tsv")
  
  #get spectrum
  spectrum = read.table(paste0(spectrum_dir, "/",sample, "_TelomerCnt_", pid, "/", pid, ".spectrum"), header=TRUE, comment.char="")
  
  # make empty spectrum summary tables
  spectrum_summary = matrix(data=0, nrow=4, ncol=(ncol(spectrum)-2), byrow=TRUE)
  row.names(spectrum_summary)=c("intra_chromosomal", "subtelomeric", "junction_spanning", "intra_telomeric")
  colnames(spectrum_summary) = colnames(spectrum)[3:ncol(spectrum)]
  spectrum_summary = data.frame(spectrum_summary)
  
  
  # get intra-telomeric reads (= unmapped reads)
  spectrum_summary["intra_telomeric",] = spectrum[spectrum$chr=="unmapped",3:ncol(spectrum)]
  
  
  for (chr in c(1:22, "X", "Y")){
    spectrum_chr = spectrum[spectrum$chr==chr,3:ncol(spectrum)]
    
    # get junction spanning reads
    spectrum_summary["junction_spanning", ] = spectrum_summary["junction_spanning", ] + spectrum_chr[1,] + spectrum_chr[nrow(spectrum_chr),]
    
    # get subtelomeric reads (= first and last band)
    spectrum_summary["subtelomeric", ] = spectrum_summary["subtelomeric", ] + spectrum_chr[2,] + spectrum_chr[nrow(spectrum_chr)-1,]
    
    # get intra-chromosomal reads (= all other bands) 
    spectrum_summary["intra_chromosomal", ] = spectrum_summary["intra_chromosomal", ] + apply(spectrum_chr[3:(nrow(spectrum_chr)-2),], 2, sum)   
    
  }
  
  
  # get total number of reads 
  readcount = read.table(read_count_file, header=TRUE, comment.char="")
  total_reads = sum(as.numeric(readcount$reads))
  
  
  #normalize
  spectrum_summary_norm = spectrum_summary[,2:ncol(spectrum_summary)] * (spectrum_summary$reads_with_pattern / apply(spectrum_summary[ ,2:ncol(spectrum_summary)], 1,sum))
  spectrum_summary_norm = spectrum_summary_norm * (1000000 / total_reads)
  
  spectrum_summary_norm_list[[sample]] = spectrum_summary_norm
}



if (length(samples)==2){
  spectrum_summary = zipFastener(spectrum_summary_norm_list[["tumor"]], spectrum_summary_norm_list[["control"]], 1)
  axis=TRUE
  axis_simple=FALSE
}else{
  spectrum_summary = spectrum_summary_norm_list[[1]]
  axis=FALSE
  axis_simple=TRUE
}


height = t(spectrum_summary)
colnames(height) = NULL


plot_dir = file.path(spectrum_dir, "plots")

if (!(file.exists(plot_dir))){
  dir.create(plot_dir, recursive=TRUE)
}


if (nchar(pid)<11){
  main = paste0(pid,": Repeat Types in Telomeric Reads")
}else{
  main = paste0(pid,":\nRepeat Types in Telomeric Reads")
}


plot_file_prefix = paste0(plot_dir,"/", pid, "_summary")
barplot_repeattype(height=height,
                   plot_file_prefix=plot_file_prefix,
                   plot_file_format=plot_file_format,
                   plot_reverse_complement=plot_reverse_complement,
                   width=20,
                   main=main,
                   repeat_threshold=repeat_threshold, count_type=count_type, mapq_threshold=mapq_threshold,
                   sample_label=TRUE, sample_label_text=rep(samples_short,4),
                   axis=axis, axis_simple=axis_simple, labels=c("Intrachromosomal", "Subtelomeric", "Junction Spanning", "Intratelomeric"), 
                   xlas=1, tick=FALSE, cex.axis=0.85, cex.lab=0.9) 
