# Load and initialze the CCSAPI Tcl interface
set ccssim2 1
set starcore_compiler 2.0
set last_printf ""
puts "    Loading ccssim2api.tcl file"
if { $ccssim2 } {
	set ccsExecPath $ccssim2ExecPath
}
set SCEXT "${ccsExecPath}/scext[info sharedlibextension]"
set ELFIOLOADER "${ccsExecPath}/elfioloader[info sharedlibextension]"
set SYSCALL "${ccsExecPath}/syscall[info sharedlibextension]"
set PPCDASM  "${ccsExecPath}/ppcdasm[info sharedlibextension]"
set ac 0
set env(CCS_LIB_PATH) ${ccsExecPath}
set TKCON(hoterrors) 1

if {[file readable $SCEXT]} {
    puts -nonewline "        Loading StarCore Extensions scext[info sharedlibextension]..."
    if {[catch {::load $SCEXT}]} {
        puts "Failed"
        return
    } else {
		puts "Done"
    }
}
if {[file readable $SYSCALL]} {
    puts -nonewline "Loading Syscall ($SYSCALL)..."
    if {[catch {::load $SYSCALL}]} {
        puts "Failed"
        return
    } else {
        puts ""
    }
}
if {[file readable $PPCDASM]} {
    puts -nonewline "Loading Ppcdasm ($PPCDASM)..."
    if {[catch {::load $PPCDASM}]} {
        puts "Failed"
        return
    } else {
        puts ""
    }
}


if {[file readable $ELFIOLOADER]} {
    puts -nonewline "        Loading Elf Loader elfioloader[info sharedlibextension]..."
    if {[catch {::load $ELFIOLOADER}]} {
        puts "Failed"
        return
    } else {
		puts "Done"
    }
}
#rename load dllload
proc showproc {proc} {
    set args [info args $proc]
    set arginfo [list]
    foreach arg $args {
        if {[info default $proc $arg def]} {
            lappend arginfo [list $arg $def]
        } else {
            lappend arginfo $arg
        }
    }
    puts -nonewline "proc $proc {$arginfo} {"
    puts -nonewline [info body $proc]
    puts "}"
}

proc showcfg {{nspace 0}} {

    if {[string is integer $nspace]} {
        set nspace [eval "set ::ccs::chain($nspace)"]
    }
    namespace eval $nspace {
        variable cindex
        variable cfg
        for {set i 0} {$i < $cindex} {incr i} {
            puts $cfg($i)
        }
    }
}

