# $CVSHeader: pal8e/src/DSSPParser.py,v 1.4 2005/02/15 01:10:25 indraneel Rel $

# basic DSSP output parser
# Does _not_ count left handed Helix as helix
# stores in Chain Residue format and also as elements

import os, sys
import string

from Log import LogFH
from PSSDParser import Element
from DSSPElements import DSSPElements

class DSSP(dict):
    def __init__(self, logger=None):
        if logger:
            self.logger = logger
            
    def __sort(self, a, b):
        return cmp(self[self.chainID][a]['#'], self[self.chainID][b]['#'])

    def store(self, fname):
        if not os.path.isfile(fname): return 'Err'
        self.fname = os.path.basename(fname)
        fh = file(fname)
        lines = fh.readlines()
        fh.close()
        for (i,line) in enumerate(lines):
            if line[2] == '#':
                break
        lines = lines[i+1:]
        ctr = 0
        for line in lines:
            aa = line[13]
            if aa == '!': continue
            chain=line[11]
            resid=int(line[6:10].lstrip())
            icode=line[10]
            ss=line[16]
            handedness = line[22]
            if (ss == 'H') and (handedness == '-'):
                ss = ' '
            if not self.has_key(chain):
                self[chain]={}
            ctr += 1
            self[chain][(resid, icode)] = {'#':ctr, 'AA':aa, 'SS':[ss]}
        dssp_elements = DSSPElements(self.logger, fname)
        typedef={'H':'H', 'G':'H', 'I':'H', 'E':'E'}
        dssp_elements.setType(typedef)
        self.elements = dssp_elements.getElements()

    def show(self, outfh):
        self.chainID = self.keys()[0]
	residues = self[self.chainID].keys()
	residues.sort(self.__sort)
	for residue in residues:
	    print >> outfh, self[self.chainID][residue]['SS'][0]

if __name__ == '__main__':
    logger = LogFH('x')
    dssp = DSSP(logger)
    dssp.store(sys.argv[1])
    dssp.show(sys.stdout)
