#! /usr/bin/python3

"""\
%prog <runsdir> [opts] M:N [M2:N2 ...]

Write random run combinations to file. Run combination specs are given in the
format M:N where N is the number of combinations to make, and M is the number of
runs from <runsdir> to randomly leave out, e.g. 0:1 for the single complete
combination, and 10:100 for 100 combinations from which 10 runs have been excluded.
"""

import optparse, os, sys
op = optparse.OptionParser(usage=__doc__)
op.add_option("--pname", "--pfile", dest="PNAME", default="params.dat", help="Name of the params file to be found in each run directory (default: %default)")
op.add_option("-o", "--output", dest="OUTNAME", default="runcombs.dat", help="Output file name (default: %default)")
op.add_option("-v", "--debug", dest="DEBUG", action="store_true", default=False, help="Turn on some debug messages")
op.add_option("-q", "--quiet", dest="QUIET", action="store_true", default=False, help="Turn off messages")
opts, args = op.parse_args()

## Get mandatory arguments
if len(args) < 1:
    print("Argument missing... exiting\n\n")
    op.print_usage()
    sys.exit(1)
RUNSDIR = args[0]


## Load the Professor machinery
import professor2 as prof
if not opts.QUIET:
    print(prof.logo)


## Load MC run histos and params
import glob
INDIRS = glob.glob(os.path.join(RUNSDIR, "*"))
try:
    PARAMS, HISTOS = prof.read_rundata(INDIRS, opts.PNAME, ignore_missing_histos=True)
    RUNS, PARAMNAMES, PARAMSLIST = prof.mk_ipolinputs(PARAMS)
except Exception as e:
    print(e)
    sys.exit(1)

with open(opts.OUTNAME, "w") as f:
    for COMB in args[1:]:
        minus, NC = map(int, COMB.split(":"))
        # The run combinations
        RC = [r for r in prof.sampling.xrandomUniqueCombinations(RUNS, len(RUNS)-minus, NC)]
        for r in RC:
            f.write("%s\n" % str(r).replace("[","").replace("]","").replace(",","").replace("'",""))


if not opts.QUIET:
    print("Run combs written to %s" % opts.OUTNAME)

sys.exit(0)