#foreach n {arm7tdmi rnbo_sync rnbo_mcore rnbo_sc140 rnbo_ipcm sc140 hawkv2 mcore mcore340 dsp563 dsp566 dsp568 rcp_sync rcp_dsp566 rcp_mcore msc8102_sync msc8102_sc140 mpc603e mpc603ei ms116 msfpga} {
foreach n {cf2 cf4 sc140 mpc603e mpc603ei e500 e300 ce 8555 8548} {
    set fn "${ccsExecPath}/t${n}.tcl"
    if {[file readable $fn]} {

        puts "        Initializing $n namespace..."

        namespace eval $n {
            set gindex 0
            set cindex 0
            set cp 0
            proc mkreg {name index} {
                variable reg
                set reg(${name}) ${index}
                set reg(${index}) ${name}
            }
            proc VarAccess {name1 name2 op} {
                set regname [namespace tail $name1]
                set regnamespace [namespace qualifiers $name1]
                if {[string match $op r]} {
                    set $name1 [ccs::read_reg [set ${regnamespace}::cp] $regname 1]
                } else {
                    ccs::write_reg [set ${regnamespace}::cp] $regname [set $name1]
                    set $name1 [ccs::read_reg [set ${regnamespace}::cp] $regname 1]
                }
            }
            if {$n == "e300" || $n == "mpc603e" || $n == "mpc603ei" || $n == "e500" || $n == "e300" || $n == "ce" || $n == "8555" || $n == "8548"} {
                proc addreg {name gindex} {
                    variable reg
                    upvar $name rname
                    set reg(${name}) ${gindex}
                    set reg(${gindex}) ${name}
                }
            } else {
				proc addreg {name} {
					variable reg
					variable gindex
					upvar $name rname
					set reg(${name}) ${gindex}
					set reg(${gindex}) ${name}
					if {0} {
						#set rcmd "eval \{set $name \\\[::ccs::read_reg \$::ac $gindex 1\\\]\}"
						set wcmd "::ccs::write_reg \$::ac $gindex \[set $name\]"
						set rname "XXXX"
						trace variable [namespace current]::$name rw "[namespace current]::VarAccess"
						#trace variable [set ::[namespace current]::name] w {eval $wcmd}
						#trace variable [set ::[namespace current]::name] r $rcmd
					}
					incr gindex
				}
			}
            proc addcfg {name} {
                variable cfg
                variable cindex
                set cfg(${name}) ${cindex}
                set cfg(${cindex}) ${name}
                incr cindex
            }
            puts "include $n ..."
            
            source $fn
            
            puts "include $n"
            
            if { $n == "msc8102_sc140" || $n == "msc8102_sync"} {
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/8102_debugger.tcl]} {
                    source ${ccsExecPath}/8102_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/msc8102_sc140.tcl]} {
                    source ${ccsExecPath}/msc8102_sc140.cfg
                }
            } elseif { $n == "sc140" } {
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                #if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                #    source ${ccsExecPath}/ppc_debugger.tcl
				#}
                if {[file readable ${ccsExecPath}/sc140_debugger.tcl]} {
                    source ${ccsExecPath}/sc140_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/sc140.cfg]} {
                    source ${ccsExecPath}/sc140.cfg
                }
            } elseif { $n == "cf2" } {
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                #if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                #    source ${ccsExecPath}/ppc_debugger.tcl
				#}
                if {[file readable ${ccsExecPath}/cf2_debugger.tcl]} {
                    source ${ccsExecPath}/cf2_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/cf2.cfg]} {
                    source ${ccsExecPath}/cf2.cfg
                }
            } elseif { $n == "cf4" } {
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                #if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                #    source ${ccsExecPath}/ppc_debugger.tcl
				#}
                if {[file readable ${ccsExecPath}/cf4_debugger.tcl]} {
                    source ${ccsExecPath}/cf4_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/cf4.cfg]} {
                    source ${ccsExecPath}/cf4.cfg
                }
            } elseif { $n == "mpc603e" } {
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                    source ${ccsExecPath}/ppc_debugger.tcl
				}
            } elseif { $n == "e500"  || $n == "e300" || $n == "8555" || $n == "8548"} {
                
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                    source ${ccsExecPath}/ppc_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/elf_debugger.tcl]} {
                    source ${ccsExecPath}/elf_debugger.tcl
                }
            } elseif { $n == "ce"} {
                
                if {[file readable ${ccsExecPath}/common_debugger.tcl]} {
                    source ${ccsExecPath}/common_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/ppc_debugger.tcl]} {
                    source ${ccsExecPath}/ppc_debugger.tcl
                }
                if {[file readable ${ccsExecPath}/elf_debugger.tcl]} {
                    source ${ccsExecPath}/elf_debugger.tcl
                }
            }
            if {[array exists Stat]} {
                foreach R $Stat(reg) {
                    for {set m 0} {$m < 32} {incr m} {
                        set StatLast${m}($R) X
                    }
                }
            }
        }

        puts "\tDone initializing $n namespace."
    }
}
proc showbits {val} {
    foreach t {31 15} b {16 0} {
        for {set i $t} {$i>=$b} {incr i -1} {
            puts -nonewline [format "|%02d" $i]
        }
        puts ""
        for {set i $t} {$i>=$b} {incr i -1} {
            puts -nonewline [format "| %d" [expr ($val >> $i) & 1]]
        }
        if {$b == 0} {
            puts ""
        } else {
            puts ""
            for {set i $t} {$i>=$b} {incr i -1} {
                puts -nonewline "+--"
            }
            puts ""
        }
    }
}
proc display {args} {

    ;# get chain configuration
    ::ccs::get_config_chain

    switch -glob [lindex $args 0] {
        *read_reg {
            if {[llength $args] != 4} {
                ccs::read_reg
            }
            ccs::display_reg [lindex $args 1] [lindex $args 2] [lindex $args 3]
        }
        *read_mem {
            if {[llength $args] != 6} {
                ccs::read_mem
            }
            ccs::display_mem [lindex $args 1] [lindex $args 2] \
                             [lindex $args 3] [lindex $args 4] \
                             [lindex $args 5]
        }
        *rtd_stat {
            if {[llength $args] != 2} {
                ccs::rtd_stat
            }
            ccs::display_rtd_stat [lindex $args 1]
        }
        *core_run_mode {
            if {[llength $args] != 2} {
                ccs::core_run_mode
            }
            ccs::display_core_run_mode [lindex $args 1]
        }
        *get_config_chain {
            if {[llength $args] != 1} {
                ccs::get_config_chain
            }
            ccs::display_get_config_chain
        }
        *template_version {
            if {[llength $args] != 2} {
                ccs::template_version
            }
            puts "Version: [ccs::template_version [lindex $args 1]]"
        }
        default {
            set values [eval $args]
            puts $values
            #foreach value $values {
            #    puts [format "0x%08X" $value]
            #}
        }
    }
}

