#!/usr/bin/env python

# Copyright (C) 2004-2006 Anders Logg (logg@simula.no)
# Licensed under the GNU GPL Version 2
#
# Modified by Johan Jansson 2005
# Modified by Ola Skavhaug 2006
#
# 2004-10-14 -- 2006-09-21
#
# 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.debug import *
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, "hvOl:d:f:", ["help", "version", "optimize", "language=", "debug="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # Check that we got a filename
    if opts == [("-v", "")] or opts == [("--version", "")]:
        version()
        sys.exit(0)
    elif not args:
        usage()
        sys.exit(2)

    # Set default arguments
    language = "dolfin"
    debuglevel = -1
    options = FFC_OPTIONS

    # Get options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-v", "--version"):
            version()
            sys.exit()
        elif opt in ("-O", "--optimize"):
            options["optimize"] = True
        elif opt in  ("-l", "--language"):
            language = arg
        elif opt in  ("-d", "--debug"):
            debuglevel = int(arg)
        elif opt in  ("-f"):
            if arg in options:
                options[arg] = True
            else:
                usage()
                sys.exit(2)

    # Set debug level
    setlevel(debuglevel)

    # Print a nice message
    if debuglevel > -1:
        version()

    # Call parser and compiler for each file
    for filename in args:
        # Parse current file
        outname = simple.parse(filename, language, options)
        # Compile generated file (also provide a namespace)
        ns = {}
        # Catch exceptions only if debug level is zero
        if debuglevel > 0:
            execfile(outname, ns)
        else:
            try:
                execfile(outname, ns)
            except FormError, exception:
                print ""
                print "*** Error at " + str(exception.expression)
                print "*** " + exception.message
                print "*** To get more information about this error, rerun ffc with the option -d1."
            except RuntimeError, exception:
                print "*** " + str(exception)
                print "*** To get more information about this error, rerun ffc with the option -d1."
            except Exception, exception:
                print "*** " + str(exception)
                print "*** To get more information about this error, rerun ffc with the option -d1."

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

  -h            display this help text and exit
  -v            display version number and exit
  -O            generate optimized code using FErari optimizations
  -l language   specify output language, one of 'dolfin' (default),
                'latex', 'raw', 'ase' or 'xml'
  -d debuglevel specify debug level (default is -1)
  -f option     specify code generation options, one of 'blas' or 'no-gpl'

Alternatively, the following long options may be used:

  --help
  --version
  --optimize
  --language language
  --debuglevel debuglevel
"""
    return

def version():
    "Display version number."
    print("This is FFC, the FEniCS Form Compiler, version %s." % FFC_VERSION)
    print("For further information, go to http://www/fenics.org/ffc/.")
    return

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