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

class shelxd(program):
  name="SHELXD"
  binary="shelxd"
  never_merge=True
  stat={}
  stat['ccweak'] = common.stats(name='correlation coef. (weak reflections mean)', 
    regexp=r"CC All\/Weak\s+\S+\s+\/\s+(\S+?)\,?\s+")
  stat['cc'] = common.stats(name='correlation coef. (all reflections mean)', 
    regexp=r"CC All\/Weak\s+(\S+)\s+\/\s+\S+?\,?\s+")
  stat['try'] = common.stats(name='try number', regexp=r"Try\s+(\d+),")
  stat['patfom'] = common.stats(name='Patterson FOM', 
    regexp=r"\s+PATFOM\s+(\S+)")
  references = ( "Sheldrick GM (2008) A short history of SHELX. " +
                 "Acta Cryst. A64, 112-122.", )


  def Interact_output(self, line, popen, empty):
    self.process.UpdateInfo(line)

  def Stop(self,popen=None):
    with open(self.project+'.fin', 'w') as f:
      f.write('fin.')

  def TreatInput(self):
    self.fa=self.inp.Get('fsigf', typ='fa', filetype='hkl')
    if not self.fa:
      common.Error('FA values not inputted to {0}'.format(self.name))
    ins=self.inp.Get('datafile', filetype='ins')
    if not ins:
      common.Error('.ins file not inputted to {0}'.format(self.name))
    # make sure the inp and hkl file names are as shelxd expects them
    if self.fa.GetFileName('hkl').endswith('.hkl'):
      self.project=self.fa.GetFileName('hkl')[:-4]
    else:
      self.project=self.fa.GetFileName('hkl')
      shutil.copy(self.project, self.project+'.hkl')
      self.fa.GetFile('hkl').name+='.hkl'
    if ins.GetFileName('ins')!=self.project+'.ins':
      shutil.copy(ins.GetFileName('ins'), self.project+'.ins')
      ins.GetFile('ins').name+='.ins'
    # we need to do the relative path manually here as such a file does not exist...
    self.SetArg(os.path.relpath(self.fa.GetFileName('hkl')[:-4], self.rundir))


  def TreatParams(self):
    if self.process.GetVirtPar('num_trials') and not self.GetKey('NTRY'):
      self.SetKey('NTRY', self.process.GetVirtPar('num_trials'))
    if self.process.GetParam('expected_num_atoms') and not self.GetKey('FIND'):
      self.SetKey('FIND', self.process.GetParam('expected_num_atoms'))
    if self.process.GetParam('high_res_cutoff') and not self.GetKey('SHEL'):
      self.SetKey('SHEL', (999., self.process.GetParam('high_res_cutoff')))
    program.TreatParams(self)


  def DefineOutput(self):
    #if self.inp.Get('model'):
    #  atomtypes,atomtype1=self.inp.Get('model').GetAtomTypes(),self.inp.Get('model').GetAtomType()
    #  xname=self.inp.Get('model').GetCrystalName()
    #  self.out.AddNew('model', self.arg_list[0]+'.pdb', filetype='pdb', typ='substr', \
    #                  atomtypes=atomtypes, atomtype1=atomtype1, xname=xname)
    if self.inp.Get('model',typ='substr'):
      mod=self.out.AddCopy(self.inp.Get('model',typ='substr'))
      self.out.SetFileToChild(mod, self.arg_list[0]+'.pdb', 'pdb')
    else:
      common.Warning('Substructure atom types and crystal name not known!')
      mod=self.out.AddNew('model', self.arg_list[0]+'.pdb', filetype='pdb', typ='substr')
    self.out.AddFileToChild(mod, self.arg_list[0]+'.res', 'res')
