#!/usr/bin/env python
#
# Copyright (C) 2005-2010 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Recompile all ffc forms (use when FFC has been updated)
# This script should be run from the top level directory.

import os

# Forms that need special options
special = {"CahnHilliard2D.ufl":       "-fsplit",
           "CahnHilliard3D.ufl":       "-fsplit",
           "AdaptivePoisson.ufl":      "-e",
           "AdaptiveNavierStokes.ufl": "-e"}

# Forms for which we should skip optimization
skip_optimization = ["HyperElasticity.ufl"]

# Directories to scan
subdirs = ["dolfin", "demo", "bench", "test"]

# Compile all form files
topdir = os.getcwd()
for subdir in subdirs:
    for root, dirs, files in os.walk(subdir):

        # Check for .ufl files
        formfiles = [f for f in files if len(f) > 4 and f[-4:] == ".ufl"]
        if len(formfiles) == 0:
            continue

        # Compile files
        os.chdir(root)
        print "Compiling forms in %s..." % root
        for f in formfiles:
            if f in special:
                options = special[f]
            else:
                options = ""
            if f in skip_optimization:
                optimization = ""
            else:
                optimization = "-O"
            command = "ffc -v %s -f no_ferari -l dolfin %s %s >> compile.log" % (optimization, options, f)
            print "  " + command
            ret = os.system(command)
            if not ret == 0:
                raise RuntimeError, "Unable to compile form: %s/%s" % (root, f)
        os.chdir(topdir)
