# vim: filetype=python expandtab sw=4 tabstop=4
# Since all frontends require very little code, we don't split this
# SConscript into several.

import os
import string

Import("commonEnvironment", "commandOptions", "util" )
Import("configure")

# Add all the options first
commandOptions.Add('buildCsound5GUI',
    'Build FLTK GUI frontend (requires FLTK 1.1.7 or later).',
    '0')
commandOptions.Add('buildWinsound',
    "Build Winsound frontend. Requires FLTK headers and libs",
    '0')
commandOptions.Add('buildOSXGUI',
    'On OSX, set to 1 to build the basic GUI frontend',
    '0')
commandOptions.Add('buildCSEditor',
    'Set to 1 to build the Csound syntax highlighting text editor. Requires FLTK headers and libs',
    '0')
commandOptions.Add('buildPDClass',
    "build csoundapi~ PD class (needs m_pd.h in the standard places)",
    '0')
commandOptions.Add('buildTclcsound',
    "Build Tclcsound frontend (cstclsh, cswish and tclcsound dynamic module). Requires Tcl/Tk headers and libs",
    '0')
commandOptions.Add('buildCsoundAC',
    'Set to 1 to build CsoundAC (needs FLTK, boost, Python, SWIG).',
    '0')
commandOptions.Add('buildCsoundVST',
    'Set to 1 to build CsoundVST (needs CsoundAC, FLTK, boost, Python, SWIG).',
    '0')

commandOptions.Update(commonEnvironment)
Help(commandOptions.GenerateHelpText(commonEnvironment))

util.fixEnvForOLPC(commonEnvironment)

# First the csound program with no dependencies
programEnvironment = commonEnvironment.Clone()
csoundSources = ['csound/csound_main.c']
if util.platform == 'linux':
    csoundSources += ['csound/sched.c'] 
csoundProgram = programEnvironment.Program('csound/csound', csoundSources)
util.installProgram(csoundProgram)
# FLTK csound5gui


