#!/usr/bin/python

import sys, optparse
from ufl.algorithms import FormData, load_forms, validate_form, ufl2latex, tree_format

# Get commandline options

usage = """Analyse a .ufl file to find errors.
Optionally write information about
the forms for further inspection.

Examples:

  ufl-analyse --quiet=0 --write=1 mass.ufl"""

def opt(long, short, t, default, help):
    return optparse.make_option("--%s" % long, "-%s" % short, action="store", type=t, dest=long, default=default, help=help)

option_list = [ \
    opt("quiet", "q", "int", 1, "Do not print form information to screen."),
    opt("write", "w", "int", 0, "Write form information to file."),
    ]

parser = optparse.OptionParser(usage=usage, option_list=option_list)
args = sys.argv[1:]
(options, args) = parser.parse_args(args=args)

if not args:
    print "Missing files!"
    print
    parser.print_usage()
    sys.exit(-1)
filenames = args

write_file = options.write
quiet = options.quiet

# Handle each form file separately
for filename in filenames:
    if not filename.endswith(".ufl"):
        print "Warning: Filename '%s' doesn't end with .ufl." % filename

    # Load form file, which triggers many consistency
    # checks while the form is being built
    print "Loading form file '%s'" % filename
    try:
        # TODO: Forms that fail will usually fail inside this, which doesn't produce any log... Perhaps we should pass a log file to load_forms?
        forms = load_forms(filename)
    except:
        print "Failed to load form file."
        raise
    formdatas = [f.form_data() for f in forms]

    outputfilename = filename + ".log"
    if write_file:
        outputfile = open(outputfilename, "w")

    def write(*items):
        text = " ".join(str(s) for s in items)
        if write_file:
            outputfile.write(text)
            outputfile.flush()
        if not quiet:
            print text
    
    # Analyse each form separately
    for fd in formdatas:
        # Check both original form and transformed version
        for (form, name) in [(fd.original_form, fd.name), (fd.form, fd.name + "<modified>")]:
            # Analyse validity of form
            errors = validate_form(form) 
            if errors:
                write("Found errors in form '%s':" % name)
                write(errors)
            else:
                write("Found no errors in form '%s'." % name)
            
            # Print form information
            s = str(fd)
            write("\nForm data:\n", s)
            
            s = str(form)
            write("\nForm pretty-print:\n", s)
            
            r = repr(form)
            write("\nForm representation:\n", r)
            
            tree = tree_format(form)
            write("\nForm tree formatting:\n", tree)
            
            latex = ufl2latex(form)
            write("\nForm LaTeX code:\n", latex)
    
    if write_file:
        outputfile.close()

