#!/usr/bin/env python

# Copyright (c) 2004-2005 Anders Logg (logg@tti-c.org)
# Licensed under the GNU GPL Version 2
#
# Modified by Johan Jansson, 2005
#
# 2004-10-14 -- 2005-09-20
#
# This script parses command-line arguments, calls
# the parser, and then compiles the generated form.

# Python modules
import sys
import getopt

# FFC modules
sys.path.append("../")
from ffc.parser import simple
from ffc.common.constants import *
from ffc.common.exceptions import *

def main(argv):
    "Main function."

    # Get command-line arguments
    try:
        opts, args = getopt.getopt(argv, "hl:c:", ["help", "language=", "license="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # Check that we got a filename
    if not args:
        usage()
        sys.exit(2)

    # Print a nice message
    print "This is FFC, the FEniCS Form Compiler, version %s." % FFC_VERSION
    print "For further information, go to http://www/fenics.org/ffc/."
    print

    # Set default arguments
    language = "C++"
    license = FFC_LICENSE

    # Get options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in  ("-l", "--language"):
            language = arg
        elif opt in  ("-c", "--license"):
            license = arg

    # Call parser and compiler for each file
    for filename in args:
        # Parse current file
        outname = simple.parse(filename, language, license)
        # Compile generated file (also provide a namespace)
        ns = {}
        try:
            execfile(outname, ns)
        except FormError, exception:
            print ""
            print "*** Error at " + str(exception.expression)
            print "*** " + exception.message
        except RuntimeError, exception:
            print "*** " + str(exception)
        except Exception, exception:
            print "*** " + str(exception)

def usage():
    "Display usage info."
    print """\
Usage: ffc [OPTION]... input.form

  -h            display this help text and exit
  -l language   specify output language, one of 'c++' (default), 'latex', 'raw' or 'ase'
  -c license    specify license for generated code (default is GPL)
  

Alternatively, the following long options may be used:

  --help
  --language language
  --license  license

Currently supported languages are C++ and LaTeX."""
    return

if __name__ == "__main__":
    main(sys.argv[1:])