if commonEnvironment['buildCsound5GUI'] != '0':
    util.confDecision("Building FLTK GUI CSOUND5GUI frontend.")
    found117 = configure.CheckHeader("FL/Fl_Spinner.H", language = "C++")
    if not found117:
        util.fatal("You specified buildCsound5GUI, but you don't have FLTK 1.17 installed.")

    csound5GUIEnvironment = programEnvironment.Clone()
    if configure.CheckLibWithHeader("jack", "jack/jack.h", language = "C", autoadd=False):
        csound5GUIEnvironment.Append(LIBS = ['jack'])
        csound5GUIEnvironment.Prepend(CPPFLAGS = ['-DHAVE_JACK'])
    if util.platform == 'linux':
        csound5GUIEnvironment.ParseConfig('fltk-config --use-images --cflags --cxxflags --ldflags')
        csound5GUIEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csound5GUIEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csound5GUIEnvironment.Prepend(LINKFLAGS = Split('''
                -mwindows -Wl,--enable-runtime-pseudo-reloc
            '''))
            csound5GUIEnvironment.Append(LIBS = Split('fltk_images fltk_png fltk_z fltk_jpeg fltk'))
        else:
            csound5GUIEnvironment.Append(LIBS = Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csound5GUIEnvironment.Prepend(CXXFLAGS = "-fno-rtti")
        csound5GUIEnvironment.Append(LIBS = Split('''
            fltk stdc++ pthread m
        '''))
        csound5GUIEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework ApplicationServices
        '''))

    csound5GUISources = Split('''
        fltk_gui/ConfigFile.cpp
        fltk_gui/CsoundCopyrightInfo.cpp
        fltk_gui/CsoundGlobalSettings.cpp
        fltk_gui/CsoundGUIConsole.cpp
        fltk_gui/CsoundGUIMain.cpp
        fltk_gui/CsoundPerformance.cpp
        fltk_gui/CsoundPerformanceSettings.cpp
        fltk_gui/CsoundUtility.cpp
        fltk_gui/CsoundEditor.cpp
        fltk_gui/Fl_Native_File_Chooser.cxx
        fltk_gui/main.cpp
    ''')
    csound5GUIFluidSources = Split('''
        CsoundAboutWindow_FLTK
        CsoundGlobalSettingsPanel_FLTK
        CsoundGUIConsole_FLTK
        CsoundGUIMain_FLTK
        CsoundPerformanceSettingsPanel_FLTK
        CsoundUtilitiesWindow_FLTK
    ''')
    csound5GUIObjectFiles = []
    csound5GUIFluidObjectFiles = []
    for i in csound5GUISources:
        csound5GUIObjectFiles += csound5GUIEnvironment.Object(i)
    csound5GUIEnvironment.Append( CPPPATH = '#/interfaces' )
    csound5GUIObjectFiles += csound5GUIEnvironment.Object(
        'fltk_gui/csPerfThread', '#/interfaces/csPerfThread.cpp')
    for i in csound5GUIFluidSources:
        csound5GUIFluidObjectFiles += csound5GUIEnvironment.Object(
            util.fluidTarget(csound5GUIEnvironment, 'fltk_gui', i,
                        csound5GUIObjectFiles, 'frontends'))
    csound5GUIObjectFiles += csound5GUIFluidObjectFiles
    csound5GUI = csound5GUIEnvironment.Program('fltk_gui/csound5gui',
                                  csound5GUIObjectFiles)
    if util.platform == 'darwin':
        appDir = 'fltk_gui/Csound5GUI.app/Contents/MacOS'
        util.addOSXResourceFork(csound5GUIEnvironment, 'csound5gui', '')
        csound5GUIEnvironment.Command(
            '%s/csound5gui' % appDir, 'csound5gui', "cp $SOURCE %s/" % appDir)
        util.addOSXResourceFork(csound5GUIEnvironment, 'csound5gui', appDir)

    util.installProgram(csound5GUI)
else:
    util.confDecision("Not building FLTK CSOUND5GUI frontend.")

# Winsound
if commonEnvironment['buildWinsound'] == '1':
    fltkfound = configure.CheckLibWithHeader("fltk", "FL/Fl.H",
            language = "C++", autoadd = False)
    if not fltkfound:
        util.fatal("You specified buildWinsound but FLTK was not found")
    util.confDecision("Building Winsound frontend")
    # should these be installed ?
    # headers += glob.glob('frontends/winsound/*.h')
    csWinEnvironment = commonEnvironment.Clone()
    # not used
    # if (commonEnvironment['noFLTKThreads'] == '1'):
    #     csWinEnvironment.Append(CCFLAGS = ['-DNO_FLTK_THREADS'])
    if util.platform == 'linux':
        csWinEnvironment.ParseConfig('fltk-config --use-images --cflags \
                --cxxflags --ldflags')
        csWinEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csWinEnvironment.Append(LIBS = Split(
                'fltk_images fltk_png fltk_z fltk_jpeg fltk'))
            csWinEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csWinEnvironment.Prepend(LINKFLAGS = Split('''
                -mwindows -Wl,--enable-runtime-pseudo-reloc
            '''))
        else:
            csWinEnvironment.Append(LIBS = Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csWinEnvironment.Append(CXXFLAGS = ['-fno-rtti'])
        csWinEnvironment.Append(LIBS = ['fltk', 'stdc++', 'pthread', 'm'])
        csWinEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework CoreAudio -framework CoreMidi
            -framework ApplicationServices
        '''))
        appDir = 'frontends/winsound/Winsound.app/Contents/MacOS'
        util.addOSXResourceFork(csWinEnvironment, 'winsound', '')
        csWinEnvironment.Command(
            '%s/winsound' % appDir, 'winsound', "cp $SOURCE %s/" % appDir)
        util.addOSXResourceFork(csWinEnvironment, 'winsound', appDir)
    flSrc = 'winsound/winsound.cpp'
    flHdr = 'winsound/winsound.h'
    fl    = 'winsound/winsound.fl'
    winsoundSrcs = csWinEnvironment.Command([flSrc, flHdr],
            fl, 'fluid -c -o frontends/%s -h frontends/%s frontends/%s' %
            (flSrc, flHdr, fl))
    # winsoundSrcs contains the header and the cpp file
    winsoundSrc = winsoundSrcs[0]
    winsoundMain = csWinEnvironment.Object('winsound/main.cxx')
    Depends(winsoundMain, winsoundSrc)
    winsound5 = csWinEnvironment.Program(
        'winsound/winsound', [winsoundMain, winsoundSrc])
    util.installProgram(winsound5)
