#  gimpClient.tcl --
#
#     Utilities to connect to a Gimp (script-fu) server
#
# SCCS: @(#) gimpClient.tcl 1.4 97/12/17 15:32:28
#

set port 10008
set host localhost

proc gimpSend {command} {
    global gimpSock
    puts -nonewline $gimpSock \
	    "G[binary format S [string length $command]]$command"
    flush $gimpSock
    gimpRead $gimpSock
}

proc gimpRead {gimpSock} {
    set l [read $gimpSock 1]
    if {[eof $gimpSock]} {
	puts stderr "eof on $gimpSock, closing..."
	close $gimpSock
	error "end of file"
    }
    if {$l != "G"} {
	puts stderr "UNKNOWN server answer \"$l\" !"
	error "protocol bug"
    }
    if {[binary scan [read $gimpSock 1] c code] != 1} {
	set msg "can't get result code"
	puts stderr $msg
	error $msg
    }
    if {[binary scan [read $gimpSock 2] S length] != 1} {
	set msg "can't get message length"
	puts stderr $msg
	error $msg
    }
    if {$length <= 0} {
	puts stderr "bogus message length $length !"
	error "invalid message length $length"
    }
    return -code $code [read $gimpSock $length]
}

proc gimpConnect {host port} {
    global gimpSock
    set gimpSock [socket $host $port]
    fconfigure $gimpSock -translation binary
}

