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

class buccaneer(program):
  name="Buccaneer"
  binary="cbuccaneer"
  labelout_prefix="BUCC_"
  modif='-'
  always_merge=True
  stat={}
  stat['res_built'] = common.stats(name='number of residues built', regexp=r"(\d+)\s+residues were built in\s+\d+\s+fragments,")
  stat['frag_built'] = common.stats(name='number of fragments built', regexp=r"\d+\s+residues were built in\s+(\d+)\s+fragments,")
  stat['compl_res'] = common.stats(name='completness by residues built', regexp=r"Completeness by residues built:\s+(\S+)\%")
  stat['compl_chain'] = common.stats(name='completness of chains', regexp=r"Completeness of chains \(number\):\s+(\S+)\%")
  references = ( "Cowtan K. (2006) The Buccaneer software for automated model building. 1. "+
                 "Tracing protein chains. Acta Cryst. D62, 1002-1011.", )

  def Init(self):
    self.SetArg('stdin')

  def TreatInput(self):
    # F,sigF
    self.fsf = self.inp.Get('fsigf',typ='average',col='f')
    if self.fsf:
      self.SetKey('mtzin-wrk', self.fsf.GetFileName('mtz'))
      self.SetKey('colin-wrk-fo', self.fsf.GetFullLabel('f','sigf'))
    else:
      common.Error('No data inputted for {0}'.format(self.name))
    for mapc in self.inp.GetAll('mapcoef',typ=('best','combined'),filetype='mtz'):
      if mapc.GetLabel('hla'):
        self.SetKey('colin-hl', mapc.GetFullLabel('hla','hlb','hlc','hld'))
        break
      if mapc.GetLabel('ph') and mapc.GetLabel('fom'):
        self.SetKey('colin-phifom', mapc.GetFullLabel('ph','fom'))
        break
    else:
      common.Error('No phase distribution inputted for {0}'.format(self.name))
    # free assignment
    free=self.inp.Get('exclude',typ='freeR',col='free')
    if free:
      self.SetKey( 'colin-free', free.GetFullLabel('free') )
    # input map (optional - phase distr. and Fo used if not inputted)
    mapc = self.inp.Get('mapcoef', col=('f','ph'), custom='build')
    if not mapc and self.process.GetVirtPar('from_weighted_map'):
      mapc = self.inp.Get('mapcoef',typ='weighted',col=('f','ph'))
    if mapc:
      self.SetKey('colin-wrk-fc', mapc.GetFullLabel('f','ph'))
    # sequence
    if self.inp.Get('sequence') and self.inp.Get('sequence').GetFileName():
      self.SetKey('seqin-wrk', self.inp.Get('sequence').GetFileName())
    if self.inp.Get('model',typ=('partial','partial+substr'),filetype='pdb'):
      self.SetKey('pdbin-wrk', self.inp.Get('model',typ=('partial','partial+substr')).GetFileName('pdb'))
      if not self.IsKey('correlation-mode'):
        self.SetKey('correlation-mode', True)

  def DefineOutput(self):
    out_model = self.out.AddNew( 'model', self.nick+'.pdb', typ='partial', xname=self.fsf.xname )

  def TreatOutput(self):
    self.SetKey( 'pdbout-wrk', self.out.model[-1].GetFileName('pdb') )
