#! /usr/bin/env python

"""\
%prog <datafile1> [<datafile2> ...]

List the contents of YODA-readable data files (sorted by path name).
"""

import yoda, sys, optparse
from yoda.script_helpers import filter_aos

parser = optparse.OptionParser(usage=__doc__)
parser.add_option('-v', '--verbose', action="store_const", const=2, default=1, dest='VERBOSITY',
                  help="print extra histogram details")
parser.add_option('-q', '--quiet', action="store_const", const=0, default=1, dest='VERBOSITY',
                  help="just print histogram details, no cosmetic filenames or blank lines")
parser.add_option("-m", "--match", dest="MATCH", metavar="PATT", default=None,
                  help="only write out histograms whose path matches this regex")
parser.add_option("-M", "--unmatch", dest="UNMATCH", metavar="PATT", default=None,
                  help="exclude histograms whose path matches this regex")
opts, filenames = parser.parse_args()

if not filenames:
    print "ERROR! Please supply at least one data file for listing"
    sys.exit(1)

for i, f in enumerate(filenames):
    if opts.VERBOSITY >= 1:
        if i > 0: print
        print "Data objects in %s:" % f
    aodict = yoda.read(f)
    filter_aos(aodict, opts.MATCH, opts.UNMATCH)
    for p, ao in sorted(aodict.iteritems()):
        extrainfo = ""
        if opts.VERBOSITY >= 2 and hasattr(ao, "sumW"):
            extrainfo = " sumW={sumw:.3g}".format(sumw=ao.sumW())
        try:
            nobjstr = "{n:4d}".format(n=len(ao))
        except:
            nobjstr = "   -"
        print "{path:<50} {type:<10} {nobjs} bins/pts".format(path=p, type=ao.type, nobjs=nobjstr) + extrainfo
