#!/usr/bin/env python
from optparse import OptionParser

parser = OptionParser()
options,args = parser.parse_args()

import sys, os
import ROOT
from ROOT import TFile, gDirectory
from rootpy.common import getObjects

def recursive_ls(path="",depth=0):
    prefix = '   '*depth
    dir = gDirectory.GetDirectory(path)
    if not dir:
        print "unable to traverse into directory %s"%dir
        return
    objects = getObjects(dir)
    for thing in objects:
        if isinstance(thing,ROOT.TDirectory):
            print prefix+thing.GetName()
            recursive_ls("/".join([path,thing.GetName()]),depth+1)
        else:
            print "%s %s"%(prefix+thing.__class__.__name__,thing.GetName())
            if hasattr(thing,"GetEntries"):
                print prefix+" Entries: %i"%thing.GetEntries()
            if hasattr(thing,"GetWeight"):
                print prefix+" Weight: %e"%thing.GetWeight()
            if hasattr(thing,"Integral"):
                print prefix+" Integral: %e"%thing.Integral()
            if hasattr(thing,"GetListOfFriends"):
                friends = thing.GetListOfFriends()
                if friends:
                    print prefix+" Friends:"
                    for friend in friends:
                        print prefix+" %s in %s"%(friend.GetName(),friend.GetTitle())
            
for filename in args:
    if not os.path.isfile(filename):
        print "file %s does not exist"%filename
        sys.exit(1)
    file = TFile.Open(filename)
    if not file:
        print "could not open file %s"%filename
    recursive_ls("")