namespace eval ccs {
    #proc gofast {} {
    #wig::write_large_memory 2 0x0020c000 2 0 0x0002
    #wig::set_speed 1
    #}

    proc mkcore {name index} {
        variable core
        set core(${name}) ${index}
        set core(${index}) ${name}
    }

    mkcore generic         0
    mkcore dsp563          1
    mkcore dsp566          2
    mkcore dsp568          3
    mkcore mcore210        4
    mkcore arm7tdmi        5
    mkcore sc140           6
    mkcore mcore340        7
    mkcore ipcm            8
    mkcore hawkv2          9
    mkcore rcp_sync       10
    mkcore rcp_dsp566     11
    mkcore rcp_mcore      12
    mkcore wcp_sync       13
    mkcore wcp_dsp566     14
    mkcore wcp_arm7tdmi   15
    mkcore rnbo_sync      16
    mkcore rnbo_sc140     17
    mkcore rnbo_mcore     18
    mkcore rnbo_ipcm      19
    mkcore testcore       20
    mkcore msc8102_sync   21
    mkcore msc8102_sc140  22

    mkcore elf            23
    mkcore etpu           24
    mkcore coldfire       25

    mkcore esys_sync      26
    mkcore esys_elf       27
    mkcore esys_etpu0     28
    mkcore esys_etpu1     29
    mkcore esys_ace       30
    mkcore mpc603e        31
    mkcore mpc603ei       32

    mkcore ms116          33
    mkcore msfpga         34

    proc mkmode {name index} {
        variable mode
        set mode(${name}) ${index}
        set mode(${index}) ${name}
    }

    mkmode debug     0
    mkmode execute   1
    mkmode sleep     2
    mkmode waitstate 3

    proc rcp_config_chain {} {
        variable core
        set ::top 0
        set ::dsp 1
        set ::mcu 2
        set ::mc 2
        config_chain [list $core(rcp_sync) $core(rcp_dsp566) $core(rcp_mcore)]
    }

    proc wcp_config_chain {} {
        variable core
        config_chain [list $core(wcp_sync) $core(wcp_dsp56600) $core(wcp_arm7tdmi)]
    }

    proc rnbo_config_chain {} {
        variable core
        set ::ed 0
        set ::sc 1
        set ::mc 2
        set ::ip 3
        set ::top 0
        set ::dsp 1
        set ::mcu 2
        set ::dma 3
        config_chain [list $core(rnbo_sync) $core(rnbo_sc140) $core(rnbo_mcore) $core(rnbo_ipcm)]
    }

    proc msc8102_config_chain {} {
        variable core
        set ::top 0
        set ::sc0 1
        set ::sc1 2
        set ::sc2 3
        set ::sc3 4
        config_chain [list $core(msc8102_sync) $core(msc8102_sc140) $core(msc8102_sc140) $core(msc8102_sc140) $core(msc8102_sc140)]
    }

    proc display_core_run_mode {chain_pos} {
        variable chain
        variable mode
        set modenum [core_run_mode $chain_pos]
        puts "$chain($chain_pos): $mode($modenum)"
    }

