import os

from waflib.Task import Task




class CreateF2pyInterfaces(Task):

    def run(self):

        os.chdir('tests/resources')

        from numpy import f2py
        extra_args = '--f90flags="-ffree-line-length-0" -I../../.bld ' \
                     '-L../../.bld/fortran -lresfort ' \
                     '-llapack'

        with open('f2py_interface.f90', 'rb') as sourcefile:
            sourcecode = sourcefile.read()
        f2py.compile(sourcecode, 'f2py_interface', extra_args,
            extension='.f90')

        os.chdir('../../')


def build(ctx):

    # Build F2PY interface
    ctx.add_to_group(CreateF2pyInterfaces(env=ctx.env))

    # Collect sources
    src = ['kw_imsl_replacements.f90', 'kw_test_additions.f90',
        'kw_dp3asim.f90']

    # Build the executable. We do not pass any flags in as otherwise errors
    # might be thrown because of DEBUG options that are unrelated to the
    # parts of the codes we are interested in.
    ctx(features=['fc', 'fcprogram'], source=src, target='kw_dp3asim',
        fcflags=['-O2'])
