# mengine module for the FreeMOL library

# executable path
import traceback
import os
import freemol

_mengine_exe = None

def validate():
    '''
    make sure that the FREEMOL environment variable is defined and
    that it contains a valid directory path

    returns 1 if valid, 0 if not
    '''
    ok = 0
    global _mengine_exe
    if _mengine_exe != None: # _mengine_exe assigned, so presume valid
        ok = 1
    elif os.environ.has_key('FREEMOL'):
        test_path = os.path.join(os.environ['FREEMOL'],"bin","mengine.exe")
        if os.path.exists(test_path) and os.path.isfile(test_path):
            _mengine_exe = freemol.quote_exe(test_path)
            ok = 1
    elif os.environ.has_key('PYMOL_PATH'):
        test_path = os.path.join(os.environ['PYMOL_PATH'],
                                 "freemol","bin","mengine.exe")
        if os.path.exists(test_path) and os.path.isfile(test_path):
            _mengine_exe = freemol.quote_exe(test_path)
            ok = 1
    return ok

def run(input):
    result = None
    global _mengine_exe
    if _mengine_exe == None:
        validate()
    if _mengine_exe != None:
        try:
            mengine_in, mengine_out, mengine_err = os.popen3(_mengine_exe)
            mengine_in.write(input)
            mengine_in.close()
            output = mengine_out.read()
            error = mengine_err.read()
            mengine_out.close()
            mengine_err.close()
            result = (output,error)
        except:
            print "Error: mengine did not run"
            traceback.print_exc()
    return result

