from __future__ import division
# LIBTBX_SET_DISPATCHER_NAME phenix.pdb.mtrix_reconstruction

from iotbx import pdb
from libtbx.utils import Sorry
from  iotbx.pdb.multimer_reconstruction import multimer
import sys, os

def mtrix_reconstruction(args, command_name="phenix.pdb.mtrix_reconstruction"):
  ''' (string) -> file

  Reconstruction of the crystallographic asymmetric unit by applying
  MTRIX transformation, from the MTRIX records in the pdb file, to all chains in file.

  Produce a new pdb file containg the rystallographic asymmetric unit information

  Arguments:
  args: a string containing the pdb file name, 'file_name.pdb' and an optional output file name
        if no file name is given, the output file will have the name 'cryst_asym_unit_file_name.pdb'

  >>> phenix.pdb.mtrix_reconstruction input_file_name.pdb
  mtrix-assembly reconstructed pdb file was added to your current directory
  /path/cryst_asym_unit_input_file_name.pdb

   >>> phenix.pdb.mtrix_reconstruction input_file_name.pdb 'output_file_name.pdb
  mtrix-assembly reconstructed pdb file was added to your current directory
  /path/output_file_name.pdb

  @author: Youval Dar (LBL 2013)
  '''
  if (len(args) == 0):
    raise Sorry('No input filename is given. Please provide a pdb file name. \n' + \
                '>>> phenix.pdb.mtrix_reconstruction input_file_name.pdb')
  elif ('--help' in args) or ('-h' in args):
    print help(mtrix_reconstruction)
  elif (len(args) > 2):
    raise Sorry('To many input parameters are given')
  elif not os.path.isfile(args[0]):
    print 'There is no file {} in the current directory \n {}'.format(args[0],os.getcwd())
    raise Sorry('File name error')
  else:
    m = multimer(file_name=args[0],reconstruction_type='cau')
    if m.number_of_transforms > 0:
      # write the mtrix-assembly reconstructed file in current directory
      if len(args) == 2:
        # output file name given
        m.write(args[1])
        print '%s was added to your current directory'%args[1]
      else:
        # output file name not given
        m.write()
        print '%s was added to your current directory'%m.pdb_output_file_name
    else:
      print 'No MTRIX information in {}'.format(args[0])

if (__name__ == "__main__"):
  mtrix_reconstruction(args=sys.argv[1:])
