
"""
Overrides the default exception handler with our own.
This exception handler filters out lines in the stack trace that are in SWIG auto generated files
"""

import sys
import trick
import traceback

def noswig_excepthook(exctype, value, tb):
    # autogen_dir holds the autogenerated directory in the simulation
    autogen_dir = trick.command_line_args_get_default_dir() + "/trick"
    # stack_trace contains the traceback information as a list of tuples.
    # The tuples hold the (file_name, line, function name, text)
    stack_trace = traceback.extract_tb(tb)
    # Interate through the traceback stopping at the first line where
    # the file_name resides in the generated directory
    ii = 0
    for item in stack_trace:
        if  item[0].startswith(autogen_dir):
            break
        ii += 1
    # print the traceback up to the point where the auto generated code starts
    traceback.print_exception(exctype, value, tb, ii)

# set the exception handler to ours.
sys.excepthook = noswig_excepthook

# This function can be called to restore the default exception hook.
def set_default_excepthook():
    sys.excepthook = sys.__excepthook__

