#!/usr/local/bin/wish
#
# tktrain
#
# $Id: tktrain,v 1.3 1997/05/26 16:46:02 bri Exp $
#

set direction(0) 0
set functions(0) 0
set speed(0) 0
set speed_max(0) 14

set d_messages(loco_info) 1

source default.tcl
source config.tcl

source common.tcl
 
source tkcab.tcl
# required for update_cabs!

if {$joystick_support} {
    source joystick.tcl
}

source tklayout.tcl

if {$use_mtd} {
    set FD [open "|./mtd" w+]
} else {
    set FD stdout
}

catch {
    fileevent $FD readable {
	set stuff [split [gets $FD]]
	set cmd [lindex $stuff 0]
	if {$cmd == "li"} {
	    set la [lindex $stuff 1]
	    set direction($la) [lindex $stuff 2]
	    set speed($la) [lindex $stuff 3]
	    set functions($la) [lindex $stuff 4]
	    set speed_max($la) [lindex $stuff 5]
	    if {$d_messages(loco_info)} {
		addmsg .textinfo "loco_info $stuff\n"
	    }
	    update_cabs $la
	} elseif {$cmd == "st" || $cmd == "mi"} {
	    set stat [lindex $stuff 1]
	    if {($stat == 0) || ($stat == "go")} {
		set stat "Up and running"
	    } elseif {$stat == 1} {
		set stat "Emergency stop"
	    } elseif {($stat == 2) || ($stat == "power_off")} {
		set stat "Track power off"
	    } elseif {$stat == "prog_mode"} {
		set stat "Programming"
	    }
	    .status config -text "Status: $stat"
	}
    }
}

proc addmsg {w msg} {
    $w config -state normal
    $w insert end "$msg"
    $w config -state disabled
    $w yview end
}

text .textinfo -state disabled -height 3 -width 60
pack .textinfo -anchor w

label .status -text "Status:" 
pack .status -anchor w

# button .b -command "create_new_cab 0 euro1" -text "New cab"
label .l -text "New Cab:"

button .basic -text "basic" -command {
    set foo [create_new_cab 0 basic]
    addmsg .textinfo "new cab $foo; basic\n"
}
button .euro1 -text "euro1" -command {
    set foo [create_new_cab 0 euro1]
    addmsg .textinfo "new cab $foo; euro1\n"
}

button .lay -command "mk_layout .layout" -text "Layout"

button .go -text "Go" -command {
    send_cmd "go"
}
button .es -text "Emergency Stop" -command {
    send_cmd "es"
}
button .po -text "Power Off" -command {
    send_cmd "po"
}

button .q -text "Quit" -command {
    close $FD
    exit
}

pack .l .basic .euro1 .lay .go .es .po .q -side left

#

proc send_cmd {cmd} {
    global FD
    puts $FD "$cmd"
    flush $FD
}

# startup

send_cmd "st"