else:
    util.confDecision("Not building Winsound")

# OSX frontend
if (util.platform == 'darwin' and commonEnvironment['buildOSXGUI'] == '1'):
    util.confDecision("Building OSX GUI frontend")
    csOSXGUIEnvironment = commonEnvironment.Clone()
    OSXGUI = csOSXGUIEnvironment.Command(
        '''OSX/build/Csound 5.app/Contents/MacOS/Csound 5''',
        'OSX/main.c',
        "cd frontends/OSX; xcodebuild -buildstyle Deployment")
    util.installProgram(OSXGUI)
else:
    util.confDecision("Not building OSX GUI frontend")

# csLadspa
print "CONFIGURATION DEFAULT:  Building csLadspa."
csLadspaEnv = commonEnvironment.Clone()
csLadspaEnv.Append(CPPPATH='#/frontends/csladspa')
if util.platform == "darwin":
    if commonEnvironment['dynamicCsoundLibrary'] != '0':
        csLadspaEnv.Append(LINKFLAGS=Split('''
            -bundle -undefined suppress -flat_namespace
             -framework CsoundLib
        '''))
    else:
        csLadspaEnv.Append(LINKFLAGS="-bundle")
    csladspa = csLadspaEnv.Program('csladspa.so',
         'csladspa/csladspa.cpp' )
else:
    csladspa = csLadspaEnv.SharedLibrary('csladspa/csladspa.cpp')
    util.installLib(csladspa, "ladspa")

