def SetGlobalFloatVar(name,value,index=0,size=16):
#     vv=SM.GLVAR(name)
#     if vv.Status() == 0:
#         gg=SM.GLSM()    # need an object for declarations
#         ans=gg.defineVariable(name,8,size) # 8 bytes always doubles
#         vv=SM.GLVAR(name)
#     if vv.Status():
#         vv.Dput(value,index)
    if Globals.GetValue(name)[0]:
        Globals.DefineGlobal(name,'DOUBLE',size)
    Globals.PutValue(name,value,index)
def SetGlobalIntVar(name,value,index=0,size=16):
#     vv=SM.GLVAR(name)
#     if vv.Status() == 0:
#         gg=SM.GLSM()    # need an object for declarations
#         ans=gg.defineVariable(name,width,size)  # 4 bytes !!!
#         vv=SM.GLVAR(name)
#     if vv.Status():
#         vv.Iput(value,index)
    if Globals.GetValue(name)[0]:
        Globals.DefineGlobal(name,'INT',size)
    Globals.PutValue(name,value,index)
def SetGlobalStringVar(name,value,length=256):
#     vv=SM.GLVAR(name)
#     if vv.Status() == 0:
#         gg=SM.GLSM()    # need an object for declarations
#         ans=gg.defineVariable(name,0,length)
#         vv=SM.GLVAR(name)
#     if vv.Status():
#         vv.Cput(value,len(value))
    if Globals.GetValue(name)[0]:
        Globals.DefineGlobal(name,'CHAR',length)
    Globals.PutValue(name,value,0,length)
def _define_vars(prt=0):
    "defines vars"

    status, kind, value = Globals.GetValue('HIDEUNUSED')
    if status:
        Globals.DefineAllGlobals(0)
    lst = [
        'NUMMODES', 'NUMLOWPASS', 'MODELIST', 'MODEID', 'MODENAMES',
        'MODECLASS', 'MODEPOOL', 'BNUMBER', 'BHEIGHT', 'BUSE', 'DEBUGMODE',
        'FREQUENCY', 'FREQSTEP', 'DISPLAY', 'LOWPASS_LIMIT', 'FMTSTRING',
        'ANYGAME'
    ]

    for nm in lst:
        status, kind, value = Globals.GetValue(nm)
        if status:
            if Globals.DefineGlobal(nm, 'INT'):
                return 1  # error defining

    return 0
