####################################
# Socket management - client part - 
####################################

namespace eval XesClient {
    variable client_socket
    set client_socket -1
}

proc XesClient::InitConnection  { {serverInfoFile xesport.esp} } {
    variable client_socket
    if {[file extension $serverInfoFile] != ".esp"} {
	append serverInfoFile ".esp"
    }
    if { [catch {open $serverInfoFile r} fd] } {
	# ERROR: cannot open file
	return -code error
    }
    while {[gets $fd line]} {
	if {[regexp {(\S+)\s+(\d+)} $line dummy host port]} {
	    if {[catch {socket $host $port} client_socket]} {
		# ERROR: cannot open socket
		return -code error
	    } else {
		return 
	    }
	}
    }
    # ERROR: bad xesport.esp file
    return -code error
}

proc XesClient::SendCsimulEvent { { string {} } } {
    variable client_socket
    if {[catch {puts $client_socket $string; flush $client_socket} err]} {
	return -code error
    }
}

proc XesClient::CloseConnection {} {
    variable client_socket
    catch {close $client_socket}
}





# Example of use for the watch program, with a very simple GUI
#-------------------------------------------------------------

# Start connection
if {[catch {XesClient::InitConnection [lindex $argv 0] } ]} {
    exit 1
}

# Create a simple menu bar
. configure -menu .menubar
menu .menubar
menu .menubar.file -tearoff false
.menubar add cascade \
    -label File \
    -menu .menubar.file
.menubar.file add command \
    -label Quit \
    -command {exit 0}

# for each UL, UR,.... creates a corresponding button .ul, .ur,...
# that sends the Csimul event: "UL;", "UL;" ...
foreach button {UL UR LL LR HS} {
    pack [button .[string tolower $button] \
	      -text $button \
	      -command "XesClient::SendCsimulEvent {$button;}"]
}
# tick.
pack [button .tick \
	  -text tick \
	  -command {XesClient::SendCsimulEvent {;}}]
      
     


