#!/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)
parser.add_option("-f","--format", action="store", type="str", dest="format",
                  help="Output format", default="xml")
options, args = parser.parse_args()

if not sys.stdin.isatty():
    args.insert(0, sys.stdin)
if len(args) > 1:
    sys.exit("Need exactly one argument or one pipe")

from goodruns import GRL

try:
    grl = GRL(args[0])
except:
    print "not a valid grl"
    sys.exit(1)

if options.output is None:
    grl.write(sys.stdout, format = options.format)
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')
            grl.write(filehandle, format = extension)
        finally:
            filehandle.close()
    except Exception, ex:
        print ex
