"""
Debugging Helper Functions
"""
#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  $Id: debug.py 82 2004-07-11 13:01:44Z henning $

import types, string, sys
from traceback import *

class nullOutput:
    "A do-nothing file (output) class"
    def write(self, var):
        pass

stdout = sys.stdout or nullOutput()

traceOutput = stdout
watchOutput = stdout
rawOutput = stdout

def watch(variableName):
    if __debug__:
        stack = extract_stack()[-2:][0]
        actualCall = stack[3]
        if actualCall is None:
            actualCall = "watch([unknown])"
        left = string.find(actualCall, "(")
        right = string.rfind(actualCall, ")")
        paramDict = {}
        paramDict["varName"] = string.strip(
            actualCall[left+1:right])
        paramDict["varType"] = str(type(variableName))[7:-2]
        paramDict["value"] = repr(variableName)
        paramDict["methodName"] = stack[2]
        paramDict["lineNumber"] = stack[1]
        paramDict["fileName"] = stack[0]
        outStr = 'File "%(fileName)s", line %(lineNumber)d, in' \
                ' %(methodName)s\n  %(varName)s <%(varType)s>' \
                ' = %(value)s\n\n'
        watchOutput.write(outStr % paramDict)

def trace(text):
    if __debug__:
        stack = extract_stack()[-2:][0]
        paramDict = {}
        paramDict["methodName"] = stack[2]
        paramDict["lineNumber"] = stack[1]
        paramDict["fileName"] = stack[0]
        paramDict["text"] = text
        outStr = 'File "%(fileName)s", line %(lineNumber)d, in' \
                ' %(methodName)s\n  %(text)s\n\n'
        traceOutput.write(outStr % paramDict)

def raw(text):
    if __debug__:
        try:
            rawOutput.write(text)
        except IOError:
            pass
                
def echo(text):
    raw(text+"\n")
