#!/bin/env python

import sys
import os
from subprocess import call
from tempfile import mkstemp

if len(sys.argv) < 3:
    sys.exit("must specify at least the destination file and an input file")

maxfiles = 500
allfiles = sys.argv[2:]
destination = sys.argv[1]
tmppath = None
tmpdest = None

if os.path.exists(destination):
    sys.exit("destination file %s exists" % destination)

if len(allfiles) == 1:
    # simple copy
    import shutil
    shutil.copy(allfiles[0], destination)
    sys.exit(0)

while allfiles:
    if tmppath:
        files = allfiles[:maxfiles-1]
        allfiles = allfiles[maxfiles-1:]
        files.insert(0, tmppath)
    else:
        files = allfiles[:maxfiles]
        allfiles = allfiles[maxfiles:]
    print "merging %i files... (%i remaining)" % (len(files), len(allfiles))
    dest = destination
    args = []
    if allfiles:
        tmpfd, tmpdest = mkstemp(suffix=".root")
        dest = tmpdest
        os.close(tmpfd)
        args.append("-f")
    files.insert(0, dest)
    call(["hadd"] + args + files)
    if tmppath:
        os.unlink(tmppath)
    tmppath = tmpdest