    proc display_get_config_chain {} {
        variable chain
        variable core
        set i 0

        set lchain [get_config_chain]
        if {![llength $lchain]} {
            puts "Chain not configured"
            return
        }
        foreach dev $lchain {
            puts "Chain Position $i: $core($dev)"
            ;#set chain($i) $core($dev)
            incr i
        }
    }

    proc display_rtd_stat {chain_pos} {
        variable chain
        set stat [rtd_stat $chain_pos]
        puts "$chain($chain_pos): available to read: [lindex $stat 0], left to write: [lindex $stat 1]"
    }

    #display ccs::read_reg in a nice way
    proc display_reg {chain_pos reg_index count} {
        variable chain
        set columns 4
        set maxpad 7
        set vals [read_reg $chain_pos $reg_index $count]
        if {![string is integer $reg_index]} {
            set nspace [eval "set chain($chain_pos)"]
            set reg_index [eval "set ::${nspace}::reg($reg_index)"]
        }
        set regnum $reg_index
        set j 0
        foreach val $vals {
            set nspace [eval "set chain($chain_pos)"]
            set regname [eval "set ::${nspace}::reg($regnum)"]
            set padlen [expr $maxpad - [string length $regname]]
            set padstr ""
            incr j
            if {$padlen < 0} {

            } else {
                for {set i 0} {$i < $padlen} {incr i} {
                    append padstr " "
                }
            }
            puts -nonewline [format "%s%s=0x%08X" $padstr $regname $val]
            if {!($j % $columns)} {
               puts ""
            } else {
               puts -nonewline " "
            }
            incr regnum
        }
        if {$j % $columns} {
            puts ""
        }
    }

    # display ccs::read_mem in a nice way
    proc display_mem {chain_pos addr size space count} {
        variable chain
        set vals [read_mem $chain_pos $addr $size $space $count]
        set nspace [eval "set chain($chain_pos)"]
        set msize $size
        puts -nonewline {            }
        if {$nspace == "dsp568" || $nspace == "hawkv2"} {
            for {set i 0} {$i<8} {incr i} {
               puts -nonewline [format "   +%X" $i]
            }
            set fmtstr " %04X"
            set msize 1
        } elseif {$size == 1} {
            for {set i 0} {$i<16} {incr i} {
               puts -nonewline [format " +%X" $i]
            }
            set fmtstr " %02X"
        } elseif {$size == 2} {
            for {set i 0} {$i<16} {incr i 2} {
               puts -nonewline [format "   +%X" $i]
            }
            set fmtstr " %04X"
        } else {
            for {set i 0} {$i<16} {incr i 4} {
               puts -nonewline [format "       +%X" $i]
            }
            set fmtstr " %08X"
        }
        for {set i 0} {$i < $count} {incr i} {
            if {!($i%(16/$size))} {
                puts -nonewline [format "\n\[0x%08X\]" [expr $addr+($i*$msize)]]
            }
            puts -nonewline [format $fmtstr [lindex $vals $i]]
        }
        puts ""
    }

    # new config_chain which keeps track of core namespaces
    proc config_chain_2 {core_names} {
        variable chain
        set cores [list]
        foreach core $core_names {
            if {![string is integer $core]} {
                lappend cores $::ccs::core($core)
            } else {
                lappend cores $core
            }
        }
        original_config_chain $cores
        set i 0
        foreach core $cores {
            set chain($i) $::ccs::core($core)
            incr i
        }
    }

    proc get_config_chain_2 {} {
        variable chain
        set cores [original_get_config_chain]
        set i 0
        foreach core $cores {
            set chain($i) $::ccs::core($core)
            incr i
        }
        return $cores
    }

    proc read_reg_2 {chain_pos reg_index count} {
        variable chain

        if {![string is integer $reg_index]} {
            set nspace [eval "set chain($chain_pos)"]
            set reg_index [eval "set ::${nspace}::reg($reg_index)"]
        }
        return [original_read_reg $chain_pos $reg_index $count]
    }

    proc write_reg_2 {chain_pos reg_index reg_list} {
        variable chain

        if {![string is integer $reg_index]} {
            set nspace [eval "set chain($chain_pos)"]
            set reg_index [eval "set ::${nspace}::reg($reg_index)"]
        }
        return [original_write_reg $chain_pos $reg_index $reg_list]
    }

