## Process the CG model of PDB file generated by cafemol initial run
## Does coordiante scaling and pdb formatting for preparing the pdb file for Cafemol AFM fit run
## Usage: Rscript process_pdb_cg.R input.pdb

# install.packages("bio3d")
library(bio3d)

#!/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 initial PDB file", call.=FALSE)
}
input.pdb = args[1]
pdb = read.pdb2(input.pdb)
# class(pdb)
# dim(pdb$xyz)
#min(pdb$atom$x)
pdb$atom$x =  pdb$atom$x - min(pdb$atom$x) + 2
pdb$atom$y =  pdb$atom$y - min(pdb$atom$y) + 2
pdb$atom$z =  pdb$atom$z - min(pdb$atom$z) + 2
xyz.mat = cbind(pdb$atom$x, pdb$atom$y, pdb$atom$z )
# class(xyz.mat)
xyz.vec = as.vector(t(xyz.mat))
# head(xyz.mat)
# head(xyz.vec)
# 
#xyz = pdb$xyz + round(-min(pdb$xyz)+2)
## set the spacing with respect to resid
pdb$atom$resid = paste0(pdb$atom$resid, " ")
# write the new pdb object to file
#write.pdb(pdb, xyz=xyz, file="/Users/bhandariyr/Documents/projects/afm/cafemol/dimer/run1/cbl_dimer_frame1000_offset.pdb")
out.pdb = paste0(tools::file_path_sans_ext(basename(input.pdb)),"_offset.pdb")
write.pdb(pdb, xyz=xyz.vec, 
          file=out.pdb)

# pdb$atom[1:4,]
# scp -pr /Users/bhandariyr/Documents/projects/afm/cafemol/test_run/cbl_run1_offset.pdb bhandariyr@biowulf.nih.gov:/gpfs/gsfs12/users/bhandariyr/cafemol/cafemol/example/cbl_afm_fit/pdb





