#!/usr/bin/python
# fixpdb.py
# This script is used to renumber residue index .
# By Qiuyu Fu

import sys,os

if len(sys.argv)<3:
    print "Usage: $0 in.pdb out.pdb"
    sys.exit(0)
infile,outfile=sys.argv[1:3]

ifp=open(infile,"r")
ofp=open(outfile,"w")

ofp.write("REMARK this file is generated by fixinsertresidu.py\n")

offset=0
insert=' '
oldresinum=0
for line in ifp:
    linetype=line[:6]
    if linetype=="ATOM  " or linetype=="HETATM":
        resinum=int(line[22:26])
        if (line[26]!=insert and resinum==oldresinum):
            offset=offset+1
        insert=line[26]
        oldresinum=resinum
        line=line[:22]+"%4d"%(resinum+offset)+" "+line[27:]
    elif linetype[:3]=="TER":
        offset=0
    ofp.write(line)

ifp.close()
ofp.close()

