#! /usr/bin/env python

"""\
%(prog)s yodafile [yodafile2]

Convert a YODA data file to another YODA file (for convenient tidying and filtering).
Like yodacnv, but allows output to stdout since the output format isn't auto-detected.
"""

import yoda, os, sys, argparse
from yoda.script_helpers import parse_x2y_args

parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument("ARGS", nargs="+", help="infile [outfile]")
parser.add_argument("-m", "--match", dest="MATCH", metavar="PATT", default=None,
                    help="only write out histograms whose path matches this regex")
parser.add_argument("-M", "--unmatch", dest="UNMATCH", metavar="PATT", default=None,
                    help="exclude histograms whose path matches this regex")
parser.add_argument("--as-scatters", dest="AS_SCATTERS", action="store_true", default=False,
                    help="convert all input analysis objects to Scatter types")

args = parser.parse_args()
in_out = parse_x2y_args(args.ARGS, [".yoda", ".yoda.gz"], [".yoda", ".yoda.gz"])
if not in_out:
    sys.stderr.write("You must specify the YODA input and output file names\n")
    sys.exit(1)
# print(in_out)

for i, o in in_out:
    analysisobjects = yoda.readYODA(i, False, args.MATCH, args.UNMATCH)
    if args.AS_SCATTERS:
        analysisobjects = [ao.mkScatter() for ao in analysisobjects]
    yoda.writeYODA(analysisobjects, o)
