#!/usr/bin/wish
#
# The simplest CW-Terminal for K2, using the internal keyer
#
# Written by Matti---TF3MA, tf3ma_at_raunvis.hi.is
# Þri Maí 27 13:10:25 GMT 2003
#
# TCL/TK --- homepage
# <a href="http://www.tcl.tk">Tcl/Tk</a>
#

wm  title . "CW_Term.tcl by TF3MA"
#
# set to the serial port you use
#
set filename(SERIAL_PORT) "/dev/ttyS0"

#
#
#
set help "CW-Term for Elecraft K2 written by TF3MA\n use F10 to toggle live\
  key sending\n"
set live_key 1
#
# init_serial, setup the serialport for i/o
#
proc init_serial {} {
    global serial_port filename

    if {[catch "open $filename(SERIAL_PORT) RDWR" serial_port]} {
	puts stderr "$filename(SERIAL_PORT) busy"
	return 1
    }\
    elseif {[catch "fconfigure $serial_port -mode 4800,n,8,2 -blocking false \
      -buffering line "]} {
	puts stderr "can't set $filename(SERIAL_PORT)"
	return 1
    }
    #fileevent $serial_port readable rig_info
    return 0
}

#
# send one character
#
proc send_live {message} {
    global serial_port

    puts $serial_port "KY $message;"
}

#
# send a word, append space
#
proc send_mess {message} {
    global serial_port

    set wordslist [split $message]
    foreach word $wordslist {
	puts $serial_port "KY [subst $word] ;"
    }
}

#
# main rutine
#
proc cw_term {} {
    global cursor_pos pre_cursor_pos cw_word live_key

    destroy .cwterm
    frame .cwterm

    if {[info exist live_key]} {
	set live_key [expr {!$live_key}]
    } else {
	set live_key 1
    }

    if {![info exists pre_cursor_pos]} {
	set pre_cursor_pos 1.0
    }

    text .cwterm.t -width 50 -height 15 -yscrollcommand ".cwterm.txs set"\
      -wrap word
    scrollbar .cwterm.txs -orient vertical -command ".cwterm.t yview"

    bind .cwterm.t <KeyRelease> {
	set cursor_pos [.cwterm.t index insert]
	set key [.cwterm.t get "$cursor_pos -1 chars"]
	if {[.cwterm.t compare "$cursor_pos" > "$pre_cursor_pos"] == 1} {
	    if {$live_key == 0} {
		if {$key == " " || $key == "\n" || $key == "/" || $key == "-"} {
		    if {[info exists cw_word]} {send_mess "$cw_word "}
		    if {$key == "/" || $key == "-"} {send_mess "$key"}
		    set cw_word {}
		}
	    } else {
		send_live $key
	    }
	}
	set cw_word [.cwterm.t get "$cursor_pos -1 chars wordstart"\
	  "$cursor_pos"]
	set pre_cursor_pos $cursor_pos
    }
    pack .cwterm.t .cwterm.txs -side left -fill y -padx .25 -padx .25
    pack .cwterm
    focus .cwterm.t
}
#
# use F10 to toggle live keys
#
bind all <F10> {cw_term}
#
# start the beast
#
init_serial
cw_term
.cwterm.t insert end $help

