#! /usr/bin/env python
import lighthisto
import logging
import sys
import os, copy, re

"""%prog

Script for merging aida files

"""

import sys
if sys.version_info[:3] < (2,4,0):
    print "rivet scripts require Python version >= 2.4.0... exiting"
    sys.exit(1)

## Try to load faster but non-standard cElementTree module
try:
    import xml.etree.cElementTree as ET
except ImportError:
    try:
        import cElementTree as ET
    except ImportError:
        try:
            import xml.etree.ElementTree as ET
        except:
            sys.stderr.write("Can't load the ElementTree XML parser: please install it!\n")
            sys.exit(1)

if __name__ == "__main__":
    import logging
    from optparse import OptionParser, OptionGroup
    parser = OptionParser(usage="%prog aidafile aidafile2 [...]")
    parser.add_option("-o", "--out", dest="OUTFILE", default="-")
    parser.add_option("--append", dest="APPEND_OUTPUT", action="store_true", default=False)
    verbgroup = OptionGroup(parser, "Verbosity control")
    verbgroup.add_option("-v", "--verbose", action="store_const", const=logging.DEBUG, dest="LOGLEVEL",
                         default=logging.INFO, help="print debug (very verbose) messages")
    verbgroup.add_option("-q", "--quiet", action="store_const", const=logging.WARNING, dest="LOGLEVEL",
                         default=logging.INFO, help="be very quiet")
    parser.add_option_group(verbgroup)
    (opts, args) = parser.parse_args()
    logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")

    ## Prefix used in dat file headers
    headerprefix = "# "

    ## Check args
    if len(args) < 1:
        logging.error("Must specify at least one AIDA histogram file")
        sys.exit(1)

    ## Get histos
    outhistos={}
    for file in args:
        if not os.access(file, os.R_OK):
            logging.error("%s can not be read" % file)
            break
        try:
            tree = ET.parse(file)
        except:
            logging.error("%s can not be parsed as XML" % file)
            break
        tree = ET.parse(file)
        ## Get histos from this AIDA file
        for dps in tree.findall("dataPointSet"):
            h = lighthisto.Histo.fromDPS(dps)
            if(h.fullPath().find("D0_2010_S8821313")>0) :
                if(h.fullPath().find("d01")>0 and file.find("-e")>0) : 
                    outhistos[h.fullPath()] = h
                elif(h.fullPath().find("d02")>0 and file.find("-mu")>0) : 
                    outhistos[h.fullPath()] = h
            else :
                outhistos[h.fullPath()] = h

    ## Choose output file
    out = None
    if opts.OUTFILE == "-":
        out = sys.stdout
    else:
        if opts.APPEND_OUTPUT:
            out = open(opts.OUTFILE, "a")
        else:
            out = open(opts.OUTFILE, "w")


   # Choose output file
    out = None
    if opts.OUTFILE == "-":
        out = sys.stdout
    else:
        if opts.APPEND_OUTPUT:
            out = open(opts.OUTFILE, "a")
        else:
            out = open(opts.OUTFILE, "w")
   ## Write out merged histos
    out.write('<?xml version="1.0" encoding="ISO-8859-1" ?>\n')
    out.write('<!DOCTYPE aida SYSTEM "http://aida.freehep.org/schemas/3.3/aida.dtd">\n')
    out.write('<aida version="3.3">\n')
    out.write('  <implementation version="1.1" package="FreeHEP"/>\n')
    for hpath, h in sorted(outhistos.iteritems()):
        logging.debug("hpath = %s" % hpath)
        out.write(h.asAIDA() + "\n\n")
    out.write('</aida>\n')

    sys.exit(0)
