namespace eval cyrillize {
}

proc cyrillize::load_table {} {
    variable convert

    set f [file join [file dirname [info script]] engrus.tbl]
    set fd [open $f]
    fconfigure $fd -encoding koi8-r
    set convert_table [read $fd]
    close $fd

    foreach {f t} $convert_table {
	set convert(eng,rus,$f) $t
	set convert(rus,eng,$t) $f
    }
}

cyrillize::load_table

#puts [array get cyrillize::engrus]

proc cyrillize::do {s from to} {
    variable convert

    set res ""
    foreach c [split $s ""] {
	if {[info exists convert($from,$to,$c)]} {
	    append res $convert($from,$to,$c)
	} elseif {[info exists convert($from,$to,[string tolower $c])]} {
	    append res [string toupper $convert($from,$to,[string tolower $c])]
	} else {
	    append res $c
	}
    }
    return $res
}

#puts [cyrillize::do Ghbdtn]

proc cyrillize::word {iw from to} {
    set ins [lindex [split [$iw index insert] .] 1]
    set line [$iw get "insert linestart" "insert lineend"]
    set wordstart [string wordstart $line [expr $ins - 1]]
    set wordend [clength [string trimright \
			      [crange $line 0 [expr $wordstart - 1]]]]
    set word [crange $line $wordstart [expr $ins - 1]]

    set newword [do $word $from $to]
    $iw delete "insert linestart +$wordstart chars" insert
    $iw insert insert $newword

    $iw mark set insert "insert linestart +$wordend chars"
}

event add <<Cyrillize-Eng-Rus>> <Control-quoteright>
event add <<Cyrillize-Eng-Rus>> <Control-yacute>
event add <<Cyrillize-Rus-Eng>> <Control-quotedbl>
event add <<Cyrillize-Rus-Eng>> <Control-Yacute>

proc cyrillize::setup_bindings {chatid type} {
    variable history

    set iw [chat::input_win $chatid]
    bind $iw <<Cyrillize-Eng-Rus>> [list [namespace current]::word $iw eng rus]
    bind $iw <<Cyrillize-Eng-Rus>> +break
    bind $iw <<Cyrillize-Rus-Eng>> [list [namespace current]::word $iw rus eng]
    bind $iw <<Cyrillize-Rus-Eng>> +break
}

hook::add open_chat_post_hook [namespace current]::cyrillize::setup_bindings



