#!/usr/bin/python
import os
import sys
import re

if sys.platform == 'win32': 
  import utils
  utils.redirectOutput('run_povray')

print "run_povray sys.argv",sys.argv

#Intercept -help command before trying to run povray
if sys.argv.count('-help'):
  print """
  CCP4mg run POV-Ray
  
  -help             Print this help
  -i filename       Input command file
  -o filename       Output file  
  -w width
  -h height
  -c commands       Command line commands
  -p executable     Full path name of POVRay executable
"""
  sys.exit()
  
cmd_file = ''
fileout = 'povray.png'
height = 300
width = 300
cmd_line = ' +A +J0 +Q9 -D'
povray = 'povray'
log = 0

# Read command line args
i=1
while i < len(sys.argv):
  if re.match('-i',sys.argv[i]):
    i=i+1
    cmd_file = sys.argv[i]
  elif re.match('-o',sys.argv[i]):
    i=i+1
    fileout = sys.argv[i]
  elif re.match('-w',sys.argv[i]):
    i=i+1
    width = int(sys.argv[i])
  elif re.match('-h',sys.argv[i]):
    i=i+1
    height = int(sys.argv[i])
  elif re.match('-c',sys.argv[i]):
    i=i+1
    cmd_line = sys.argv[i]
  elif re.match('-p',sys.argv[i]):
    i=i+1
    povray = sys.argv[i]
  elif re.match('-l',sys.argv[i]):
    i=i+1
    log = int(sys.argv[i])
  i = i + 1


#print "run_povray",cmd_file

import mg_ex_utility
ex_ut = mg_ex_utility.mg_ex_utility()
  
# No cmd_file -> no hope
if not cmd_file:
  print "ERROR in CCP4mg run POV-Ray: no command file"
  ex_ut.WriteLog(status="FAILED in run POV-Ray: no command file" )
  sys.exit()
if not os.path.exists(cmd_file):
  print "ERROR in CCP4mg run POV-Ray:"+cmd_file+'not found'
  ex_ut.WriteLog(status="FAILED in run POV-Ray:"+cmd_file+'not found' )
  sys.exit()

if sys.platform == 'win32':
  # This is to deal with a really annoying flaw in PovRay
  fileout = fileout.split('/')
  _fo = ''
  if(len(fileout)>0):
    if fileout[0].find(':') > 0:
      fileout[0] = fileout[0] + '\\'
  for fobit in fileout:
    _fo = os.path.join(_fo,fobit)
  fileout = _fo
  cmd_file = cmd_file.split('/')
  _fi = ''
  if(len(cmd_file)>0):
    if cmd_file[0].find(':') > 0:
      cmd_file[0] = cmd_file[0] + '\\'
  for fobit in cmd_file:
    _fi = os.path.join(_fi,fobit)
  cmd_file = _fi

if os.path.exists(fileout):os.remove(fileout)
logfile = os.path.splitext(fileout)[0]+'_povray.log'

if sys.platform == 'win32':
  cmd = povray + ' ' + cmd_file + ' +W' + str(width) + ' +H'+str(height)+ cmd_line + ' +O' + fileout
else:
  cmd = povray + ' ' + cmd_file + ' +W' + str(width) + ' +H'+str(height)+ cmd_line + ' +O' + fileout

if log:
 cmd = cmd+' +GA'+logfile
else:
 cmd = cmd+' -GA'
 
print "cmd",cmd
ret = os.system(cmd)
if ret:
  ex_ut.WriteLog(status="FAILED Can not run POV-Ray")
  sys.exit()


ex_ut.WriteLog(status="FINISHED")
if sys.platform == 'win32': sys.stdout.close()
sys.exit()
