#!/usr/bin/python
import os, sys

def replace_by_word(origin_word, replace_word):
    nLines1 = []
    nLines2 = []
    f_name = file_name
    f_id = open(f_name, 'r')
    nLines1 = f_id.readlines()
    f_id.close()
    os.remove(f_name)
    nLen = len(nLines1)
    kk=0
    while kk < nLen:
        line = nLines1[kk]
        nLines2.append(line.replace(origin_word, replace_word))
        kk = kk+1
        #print line
    f_id = open(f_name, 'w')
    f_id.writelines(nLines2)
    f_id.close()

def remove_H(in_file, out_file):
    with open(in_file,'r') as fin, open(out_file, 'w') as fout :  
        xyz = []
        for line in fin:
            Hydrogen_present = False
            n = line[12:16].strip()
            for i in range(len(n)):
              if (n[i] == "H"):
                Hydrogen_present = True
            if (line.startswith("ATOM")==1 and Hydrogen_present==False):
              fout.write(line)        

#==========================================================================
# start program
#==========================================================================

# check if argument is there
if len(sys.argv) == 2:
        file_name = sys.argv[1]
        replace_by_word("GUA", "G  ")
        replace_by_word("ADE", "A  ")
        replace_by_word("CYT", "C  ")
        replace_by_word("URI", "U  ")
        ## remove H atoms and write new PDB
        in_file = file_name
        out_file = "refine_final1.pdb"
        remove_H(in_file, out_file )
         
        
else:
    message = """
ERROR: missing pdb filename as argument
usage: %s file.pdb""" %(sys.argv[0])
    sys.exit(message)
#==========================================================================