def _parse_parblock(filename,
                    dbasedict,
                    edict=None,
                    prt=0,
                    forcerebuild=0,
                    oldtype=0,
                    writeme=0,
                    firstrun=0):
    "parse parameter block and store variables"
    global pmodelist, kindstring, labellist, anygame, layoutdict, loaded, pardic, parxdic, pardicname

    ans = _verf_text(edict, dbasedict, writeme, firstrun)
    if ans:
        #print '353',ans
        #return -5
        pass
    if forcerebuild > 0:
        flist = glob.glob(os.path.join(os.path.split(filename)[0], '*.bfn'))
        for f in flist:
            os.unlink(f)
    pardicname = dbasedict
    if not pardic:
        if type(dbasedict) == type('xxx'):
            # oops, filename passed in during devel phase
            dbn = dbasedict
            try:
                dbasedict = IniAid.LoadConfig(dbn)
            except:
                return -3
        if dbasedict.has_key('__filename'):
            del dbasedict['__filename']
        dbx = IniAid.MakesXdict(dbasedict)  #list of keys format (unique id's)
        pardic = dbasedict
        parxdic = dbx

    try:
        d = IniAid.LoadConfig(filename)
        if prt:
            print 'load success on', filename
    except:
        if prt:
            print 'load failure on', filename
        return -1
    del d['__filename']

    sk = IniAid.MakesXdict(d)
    # see if binary file exists
    #make bin filename
    bfn = filename + '.bfn'
    bfndate = _get_fdate(bfn)
    ftype = os.path.basename(filename)[3]  # shoud be E A or S

    errors = 0
    g = _define_vars(prt)
    if g:
        return -2
    pfdate = os.stat(filename)
    pardate = pfdate[8]
    pardatetime = (pfdate[7], pfdate[8])
    rebuild = bfndate < pardate or pardate > _get_fdate(pardicname)
    if forcerebuild < 0:
        rebuild = forcerebuild
    if not rebuild:
        loaded = Loaded()
        fd = open(bfn, 'rb')
        ver = struct.unpack("=L", fd.read(struct.calcsize("=L")))[0]
        if ver != VERSIONCODE:
            rebuild = 1
            fd.close()

    if rebuild:
        #here to reparse things

        loaded = Loaded()
        pmodelist = []
        layoutdict = {}
        anygame = 0
        if type(pardicname) == type('xxx'):
            # oops, filename passed in during devel phase
            dbn = pardicname
            try:
                dbasedict = IniAid.LoadConfig(dbn)
            except:
                return -3
        if dbasedict.has_key('__filename'):
            del dbasedict['__filename']
        dbx = IniAid.MakesXdict(dbasedict)  #list of keys format (unique id's)
        pardic = dbasedict
        parxdic = dbx
        if ftype == 'A':
            kn = 'atlayouts'
        else:
            kn = 'layouts'
        if dbx.has_key(kn):
            lkeys = dbx[kn]
            for lk in lkeys:
                layoutdict[lk] = dbasedict[kn + '.' + lk]

        #$$num_modes=0
        #$$max_lowpass_channels=0
        heapstart = 1
        keylist = sk.keys()
        keylist.sort()  # into numeric order for modes
        biggest_chan = 0
        usage = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        loaded.modeclass = [0 for i in range(MAXFILTERMODES)]
        modeclass = loaded.modeclass
        kindstring = ''
        labelstring = ''
        xmap = {}
        rmap = {}
        #$$for i in range(32):
        #$$    Globals.PutValue('MODECLASSES',0,i)
        for eachid in range(len(keylist)):
            num_lowpass_channels = 0
            if keylist[eachid][0] < '0' or keylist[eachid][0] > '9':
                # here for 'other' fields  like hsd colors
                pass
            else:
                try:
                    id = d[keylist[eachid] + '.id']
                except:
                    errors += 1
                    if prt:
                        print 'id not found for ', keylist[eachid]
                    continue
                try:
                    namefound = d[keylist[eachid] + '.name']
                except:
                    namefound = ''
                nametext = ''
                try:
                    these = dbx[id]  # all elements of a particular id
                except:
                    errors += 1
                    if prt:
                        print 'id not found in database', repr(id)
                        if eachid == 0:
                            print dbx.keys()
                    continue
                # here to process entries
                # get list of all keys with the same first part
                these.sort()  # the elements of each mode
                loaded.modelist.append(heapstart)
                #$$Globals.PutValue('MODELIST',heapstart,eachid)
                #$$num_modes += 1
                loaded.nummodes += 1
                #$$Globals.PutValue('NUMMODES',num_modes)
                foundextra = ['$' for i in range(17)]
                foundextra[0] = '&'
                level = 0
                for each in these:
                    try:
                        thisone = dbasedict[id + '.' + each]
                    except:
                        errors += 1
                        if prt:
                            print id, each, ' not found in dbasedict', these
                        continue
                    if each == 'name':
                        if namefound == '':
                            namefound = thisone
                        continue
                    if each == 'level':
                        try:
                            v = int(thisone)
                            if not oldtype:
                                if v != 0:
                                    if prt:
                                        print '*************old level value***********', eachid, thisone, id, each
                                v = 0x1f  # make them have everything
                        except:
                            pts = str(thisone).split('+')
                            v = 0
                            for lname in pts:
                                try:
                                    vpart = l_list.index(lname.upper().strip())
                                except:
                                    # I know its an error if not there!!!
                                    if prt:
                                        print '********unknown level value****', eachid, lname, id, each
                                    v |= 0x1f
                                    continue

                                if vpart:
                                    v |= (
                                        1 << (vpart - 1)
                                    )  #just using order in list as bit number

                        level = v
                        ##print '532','level=',level,pts
                        continue
                    if each == 'text':  # explanatory text
                        nametext = thisone
                        continue
                    if each == 'kind':
                        if kindstring == '':
                            kindstring = thisone
                            loaded.kindstring = thisone
                        else:
                            if kindstring != thisone:
                                errors += 1
                                if prt:
                                    print 'mismatched layout', kindstring, thisone, each
                        continue
                    if each == 'label':
                        if labelstring == '':
                            labelstring = thisone
                            loaded.labelstring = thisone
                        continue

                    item = string.split(thisone.lower(), ',')
                    itemuc = string.split(thisone, ',')
                    # first field is funcname
                    if item[0] in funcnames:
                        #ok so far
                        index = funcnames.index(item[0])
                    else:
                        if prt:
                            print item[
                                0], ' not in funcnames', id, item  #each,keylist[i],id,item
                        errors += 1
                        continue
                    ##modeclass[eachid] |= funcclass[index]   # save license reqmt
                    modeclass[eachid] = level
                    ##print '564',id,eachid,modeclass[eachid],index,funcclass[index],item
                    ##loaded.modeclass[eachid] |= funcclass[index]
                    zcmp = 0
                    if item[0] == 'zcomp':
                        zcmp = 1
                    # remainder is keyword list
                    flags = 0
                    num_inputs = 0
                    inp = [0, 0, 0, 0, 0, 0]
                    num_inhib = 0
                    inhib = [0, 0, 0, 0, 0, 0]
                    procfound = 0
                    out = 16
                    rewardgroup = 0
                    backingset = 0
                    hasgame = 0
                    hasinhibit = 0
                    exfnd = 0
                    for k in range(1, len(item)):
                        if item[k] == 'display':
                            flags |= 1
                            if item[0] == 'lowpass':
                                #if num_lowpass_channels != stream:
                                #    errors += 1 # non-sequential lowpass channels
                                num_lowpass_channels += 1
                            continue
                        if item[k] == 'extra':
                            flags |= 4
                            exfnd = 1
                            foundextra[out] = 'E'
                            ##print out,thisone
                            foundextra[16] = 'X'
                            continue
                        if item[k][0:3] == 'in=':
                            sublist = string.split(item[k][3:], '-')
                            for m in range(len(sublist)):
                                if m >= 6:
                                    if prt:
                                        print 'too many inp', id, namefound, each
                                    errors += 1  # too many!!
                                    break
                                inp[m] = int(sublist[m])
                                if inp[m] > 15:
                                    if prt:
                                        print 'in channel too big', id, namefound, each
                                    errors += 1
                                num_inputs += 1
                            continue
                        if item[k][0:4] == 'out=':
                            out = int(item[k][4:])
                            if out > 15:
                                if prt:
                                    print 'out stream too big', id, namefound, each
                                errors += 1
                            else:
                                if out > biggest_chan:
                                    biggest_chan = out
                                    loaded.biggest_chan = out
                            continue
                        if item[k][0:8] == 'inhibit=':
                            hasinhibit = 1
                            sublist = string.split(item[k][8:], '-')
                            for m in range(len(sublist)):
                                if m >= 6:
                                    if prt:
                                        print 'too many inhibits', id, namefound, each
                                    errors += 1  # too many!!
                                    break
                                inhib[m] = int(sublist[m])
                                if inhib[m] > 15:
                                    if prt:
                                        print 'inhibit stream too big', id, namefound, each
                                    errors += 1
                                num_inhib += 1
                            continue
                        if item[k][0:5] == 'game=':
                            hasgame = 1
                            loaded.anygame = 1
                            sublist = string.split(item[k][5:], '-')
                            for m in range(len(sublist)):
                                if m >= 1:
                                    #if prt:
                                    print 'too many game chan selections', id, namefound, each
                                    errors += 1  # too many!!
                                    break
                                inhib[m] = int(sublist[m])
                                num_inhib += 1
                            gameout = int(sublist[0])
                            flags |= 8  # flag for amplitude outputs
                            continue
                        if item[k][0:12] == 'rewardgroup=':
                            rewardgroup = int(item[k][12:])
                            if rewardgroup > 3:
                                if prt:
                                    print 'reward group too big', id, namefound, each
                                errors += 1
                                rewardgroup = 3
                            continue
                        if item[k][0:11] == 'backingset=':
                            backingset = int(item[k][11:])
                            if backingset > 3:
                                if prt:
                                    print 'backing set index too big', id, namefound, each
                                errors += 1
                                backingset = 0
                            continue
                        if item[k][0:5] == 'proc=':
                            pn = itemuc[k][5:].strip()
                            ## do this to build up the list!!!
                            ##if not pn in procnames:
                            ##    procnames.append(pn)
                            ##
                            try:
                                procfound = procnames.index(pn)
                            except:
                                if prt:
                                    print 'unable to locate proc name ', pn, id, namefound, each
                                errors += 1
                            if item[0] == 'qpsfun' or item[0] == 'qasfun':
                                #more decoding necessary
                                if pn[3] == 'm':  # QPSmod
                                    flags |= 0x10
                                elif pn[3] == 'd':  # QPSdev
                                    flags |= 0x20
                            continue
                        # getting here means errors
                        errors += 1
                        if prt:
                            print 'unknown keyword ', item[k], item, id
                    if zcmp:
                        foundextra[out] = 'Z'
                        foundextra[16] = 'X'
                    # do some error checking
                    if funcclass[index] > 1 or (funcclass[index] == 1
                                                and flags & 4):
                        # if extra bit not set on 1 -->not a reward proc
                        if procfound == 0:
                            errors += 1
                            if prt:
                                print 'no proc found on reward process type', thisone, id, each
                    # now pack struct
                    if num_inputs > 1:
                        flags |= 2  # remember multiple inputs
                    flags |= (backingset << 6
                              )  # pass in the backing set offset
                    inhs = inhib[0:3]
                    if num_inhib > 3:  # must pack into nibbles if > 3 inhibits
                        inhs = [(inhib[0] << 4) | inhib[1],
                                (inhib[2] << 4) | inhib[3],
                                (inhib[4] << 4) | inhib[5]]
                    inps = inp[0:3]
                    if num_inputs > 3:
                        inps = [(inp[0] << 4) | inp[1], (inp[2] << 4) | inp[3],
                                (inp[4] << 4) | inp[5]]
                    ostreamgrp = ((rewardgroup & 3) << 6) | out
                    v = struct.pack('@BBBBBBBBBBBB', index, flags, ostreamgrp,
                                    procfound, num_inputs, inps[0], inps[1],
                                    inps[2], num_inhib, inhs[0], inhs[1],
                                    inhs[2])
                    vv = struct.unpack('@lll', v)
                    #$$Globals.PutValue('MODEPOOL',vv[0],heapstart)
                    #$$Globals.PutValue('MODEPOOL',vv[1],heapstart+1)
                    #$$Globals.PutValue('MODEPOOL',vv[2],heapstart+2)
                    #$$Globals.PutValue('MODEPOOL',0,heapstart+3)
                    loaded.modepool.extend(vv)
                    loaded.modepool[0] = heapstart + 3

                    ##print heapstart
                    heapstart += 3
                    if hasgame:
                        if num_inhib > 1:
                            print 'illegal mapping of game output to multiple channels \n', string.join(
                                item, ',')
                        if xmap.has_key(gameout):
                            if xmap[gameout] != gameout:
                                print 'game/out map error ', gameout, id, namefound, each
                                print xmap.keys()
                        else:
                            xmap[gameout] = gameout
