from buildutils import *

Import('env', 'build', 'install')

localenv = env.Clone()
linkflags = []

matlab_include = pjoin(localenv['matlab_path'], 'extern', 'include')

if localenv['OS'] == 'Windows':
    mexPlatform = 'w'
    linklibs = ['cantera_shared']
    linklibs += ['libmx', 'libmex', 'libmat']
    if localenv['OS_BITS'] == 32:
        matlab_libs = pjoin(localenv['matlab_path'], 'extern',
                            'lib' ,'win32', 'microsoft')
    else:
        matlab_libs = pjoin(localenv['matlab_path'], 'extern',
                    'lib' ,'win64', 'microsoft')

    if localenv['CC'] == 'cl':
        linkflags.append('/export:mexFunction')
        linkflags.append('/MACHINE:X%i' % localenv['OS_BITS'])
    elif localenv['CC'] == 'gcc':
        linkflags.append('-Wl,--export-all-symbols')
        linkflags.extend(['-static-libgcc', '-static-libstdc++'])

elif localenv['OS'] == 'Darwin':
    linklibs = ['cantera']
    linklibs += ['mx', 'mex', 'mat'] + env['LIBM']
    mexPlatform = 'maci'
    linkflags.extend(['-Wl,-exported_symbol,_mexFunction'])
    localenv.Append(FRAMEWORKS=['Accelerate'])

    if localenv['OS_BITS'] == 64:
        matlab_libs = pjoin(localenv['matlab_path'], 'bin', 'maci64')
    else:
        matlab_libs = pjoin(localenv['matlab_path'], 'bin', 'macx86')

elif os.name == 'posix':
    linklibs = ['cantera']
    linklibs += ['mx', 'mex', 'mat'] + env['LIBM']
    mexPlatform = 'a'

    if localenv['OS_BITS'] == 64:
        matlab_libs = pjoin(localenv['matlab_path'], 'bin', 'glnxa64')
    else:
        matlab_libs = pjoin(localenv['matlab_path'], 'bin', 'glnx86')

mexSuffix = '.mex%s%i' % (mexPlatform, localenv['OS_BITS'])

localenv.Append(CPPPATH=['#include', '#src', matlab_include],
                CPPDEFINES=['MATLAB_MEX_FILE'],
                LIBPATH=[matlab_libs])

linklibs += localenv['sundials_libs']
linklibs += localenv['blas_lapack_libs']

ctmethods = build(localenv.SharedLibrary('#interfaces/matlab/toolbox/ctmethods',
                                         mglob(localenv, '.', 'cpp'),
                                         LIBPREFIX='',
                                         SHLIBPREFIX='',
                                         SHLIBSUFFIX=mexSuffix,
                                         LIBS=linklibs,
                                         LINKFLAGS=linkflags))

### Install the Matlab toolbox ###

# 'ctpath.m'
target = build(localenv.SubstFile('#interfaces/matlab/ctpath.m',
                                  '#interfaces/matlab/ctpath.m.in'))
install('$inst_matlab_dir', target)

# 'cantera_demos.m'
install('$inst_matlab_dir', '#samples/matlab/cantera_demos.m')
install(localenv.RecursiveInstall, '$inst_matlab_dir', '#interfaces/matlab/toolbox')
install(localenv.RecursiveInstall, pjoin('$inst_sampledir', 'matlab'), '#samples/matlab')

if os.name == 'nt':
    install('$inst_matlab_dir', localenv['cantera_shlib'])