# Cseditor
if commonEnvironment['buildCSEditor'] == '1':
    fltkfound = configure.CheckLibWithHeader("fltk", "FL/Fl.H",
            language = "C++", autoadd = False)
    if not fltkfound:
        util.Fatal("You specified buildCSeditor, but FLTK was not found")
    util.confDecision('Building Csound Text Editor.')
    csEditorEnvironment = commonEnvironment.Clone()
    if util.platform == 'linux':
        csEditorEnvironment.ParseConfig(
                'fltk-config --use-images --cflags --cxxflags --ldflags')
        csEditorEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csEditorEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csEditorEnvironment.Prepend(LINKFLAGS =
                    Split('''-mwindows -Wl,--enable-runtime-pseudo-reloc'''))
            csEditorEnvironment.Append(LIBS = 
                    Split('fltk_images fltk_png fltk_z fltk_jpeg fltk'))
        else:
            csEditorEnvironment.Append(LIBS =
                    Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csEditorEnvironment.Prepend(CXXFLAGS = "-fno-rtti")
        csEditorEnvironment.Append(LIBS = Split('fltk stdc++ pthread m'))
        csEditorEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework ApplicationServices
        '''))
        csEditorEnvironment.ParseConfig(
                "fltk-config --use-images --cflags --cxxflags --ldflags")

    csEditor = csEditorEnvironment.Program( 'cseditor/cseditor',
            'cseditor/cseditor.cxx')
    util.installProgram(csEditor)
else:
    util.confDecision('Not building Csound Text Editor.')

if commonEnvironment['buildPDClass'] != '0':
    if not configure.CheckHeader('m_pd.h', language = 'C'):
        util.fatal('You specified buildPDClass but PD was not found')
    pdClassEnvironment = commonEnvironment.Clone()
    if util.platform == 'darwin':
        pdClassEnvironment.Append(LINKFLAGS = Split('''
            -bundle -flat_namespace -undefined suppress
            -framework Carbon -framework ApplicationServices
        '''))
        pdClass = pdClassEnvironment.Program(
            'csoundapi_tilde/csoundapi~.pd_darwin',
            'csoundapi_tilde/csoundapi_tilde.c')
    elif util.platform == 'linux':
        pdClass = pdClassEnvironment.SharedLibrary(
            'csoundapi_tilde/csoundapi~.pd_linux',
            'csoundapi_tilde/csoundapi_tilde.c',
            SHLIBPREFIX = '', SHLIBSUFFIX = '')
    elif util.platform == 'win32':
        pdClassEnvironment.Append(LIBS = ['pd'])
        pdClassEnvironment.Append(SHLINKFLAGS = ['-module'])
        pdClassEnvironment['ENV']['PATH'] = os.environ['PATH']
        pdClass = pdClassEnvironment.SharedLibrary(
            'csoundapi_tilde/csoundapi~',
            'csoundapi_tilde/csoundapi_tilde.c')
    util.installLib(pdClass, "pd/extra")

# Tclcsound
if commonEnvironment['buildTclcsound'] == '1':
    util.confDecision("Building Tclcsound frontend")
    # The header we don't care version
    if util.platform == "linux":
        tclIncludePath = Split('''
            /usr/include/tcl
            /usr/include/tcl8.5
            /usr/include/tcl8.4
            /usr/include/tk
            /usr/include/tk8.5
            /usr/include/tk8.4
        ''')
    elif util.platform == "darwin":
        tclIncludePath = Split('''
            /Library/Frameworks/Tcl.Framework/Headers
            /Library/Frameworks/Tk.Framework/Headers
            /System/Library/Frameworks/Tcl.Framework/Headers
            /System/Library/Frameworks/Tk.Framework/Headers
        ''')
    tclhfound = configure.CheckHeader('tcl.h', language ='C')
    for path in tclIncludePath:
        tclhfound = tclhfound or configure.CheckHeader('%s/tcl.h' % path,
            language ='C')

    if not tclhfound:
        util.fatal("You specified buildTclcsound but tcl.h was not found!")

    csTclEnvironment = commonEnvironment.Clone()
    csTclEnvironment.Append(CPPPATH = tclIncludePath)

    # Look for tcl and tk libs, try 8.5 first and then 8.4
    tcllibfound = False
    tklibfound = False
    if util.platform == "linux" or util.platform == "win32":
        for version in ['8.5', '85', '8.4', '84']:
            tcllibfound = tcllibfound or configure.CheckLib("tcl%s" % version,
                    autoadd=0)
            tklibfound = tklibfound or configure.CheckLib("tk%s" % version,
                    autoadd=0)
            if tcllibfound and tklibfound:
                csTclEnvironment.Append(LIBS =
                        ['tcl%s' % version, 'tk%s' % version])
                break
    elif util.platform == "darwin":
        csTclEnvironment.Append(LINKFLAGS = Split(
            '-framework tk -framework tcl'))

    if util.platform == 'win32':
        csTclEnvironment.Append(SHLINKFLAGS = ['-module'])

    csTclCmdObj     = csTclEnvironment.SharedObject('tclcsound/commands.c')
    csTcl           = csTclEnvironment.Program(
        'tclcsound/cstclsh', ['tclcsound/main_tclsh.c', csTclCmdObj])
    csTk            = csTclEnvironment.Program(
        'tclcsound/cswish', ['tclcsound/main_wish.c', csTclCmdObj])
    Tclcsoundlib    = csTclEnvironment.SharedLibrary(
        'tclcsound/tclcsound', ['tclcsound/tclcsound.c', csTclCmdObj],
        SHLIBPREFIX = '')
    util.installProgram([csTcl,csTk])
    util.installLib(Tclcsoundlib, "tclcsound")
    if util.platform == 'darwin':
        tmp = "/Developer/Tools/Rez -i APPL -o cswish frontends/tclcsound/cswish.r"
        csTclEnvironment.Command('cswish_resources', 'cswish', tmp)
        if commonEnvironment['dynamicCsoundLibrary'] == '1':
            tmp  = 'mkdir /Library/Frameworks/CsoundLib.framework/Resources/TclTk'
            tmp += '; cp -R tclcsound.dylib /Library/Frameworks/CsoundLib.framework/Resources/TclTk/'
            csTclEnvironment.Command('tclcsound_install', 'tclcsound.dylib',
                                    tmp)
#    try     : os.mkdir('tclcsound', 0755)
#    except  : pass
#    if util.platform == 'darwin':
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound.dylib','cp tclcsound.dylib tclcsound; tclsh pkgbuild.tcl')
#    elif util.platform == 'linux':
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound.so','cp tclcsound.so tclcsound; tclsh pkgbuild.tcl')
#    elif  util.platform == 'win32':
#      csTclEnvironment.Command('tclcsound/tclcsound.dll', 'tclcsound.dll','cp tclcsound.dll tclcsound')
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound/tclcsound.dll','tclsh84 pkgbuild.tcl')

else:
    util.confDecision("Not building Tclcsound")

# CsoundAC

if commonEnvironment['buildCsoundAC'] == '1':
    fltkfound = configure.CheckLibWithHeader("fltk", "FL/Fl.H",
            language = "C++", autoadd = False)
    if not fltkfound:
        util.fatal("You specified buildCsoundAC but FLTK was not found")
    if not 'swig' in commonEnvironment['TOOLS']:
        util.fatal('You specified buildCsoundAC but SWIG was not found')
    if not configure.CheckHeader("boost/any.hpp", language = "C++"):
        util.fatal('You specified buildCsoundAC but Boost was not found')
    acEnvironment = commonEnvironment.Clone()
    if not util.fixEnvForPython(acEnvironment, configure):
        util.fatal('You specified buildCsoundAC but Python was not found')

    Import("csoundInterfaces")
    try:
        asdf = csoundInterfaces
    except NameError:
        util.fatal("You specified buildCsoundAC but you didn't specify buildInterfaces")

    util.confDecision('Building CsoundAC extension module for Csound with algorithmic composition.')

    acEnvironment.Prepend(CPPPATH   = ['#frontends/CsoundAC', '#interfaces'])
    acEnvironment.Prepend(LIBS      = csoundInterfaces[0])
    acEnvironment.Prepend(LIBPATH   = ['#interfaces'])
    acEnvironment.Append(SWIGFLAGS  = Split(
        '-c++ -includeall -verbose'))
    # fltk_images doesn't interact well with this flag
    flag = '-Wl,-as-needed'
    if flag in acEnvironment['LINKFLAGS']:
        acEnvironment['LINKFLAGS'].remove(flag)
    if flag in acEnvironment['SHLINKFLAGS']:
        acEnvironment['SHLINKFLAGS'].remove(flag)
    if util.platform == 'linux':
        acEnvironment.Append(LIBS               = ['util', 'dl', 'm'])
        acEnvironment.Append(SHLINKFLAGS        = '--no-export-all-symbols')
        acEnvironment.Append(LINKFLAGS          = ['-Wl,-rpath-link,interfaces'])
        acEnvironment.Append(LIBS               = ['fltk', 'fltk_images'])
        try     : os.symlink('lib_CsoundAC.so', '_CsoundAC.so')
        except  : pass
        Clean('_CsoundAC.so', 'lib_CsoundAC.so')
    elif util.platform == 'darwin':
        acEnvironment.Append(LIBS = ['dl', 'm'])
        acEnvironment.Append(SHLINKFLAGS = '--no-export-all-symbols')
        acEnvironment.Append(SHLINKFLAGS = '--add-stdcall-alias')
        acEnvironment['SHLIBSUFFIX'] = '.dylib'
    elif util.platform == 'win32':
        if  util.compilerGNU():
            acEnvironment.Prepend(LIBS = Split(
                'fltk fltk_images fltk_png fltk_jpeg fltk_z'))
        else:
            acEnvironment.Prepend(LIBS = Split(
                'fltk fltkimages fltkpng fltkjpeg fltkz'))
    for option in acEnvironment['CCFLAGS']:
        if string.find(option, '-D') == 0:
            acEnvironment.Append(SWIGFLAGS = [option])
    for option in acEnvironment['CPPFLAGS']:
        if string.find(option, '-D') == 0:
            acEnvironment.Append(SWIGFLAGS = [option])
    for option in acEnvironment['CPPPATH']:
        acEnvironment.Append(SWIGPATH = [option])
    csoundAcSources = Split('''
    CsoundAC/Cell.cpp             CsoundAC/Composition.cpp
    CsoundAC/Conversions.cpp      CsoundAC/Counterpoint.cpp
    CsoundAC/CounterpointNode.cpp CsoundAC/Event.cpp
    CsoundAC/Hocket.cpp           CsoundAC/ImageToScore.cpp
    CsoundAC/Lindenmayer.cpp      CsoundAC/MCRM.cpp
    CsoundAC/Midifile.cpp         CsoundAC/MusicModel.cpp
    CsoundAC/Node.cpp             CsoundAC/Random.cpp
    CsoundAC/Rescale.cpp          CsoundAC/Score.cpp
    CsoundAC/ScoreNode.cpp        CsoundAC/Sequence.cpp
    CsoundAC/Shell.cpp            CsoundAC/Soundfile.cpp
    CsoundAC/StrangeAttractor.cpp CsoundAC/System.cpp
    CsoundAC/Voicelead.cpp        CsoundAC/VoiceleadingNode.cpp
    ''')
    acWrapperEnvironment = acEnvironment.Clone()
    util.fixCFlagsForSwig(acWrapperEnvironment)
    if commonEnvironment['dynamicCsoundLibrary'] == '1':
        csoundac = acEnvironment.SharedLibrary('CsoundAC', csoundAcSources)
    else:
        csoundac = acEnvironment.Library('CsoundAC', csoundAcSources)

    util.installLib(csoundac)

    acWrapperEnvironment.Append(SWIGFLAGS =
        ['-python', '-outdir', 'frontends/CsoundAC'])
    csoundAcPythonWrapper = acWrapperEnvironment.SharedObject(
        'CsoundAC/CsoundAC.i')
    acWrapperEnvironment.Clean('.', 'CsoundAC/CsoundAC_wrap.h')
    acPythonEnvironment  = acEnvironment.Clone()

    acPythonEnvironment.Prepend(LIBS        = ['CsoundAC'])

    csoundAcPythonModule = util.makePythonModule(
        acPythonEnvironment, 'CsoundAC', [csoundAcPythonWrapper])

    counterpoint = acEnvironment.Program('counterpoint',
        ['CsoundAC/CounterpointMain.cpp'], LIBS = ['CsoundAC'] )
    util.installProgram(counterpoint)
else:
    util.confDecision('Not building CsoundAC extension module for Csound with algorithmic composition.')


# Build CsoundVST

if commonEnvironment['buildCsoundVST'] == '1':
    if not configure.CheckLibWithHeader("fltk", "FL/Fl.H",
     language = "C++", autoadd = False):
        util.fatal("You specified buildCsoundVST but FLTK was not found")
    if not configure.CheckHeader("boost/any.hpp", language = "C++"):
        util.fatal('You specified buildCsoundVST but Boost was not found')
    vstHeader   = "CsoundVST/vstsdk2.4/public.sdk/source/vst2.x/audioeffectx.h"
    if not configure.CheckHeader(vstHeader, language = "C++"):
        util.fatal("You specified buildCsoundVST but the VST SDK was not found")
    util.confDecision('Building CsoundVST plugin and standalone.')

    vstEnvironment = commonEnvironment.Clone()
    vstEnvironment.Append(CXXFLAGS = '-DVST_FORCE_DEPRECATED=0')
    vstEnvironment.ParseConfig('fltk-config --use-images --cflags --cxxflags --libs')
    flag = '-Wl,-as-needed'
    if flag in vstEnvironment['LINKFLAGS']:
        vstEnvironment['LINKFLAGS'].remove(flag)
    if flag in vstEnvironment['SHLINKFLAGS']:
        vstEnvironment['SHLINKFLAGS'].remove(flag)

    guiProgramEnvironment = commonEnvironment.Clone()
    vstEnvironment.Prepend(CPPPATH = ['#interfaces', 'CsoundVST'])
    guiProgramEnvironment.Append(CPPPATH = ['CsoundVST', '#interfaces'])
    vstEnvironment.Prepend(LIBS = ['csnd'], LIBPATH=['#interfaces'])

    if util.platform == 'win32':
        if util.compilerGNU():
            vstEnvironment.Append(          LINKFLAGS   = "--subsystem:windows")
            guiProgramEnvironment.Append(   LINKFLAGS   = "--subsystem:windows")
            vstEnvironment.Append(          LIBS        = ['stdc++', 'supc++'])
            guiProgramEnvironment.Append(   LIBS        = ['stdc++', 'supc++'])
    else:
        if util.platform == 'linux':
            vstEnvironment.Append(          LIBS = ['dl'])
            guiProgramEnvironment.Append(   LIBS = ['dl'])
        vstEnvironment.Append(              LIBS = ['stdc++', 'pthread', 'm'])
        guiProgramEnvironment.Append(       LIBS = ['stdc++', 'pthread', 'm'])

    if util.platform == 'linux':
        vstEnvironment.Append(LIBS              = ['util', 'dl', 'm'])
    elif util.platform == 'darwin':
        vstEnvironment.Append(LIBS              = ['dl', 'm'])
        vstEnvironment.Append(SHLINKFLAGS       = '--no-export-all-symbols')
        vstEnvironment.Append(SHLINKFLAGS       = '--add-stdcall-alias')
        vstEnvironment['SHLIBSUFFIX']           = '.dylib'
    elif util.platform == 'win32':
        if util.compilerGNU():
            vstEnvironment['ENV']['PATH']       = os.environ['PATH']
            vstEnvironment.Append(SHLINKFLAGS   = Split('-Wl,--add-stdcall-alias --no-export-all-symbols'))
            vstEnvironment.Append(CCFLAGS       = ['-DNDEBUG'])
            guiProgramEnvironment.Prepend(LINKFLAGS = Split(
                '-mwindows -Wl,--enable-runtime-pseudo-reloc'))
            vstEnvironment.Prepend(LINKFLAGS =
                ['-Wl,--enable-runtime-pseudo-reloc'])
            guiProgramEnvironment.Append(LINKFLAGS  = '-mwindows')
    csoundVstSources = Split('''
    CsoundVST/vstsdk2.4/public.sdk/source/vst2.x/audioeffect.cpp
    CsoundVST/vstsdk2.4/public.sdk/source/vst2.x/audioeffectx.cpp
    CsoundVST/vstsdk2.4/public.sdk/source/vst2.x/vstplugmain.cpp
    CsoundVST/CsoundVST.cpp
    CsoundVST/CsoundVstFltk.cpp
    CsoundVST/CsoundVSTMain.cpp
    CsoundVST/CsoundVstUi.cpp
    ''')
    if util.platform == 'win32':
        if util.compilerGNU():
           vstEnvironment.Append(SHLINKFLAGS = ['-module'])
        csoundVstSources.append('CsoundVST/_CsoundVST.def')
    csoundvst = vstEnvironment.SharedLibrary('CsoundVST', csoundVstSources)
    csoundvstGui = guiProgramEnvironment.Program(
        'CsoundVSTShell', ['CsoundVST/csoundvst_main.cpp'])
    Depends(csoundvstGui, csoundvst)
    util.installLib(csoundvst)
    util.installProgram(csoundvstGui)
else:
    util.confDecision('Not building CsoundVST plugin and standalone.')
