## Make a destination directory to copy one PDB file from each folder containing the top PDBs for each Kappa.
## Usage: Rscript collect_topPDB.R input.folder 
## input.folder is the master folder that contains the kappa folders
## the destination folder is named topPDBs by default

args = commandArgs(trailingOnly=TRUE)
if (length(args)!=1) {
  cat("Make a destination directory to copy one PDB file from each sub-folder containing the top PDBs\n")
  cat("Usage:\n")
  cat("       Rscript collect_topPDB.R input_folder\n")
  cat("       input_folder    master folder that contains the kappa/z-scan folders\n")
  cat("       The pdbs are written in output directory is called topPDBs\n\n")
  quit()
}

in.folder = args[1]
out.folder = "topPDBs"
unlink(out.folder, recursive = T) ## remove output directory if exists.
dir.create(out.folder)
# dest.folder = "/Users/bhandariyr/Documents/projects/afm/docs/yxw_files/PCA/rnaseP/topPDBs" 
# in.folder = "/data/PNAI/yuntzai/CafeMol_AFM/cafe_runs/trRNaseP/yxw_results/Particle4class/"

P_pdb_to_avoid = c()  ## if nothing leave empty 
P_pdb_to_avoid = paste("P", P_pdb_to_avoid, sep = "")

S_pdb_to_avoid = c()
S_pdb_to_avoid = paste("S", S_pdb_to_avoid, sep = "")

pdb_to_avoid = unique(c(P_pdb_to_avoid, S_pdb_to_avoid))
#length(pdb_to_avoid)

files = list.files(path = in.folder )
print(length(files))
print(files)
count = 0
for (file in files){
  if (!file %in% pdb_to_avoid) {
  pdb.filepath = paste(in.folder, file, sep = "/")
  pdb.files = list.files(pdb.filepath, pattern = ".pdb")
  #print(paste("pdb file names: ", pdb.files, sep = " "))
  ## copy the first pdb file from each directory
  if (!is.na(pdb.files[1])){
    #print(pdb.files[1])
    count = count + 1
    base.pdb = paste(tools::file_path_sans_ext(basename(pdb.files[1])), "_", file, ".pdb", sep = "")
    file.copy(paste(pdb.filepath, pdb.files[1], sep = "/"), 
              paste(out.folder, base.pdb, sep = "/"))
  }
  }
  }
print(paste("total PDBs added: ", count, sep=""))

## Quick check to see if the filter for pdb_to_avoid worked
test.path = "/data/PNAI/yuntzai/CafeMol_AFM/cafe_runs/trRNaseP/yxw_results/Particle4class/"
files = list.files(path = test.path)
print("Printing folders that are removed")
print(files[files %in% pdb_to_avoid])



