#!/usr/bin/env python

import sys
import os
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-o","--output", action="store", type="str", dest="output",
                  help="Output filename", default=None)
options, args = parser.parse_args()

if not sys.stdin.isatty():
    args.insert(0, sys.stdin)
if len(args) < 2:
    sys.exit("Need at least two arguments or one pipe and one or more arguments")

from goodruns import GRL, diffed

try:
    diffgrl = diffed(*[GRL(arg) for arg in args])
except:
    print "could not parse one or more grls"
    sys.exit(1)

if options.output is None:
    diffgrl.write(sys.stdout, format = 'xml')
else:
    head, tail = os.path.split(options.output)
    if not tail:
        sys.exit("Invalid filename")
    if '.' not in tail:
        sys.exit("Filename must contain an extension")
    extension = tail.split('.')[-1]
    try:
        try:
            filehandle = open(options.output, 'w')
            diffgrl.write(filehandle, format = extension)
        finally:
            filehandle.close()
    except Exception, ex:
        print ex
