def doDatacards(analysis,period,combineDir,bp):
    '''A function to move into the combined limits folder, run higgs combine tool on all datacards
       produced by the mklimits script, then copy the root files back here.'''
    datacardDir = 'datacards/%s_%itev/%s' % (analysis, period, bp)
    combineDatacardDir = '%s/%s_%itev' % (combineDir, analysis, period)
    datacardLimitsDir = 'limitData/%s_%itev/%s' % (analysis, period, bp)
    python_mkdir(combineDatacardDir)
    os.system('cp -r %s %s' %(datacardDir, combineDatacardDir))
    masses = _3L_MASSES if analysis == 'Hpp3l' else _4L_MASSES
    if period==13: masses = [500]
    for mass in masses:
        os.system('cd %s/%s/%i; pwd; eval `scramv1 runtime -sh`; combine -M MaxLikelihoodFit -t -1 --expectSignal 0 %s.txt; python $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/test/diffNuisances.py -a mlfit.root -g plots.root; combine -M MaxLikelihoodFit -t -1 --expectSignal 0 %s.txt; python $CMSSW_BASE/src/HiggsAnalysis/CombinedLimit/test/diffNuisances.py -a mlfit.root -g plots.root' % (combineDatacardDir, bp, mass, bp, bp))
def doDatacards(analysis,region,period,bp,bgMode,do4l,doBoth):
    '''A function to move into the combined limits folder, run higgs combine tool on all datacards
       produced by the mklimits script, then copy the root files back here.'''
    logging.info('Processing %s with mode %s' % (bp,bgMode))
    pipe = subprocess.PIPE
    # do the combination
    combos = {
        'HppComb': ['Hpp3l', 'Hpp4l'],
        'HppAP': ['Hpp3l'],
        'HppPP': ['Hpp4l'],
    }
    datacardDir = 'datacards/%s_%itev_%s/%s' % (analysis, period, region, bp)
    combineDatacardDir = 'combineWorking/%s_%itev_%s' % (analysis, period, region)
    datacardLimitsDir = 'limitData/%s_%itev_%s/%s' % (analysis, period, region, bp)
    masses = _3L_MASSES if analysis == 'Hpp3l' else _4L_MASSES
    if do4l: masses = _4L_MASSES
    if doBoth: masses = _4L_MASSES
    if period==13: masses = [500]
    datacardString = '' if bgMode == "sideband" else "_{0}".format(bgMode)
    if do4l: datacardString += "_4l"
    if doBoth: datacardString += "_APandPP"
    python_mkdir(combineDatacardDir)
    # merge for combine
    if analysis in combos:
        for mass in masses:
            # merge the inputs
            logging.info('%s: Merging %i' % (bp,mass))
            mergeCommands = []
            mergeCommands += ['pushd datacards/{1}/{0}/{2}; combineCards.py {0}_[em][em][em].txt > {0}_comb.txt'.format(bp,'Hpp3l_8tev_Hpp3l',mass)]
            mergeCommands += ['pushd datacards/{1}/{0}/{2}; combineCards.py {0}_[em][em][em]_4l.txt > {0}_comb_4l.txt'.format(bp,'Hpp3l_8tev_Hpp3l',mass)]
            mergeCommands += ['pushd datacards/{1}/{0}/{2}; combineCards.py {0}_[em][em][em]_APandPP.txt > {0}_comb_APandPP.txt'.format(bp,'Hpp3l_8tev_Hpp3l',mass)]
            mergeCommands += ['pushd datacards/{1}/{0}/{2}; combineCards.py {0}_[em][em][em][em].txt > {0}_comb.txt'.format(bp,'Hpp4l_8tev_Hpp4l',mass)]
            for command in mergeCommands:
                out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]
            # merge the merged cards
            theCards = []
            if analysis in ['HppAP']: theCards += ['datacards/Hpp3l_%itev_Hpp3l/%s/%i/%s%s.txt' % (period, bp, mass,bp,datacardString)]
            if analysis in ['HppPP','HppComb']: theCards += ['datacards/Hpp4l_%itev_Hpp4l/%s/%i/%s%s.txt' % (period, bp, mass,bp,datacardString)]
            if analysis in ['HppPP']: theCards += ['datacards/Hpp3l_%itev_Hpp3l/%s/%i/%s%s_4l.txt' % (period, bp, mass,bp,datacardString)]
            if analysis in ['HppComb']: theCards += ['datacards/Hpp3l_%itev_Hpp3l/%s/%i/%s%s_APandPP.txt' % (period, bp, mass,bp,datacardString)]
            cardsToCombine = [x for x in theCards if os.path.isfile(x)]
            outCard = '%s/%i/%s%s.txt' %(datacardDir,mass,bp,datacardString)
            python_mkdir('%s/%i' %(datacardDir,mass))
            command = 'combineCards.py %s > %s' % (' '.join(cardsToCombine),outCard)
            out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]
    else: # merge for individual analyses
        for mass in masses:
            logging.info('%s: Merging %i' % (bp,mass))
            if analysis in ['Hpp3l']:
                if do4l: command = 'pushd {1}/{2}; combineCards.py {0}_[em][em][em]_4l.txt > {0}_comb_4l.txt'.format(bp,datacardDir,mass)
                elif doBoth: command = 'pushd {1}/{2}; combineCards.py {0}_[em][em][em]_APandPP.txt > {0}_comb_APandPP.txt'.format(bp,datacardDir,mass)
                else: command = 'pushd {1}/{2}; combineCards.py {0}_[em][em][em].txt > {0}_comb.txt'.format(bp,datacardDir,mass)
            if analysis in ['Hpp4l']:
                command = 'pushd {1}/{2}; combineCards.py {0}_[em][em][em][em].txt > {0}_comb.txt'.format(bp,datacardDir,mass)
            out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]
            
    command = 'cp -r %s %s' %(datacardDir, combineDatacardDir)
    out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]
    python_mkdir(datacardLimitsDir)
    for mass in masses:
        logging.info('%s: Calculating limit for %i' % (bp,mass))
        command = 'cd %s/%s/%i; combine -m %i -M Asymptotic %s%s.txt' % (combineDatacardDir, bp, mass, mass, bp, datacardString)
        out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]
        command = 'cp %s/%s/*/higgsCombineTest.Asymptotic.mH%i.root %s/higgsCombineTest.Asymptotic.mH%i%s.root' % (combineDatacardDir, bp, mass, datacardLimitsDir, mass, datacardString)
        out = subprocess.Popen(command, shell=True,stdout=pipe,stderr=subprocess.STDOUT).communicate()[0]