proc checkEnvironment {} {
    set name [info nameofexecutable]
    # Remove the path and the extension.
    regsub "^.*/" $name "" name
    regsub "\.exe$" $name "" name

    if       {$name eq "vish"} {
        variable interpreter   "msim"
    } elseif {$name eq ""} {
        variable interpreter   "project_navigator"
    } elseif {$name eq "xtclsh"} {
        variable interpreter   "xtclsh"
    } else {
        variable interpreter   "isesim"
    }

    variable shell "sh"
    if {$::tcl_platform(platform) eq "windows"} {
        set shell "sh.exe"
    }
}

proc checkResult {command} {
    puts stdout "Marker for check"
    eval $command
    set iChannel [open transcript r]

    set err 0
    while {1} {
        set rc [gets $iChannel line]
        if {$rc == -1} {
            break
        }
        if [regexp "^# Marker for check" $line] {
            set err 0
        } elseif [regexp {[Ee]rror} $line] {
            set err 1
        }
    }
    close $iChannel

    if {! $err} {
        return 1
    } else {
        return 0
    }
}


checkEnvironment

if {$::interpreter eq "msim"} {
    # To call "fsm.tcl" easily.
    set dir ""
    variable hdl
    foreach {i} [project compileorder] {
        if [regexp "(.*)/model/NOODLYBOX.(vh?d?)" $i dummy dir hdl] {
            unset dummy
            if {$hdl eq "vhd"} {
                set hdl "vhdl"
            } else {
                set hdl "verilog"
            }
            break
        }
    }
    if {$dir ne ""} {
        array set env "DOPATH $dir/tcl"
    }
    unset i dir
    
    proc c {} {
        project compileoutofdate
    }
    proc ca {} {
        project compileall
    }
    proc co {} {
        project calculateorder
    }
    proc qs {} {
        quit -sim
    }
    proc aq {} {
        abort
        quit -sim
    }
    proc make {} {
        set currentDir [pwd]
        if {$::tcl_platform(platform) eq "windows"} {
            regsub ":" $currentDir "" currentDir
            set currentDir "/$currentDir"
        }
        exec $::shell --login -i -c \
        "cd $currentDir/../..; . settings.sh; cd $currentDir; make"
        project compileoutofdate
    }
} elseif {$::interpreter eq "project_navigator"} {
    proc . {file} {
        source $file
    }
    proc pc {} {
        project close
    }
    proc ls {} {
        exec cmd /C dir
    }
    proc sy {} {
        process run "Synthesize"
    }
    proc im {} {
        process run "Implement Design"
    }
    proc gp {} {
        process run "Generate Programming File"
    }
}