    proc config_template_2 {chain_pos index value} {
        variable chain
        if  {![string is integer $index]} {
            set nspace [eval "set chain($chain_pos)"]
            set index [eval "set ::${nspace}::cfg($index)"]
        }
        return [original_config_template $chain_pos $index $value]
    }

    proc view_messages {chain_pos} {
        return [get_messages $chain_pos 5318008]
    }

	if { ! $ccssim2 } {
    # Rename procedures if necessary
		if {![info exists procsRenamed]} {
			set procsRenamed 0
			rename config_chain original_config_chain
			rename config_chain_2 config_chain

			rename get_config_chain original_get_config_chain
			rename get_config_chain_2 get_config_chain

			rename read_reg original_read_reg
			rename read_reg_2 read_reg

			rename write_reg original_write_reg
			rename write_reg_2 write_reg

			rename config_template original_config_template
			rename config_template_2 config_template
		}
	}
    proc show_connections {} {
        variable clients
        variable bytesSent
        variable bytesRecv
        variable connectTime
        set i 0
        set currentTime [clock seconds]
        foreach client $clients sent $bytesSent recv $bytesRecv time $connectTime {
            incr i
            set deltaT [expr $currentTime-$time]
            set duration [format "%02d:%02d:%02d" [expr $deltaT/(60*60)] [expr $deltaT/60] [expr $deltaT%60]]
            puts "#$i: $client connected for $duration, [expr $sent+$recv] bytes transferred"
        }
    }

    proc step {{chain_pos 0}} {
        variable chain
        ::ccs::get_config_chain
        set nspace [eval "set chain($chain_pos)"]
        array set Stat [array get "::${nspace}::Stat"]
        set runmode [::ccs::core_run_mode $chain_pos]
        if {$runmode != 0} {
            puts "$Stat(core) in $::ccs::mode($runmode) mode"
            return
        }
        ::ccs::step_core $chain_pos 1
        stat $chain_pos
    }

    proc stat {{chain_pos 0}} {
        variable chain
        variable statList
        ::ccs::get_config_chain
        set nspace [eval "set chain($chain_pos)"]
        set runmode [::ccs::core_run_mode $chain_pos]
        array set Stat [array get "::${nspace}::Stat"]
        array set StatLast [array get "::${nspace}::StatLast${chain_pos}"]
        puts -nonewline ""
        cputs "<f=darkgreen>{ $chain_pos : $Stat(core) }<f=x>"
        if {$runmode != 0} {
            cputs "$::ccs::mode($runmode) mode"
            return
        }
        foreach r $Stat(reg) s $Stat(size) {
            set $r [::ccs::read_reg $chain_pos $r 1]
            if {[string is integer $StatLast($r)] && $StatLast($r) != [set $r]} {
                set formatstr "<f=red>0x%0${s}X<f=x>"
            } else {
                set formatstr "0x%0${s}X"
            }
            set fmt(${r}) [format $formatstr [set $r]]
            set "::${nspace}::StatLast${chain_pos}($r)" [set $r]
        }
        if {![info exists Stat(memspace)]} {
            set Stat(memspace) 0
        }
        if {[info exists pc]} {
            set meml [ccs::read_mem $chain_pos $pc $Stat(inst) $Stat(memspace) $Stat(icnt)]
            eval "set foutput \"$Stat(fmt)\""
            cputs -nonewline "$foutput \["
            set i 0
            foreach dat $meml {
                if {$i} {
                    cputs -nonewline " "
                }
                incr i
                cputs -nonewline [format "%0[expr $Stat(inst)*2]X" $dat]
            }
            cputs "\]"
            set intpc [expr $pc]
            if {[info exist statList(${chain_pos},${intpc})]} {
                cputs "$statList(${chain_pos},${intpc})"
            }
        }
        puts -nonewline ""
    }

