#!/usr/bin/python
import os,sys
from process import process
import common


class mb(process):
  name="real space model building"
  name="model tracing"
  supported_progs=["buccaneer"]
  supported_params={}
  supported_params['from_weighted_map'] = common.parameter(desc='Build from weigted maps (if available)',typ=bool)

  def TreatInOutPar(self, set_all_par=False):
    if not self.GetProg(supported=True):
      self.AddProg('buccaneer')
    process.TreatInOutPar(self,set_all_par)

  def RunPostprocess(self,restore=True,*args,**kwargs):
    prog=self.GetProg()
    self.Info('')
    self.Info("{0} residues in {1} fragments built.".format(
      prog.GetStat('res_built'), prog.GetStat('frag_built')))
    self.Info("Completness of uniquely located residues against sequence {0}%, against built {1}%.".format(
      prog.GetStat('compl_chain'), prog.GetStat('compl_res')))
    self.Info('')
    # temporary and bad workaround for the problem of hybrid36 incompatibility between buccaneer and refmac
    # all the non-numerical seqID residues from the built models are removed!
    h36=False
    new_cont=[]
    out_pdb=self.out.Get('model',filetype='pdb').GetFileName()
    with open(out_pdb) as f:
      for line in f:
        if (line.startswith('ATOM') or line.startswith('HETATM')) and \
           len(line)>60 and line[22]!=' ' and line[22] not in [str(i) for i in range(10)]:
          h36=True
        else:
          new_cont.append(line)
    if h36:
      common.Warning('Hybrid36 extension residues found in the built PDB. These residues will be removed as Refmac does not support hybrid36.')
      new_pdb=out_pdb[:-4]+'_h36_removed.pdb'
      with open(new_pdb,'w') as g:
        for line in new_cont:
          g.write(line)
      self.out.AddFileToChild(self.out.Get('model',filetype='pdb'), new_pdb)
    process.RunPostprocess(self,restore,*args,**kwargs)
