#!/usr/bin/env python
import os, shlex
import subprocess
import glob
import shutil
import ROOT
from collections import OrderedDict

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--inputPath", type="string", dest="inputPath", help="Full path of where prepareDatacards.root are ")
parser.add_option("--outPath", type="string", dest="outPath", help="Full path of where the cards should be created ")

(options, args) = parser.parse_args()

inputPath = options.inputPath
outPath = options.outPath

commands = []

listproc = glob.glob( "%s/2018/*.root" % inputPath)

for card in listproc:
    cardname = card.split("/")[-1]
#    commands.append('hadd %s/%s  %s/2017/%s %s/2018/%s'%(outPath,cardname,inputPath,cardname,inputPath,cardname))
    commands.append('hadd %s/%s %s/2016/%s %s/2017/%s %s/2018/%s'%(outPath,cardname,inputPath,cardname,inputPath,cardname,inputPath,cardname))


for command in commands:
    print command
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in p.stdout.readlines():
        print line.rstrip("\n")
    print 'done'
    retval = p.wait()