##                    if hasinhibit:
##                        if rmap.has_key(inp[0]):
##                            if rmap[inp[0]] != rewardgroup:
##                                print 'reward map error',rewardgroup,inp[0],rmap,id,eachid,filename,item
##                        else:
##                            rmap[inp[0]] = rewardgroup
##                            print 'adding ',inp[0],rewardgroup,item
                    if level & 2:
                        modeclass[eachid] |= 8  # 4channel for qps
                modeclass[eachid] = level
                ##print '747',eachid,level,pts
                # pack an empty word
                loaded.modepool.append(0)
                #$$Globals.PutValue('MODEPOOL',0,heapstart)
                heapstart += 1
                if num_lowpass_channels > loaded.num_lowpass_channels:
                    loaded.num_lowpass_channels = num_lowpass_channels
                if namefound == '':
                    if prt:
                        print 'failed to find name of mode'
                    namefound = 'ERROR'
                #          01234567
                # level codes now mean something different -  must change interp
                # added exp logic
                try:
                    levelcode = ' . ,..,,,,,,,,,,,,,,,,,,,,,,,,,,'[level
                                                                   & 0x1f]
                except:
                    print '!! *************', repr(level)
                    raise
                if level & 0x20:
                    levelcode = chr(
                        level + 0x20)  # makes it 40 N L  for space per comma
                ##print '767',repr(levelcode),'%x'%level,namefound,eachid  ,modeclass
                # '.' means advanced and ',' means really really advanced
                #$$Globals.PutValue('MODENAMES',namefound[0:15]+levelcode,eachid*16,16) # save the 'name' of the mode
                loaded.modename.append(namefound[0:15] + levelcode)
                #$$Globals.PutValue('MODECLASSES',modeclass[eachid],eachid)
                # E for extra flag found,Z for zcomp found, B for both
                textra = ''
                #if foundextra[16] == 'X':
                textra = ''.join(
                    foundextra[:16])  # extra only, zcomp only, both
                prompt = '%-16s : %s|%s|%s|' % (namefound, nametext, textra,
                                                levelcode)
                foundextra = ''
                foundzcomp = ''
                loaded.prompts.append(prompt)
                pmodelist.append(prompt)
                #$$Globals.PutValue('MODEID',int(id),eachid)
                loaded.modeid.append(int(id))
                loaded.modeclass = modeclass

        for i in range(MAXFILTERMODES):
            if i and i >= len(procnames):
                v = ''
                mc = ''
            else:
                v = procnames[i]
                loaded.nummodeprocs += 1
                mc = modeclass[i]
            #$$Globals.PutValue('MODEPROCS',v,i*16,16)   # write out names of the proc modes
            loaded.modeproc.append(v)