    array set statList [list]
    proc uselst {chain_pos lstfile} {
        variable statList
        array set statList [list]
        set pcint -1
        set fp [open $lstfile "r"]
        while {![eof $fp]} {
            set line [gets $fp]
            set asmline [regexp {^([0-9]+) +P:(........) ([0-9A-F]+) +(.*)} $line mVar lnum pc opcode asm]
            set hexline [regexp {^ +([0-9]+) *$} $line mVar operand]
            if {$asmline} {
                set pcint [expr "0x${pc}"]
                regsub -all { +} $asm { } asm ;# collapse all spaces
                set statList(${chain_pos},${pcint}) "<f=yellow><b=darkblue> [file tail $lstfile]#${lnum} <b=x><f=darkgreen> ${asm} => ${opcode}<f=x>"
            } elseif {$hexline && ($pcint != -1)} {
                append statList(${chain_pos},${pcint}) " <f=darkgreen>${operand}<f=x>"
            }
        }
        close $fp
    }

    proc load {chain_pos lstfile} {
        variable chain
        variable statList
        ::ccs::get_config_chain
        set nspace [eval "set chain($chain_pos)"]
        array set Stat [array get "::${nspace}::Stat"]
        if {![llength [namespace eval ::${nspace} {info procs load}]]} {
            cputs "$Stat(core) does not support load"
            return
        }
        set runmode [::ccs::core_run_mode $chain_pos]
        if {$runmode != 0} {
            cputs "$Stat(core) in $::ccs::mode($runmode) mode"
            return
        }
        ::${nspace}::load $chain_pos $lstfile
    }

    proc all_run_mode {} {
        set lchain [get_config_chain]
        set i 0
        foreach core $lchain {
            display core_run_mode $i
            incr i
        }
        if {!$i} {
            puts "Chain not configured"
        }
    }

    proc datlist {length} {
        for {set i 0} {$i<$length} {incr i} {
            lappend dat [expr 0xDA7A0000 + $i]
        }
        return $dat
    }
    proc download {file chain_pos addr size} {
        set fp [open $file r]
        set data [read $fp]
        close $fp
        ccs::write_mem $chain_pos $addr $size 0 $data
        set bytes [expr [llength $data]*$size]
        puts "$bytes bytes written"
    }

    proc dumpParam {} {
        variable param
        if {![array exists param]} {
            puts "param is not an array"
            return 0
        }
        foreach {name value} [array get param] {
            puts "$value param->$name"
        }
        return 0
    }

    proc dumpReply {} {
        variable reply
        if {![array exists reply]} {
            puts "reply is not an array"
            return 0
        }
        foreach {name value} [array get ::reply] {
            puts "$value reply->$name"
        }
        return 0
    }
    proc initEnum {varBase procBase enumList} {
        variable enumName_${varBase}
        variable enumIndex_${varBase}
        catch {unset enumName_${varBase}}
        catch {unset enumIndex_${varBase}}
        set i 0
        foreach name $enumList {
            set enumName_${varBase}($i) $name
            set enumIndex_${varBase}($name) $i
            incr i
        }
        set newProcs [subst {
            proc get${procBase}Name {index} {
                return \[getEnumName $varBase \$index\]
            }
            proc get${procBase}Index {name} {
                return \[getEnumIndex $varBase \$name\]
            }
        }]
        eval $newProcs
        namespace export get${procBase}Name
        namespace export get${procBase}Index
        if {0} {
        namespace eval :: [list namespace import -force [namespace current]::get${procBase}Name]
        namespace eval :: [list namespace import -force [namespace current]::get${procBase}Index]
        }
    }

    proc getEnumName {base index} {
        variable enumName_${base}
        if {[info exists enumName_${base}($index)]} {
            return [set enumName_${base}($index)]
        }
        return ""
    }
    proc getEnumIndex {base name} {
        variable enumIndex_${base}
        foreach casename [list $name [string toupper $name] [string tolower $name]] {
            if {[info exists enumIndex_${base}($casename)]} {
                return [set enumIndex_${base}($casename)]
            }
        }
        return ""
    }

