#! /usr/bin/env python

"""\
%prog <infile> <outfile>

Convert between YODA-supported data formats (.yoda, .aida, .dat)
"""

import yoda, os, sys, optparse, re
# TODO: Support an extra arg or option to choose the target format and hence convert many files at once with auto-naming
# from yoda.script_helpers import parse_x2y_args

parser = optparse.OptionParser(usage=__doc__)
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, args = parser.parse_args()
if not len(args) == 2:
    sys.stderr.write("You must specify the in and out file names\n")
    sys.exit(1)
i, o = args

## Read, filter, and write out histos
aos = yoda.read(i)
if opts.MATCH:
    re_match = re.compile(opts.MATCH)
    for k in aos.keys():
        if not re_match.match(k):
            del aos[k]
if opts.UNMATCH:
    re_unmatch = re.compile(opts.UNMATCH)
    for k in aos.keys():
        if re_unmatch.match(k):
            del aos[k]
yoda.write(aos, o)