##        if Globals.GetValue('NUMMODES')[2]==0:
##            if prt:
##                print 'failed writing nummodes'

##        Globals.DefineGlobal('OMAP','INT',16)
##        m=[-1 for x in range(16)]
##        for k,v in xmap.items():
##            m[k]=v
##        for i in range(16):
##            Globals.PutValue('OMAP',m[i],i)
##        Globals.DefineGlobal('RMAP','INT',16)
##        m=[-2 for x in range(16)]
##        for k,v in rmap.items():
##            m[k]=v
##        for i in range(16):
##            Globals.PutValue('RMAP',m[i],i)
##        if len(rwstreams) > 4:
##            rwstreams=rwstreams[:4]
        for i in range(loaded.biggest_chan + 1):
            try:
                k = fletters.index(kindstring[i])
            except:
                k = 0
            try:
                if kindstring[i] == 'R':
                    loaded.rstream[loaded.numrewards] = i
                    loaded.numrewards += 1
            except:
                print i, kindstring, bfn
        # NOW we write out the file!!!!!!!
        if rebuild > 0:
            fd = open(bfn, 'wb')
            fd.write(
                struct.pack("=L18s82sLLLLLLLLLLL", VERSIONCODE,
                            loaded.kindstring, loaded.labelstring,
                            loaded.anygame, loaded.biggest_chan,
                            loaded.num_lowpass_channels, loaded.nummodes,
                            loaded.numrewards, loaded.rstream[0],
                            loaded.rstream[1], loaded.rstream[2],
                            loaded.rstream[3], loaded.modepool[0] + 1,
                            loaded.nummodeprocs))
            for i in range(loaded.nummodes):
                fd.write(struct.pack("=L", loaded.modelist[i]))
            for i in range(loaded.nummodes):
                fd.write(struct.pack('=L', loaded.modeid[i]))
            for i in range(loaded.modepool[0] + 1):
                fd.write(struct.pack("=L", loaded.modepool[i]))
            for i in range(loaded.nummodes):
                fd.write(struct.pack("=16s", loaded.modename[i]))
            for i in range(loaded.nummodeprocs):
                fd.write(struct.pack('=16s', loaded.modeproc[i]))
            for i in range(loaded.nummodes):
                fd.write(struct.pack('=b', loaded.modeclass[i]))
            for i in range(loaded.nummodes):
                fd.write(struct.pack('=100s', loaded.prompts[i]))
            kv = layoutdict.keys()
            stl = ''
            for k in kv:
                part = k + '=' + layoutdict[k] + '|'
                stl = stl + part
            fmt = '=L%ds' % len(stl)
            fd.write(struct.pack(fmt, len(stl), stl))
            fd.write(chr(0))
            fd.write(chr(0))  # just in case
            fd.close()
            os.utime(bfn, pardatetime)
            loaded.fname = bfn

    else:
        # read IN the file
        sz = struct.calcsize("=18s82sLLLLLLLLLLL")
        loaded.kindstring,loaded.labelstring,loaded.anygame,loaded.biggest_chan,\
                             loaded.num_lowpass_channels,loaded.nummodes,loaded.numrewards,loaded.rstream[0],\
                             loaded.rstream[1],loaded.rstream[2],loaded.rstream[3],loaded.modepool[0],\
                             loaded.nummodeprocs =struct.unpack("=18s82sLLLLLLLLLLL",fd.read(sz))
        # must fix unpack issues
        loaded.kindstring = cstring(loaded.kindstring)
        loaded.labelstring = cstring(loaded.labelstring)
        showlist=['kindstring','labelstring','anygame','biggest_chan',\
                             'num_lowpass_channels','nummodes','numrewards','rstream',\
                             'modepool',\
                             'nummodeprocs']
        if prt:
            for n in showlist:
                print n, ':', loaded.__dict__[n]
        ##print fd.tell()
        sz = struct.calcsize("=L")
        for i in range(loaded.nummodes):
            loaded.modelist.append(struct.unpack("=L", fd.read(sz))[0])
        ##print fd.tell()
        for i in range(loaded.nummodes):
            loaded.modeid.append(struct.unpack("=L", fd.read(sz))[0])
        ##print fd.tell()
        for i in range(loaded.modepool[0]):
            loaded.modepool.append(struct.unpack("=L", fd.read(sz))[0])
        ##print fd.tell()
        for i in range(loaded.nummodes):
            loaded.modename.append(
                cstring(struct.unpack("=16s", fd.read(16))[0]))
        ##print fd.tell()
        for i in range(loaded.nummodeprocs):
            loaded.modeproc.append(
                cstring(struct.unpack("=16s", fd.read(16))[0]))
        ##print fd.tell()
        loaded.modeclass = []
        for i in range(loaded.nummodes):
            loaded.modeclass.append(struct.unpack("=b", fd.read(1))[0])
        while len(loaded.modeclass) < 32:
            loaded.modeclass.append(0)
        pmodelist = []
        for i in range(loaded.nummodes):
            loaded.prompts.append(
                cstring(struct.unpack("=100s", fd.read(100))[0]))
            pmodelist.append(loaded.prompts[i])
        ##print fd.tell()
        numbytes = struct.unpack("=L", fd.read(sz))[0]
        fmt = "=%ds" % numbytes
        ##print fmt
        lstring = cstring(struct.unpack(fmt, fd.read(struct.calcsize(fmt)))[0])
        parts = lstring.split('|')
        layoutdict = {}
        for some in parts:
            v = some.split('=')
            if len(v) != 2:
                continue
            layoutdict[v[0]] = v[1]

        loaded.fname = bfn
        fd.close()
        modeclass = loaded.modeclass

    ##print '915',modeclass
    # now have to set/reset values for Python code use and existing initialization logic
    #MODECLASSES,PROMPTS->modelist
    Globals.PutValue('NUMLOWPASS', loaded.num_lowpass_channels)
    Globals.PutValue('ANYGAME', loaded.anygame)  # remember if any game outputs
    Globals.PutValue('FMTSTRING', loaded.kindstring, 0, 16)
    kindstring = loaded.kindstring
    # here we process the other blocks:
    # HSDinit
    Globals.PutValue('BNUMBER', loaded.biggest_chan + 1)
    if loaded.biggest_chan > 8:
        Globals.PutValue('BHEIGHT', 40)
    elif loaded.biggest_chan > 6:
        Globals.PutValue('BHEIGHT', 75)
    else:
        Globals.PutValue('BHEIGHT', 90)
    Globals.PutValue('DEBUGMODE', 1)
    Globals.PutValue('FREQUENCY', 256)
    Globals.PutValue('FREQSTEP', .50)
    Globals.PutValue('DISPLAY', 1)
    Globals.PutValue('LOWPASS_LIMIT', 40)

    toggle = [0, 0, 0, 0, 0]
    labellist = loaded.labelstring.split(',')
    #$$rwstreams=[]
    for i in range(loaded.biggest_chan + 1):
        try:
            k = fletters.index(kindstring[i])
        except:
            k = 0
        #$$if kindstring[i] == 'R':
        #$$    rwstreams.append(i)

        Globals.PutValue('BUSE', k, i)
        ##        if prt:
        ##            print i,k,g['BUSE'].Iget(i)
        Globals.PutValue('BFUNCTION%d' % i, labellist[i], 0, len(labellist[i]))
        ##print kindstring,k,i
        fl = frqs[k]
        if len(fl) > 1:
            fr = fl[toggle[k]]
            toggle[k] += 1
            if toggle[k] >= len(fl):
                toggle[k] = 0
        else:
            fr = fl[0]
        x = '%5.2f-%5.2f                             ' % (fr[0], fr[1])

        Globals.PutValue('BNAME%d' % i, x, 0, len(x))
        ##        if prt:
        ##            print x
        Globals.PutValue('LOWFREQ', fr[0], i)
        Globals.PutValue('HIGHFREQ', fr[1], i)

    Globals.PutValue('NUMREWARDS', loaded.numrewards, 0)
    Globals.PutValue('REWSTREAM', loaded.rstream[0], 0)
    Globals.PutValue('REWSTREAM', loaded.rstream[1], 1)
    Globals.PutValue('REWSTREAM', loaded.rstream[2], 2)
    Globals.PutValue('REWSTREAM', loaded.rstream[3], 3)
    ##print rwstreams,kindstring
    tclst = [
        ('AVERAGETC', 30.0),
        ('INTEGRALTC', .5),
        ('PROBABILITYTC', 30.),
        ('DCCOMPTC', 10.),
        ('ARTIFACTTC', .25),
        ('OVERALLTC', 30.0),
        ('REWARDTC', .5),
        ('AVERAGESHAMTC', 30.0),
        ('ShamFastTC', .5),
    ]
    if edict:
        if edict.has_key('SETTINGS'):
            for nm, tc in tclst:
                if edict['SETTINGS'].has_key(nm):
                    tc = float(edict['SETTINGS'][nm])
                Globals.PutValue(nm, tc)

    for specials in ('hsdinit', 'rsfinit'):
        if sk.has_key(specials):
            vars = sk[specials]
            for nm in vars:
                dname = specials + '.' + nm
                val = d[dname]
                Globals.DefineGlobal(nm, 'INT', 0)
                try:
                    Globals.PutValue(nm, int(val))
                except ValueError:
                    try:
                        Globals.PutValue(nm, int(val, 16))
                    except ValueError:
                        if prt:
                            print 'invalid int value ', val


##    if prt:
##        print 'ending pool',heapstart

    del d
    del sk
    return errors