#! /usr/bin/env python
################################################################################
#
# Copyright (c) 2011 The MadGraph Development team and Contributors
#
# This file is a part of the MadGraph 5 project, an application which 
# automatically generates Feynman diagrams and matrix elements for arbitrary
# high-energy processes in the Standard Model and beyond.
#
# It is subject to the MadGraph license which should accompany this 
# distribution.
#
# For more information, please visit: http://madgraph.phys.ucl.ac.be
#
################################################################################
""" This is the main script in order to generate events in MadEvent """

import logging
import logging.config
import os
import re
import shutil
import subprocess
import sys
import time

root_path = os.path.split(os.path.dirname(os.path.realpath( __file__ )))[0]
pjoin = os.path.join

if not sys.version_info[0] == 2 or sys.version_info[1] < 6:
    sys.exit('MadEvent works with python 2.6 or higher (but not python 3.X).\n\
               Please upgrade your version of python.')

# Check if optimize mode is (and should be) activated
if __debug__ and (not os.path.exists(pjoin(root_path,'../..', 'bin','create_release.py'))):
    print 'launch in debug mode'
    subprocess.call([sys.executable] + ['-O'] + sys.argv)
    sys.exit()


sys.path.append(pjoin(root_path,'bin','internal'))
import madevent_interface as ME        


import logging
import logging.config

try: 
    import readline
except ImportError:
    try:
        import pyreadline as readline
    except:
        print "For tab completion and history, install module readline."
else:
    import rlcompleter

    if 'r261:67515' in sys.version and  'GCC 4.2.1 (Apple Inc. build 5646)' in sys.version:
        readline.parse_and_bind("bind ^I rl_complete")
        readline.__doc__ = 'libedit'  
    
    elif hasattr(readline, '__doc__'):
        if 'libedit' not in readline.__doc__:
            readline.parse_and_bind("tab: complete")
        else:
            readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.__doc__ = 'GNU'
        readline.parse_and_bind("tab: complete")
        
    # charge history file
    try:
        history_file = os.path.join(os.environ['HOME'], '.mg5', 'me5history')
        readline.read_history_file(history_file)
    except:
        pass

try:
   import psyco
   psyco.full()
except:
   pass

if __debug__:
        print 'Running MG5 in debug mode'



def set_configuration():
    import coloring_logging
    logging.config.fileConfig(os.path.join(root_path, 'bin', 'internal', 'me5_logging.conf'))
    logging.root.setLevel(logging.INFO)
    logging.getLogger('madevent').setLevel(logging.INFO)
    logging.getLogger('madgraph').setLevel(logging.INFO)    


def treat_old_argument(argument):
    """Have the MG4 behavior for this script"""

    try:
        mode = int(argument[1])
    except:
        mode = int(raw_input('Enter 2 for multi-core, 1 for parallel, 0 for serial run\n'))
    if mode == 0:
        try:
            name = argument[2]
        except:
            name = raw_input('Enter run name\n')
    else:
        try:
            opt = argument[2]
        except:
            if mode == 1: 
                opt = raw_input('Enter name for jobs on pbs queue\n')
            else:
                opt = int(raw_input('Enter number of cores\n'))
        
        try:
            name = argument[3]
        except:
            name = raw_input('enter run name\n')

#    launch = ME.MadEventCmd(me_dir=root_path)
        

    if mode == 1:
        argument = ['fake','-f', str(name), '--cluster']
    elif mode == 2:
        argument = ['fake','-f', '--multicore', str(name), '--nb_core=%s' % opt]
    else:
        argument = ['fake','-f', name, '--nb_core=1']

    return argument







################################################################################  
##   EXECUTABLE
################################################################################                                
if '__main__' == __name__:
    # Check that python version is valid

    set_configuration()
    argument = sys.argv
    try:
        if '-h' in argument or '--help' in argument:
            launch = ME.MadEventCmd(me_dir=root_path)
            launch.exec_cmd('help generate_events')
            sys.exit()
        elif len(argument) > 1 and argument[1] in ['0', '1', '2']:
            argument = treat_old_argument(argument)
        
        launch = ME.MadEventCmd(me_dir=root_path)
        launch.run_cmd('generate_events %s' % ' '.join(argument[1:]))
        launch.run_cmd('quit')
    except KeyboardInterrupt:
        try:
            launch.run_cmd('quit')
        except:
            pass
    except ME.MadEventAlreadyRunning, error:
        logging.error(str(error))
        sys.exit()
                          
    if os.path.exists(pjoin(root_path, 'RunWeb')):  
        os.remove(pjoin(root_path, 'RunWeb'))      
            
    # reconfigure path for the web 
    #if len(argument) == 5:
    #    ME.pass_in_web_mode()

             
        

        
    
    
    
    
    
    
    
