from buildutils import *

Import('env', 'buildDir', 'buildTargets', 'installTargets')
localenv = env.Clone()

# (subdir, library name, (file extensions))
libs = [('tpx','tpx',['cpp'])]

if env['build_with_f2c']:
    libs.append(('f2c_math', 'ctmath', ['cpp','c']))

    localenv.Append(CPPPATH=Dir('#ext/f2c_libs'))
    if not localenv['HAS_TIMES_H']:
        localenv.Append(CPPDEFINES=['USE_CLOCK'])
    if not localenv['HAS_UNISTD_H']:
        localenv.Append(CPPDEFINES=['MSDOS'])

    # Create arith.h using the arithchk program
    if not os.path.exists('arith.h'):
        arithenv = env.Clone()
        # TODO: make link flag more general
        arithenv.Append(CPPFLAGS='-DNO_FPINIT')
        arithenv.Program('f2c_libs/arithchk/arithchk', source='f2c_libs/arithchk/arithchk.c',
                         LIBS=env['LIBM'])
        arithenv.Command('#ext/f2c_libs/arith.h', 'f2c_libs/arithchk/arithchk$PROGSUFFIX',
                         '$SOURCE > $TARGET')

    # Possibly system-depenent headers
    localenv.Command('#ext/f2c_libs/signal1.h', 'f2c_libs/signal1.h0',
                     Copy('$TARGET', '$SOURCE'))

    localenv.Command('#ext/f2c_libs/sysdep1.h', 'f2c_libs/sysdep1.h0',
                     Copy('$TARGET', '$SOURCE'))

    libs.append(('f2c_libs', 'ctf2c', 'c'))

    if env['BUILD_BLAS_LAPACK']:
        libs.append(('f2c_blas', 'ctblas', ['c']))
        libs.append(('f2c_lapack', 'ctlapack', ['c']))

else:
    libs.append(('math', 'ctmath', ['cpp','c','f']))

    if env['BUILD_BLAS_LAPACK']:
        libs.append(('blas', 'ctblas', ['f']))
        libs.append(('lapack', 'ctlapack', ['f']))

if env['use_sundials'] == 'n':
    libs.append(('cvode/source', 'cvode', ['c']))
    localenv.Append(CPPPATH=Dir('#ext/cvode/include'))

for subdir, libname, extensions in libs:
    lib = localenv.Library(pjoin('../lib', libname),
                           source=mglob(localenv, subdir, *extensions))
    inst = localenv.Install('$inst_libdir', lib)
    buildTargets.extend(lib)
    installTargets.extend(inst)
