## Edit pdb file to subtract a constant number from X, Y or Z columns

library(bio3d)

args = commandArgs(trailingOnly=TRUE)
if (length(args) == 0) {
  cat("Subtract a constant number from X,Y, or Z columns in a PDB file \n")
  cat("Usage: \n")
  cat("      Rscript edit_pdb.R pdb_file axes Num\n\n")
  cat("      pdb_file   input pdb file \n")
  cat("      axes       either X, Y or Z \n")
  cat("      Num        constant number to subtract\n")
  cat("      Example: Rscript edit_pdb.R pdb_file Z 20 \n")
  quit()
}  
input.pdb = args[1]
coor.col = toupper(args[2])
const.num = as.numeric(args[3])
# setwd("/Users/bhandariyr/Documents/projects/afm/scripts/edit_pdb/")

# input.pdb = "/Users/bhandariyr/Documents/projects/afm/scripts/edit_pdb/best_cc_frame_2434.pdb"
# coor.col = "X"
# const.num = 20

pdb = read.pdb2(input.pdb)

if (coor.col == "X"){
  pdb$atom$x = pdb$atom$x - const.num
} else {
  if ( coor.col == "Y") {
    pdb$atom$y = pdb$atom$y - const.num
  } else {
    if (coor.col == "Z"){
      pdb$atom$z = pdb$atom$z - const.num
    }
  }
} 

xyz.mat = cbind(pdb$atom$x, pdb$atom$y, pdb$atom$z )
# class(xyz.mat)
xyz.vec = as.vector(t(xyz.mat))

out.pdb = paste0(tools::file_path_sans_ext(basename(input.pdb)),"_mod.pdb")
write.pdb(pdb, xyz=xyz.vec, 
          file=out.pdb)


