# > !NewsStats.!RunImage

import os, sys, swi, traceback

debug = 0     # debugging mode (throwback etc)
profile = 0   # profiling switched on

sys.path.insert(0, '<NewsStats$Dir>.py')
import Main, wimp

if debug:
    sys.stderr = sys.stdout = open('<NewsStats$Dir>.^.Output', 'w')

if debug > 1:
    depth = 0
    def trace(frame, event, arg):
        global depth
        if event == 'line':
            print depth * ' ', frame.f_lineno
        elif event == 'call':
            print depth * ' ', frame.f_code.co_name + '(', arg, ')'
            depth = depth + 1
        elif event == 'return':
            print depth * ' ', 'return', arg
            depth = depth - 1
        else:
            print depth * ' ', event + ':', arg
        return trace
    sys.settrace(trace)

try:
    if profile:
        import profile
        profile.run('Main.main()', '<NewsStats$Dir>.^.Profile')
    else:
        Main.main()
except SystemExit:
    pass
except RuntimeError, value:
    swi.swi(0x400df, 'sis', '    ' + str(value), 1, wimp.task_name)
except:
    if debug > 1:
        sys.settrace(None)
   
    type, value, traceb = sys.exc_info()
    swi.swi(0x400df, 'sis', '    Internal error - must exit (' + str(type) + ': ' + str(value) + ')',
                            1, wimp.task_name)

    if debug:
        traceback.print_exc()
        trace = traceback.extract_tb(traceb)
        try:
            swi.swi('DDEUtils_ThrowbackStart', '')
            swi.swi('DDEUtils_ThrowbackSend', '0.s', trace[-1][0])
            swi.swi('DDEUtils_ThrowbackSend', '1.si1s', trace[-1][0], trace[-1][1],
                                              str(type) + ': ' + trace[-1][2] + ': ' + trace[-1][3])
            swi.swi('DDEUtils_ThrowbackEnd', '')
        except:
            pass
    
        if sys.stderr.tell() > 0:
            sys.stderr.close()
            os.system('Filer_Run <NewsStats$Dir>.^.Output')
        else:
            sys.stderr.close()

if wimp.task_handle:
    # Wimp_CloseDown
    swi.swi(0x400dd, 'ii', wimp.task_handle, 0x4b534154)
