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

class mtz2various(program):
  name="MTZ2VARIOUS"
  binary="mtz2various"
  ccp4_parsing=True
  # mapping between the filetype ('outputformat' parameter) and mtz2various 'output' key value
  out_key = { 'hkl': 'shelx', 'sca': 'scal', 'phs': "user '(3I4,2F7.1,I4)'" }

  def Init(self):
    self.outfilename = {}
    for out in self.out_key: 
      self.outfilename[out] = self.name+'.'+out

  def TreatInput(self):
    self.inpcont=self.inp.GetAll(filetype='mtz')
    if self.inpcont:
      self.SetArg('hklin',self.inpcont[0].GetFileName('mtz'))
      for cont in self.inpcont:
        # intensities get priority over f's
        if cont.GetType()=='plus' and cont.GetLabel('i'):
          self.AddToKey('labin', ('I(+)='+cont.GetLabel('i'), 'SIGI(+)='+cont.GetLabel('sigi')))
        elif cont.GetType()=='plus' and cont.GetLabel('f'):
          self.AddToKey('labin', ('F(+)='+cont.GetLabel('f'), 'SIGF(+)='+cont.GetLabel('sigf')))
        elif cont.GetType()=='minus' and cont.GetLabel('i'):
          self.AddToKey('labin', ('I(-)='+cont.GetLabel('i'), 'SIGI(-)='+cont.GetLabel('sigi')))
        elif cont.GetType()=='minus' and cont.GetLabel('f'):
          self.AddToKey('labin', ('F(-)='+cont.GetLabel('f'), 'SIGF(-)='+cont.GetLabel('sigf')))
        elif cont.GetType()=='average' and cont.GetLabel('i'):
          self.AddToKey('labin', ('I='+cont.GetLabel('i'), 'SIGI='+cont.GetLabel('sigi')))
        elif cont.GetType()=='average' and cont.GetLabel('f'):
          self.AddToKey('labin', ('FP='+cont.GetLabel('f'), 'SIGFP='+cont.GetLabel('sigf')))
    else:
      Error('No mtz file inputted to {0}'.format(self.name))

  def TreatParams(self):
    if not self.process.IsParam('outputformat') and not self.IsKey('output'):
      common.Error('Output file type not specified for {0}'.format(self.name))
    elif not self.IsKey('output'):
      self.SetKey('output', self.out_key[self.process.GetParam('outputformat')])
    else:
      if self.GetKey('output') in out_key.itervalues:
        of = [of for of,o in out_key if o==self.GetKey('output')][0]
        self.process.SetParam('outputformat', of)
      else:
        common.Warning('Output "{0}" not predefined for {1}'.format(self.GetKey('output'),self.name))
    program.TreatParams(self)

  def DefineOutput(self):
    for cont in self.inpcont:
      outcont=self.out.Add(cont)
      outtyp = self.process.GetParam('outputformat')
      self.out.AddFileToChild(outcont, self.outfilename[outtyp], outtyp)

  def TreatOutput(self):
    self.SetArg('hklout', self.out.Get().GetFileName(self.process.GetParam('outputformat')))
