import getopt
import os
import profile
import pstats
import sys

from Products.ParsedXML.DOM import Core, ExpatBuilder
from Products.ParsedXML.ExtraDOM import writeStream


FILE = os.path.join(sys.modules['Products.ParsedXML'].__path__[0],
    'tests', 'xml', '4ohn4ktj.xml')
PROFILEDATA = "@parsefile.prof"


def parsefile(filename, namespaces):
    return ExpatBuilder.parse(filename, namespaces=namespaces)

def printDOM(document):
    writeStream(document)


_getattr_counts = {}

def main():
    namespaces = 1
    profiledata = None
    proflines = 20
    filename = FILE
    opts, args = getopt.getopt(sys.argv[1:], "nd:p:")
    for opt, arg in opts:
        if opt == "-n":
            namespaces = not namespaces
        elif opt == "-p":
            proflines = int(arg)
        elif opt == "-d":
            profiledata = arg
    if len(args) >= 2:
        print "One file at a time, please!"
        sys.exit(2)
    elif args:
        filename = args[0]

    doc = parsefile(filename, namespaces)
    profiler = profile.Profile()
    profiler.runctx('printDOM(doc)', locals(), globals())
    profiler.dump_stats(profiledata or PROFILEDATA)
    p = pstats.Stats(profiledata or PROFILEDATA)
    p.strip_dirs().sort_stats('time').print_stats(proflines)
    #p.print_callers(proflines)
    #p.strip_dirs().sort_stats('cum').print_stats(proflines)
    if not profiledata:
        os.unlink(PROFILEDATA)


if __name__ == "__main__":
    main()