    # ccsapi/ccsio enumerations
    initEnum ccs_command Cmd {
        SETUP_CC
        DELETE_CC
        SERVER_VERSION
        CC_VERSION
        AVAILABLE_CONNECTIONS
        CONFIG_CHAIN
        SET_MAX_TCK
        TEMPLATE_VERSION
        CONFIG_TEMPLATE
        CORE_RUN_MODE
        RESET_TO_DEBUG
        RESET_TO_USER
        RESET_TO_MIXED
        READ_MEM
        WRITE_MEM
        FILL_MEM
        READ_REG
        WRITE_REG
        RUN_CORE
        RUN_MULTI_CORE
        STOP_CORE
        STOP_MULTI_CORE
        STEP_CORE
        STEP_MULTI_CORE
        RTD_READ
        RTD_WRITE
        RTD_STAT
        RESET_INTERFACE
        SERVER_ALIVE
        KILL_SERVER
        UNSUPPORTED_0
        UNSUPPORTED_1
        UNSUPPORTED_2
        UNSUPPORTED_3
        GET_CONFIG_CHAIN
        SEND_MESSAGE
        GET_MESSAGES
        CHECK_MIN_VERSION
        UPDATE_NHTI
        GET_SPEED
        READ_PIPED_REG
        UNSUPPORTED_4
        UNSUPPORTED_5
        STRCMD
        SUPPORTED_CONNECTIONS
        HTI_GET_CRC32
        HTI_SET_CRC32
        COUNT
    }

    initEnum ccs_error Error {
        ok
        unimplemented
        network_timeout
        network_fault
        cable_disconnected
        core_not_responding
        invalid_parameter
        invalid_handle
        library_not_found
        core_not_in_debug
        connection_refused
        max_cc_reached
        api_below_min_ver
        ccs_below_min_ver
        invalid_sequence_number
        download_invalid_length
        download_invalid_checksum
        download_invalid_srec
        cc_communications_timeout
        cc_communications_fault
        rtd_buffer_full
        internal_failure
        data_overflow
        cc_not_present
        cc_driver_failure
        usb_open_failure
        usb_not_configured
        usb_transfer_failure
        usb_receive_wait
        usb_receive_reply
        usb_transmit_setup
        usb_transmit_command
        usb_download_setup
        usb_download_checksum
        usb_download_data
        usb_download_wait
        usb_restart_failure
        count
    }

    initEnum ccs_mode Mode {
        debug
        execute
        sleep
        waitstate
        undefined
    }

    namespace export config_chain
    namespace export config_template
    namespace export core_run_mode
    namespace export read_mem
    namespace export read_reg
    namespace export reset_to_debug
    namespace export reset_to_user
    namespace export run_core
    namespace export stop_core
    namespace export write_mem
    namespace export write_reg
    namespace export download
}

set Cputs_nextcolortag stdout
set Cputs_colortag stdout
set Cputs_bgcolor white
set Cputs_fgcolor blue
proc cputs args {
    variable Cputs_colortag
    variable Cputs_nextcolortag
    variable Cputs_bgcolor
    variable Cputs_fgcolor
    if {[lindex $args 0] == "-nonewline"} {
        set str [lindex $args 1]
        set putnewline 0
    } else {
        set str [lindex $args 0]
        set putnewline 1
    }
    set regexpFBColor {^(.*?)<([fb]=[^ <>]+)>(.*)$}
    set regexpColorSwitch {([fb])=(.*)}
    while {[string length $str]} {
        if {[regexp -nocase $regexpFBColor $str match outtext colorswitch remain]} {
            set str $remain
            regexp -nocase $regexpColorSwitch $colorswitch match ground color
            if {[string equal -nocase $ground f]} {
                if {[string equal -nocase $color x]} {
                    set color blue
                }
                set Cputs_fgcolor $color
            } else {
                if {[string equal -nocase $color x]} {
                    set color white
                }
                set Cputs_bgcolor $color
            }
            set Cputs_nextcolortag ${Cputs_fgcolor}${Cputs_bgcolor}
            tkcon console tag configure $Cputs_nextcolortag -foreground ${Cputs_fgcolor} -background ${Cputs_bgcolor}
        } else {
            set outtext $str
            set str ""
        }
        if {[string length $outtext]} {
            tkcon console insert output $outtext $Cputs_colortag
        }
        set Cputs_colortag $Cputs_nextcolortag
    }
    if {$putnewline} {
        tkcon console insert output "\n" stdout
    }
    puts -nonewline ""
}


	if {[file readable $ccssim2ExecPath/sim_debugger.tcl]} {
		catch {uplevel \#0 source $ccssim2ExecPath/sim_debugger.tcl}
	}

puts "    Done loading ccssim2api.tcl"
