from SCons.Script import *
import tempfile
from util import get_suffix, replace_suffix

#----------------------------------------------------------
# builder: HDL files -> .ngc, .syr
# intermediate steps: create .prj and .xst files
#----------------------------------------------------------

enforced_options = {
    'ifmt': 'mixed',
    'ofmt': 'NGC'
}

def xst_targets(env, target, source):
    syr_file = replace_suffix(target[0], '.syr')
    target.append(syr_file)
    return target, source

def run_xst(env, target, source):
    ngc_file, syr_file = map(str, target)
    prj = tempfile.NamedTemporaryFile(suffix='.prj', dir='.')
    prj_file = prj.name
    tmpdir = tempfile.mkdtemp(dir='.')

    for s in source:
        lang = {'.v': 'verilog',
                '.vhd': 'vhdl'}[get_suffix(s)]
        print >> prj, '%s work "%s"' % (lang, str(s))
    prj.flush()

    options = env['options']
    options['ifn'] = prj_file
    options['ofn'] = ngc_file
    options['tmpdir'] = tmpdir
    options.update(enforced_options)
    try:
        intstyle = '-intstyle %s' % (options.pop('intstyle'))
    except KeyError:
        intstyle = ''

    with tempfile.NamedTemporaryFile(suffix='.xst', dir='.') as f:
        print >> f, "run"
        for k, v in options.iteritems():
            print >> f, "-%s %s" % (k, str(v))
        f.flush()
        env.Execute('xst %s -ifn %s -ofn %s' % (
                    intstyle, f.name, syr_file))

    prj.close()
    for suf in ['.lso', '.ngc_xst.xrpt']:
        Execute(Delete(replace_suffix(ngc_file, suf)))
    Execute(Delete(tmpdir))
    Execute(Delete('xst'))
    Execute(Delete('_xmsgs'))

#----------------------------------------------------------

def generate(env, **kw):
    xst_ngc_builder = Builder(action=run_xst,
                              suffix='.ngc',
                              src_suffix='.prj',
                              emitter=xst_targets)

    env.Append(BUILDERS={'XstSynthesis': xst_ngc_builder})
    
# this is not actually called by scons...
def exists(env):
    return env.Detect('xst')


@@ -691,16 +691,106 @@
 dir='.')
+%0A    try:%0A        libraries = env%5B'libraries'%5D%0A    except KeyError:%0A        libraries = %7B%7D
 %0A%0A    fo
@@ -884,16 +884,60 @@
 fix(s)%5D%0A
+        lib = libraries.get(str(s), 'work')%0A
         
@@ -954,20 +954,18 @@
 rj, '%25s 
-work
+%25s
  %22%25s%22' %25
@@ -971,16 +971,21 @@
 %25 (lang,
+ lib,
  str(s))

allow setting different libraries than "work" in Xst