#!/usr/bin/env python3

import re
import argparse


def merger(infiles, outfile):
    header = ''
    graphs = ''
    counter = 0
    for f in infiles:
        headerflag = True
        for line in f.readlines():
            if re.match('@with [Gg][0-9]', line):
                headerflag = False
                # one graph per file, adjust graph number
                line = '@with g{}\n'.format(counter)
            if headerflag:
                if graphs == '':
                    # save fonts, colors etc. of first file
                    header += line
                elif re.match('@[Gg][0-9]', line):
                    # save graph specifications of following files
                    line = re.sub('@[Gg][0-9]', '@g{}'.format(counter), line)
                    header += line
                else:
                    pass
            else:
                # save sets 
                if re.match('@target [Gg][0-9]', line):
                    line = re.sub('@target [Gg][0-9]',
                                  '@target G{}'.format(counter), line)
                graphs += line
        counter += 1
    outfile.write(header+graphs)


parser = argparse.ArgumentParser()

parser.add_argument('input', nargs='+', type=argparse.FileType('r'),
                    help='One or more input files')
parser.add_argument('--output', '-o', nargs='?', type=argparse.FileType('w'),
                    default='merger_grace.agr',
                    help='Output file (default=merged_grace.agr)')

args = parser.parse_args()

merger(args.input, args.output)
