## Usage: Rscript plot_timestep.R cafemol_inputfile
## the input_file is a cafemol input file
## the output will be a correlation vs timestep plot

#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
#print(args[1])
#length(args)
## test if there is at least one argument: if not, return an error
if (length(args)==0) {
  stop("Please provide the cafemol inputfile", call.=FALSE)
}
  
library(dplyr)
library(stringr)
#file = "/Users/bhandariyr/Documents/projects/afm/cafemol/dimer/onechain/run2_rescaled/output1/cbl_afm.ts"
cafe.input = args[1]
## Read the cafemol input file to parse paths for pdb, dcd and timestep file
for (lines in readLines(cafe.input)){
  if (startsWith(lines, "path ")){
    result.path = trimws(unlist(strsplit(lines,"="))[2])
  }
  if (startsWith(lines, "filename ")){
    result.prefix = trimws(unlist(strsplit(lines,"="))[2])
  }
}
timestep.file = paste(result.path, paste0(result.prefix, ".ts"), sep = "/")

data.ts.lines = readLines(timestep.file)[grep("#all", readLines(timestep.file))]
data.ts =  data.ts.lines %>%
              strsplit("\\s+") %>%
              do.call(rbind, .) %>%
              data.frame()
# dim(data.ts)
# Open a pdf file
out.file = paste0(tools::file_path_sans_ext(basename(timestep.file)),"_ccplot.pdf")
pdf(out.file) 
plot(data.ts[,2], data.ts[,15], xlab = "time step", ylab = "correlation")

# Close the pdf file
dev.off() 
