#!/usr/bin/wish -f

#
# copyright Nov 16, 2001, Marteinn Sverrisson, TF3MA\
  matti_at_raunvis_dot_hi_dot_is
# This software is available under the terms of the GNU Public License
#
# $Id: MALog.tcl,v 1.15 2003/11/23 09:30:17 matti Exp matti $
#
# Simple logging program for Radio Amateurs written in tcl/tk
# by TF3MA.
#
# The original logfile was a flat text file, entries are separated by "|"
# The current logfile is a TCL list, i.e. entries separated by a Space
# and grouped via {} pair, this speed i/o and processing
#
# Usage: MALog.tcl
#
# use the mouse to select any entry
# or Tab to go to the next entry
#
# press: Log to log the QSO, the logfile will be save to disk
#        using the name $filename.new
# press: Quit to exit the program, 
#        $filename.new will be moved to $filename 
# press: Press Tími to update the time entry
# press: Press Hreinsa to clear the entries
#
# when the first letters of the callsign have been entered
# the program displayes the matching entries in the log
# and look the entry up in the DXCC/IOTA lists
#
#  
#
# History:
# initial version 0.1: Þri Nóv 13 09:49:20 GMT 2001
#                 0.1: Mið Nóv 14 20:49:45 GMT 2001
#                      Bætti við DXCC landaslista
#                 1.16: Lau Nóv 17 09:14:01 GMT 2001 
#                        scrolling windows, improved packing of windows 
#                      Mán Nóv 26 22:18:42 GMT 2001
#                      Bætti við Band 
#                 1.23 margar vidbætur
#                      11. dec 2001
#                      datastructure a la ADIF
#		1.28
#			prentun á formi sem hentar fyrir labelnation	
#			5.2.2003
#		1.34 New format for logfiles, now each line is
#			saved as a TCL list, with white space separator
#			and curly {} brackets for eliments
#			The conversion is automatic
#
#		1.38 Code cleanup, Del button added
#		1.41 Info now displays in info window
#		1.42 Popup asks for confirm, after edit
#			edit the logfilentry in the info window
#			as well as the one in the qsl window
#			middle mouse button on Pr button pops up a menu
#			to select what to print QSL, ADI or CBR
#		1.44 Added an array of callsigns to speed lookup, mklist
#		1.50 Added reports for DXCC etc and some statistics
#		1.57 Added serial connection to K2, and rig_info
#		1.69 Do not use serial port if busy, dxcc file read
#		1.71 Use right mouse button to lookup Name, Qth, Call info
#		1.72 Use right mouse button in info mod to lookup all contacts
#                    to the selected country
############# Install Instructions #############################
#
# Install this program under any name, and make it executable (chmod 755)!!
# it gets its installed name from "set programname [file tail [info script]]"
#
# The program reads a rc file: .${programname}rc
# if the file does not exist the progam uses the names:
#        "logfiles"            for the log directory and
#        ".${programname}.dat" for the logfile
#
# i.e. if the program is installed under the name "hamlog"
# then the log is stored in the file ~/logfiles/hamlog.dat
#
# If separate logs are preferred for different operations
# make symbolic links to the actual program with the prefered
# logfile names without the .dat suffixt and you are done.
# or use the rc file to set the logfile name.
#
# for example: ln -s MALog.tcl contest
# when invoked as "contest" it reads the initfile .contestrc
# 
# the rc file uses the following syntax, see .*rc file for full list:
#
#         CALLSIGN  your_callsign
#         MYNAME  your_name
#         QTH   your_own_qth
#         ADDRESS your_mailing_address
#         QRZ     your_qrz_zone
#         IOTA   your_iota_zone
#         ITUZ   your_itu_zone
#         LIC   your_licence_year
#         LATLONG   your_latitud_and_longitude
#         GRIDSQUARE     your_grid_locator
#         LOGDIR  your_logdir_name
#         LOGFILE  your_logfile_name
#         LIBRARY  your_library_dir
#         DXCC_FILE  your_dxccfile_name
#         OFFSET  where to start when looking up old QSO's
#         EQSL  where to start when exporting eQSL
#         GUI_LANG  the GUI language, is or en are currently supported
# 
# dxcc list is used for looking up the country informations
#
# Download the DXCC file from "http://www.arrl.org/files/infoserv/tech/dxcck2di.txt"
#
# Remember to install the "gcb" package for Linux
#
# The program uses Mozilla to lookup callsigns in qrz.com
#
#############

set Rev "\$Revision: 1.15 $"

# This is for the MATerm program.
set MALog 1
#
# first initialize some data structures
#
#set font {-*-courier-demi-r-*-*-12-*}
set font {-*-courier-bold-r-*-*-12-*}

set programname [file tail [info script]]

set Credit "$programname $Rev\n QSO logging program\n written from scratch by\
  TF3MA\n distributed under the GPL v2 Licence\n"

set Help "\nSimple Help: Use the Mouse and the buttons or\nTAB -- for next\
  entry    F9 -- to log the QSO\n"

set loggrc .${programname}rc

set refresh 10
set block 1


set val(Call) {}

set tfreeze 0

set qrz_lookup 0

set serial_busy 0

set rig_initstring "K22;AI2;AN;FA;FB;FR;FT;FW;GT;KS;LK;MD;NB;PA;PC;RA;RC;RD;XT;"

#
# Language specific texts
# The Box texts, use for setting different languaes
# Please note the length of the stings
#

# set lang "en"
set lang "is"
set logbook(is) "Loggbók"
set logbook(en) "Logbook"
# The box texts
set box_date(en) "Date"
set box_date(is) "Dags"
set box_time(is) "Tími"
set box_time(en) "Time"
set box_station(is) "Stöð kölluð"
set box_station(en) "Station called"
set box_band(is) "Band"
set box_band(en) "Band"
set box_freq(en) "Freq"
set box_freq(is) "Tíðni"
set box_mode(is) "Teg"
set box_mode(en) "Mode"
set box_rst_sent(is) "Rst_sent"
set box_rst_sent(en) "Rst_sent"
set box_rst_rcvd(is) "Rst_mótt"
set box_rst_rcvd(en) "Rst_rcvd"
set box_qsl(is) "Qsl"
set box_qsl(en) "Qsl"
set box_name(is) "Nafn"
set box_name(en) "Name"
set box_qth(is) "Qth"
set box_qth(en) "Qth"
set box_rig(is) "Tæki"
set box_rig(en) "Rig"
set box_notes(is) "Athugas"
set box_notes(en) "Notes"
set box_time_off(is) "Endar"
set box_time_off(en) "Ends"
# The button texts and the last qso text
set b_text_auto(is) "Sjálfv"
set b_text_auto(en) "Auto"
set b_text_manual(is) "Handv"
set b_text_manual(en) "Manual"
set b_text_time(is) "Tími"
set b_text_time(en) "Time"
set b_text_log(is) "Skrá"
set b_text_log(en) "Log"
set b_text_clear(is) "Hreinsa"
set b_text_clear(en) "Clear"
set b_text_file(is) "Sýsl"
set b_text_file(en) "File"
set b_text_time_off(is) "Endar"
set b_text_time_off(en) "Ends"
set b_text_station(is) "Stöð"
set b_text_station(en) "Station"
set b_text_sent(is) "Se"
set b_text_sent(en) "Se"
set b_text_recvd(is) "Mó"
set b_text_recvd(en) "Rc"
set b_text_print(is) "Pr"
set b_text_print(en) "Pr"
set b_text_upd(is) "Tölfr"
set b_text_upd(en) "Info"
set b_text_edit(is) "Edit"
set b_text_edit(en) "Edit"
set b_text_info(is) "->"
set b_text_info(en) "Info"
set b_text_last(is) "Logg #"
set b_text_last(en) "QSO #"

set tmode $b_text_auto($lang)

#
proc clr_callinfo {} {
    global callinfo
    set callinfo(dxcc) {-1}
    set callinfo(country) {}
    set callinfo(cont) {}
    set callinfo(itu) {}
    set callinfo(zone) {}
    set callinfo(prefix) {}
}
clr_callinfo

#
# Here is the structure of the logfile and the entries to display
#
set logstructure {QSO_DATE TIME_ON CALL BAND MODE RST_SENT STX RST_RCVD\
  SRX CQZ ITUZ STATE QSL_SENT QSLSDATE QSL_RCVD QSLRDATE NAME QTH TIME_OFF RIG\
  FREQ TX_PWR RX_PWR CONTEST_ID DXCC PFX CONT COUNTRY CNTY IOTA VE_PROV\
  QSL_VIA NOTES ANT}

set display {QSO_DATE TIME_ON CALL BAND MODE RST_SENT STX RST_RCVD\
  SRX QSL_SENT QSL_RCVD NAME QTH RIG TX_PWR CONTEST_ID}

set todisplay {}

foreach i $logstructure {
    set log_index($i) [lsearch -exact $logstructure $i]
    #puts stderr "$log_index($i) $i"
}

foreach i $display {
    #puts stderr "$i: [lsearch -exact $logstructure $i]"
    lappend todisplay $log_index($i)
}

#
# The structure of the cabrillo file header
#
set cab_struct {CALLSIGN CATEGORY CONTEST ARRL-SECTION CLAIMED-SCORE\
NAME ADDRESS SOAPBOX}
#
# The structure of the rc file
#
set rc_struct {
{CALLSIGN  your_callsign}\
{MYNAME  your_name}\
{PREFIX  your_callsign_prefix}\
{QTH   your_own_qth}\
{NAME   your_full_name}\
{ADDRESS {your_mailing_address}}\
{QRZ     your_qrz_zone}\
{IOTA   your_iota_zone}\
{ITUZ   your_itu_zone}\
{LIC   your_licence_year}\
{LATLONG 64N22W}\
{GRIDSQUARE    your_grid_locator}\
{LOGDIR  logfiles}\
{LOGFILE my_log}\
{LIBRARY  /usr/local/lib/ham}\
{DXCC_FILE  dxcck2di.txt}\
{OFFSET  0}\
{EQSL  0}\
{GUI_LANG  is}\
{F1_QSO {cq cq cq de $filename(CALLSIGN) k}}\
{F1_CONTEST {test de $filename(CALLSIGN) test k}}\
{F2_QSO {$log(RST_SENT)}}\
{F2_CONTEST {5nn $log(STX)}}\
{F3_QSO {73}}\
{F3_CONTEST {tu}}\
{F4 {$filename(CALLSIGN)}}\
{F5 {$log(CALL)}}\
{F6 {$log(CALL) qso b4}}\
{F7 {$log(STX)}}\
{F8 {agn}}\
{RIG  {my_rig1 my_rig2 {my rig 3} }}\
{ANT  {my_ant1 my_ant2 {my ant 3} }}\
{TX_PWR {1 5 10 50 100 500 1k}}\
{MODE  {SSB CW RTTY BPSK31 QBSK31 MFSK16 SSTV FM AM}}\
{BAND  {160m 80m 40m 30m 20m 17m 15m 12m 10m 6m 2m}}\
{CONTEST_ID {QSO CQ-WW CQ-WPX CQ-160 ARRL-10 ARRL-160 ARRL-DX IARU WAE SAC JIDX\
  SPDX Contest}}\
{SERIAL_PORT {/dev/ttyS0}}\
{PAR_PORT {/dev/lpt1}}\
}
#
# initialize the log array
#
foreach x $logstructure {
    set log($x) {}
}
#
set log(MODE) SSB
set log(RIG) K2
set log(ANT) Dipole
set log(TX_PWR) 100
set log(BAND) 20m
set log(STX) 1
set log(CONTEST_ID) QSO

#
# make the rcfile if it is not there and put in default values
#
proc make_rc {} {
    global loggrc env filename rc_struct

    set file [open $env(HOME)/$loggrc w]
    foreach rcline $rc_struct {
	puts $file "[lindex $rcline 0] {[lindex $rcline 1]}"
    }
    flush $file
    close $file
}

#
# open the rcfile and read it, if the rcfile does not exist use default 
# names for the logdir and the logfile
#
proc readrc {} {
    global loggrc env filename invoke_rc

    puts stderr "Reading $loggrc"
    if {[file readable $env(HOME)/$loggrc] == 0} {
	puts "Missing: $env(HOME)/$loggrc"
	puts "I am now making your rc file"
	puts "please edit the rcfile: \"$env(HOME)/$loggrc\""
	make_rc
	set invoke_rc 1
    }
    set file [open $env(HOME)/$loggrc r]
    set rcinfo [split [read $file] \n]
    array set filename [join $rcinfo]
    #          puts  [array get filename]
    #          puts "innlestri loggrc fyrir $filename(CALLSIGN) lokið"
}

readrc


set callsign $filename(CALLSIGN)
set prefix $filename(PREFIX)
set c_sel $filename(OFFSET)
set lang $filename(GUI_LANG)

wm title . "$callsign $logbook($lang) -- written by TF3MA -- $Rev"

#
# make the logdir if it does not exists
#
set logdir $env(HOME)/$filename(LOGDIR)
if {[file isdirectory $logdir] == 0 && [file isfile $logdir] == 0} {
    file mkdir $logdir
}

#
# check_lock check if the logfile is in use
#
proc check_lock {} {
    global logdir filename
    if {[file exists $logdir/.$filename(LOGFILE).lock]} {
	set svar [tk_messageBox -message "Logfile:$filename(LOGFILE) is in use\
	  --- continue?" -type yesno -icon question]
	switch -- $svar {
	no {
		exit
	    }
	}
    }
    open $logdir/.$filename(LOGFILE).lock w
}

proc rm_lock {} {
    global logdir filename
    file delete $logdir/.$filename(LOGFILE).lock
}

############
#
# update the time and date entries on the screen
#
proc do_time {} {
    global log
    set log(QSO_DATE) [clock format [clock seconds] -format %Y%m%d]
    set log(TIME_ON) [clock format [clock seconds] -format %H%M]
    set log(TIME_OFF) ""
}


#
# read in the actual logfile, first make a backup copy of it
# listi() is an array of all logentries
#
proc lesa_inn {} {
    global listi num logdir logstructure log_index filename val infoentry log\
      country_gluggi
    puts stderr "Reading $logdir/$filename(LOGFILE)"
    set num 0
    set listi(0) {}
    if {[file writable $logdir/$filename(LOGFILE)]} {
	set logfile [open $logdir/$filename(LOGFILE) r]
	set i 0
	set firstel [read $logfile 9]
	seek $logfile 0 start
	# Read the logstructure, the first entry should be QSO_DATE
	gets $logfile firstline
	if {[lindex $firstline 0] != "QSO_DATE"} {
	    seek $logfile 0 start
	    #puts stderr "No struct line"
	} else {
	    #puts stderr "Struct line:\n$firstline"
	}
	#             is this old or new format?
	if {[string first | $firstel] == 8} {
	    $country_gluggi delete 1.0 end
	    $country_gluggi insert end "Old format logfile detected!!\n"
	    $country_gluggi insert end "Backup is saved as\
	      $filename(LOGFILE).oldf\n"
	    $country_gluggi insert end "\nPress Info to convert the logfile to\
	      the new format\n"
	    $country_gluggi insert end "\nThis can take several minutes for a\
	      big file\n"
	    file copy -force $logdir/$filename(LOGFILE)\
	      $logdir/$filename(LOGFILE).oldf
	    foreach line [split [read $logfile] \n] {
		set listi($i) [split $line |]
		incr i
	    }
	} else {
	    file copy -force $logdir/$filename(LOGFILE)\
	      $logdir/$filename(LOGFILE).bak
	    foreach line [split [read $logfile] \n] {
		if {$line != {}} {
		    set listi($i) $line
		    incr i
		}
	    }
	}
	set num [expr {$i - 1}]
	#             puts stderr $listi(0)
	#             puts stderr $listi($num)
	set infoentry $listi($num)
	set val(Num) $num
	set val(Call) [lindex $listi($num) $log_index(CALL)]
	set log(CONTEST_ID) [lindex $listi($num) $log_index(CONTEST_ID)]
	set log(BAND) [lindex $listi($num) $log_index(BAND)]
	set log(FREQ) [lindex $listi($num) $log_index(FREQ)]
	set log(MODE) [lindex $listi($num) $log_index(MODE)]
	set log(RIG) [lindex $listi($num) $log_index(RIG)]
	set log(TX_PWR) [lindex $listi($num) $log_index(TX_PWR)]
	set log(RST_SENT) [lindex $listi($num) $log_index(RST_SENT)]
	set log(RST_RCVD) [lindex $listi($num) $log_index(RST_RCVD)]
	set log(STX) [lindex $listi($num) $log_index(STX)]
    }
}


#
# read in the dxcc file used to lookup countries and zones
#
proc dxcc_inn {} {
    global filename dxcclist
    if {$filename(DXCC_FILE) != {}} {
	if {[file readable $filename(LIBRARY)/$filename(DXCC_FILE)] == 1} {
	    puts stderr "Reading DXCC file"
	    set listfile [open $filename(LIBRARY)/$filename(DXCC_FILE) r]
	    set list [split [read $listfile] \n]
	    close $listfile
	    set i 0
	    foreach line $list {
		if {[regexp -- "^---.*" $line]} {
		    incr i
		} else {
		    if {[expr {$i >= 1}]} {
			array set dxcclist [list [array size dxcclist]\
			  "[split $line :]"]
		    }
		}
	    }
	    puts stderr "dxcc: [array size dxcclist]"
	} else { puts stderr "Can not open DXCC file" }
    } else { puts stderr "No DXCC file" }
}


#
# Make regular expressions out of all prefixes
# and put in regexplist array, index is the same index of dxcclist
# so it can be used to printout dxcc entries
#

proc mkreg {} {
    global dxcclist regexplist deletedlist

    for {set i 0} {$i < [array size dxcclist]} {incr i} {
	set pre {}
	set rlist {}
	set deletedlist($i) 0
	append pre [lindex $dxcclist($i) 0]
	if {$pre == {}} {
	    set pre ~
	}
	#
	# deleted counries are looked up  
	#
	while {[set l [string first * $pre]] > 0} {
	    set deletedlist($i) 1
	    #            puts stderr "$l : $pre"
	    set pre [string replace $pre $l $l]
	    #            puts stderr "$l : $pre"
	}
	set aukapre [concat [split [lindex $dxcclist($i) 8] ,] [split\
	  [lindex $dxcclist($i) 9] ,]]

	set pre "^$pre"
	lappend rlist $pre

	foreach auka $aukapre {
	    if {$auka != {}} {
		set auka "^$auka"
	    }

	    while {[set l [string first ~ $auka]] > 0} {
		set auka [string replace $auka $l $l]
		#           puts stderr "$l:$auka"
	    }

	    while {[set l [string first _ $auka]] > 0} {
		set auka [string replace $auka $l $l \[0-9\]]
		#           puts stderr $auka
	    }
	    if {[string index $auka 3] == "-"} {
		set rreg {}
		append rreg ^[string index $auka 1] \[[string index $auka\
		  2]-[string index $auka 5]\]
		lappend rlist $rreg
	    }\
	    elseif {[string index $auka 4] == "-"} {
		set rreg {}
		append rreg ^[string index $auka 1][string index $auka 2]\
		  \[[string index $auka 3]-[string index $auka 7]\]
		lappend rlist $rreg
	    } else {
		set rlist [concat $rlist $auka]
	    }
	    set reg [join $rlist |]
	}
	set reg [join $rlist |]
	#    puts "$reg"
	set regexplist($i) $reg
    }
}

#
# mklist --- make an array of all callsigns
#
proc mklist {} {
    global logstructure listi num call_list name_list qth_list dxcc_list date_list
        for {set numer 0} {$numer <= $num} {incr numer} {
	set call_list($numer) [lindex $listi($numer) [lsearch\
	  -exact $logstructure {CALL}]]
	set name_list($numer) [lindex $listi($numer) [lsearch\
	  -exact $logstructure {NAME}]]
	set qth_list($numer) [lindex $listi($numer) [lsearch\
	  -exact $logstructure {QTH}]]
	set dxcc_list($numer) [lindex $listi($numer) [lsearch\
	  -exact $logstructure {DXCC}]]
	set date_list($numer) [lindex $listi($numer) [lsearch\
	  -exact $logstructure {QSO_DATE}]]
    }
}

#
# clear the log entries after adding a new entry to the logfile
#
proc upphaf {clear} {
    global log tfreeze prefix val b_text_auto lang tmode auto filename

    set tfreeze 0
    set log(QSL_SENT) I
    set log(QSL_RCVD) I
    set log(CALL) ""
    set log(NAME) ""
    set log(QTH) ""

    set log(RST_SENT) ""
    set log(RST_RCVD) ""
    if {$log(CONTEST_ID) != "QSO"} {
	set log(SRX) {}
	if {$log(CONTEST_ID) == "CQ-WW"} {
	    set log(STX) 40
	}
	if {$log(CONTEST_ID) == "ARRL-10"} {
	    set log(STX) $prefix
	}
	if {$log(CONTEST_ID) == "CQ-160"} {
	    set log(STX) $prefix
	}
	if {$log(CONTEST_ID) == "JIDX"} {
	    set log(STX) $filename(QRZ)
	}
	if {$log(CONTEST_ID) == "IARU"} {
	    set log(STX) $filename(ITUZ)
	}
	if {$log(CONTEST_ID) == "WAE"} {
	    set log(STX) $filename(LIC)
	}
	if {$log(MODE) == "CW"} {
	    set log(RST_SENT) 599
	    set log(RST_RCVD) 599
	} else {
	    set log(RST_SENT) 59
	    set log(RST_RCVD) 59
	}
	if {$log(CONTEST_ID) == "CQ-WPX" || $log(CONTEST_ID) ==\
	  "SPDX" ||[string toupper $log(CONTEST_ID)] == "CONTEST"} {
	    if {$log(STX) == {}} {
		set log(STX) 1
	    } else {
		if {$clear == 1} {
		    incr log(STX)
		}
	    }
	}
    } else {
	set log(SRX) {}
	set log(STX) {}
    }
    set tmode $b_text_auto($lang)
    focus .call.stod
}

#
# read in the adif logfile and append it to the current logfile
# adif file fields have the same name as the log array fields.
#
proc lesa_adif {filename} {
    global log
    set adif_file [open $filename r]
    set safn [read $adif_file]
    # get rid of all NL and CR and TAB
    regsub -all {[\n\r\t]} $safn {} ssafn
    set first [string index $ssafn 0]
    if {$first != "<"} {
	#	puts stderr "header"
	regsub -all -nocase {<EOH>} $ssafn "\n" safn
	set ssafn [split $safn \n]
	set header [lindex $ssafn 0]
	set body [lindex $ssafn 1]
	#	puts stderr $header
	#	puts stderr "header ends"
    } else {
	#	puts stderr "no header"
	set body $ssafn
    }
    regsub -all -nocase {<EOR>} $body "\n" safn
    #       puts stderr $safn
    foreach line [split $safn \n] {
	while {[string length $line] != 0} {
	    set j [string first {<} $line]
	    incr j
	    set l [string first {:} $line]
	    incr l -1
	    set m [string first {>} $line]
	    incr m -1
	    set n [string length $line]
	    set fname [string range $line $j $l]
	    set fname [string toupper $fname]
	    incr l +2
	    set w [string range $line $l $m]
	    incr w -1
	    incr m 2
	    set line [string range $line $m $n]
	    set fval [string range $line 0 $w]
	    set log($fname) $fval
	    incr w
	    #           puts stdout "$fname $fval"
	    set line [string range $line $w $n]
	}
	append_log
    }
}

#
# do_edit Update the QSL information for QSO 
#
proc do_edit {val what call} {
    global edit listi num logstructure callinfo
    set newentry {}
    if {([expr {$val <= $num}]) &&($call != {})} {
	set editline $listi($val)
	#               puts stderr "edit: $editline"
	set numer 0
	foreach i $logstructure {
	    set edit($i) [lindex $editline $numer]
	    incr numer
	}
	if {$what == "QSLS"} {
	    set edit(QSL_SENT) Y
	    set edit(QSLSDATE) [clock format [clock seconds] -format %Y%m%d]
	}
	if {$what == "QSLR"} {
	    set edit(QSL_RCVD) Y
	    set edit(QSLRDATE) [clock format [clock seconds] -format %Y%m%d]
	}
	if {$what == "LOG"} {
	    set edit(DXCC) $callinfo(dxcc)
	    set edit(CQZ) $callinfo(zone)
	    set edit(ITUZ) $callinfo(itu)
	    set edit(CONT) $callinfo(cont)
	    set edit(COUNTRY) $callinfo(country)
	    set edit(PFX) $callinfo(prefix)

	}
	foreach i $logstructure {
	    lappend newentry $edit($i)
	}
	# delete the logfile entry
	if {$what == "DEL"} {
	    set oldentry $listi($val)
	    set newentry {}
	}
	#               puts stderr  $newentry
	set listi($val) $newentry
    }
}

#
# add_info, add country info to the logfile
#
proc add_info {firstnum force} {
    global log_index listi num callinfo
    for {set i $firstnum} {[expr {$i <= $num}]} {incr i} {
	set date [lindex $listi($i) $log_index(QSO_DATE)]
	set year [string range $date 0 3]
	set call [lindex $listi($i) $log_index(CALL)]
	set prefix [lindex $listi($i) $log_index(PFX)]
	if {$prefix == {} || $force == 1} {
	    check_pre $call
	    check_country $call $year
	    #puts stderr [array get callinfo]
	    if {$callinfo(dxcc) == ""} {
		puts stderr [array get callinfo]
		set callinfo(dxcc) "-1"
	    }
	    do_edit $i LOG $call
	}
    }
}

#
# info, add/display country info for the logfile
#
proc get_info {firstnum} {
    global log_index listi num callinfo country_gluggi logdir info_gluggi\
      info_array
    for {set i $firstnum} {[expr {$i <= $num}]} {incr i} {
	set date [lindex $listi($i) $log_index(QSO_DATE)]
	set call [lindex $listi($i) $log_index(CALL)]
	set band [lindex $listi($i) $log_index(BAND)]
	set zones [lindex $listi($i) $log_index(CQZ)]
	set itu [lindex $listi($i) $log_index(ITUZ)]
	set qsl [lindex $listi($i) $log_index(QSL_RCVD)]
	set mode [lindex $listi($i) $log_index(CONTEST_ID)]
	set country [lindex $listi($i) $log_index(DXCC)]
#		if {$country == ""} {puts stderr $i}
	set prefix [lindex $listi($i) $log_index(PFX)]
	set cont [lindex $listi($i) $log_index(CONT)]
	set c_name [lindex $listi($i) $log_index(COUNTRY)]
	if {$qsl == "Y"} {
	    set q_count([string toupper $country]) 1
	    set q_b_c_c([string toupper $country],$band) 1
	}
	set c_count([string toupper $country]) 1
	set p_count([string toupper $prefix]) 1
	set b_c_c([string toupper $country],$band) 1
	set z_count([string toupper $zones]) 1
	set i_count([string toupper $itu]) 1
	set cont_count([string toupper $cont]) 1
	if {$country != ""} {
	   set country_name($country) $c_name
	} else {
	   set country_name($country) "Unknown"
	}
    }
    $country_gluggi delete 1.0 end
    set count [array size c_count]
    set pcount [array size p_count]
    set zone [array size z_count]
    set itu [array size i_count]
    set qsl [array size q_count]
    set cont [array size cont_count]
    $country_gluggi insert end "Total QSO's: [expr {$num - $firstnum + 1}]\
      From [lindex $listi($firstnum) 0] to [lindex $listi($num) 0]\n"
    $country_gluggi insert end "Countries: $count (334)\n"
    $country_gluggi insert end "Confirmed: $qsl (334)\n"
    $country_gluggi insert end "Zones: $zone (40)\n"
    $country_gluggi insert end "ITU: $itu (90)\n"
    $country_gluggi insert end "Continents $cont (6)\n"
    $country_gluggi insert end "Prefixes $pcount\n"
    set infofile [open $logdir/info.txt w]
    $info_gluggi delete 0 end
    set printstring "                                   80m 30m 17m 12m  6m"
    puts $infofile $printstring
    $info_gluggi insert end $printstring
    set printstring "DXCC  Country                   160m|40m|20m|15m|10m| 2m"
    puts $infofile $printstring
    $info_gluggi insert end $printstring
    set printstring "                                  | | | | | | | | | | |"
    puts $infofile $printstring
    $info_gluggi insert end $printstring
    set bands {160m 80m 40m 30m 20m 17m 15m 12m 10m 6m 2m}
    foreach band $bands {
	set cnt($band) 0
	set cntY($band) 0
	set cntN($band) 0
    }
    set sorted [lsort -dictionary [array names c_count]]
    foreach index $sorted {
	set printlist {}
	foreach band $bands {
	    if {[info exist b_c_c($index,$band)]} {
		if {[info exist q_b_c_c($index,$band)]} {
		    append printlist "Y "
		    incr cntY($band)
		} else {
		    append printlist "N "
		    incr cntN($band)
		}
		incr cnt($band)
	    } else {
		append printlist "- "
	    }
	}
	set printstring [format "%-5s %-27s %s" $index $country_name($index)\
	  $printlist]
	set infostring [format "%-5s %s" $index $printlist]
	puts $infofile $printstring
	$info_gluggi insert end $printstring
	set info_array($index) $infostring
    }
    set printstring ""
    puts $infofile $printstring
    $info_gluggi insert end $printstring
    set printstring [format "Band       Total        N        Y"]
    puts $infofile $printstring
    $info_gluggi insert end $printstring
    foreach band $bands {
	set printstring [format "%+4s -- %+8s %+8s %+8s" $band $cnt($band)\
	  $cntN($band) $cntY($band)]
	puts $infofile $printstring
	$info_gluggi insert end $printstring
    }
    puts $infofile ""
    puts $infofile "From [lindex $listi($firstnum) 0] to [lindex $listi($num)\
      0]"
    puts $infofile "QSO's: [expr {$num - $firstnum + 1}]"
    puts $infofile "Countries: $count (334)"
    puts $infofile "Confirmed: $qsl (334)"
    puts $infofile "Zones: $zone (40)"
    puts $infofile "ITU: $itu (75)"
    puts $infofile "Continents $cont (6)"
    puts $infofile "Prefixes $pcount"
    close $infofile
}

#
# tail_log -- display the 50 last entries in the log
#
proc tail_log {} {
    global last_gluggi listi todisplay log_index
    $last_gluggi delete 1.0 end
    set last [array size listi]
    set lengd $last
    if {$lengd >= 50} {
	set lengd 50
    }
    for {set lognr 1} {$lognr < $lengd} {incr lognr} {
	set lina {}
	foreach i $todisplay {
	    if {$i == $log_index(CALL)} {
		append lina " [format "%-8s " [lindex $listi([expr {$last\
		  - $lognr}]) $i]]"
	    } else {
		append lina " [lindex $listi([expr {$last - $lognr}]) $i]"
	    }
	}
	$last_gluggi insert end $lina
	$last_gluggi insert end \n
    }
}

#
# check_entry, lookup the callsign/name for the entered callsign/name
# as soon as the first character of the callsign is entered
# start from entry num/sel
#
proc check_entry {sel to_check CNQ} {
    global todisplay listi num info_gluggi call_list name_list qth_list\
    dxcc_list log_index date_list
    if {[string length $to_check] >= 1} {
	set numer 0
	# puts $sel
	$info_gluggi delete 0 end
	set to_check [string toupper $to_check]
	for {set numer $sel} {$numer <= $num} {incr numer} {
	    set lina {}
        if {$CNQ == "CALL"} {
           set check_list $call_list($numer)
           }
        if {$CNQ == "NAME"} {
           set check_list $name_list($numer)
           }
        if {$CNQ == "QTH"} {
           set check_list $qth_list($numer)
           }
        if {$CNQ == "DXCC"} {
           set check_list $dxcc_list($numer)
	   if {$check_list == "0"} {puts stdout $numer}
           }
        if {$CNQ == "DATE"} {
           set check_list $date_list($numer)
           }
	    #	    if {[regexp -- ^$to_check [lindex $listi($numer) 2]]} {}
	    if {($CNQ == "DATE")&&($date_list($to_check) == $check_list)||(($CNQ == "DXCC")&&($to_check == $check_list)) || ($CNQ != "DXCC")&&([regexp -- ^$to_check [string toupper $check_list]])} {
		#                    $info_gluggi insert end "$numer: "
		append lina "$numer - "
		foreach i $todisplay {
		    #                      $info_gluggi insert end "\
		      [lindex $listi($numer) $i]"
		    if {$i == $log_index(QSO_DATE)} {
			append lina [clock format [clock scan\
			  [lindex $listi($numer) $i]] -format "%d %h %Y"]
		    } else {
			if {$i == $log_index(CALL)} {
			    append lina " [format "%-8s"\
			      [lindex $listi($numer) $i]]"
			} else {
			    append lina " [lindex $listi($numer) $i]"
			}
		    }
		}
		#                    $info_gluggi insert end \n
		$info_gluggi insert end $lina
	    }
	}
    }
}

#
# check_pre --- return the prefix of call/pre or pre/call
#
proc check_pre {callsign} {
    global callinfo
    set comp [split $callsign /]
    set call [lindex $comp 0]
    set ext [lindex $comp 1]
    set pmatch {}
    #puts stdout "$callsign=$call+$ext"
    if {[regexp {^[A-Z].} $call match] == 1} {
	set pmatch $match
	#puts stderr "1: $match"
    }
    if {[regexp {^[A-Z].*[0-9]} $call match] == 1} {
	set pmatch $match
	#puts stderr "2: $match"
    }
    if {[regexp {^[0-9][A-Z]} $call match] == 1} {
	set pmatch $match
	#puts stderr "3: $match"
    }
    if {[regexp {^[0-9].[A-Z]*[0-9]} $call match] == 1} {
	set pmatch $match
	#puts stderr "4: $match"
    }
    set prefix $pmatch
    if {([string length $ext] == 1) &&([regexp {[0-9]} $ext])} {
	regsub {[0-9]} $pmatch $ext prefix
	set ext {}
    }
    if {($ext == {P}) ||($ext == {M}) ||($ext == {AM}) ||($ext ==\
      {MM}) ||($ext == {QRP})} {
	set ext {}
    }
    if {($ext != {}) &&[expr {[string length $ext] <= [string length $call]}]} {
	if {[regexp {^[A-Z].} $ext prefix] == 1} {
	    set prefix $ext
	    #        puts stderr "3: $ext"
	}
	if {[regexp {^[A-Z].*[0-9]} $ext prefix] == 1} {
	    set prefix $ext
	    #        puts stderr "3: $ext"
	}
	if {[regexp {^[0-9].[A-Z]*[0-9]} $ext prefix] == 1} {
	    set prefix $ext
	    #        puts stderr "4: $ext"
	}
	set call $ext
    }
    #puts "$prefix $call:$ext:$prefix"
    set callinfo(prefix) $prefix
    #puts stderr "$call $prefix"
    return $call
}
#
# check_country, lookup the country in the DXCC list
#
proc check_country {callsign qsoyear} {
    global dxcc_gluggi country_gluggi dxcclist regexplist deletedlist dist\
      callinfo info_array
    set prefix {}
    clr_callinfo
    if {[string length $callsign] >= 1} {
	$country_gluggi delete 1.0 end
	$dxcc_gluggi delete 1.0 end
	set flag 0
	set call [check_pre $callsign]
	#set callsign $callinfo(prefix)
	for {set k 0} {$k < [array size regexplist]} {incr k} {
	    if {[expr {$qsoyear < 2000}] || $deletedlist($k) == 0} {
		if {[regexp -- $regexplist($k) $call match]} {
		    set cntry [lindex $dxcclist($k) 0]
		    #puts stdout "$match: $cntry"
		    $country_gluggi insert end $dxcclist($k)
		    $country_gluggi insert end \n
		    if {$match == $cntry} {
			set flag 0
		    }
		    if {($flag == 0) && [regexp -- $cntry\
		      [lindex $dxcclist($k) 0]]} {
			set callinfo(dxcc) [lindex $dxcclist($k) 0]
			set callinfo(country) [lindex $dxcclist($k) 1]
			set callinfo(cont) [lindex $dxcclist($k) 2]
			set callinfo(itu) [lindex $dxcclist($k) 3]
			set callinfo(zone) [lindex $dxcclist($k) 4]
			if {$match == $cntry} {
			    set flag 1
			}
			#        puts stderr "$callsign : $regexplist($k) :\
				  $match"
			#        puts stderr [array get callinfo]
			#set flag 1
			#if {[expr [string length $cntry] > 1] } {set flag 1}
		    }
		    #
		    # calculate the distance and bearing to the countrie
		    #
		    set Long [lindex $dxcclist($k) 6]
		    set Lat [lindex $dxcclist($k) 7]
		    $country_gluggi insert end \n
		    $country_gluggi insert end [dist $Long $Lat]
		    $country_gluggi insert end \n
		    if {[info exists info_array($callinfo(dxcc))]} {
			$dxcc_gluggi delete 1.0 end
			set printstring "    160m|40m|20m|15m|10m| 2m"
			$dxcc_gluggi insert end $printstring
			$dxcc_gluggi insert end \n
			$dxcc_gluggi insert end $info_array($callinfo(dxcc))
		    }
		}
	    }
	}
    }
}

#
# qrz --- lookup the callsign
#
proc qrz {callsign} {
    global qrz_lookup
    if {$qrz_lookup == 1} {
	exec mozilla -remote "openurl(http://www.qrz.com/callsign/$callsign)"
    }
}

#
# append_info, append country info to the logfile
#
proc append_info {} {
    global log callinfo
    if {($log(CALL) != "")} {
	set log(DXCC) $callinfo(dxcc)
	set log(CQZ) $callinfo(zone)
	set log(ITUZ) $callinfo(itu)
	set log(CONT) $callinfo(cont)
	set log(COUNTRY) $callinfo(country)
	set log(PFX) $callinfo(prefix)
    }
}
#
# append_log, add the entered QSO to the listi
#
proc append_log {} {
    global logstructure log listi num val infoentry tmode lang b_text_auto\
      call_list
    if {($log(CALL) != "")} {
	foreach i $logstructure {
	    lappend newentry $log($i)
	}
	incr num
	set listi($num) $newentry
	set call_list($num) $log(CALL)
	set infoentry $newentry
	set val(Num) $num
	upphaf 1
	unset newentry
    } else {
	#       puts stderr "Engin ný færsla"
    }
}
#
# Write out the modified logfile, this takes some time
#
proc write_log {} {
    global logfile listi filename logdir num tmode lang b_text_auto logstructure
    set logfile [open $logdir/$filename(LOGFILE) w]
    puts $logfile [join $logstructure]
    for {set i 0} {$i <= $num} {incr i} {
	puts $logfile $listi($i)
    }
    #      flush $logfile
    close $logfile
    tail_log
    set tmode $b_text_auto($lang)
    focus .call.stod
}

#
# Print out the selected QSL entry and append it to qsl.txt
#
proc prenta {val Call} {
    global env listi logstructure logdir filename dxcc_gluggi
    if {$Call == {}} return
    set printfile [open $logdir/qsl.txt a]
    set numer 0
    foreach i $logstructure {
	set prent($i) [lindex $listi($val) $numer]
	incr numer
    }
    set old_env $env(LANG)
    set env(LANG) en_US
    puts $printfile "   $filename(CALLSIGN) Confirming QSO with $prent(CALL)"
    puts $printfile "   On [clock format [clock scan $prent(QSO_DATE)]\
      -format "%d %h %Y"] at $prent(TIME_ON) UTC"
    puts $printfile "   Using $prent(MODE) on the $prent(BAND) Band, your\
      RS(T) $prent(RST_SENT)"
    puts $printfile "   Pse/Tnx QSL, 73 $filename(MYNAME)"
    set env(LANG) $old_env
    #    puts $printfile "Rig: $prent(RIG), PWR: $prent(TX_PWR) W, Antenna:\
    #  $filename(ANT)"
    puts $printfile "-----"
    close $printfile
    exec labelnation -d "-----" -p $logdir/parfile -l -i $logdir/qsl.txt\
      -o $logdir/qslout.ps
    $dxcc_gluggi delete 1.0 end
    $dxcc_gluggi insert end "QSL label is in the file\n$logdir/qslout.ps"
}

proc get_swl {} {
    toplevel .swl
    frame .swl.e
    label .swl.e.l -text SWL
    entry .swl.e.e -textvariable swl -width 15 -relief sunken
    button .swl.e.p -text "Print SWL" -command {prenta_swl $val(Num)\
      $val(Call) $swl}
    button .swl.e.x -text Close -command {destroy .swl}
    pack .swl.e.l .swl.e.e .swl.e.p .swl.e.x -side left -padx .25
    pack .swl.e
}

proc prenta_swl {val Call Swl} {
    global env listi logstructure logdir filename dxcc_gluggi
    if {$Call == {} || $Swl == {}} return
    set printfile [open $logdir/qsl.txt a]
    set numer 0
    foreach i $logstructure {
	set prent($i) [lindex $listi($val) $numer]
	incr numer
    }
    set old_env $env(LANG)
    set env(LANG) en_US
    puts $printfile "   $filename(CALLSIGN) Confirming SWL with $Swl"
    puts $printfile "   On [clock format [clock scan $prent(QSO_DATE)]\
      -format "%d %h %Y"] at $prent(TIME_ON) UTC, Using $prent(MODE)"
    puts $printfile "   on the $prent(BAND) Band,  in QSO with $prent(CALL)"
    puts $printfile "   Tnx QSL, 73 $filename(MYNAME)"
    set env(LANG) $old_env
    #    puts $printfile "Rig: $prent(RIG), PWR: $prent(TX_PWR) W, Antenna:\
    #  $filename(ANT)"
    puts $printfile "-----"
    close $printfile
    exec labelnation -d "-----" -p $logdir/parfile -l -i $logdir/qsl.txt\
      -o $logdir/qslout.ps
    $dxcc_gluggi delete 1.0 end
    $dxcc_gluggi insert end "SWL label is in the file\n$logdir/qslout.ps"
}


#
# Print out the logfile in ADIF format
#
proc adif {firstnum lastnum} {
    global logdir listi logstructure filename
    set adiffile [open $logdir/$filename(LOGFILE).adi w]
    puts $adiffile "Operator:[string length $filename(CALLSIGN)] [format\
      "%s" $filename(CALLSIGN)]<adif_ver:4>1.00<eoh>"
    for {set val $firstnum} {$val < $lastnum + 1} {incr val} {
	set numer 0
	foreach i $logstructure {
	    set prent($i) [lindex $listi($val) $numer]
	    incr numer
	}
	puts -nonewline $adiffile "<Call:[string length $prent(CALL)]>[format\
	  "%s" $prent(CALL)]"
	puts -nonewline $adiffile "<QSO_Date:[string length\
	  $prent(QSO_DATE)]>[format "%s" $prent(QSO_DATE)]"
	puts -nonewline $adiffile "<Time_On:[string length\
	  $prent(TIME_ON)]>[format "%s" $prent(TIME_ON)]"
	puts -nonewline $adiffile "<Band:[string length $prent(BAND)]>[format\
	  "%s" $prent(BAND)]"
	puts -nonewline $adiffile "<Mode:[string length $prent(MODE)]>[format\
	  "%s" $prent(MODE)]"
	puts -nonewline $adiffile "<Rst_Sent:[string length\
	  $prent(RST_SENT)]>[format "%s" $prent(RST_SENT)]"
	puts -nonewline $adiffile "<Rst_Rcvd:[string length\
	  $prent(RST_RCVD)]>[format "%s" $prent(RST_RCVD)]"
	if {[string length $prent(CONTEST_ID)] == "0" || $prent(CONTEST_ID) ==\
	  "QSO"} {
	    puts -nonewline $adiffile "<Name:[string length\
	      $prent(NAME)]>[format "%s" $prent(NAME)]"
	    puts -nonewline $adiffile "<Qth:[string length\
	      $prent(QTH)]>[format "%s" $prent(QTH)]"
	} else {
	    puts -nonewline $adiffile "<Stx:[string length\
	      $prent(STX)]>[format "%s" $prent(STX)]"
	    puts -nonewline $adiffile "<Srx:[string length\
	      $prent(SRX)]>[format "%s" $prent(SRX)]"
	    puts -nonewline $adiffile "<Contest_id:[string length\
	      $prent(CONTEST_ID)]>[format "%s" $prent(CONTEST_ID)]"
	}
	puts $adiffile "<eor>"
    }
    close $adiffile
}

#
# Print out the logfile in cabrillo format
#
proc cbr {firstnum lastnum} {
    global logdir listi logstructure filename cab_struct cab_header
    set CBR(SSB) PH
    set CBR(LSB) PH
    set CBR(USB) PH
    set CBR(AM) PH
    set CBR(CW) CW
    set CBR(PSK31) BPSK31
    set CBR(BPSK31) BPSK31
    set CBR(QPSK31) QPSK31
    set CBR(MFSK16) MFSK16
    set CBR(RTTY) RTTY
    set CBR(SSTV) SSTV
    set CBR(160m) 1800
    set CBR(80m) 3500
    set CBR(40m) 7000
    set CBR(30m) 10100
    set CBR(20m) 14000
    set CBR(17m) 18100
    set CBR(15m) 21000
    set CBR(12m) 24900
    set CBR(10m) 28000
    set CBR(6m) 54000
    set CBR(2m) 144000
    set testline\
      "00000000011111111112222222222333333333344444444445555555555666666666677777777778
12345678901234567890123456789012345678901234567890123456789012345678901234567890"
    set cbrfile [open $logdir/$filename(LOGFILE).cbr w]
    #    puts $cbrfile $testline
    puts $cbrfile "START-OF-LOG: 2.0"
    foreach hline $cab_struct {
	puts $cbrfile "$hline: $cab_header($hline)"
    }
    for {set val $firstnum} {$val < $lastnum + 1} {incr val} {
	set numer 0
	foreach i $logstructure {
	    set prent($i) [lindex $listi($val) $numer]
	    incr numer
	}
	set date [string range $prent(QSO_DATE) 0 3]
	set mon [string range $prent(QSO_DATE) 4 5]
	set day [string range $prent(QSO_DATE) 6 7]
	set call [format "%-13s" $filename(CALLSIGN)]
	puts $cbrfile "QSO: [format "%-5s" $CBR($prent(BAND))]\
	  $CBR($prent(MODE)) $date-$mon-$day $prent(TIME_ON) [format\
	  "%-13s" $filename(CALLSIGN)] [format "%-3s" $prent(RST_SENT)]\
	  [format "%-6s" $prent(STX)] [format "%-13s" $prent(CALL)] [format\
	  "%-3s" $prent(RST_RCVD)] [format "%-6s" $prent(SRX)]"
    }
    puts $cbrfile "END-OF-LOG:"
    close $cbrfile
}

#
# print out in TAB limited ascii format
#
proc convert_log {logdir filename my_call} {
   global logstructure

   set i 0
   set logfile [open $logdir/$filename r]
   set outfile [open $logdir/$filename.tab w]

   foreach line [split [read $logfile] \n] {
       if {( $i > 0 ) && ($line != {}) } {
           puts -nonewline $outfile "$i\t $my_call\t"
       foreach dalk $logstructure {
	   set value "[lindex $line [lsearch -exact $logstructure $dalk]]"
           if { ($dalk == "TIME_ON") || (($dalk == "TIME_OFF" ) && ($value != ""))} {
	      append value "00"
	   } 
	      puts -nonewline  $outfile "$value\t"
	   }
	   puts $outfile ""
       }
       incr i
   }
   close $logfile
   close $outfile
}

#
# Print out the logfile in ASCII format
#
proc ascii {firstnum lastnum} {
    global logdir listi logstructure filename logbook
    set testline\
      "00000000011111111112222222222333333333344444444445555555555666666666677777777778
12345678901234567890123456789012345678901234567890123456789012345678901234567890"
    set asciifile [open $logdir/$filename(LOGFILE).txt w]
    #    puts $asciifile $testline
    for {set val $firstnum} {$val < $lastnum + 1} {incr val} {
	set numer 0
	foreach i $logstructure {
	    set prent($i) [lindex $listi($val) $numer]
	    incr numer
	}
	set year [string range $prent(QSO_DATE) 0 3]
	set mon [string range $prent(QSO_DATE) 4 5]
	set day [string range $prent(QSO_DATE) 6 7]
	set date [clock format [clock scan $prent(QSO_DATE)] -format "%d %h %Y"]
	set call [format "%-13s" $filename(CALLSIGN)]
	puts $asciifile "$date $prent(TIME_ON) [format "%-10s" $prent(CALL)]\
	  [format "%-6s" $prent(BAND)] [format "%-6s" $prent(MODE)] [format\
	  "%-4s %-4s" $prent(RST_SENT) $prent(STX)] [format "%-4s %-4s"\
	  $prent(RST_RCVD) $prent(SRX)] $prent(QSL_SENT) $prent(QSL_RCVD)\
	  [format "%-10s" $prent(NAME)] [format "%-32s" $prent(QTH)] [format\
	  "%-6s" $prent(RIG)] [format "%-3s" $prent(TX_PWR)] $prent(CONTEST_ID)"
    }
    close $asciifile
    # print the logfile using mpage and landscape
    exec mpage -1 -l -h$logbook($filename(GUI_LANG))_for_$filename(CALLSIGN) -X\
      -H $logdir/$filename(LOGFILE).txt >$logdir/$filename(LOGFILE).ps
}
#
# calculate the distance and bearing to the station
#
proc dist {Lat Long} {
    global filename
    #         set svar [exec gcb k 64N21W $Lat$Long]
    set svar [exec gcb k $filename(LATLONG) $Lat$Long]
    #         puts stdout $svar
    return $svar
}

#
# save the rcfile
#
proc save_rc {} {
    global rc_struct filename env loggrc
    set file [open $env(HOME)/$loggrc w]
    foreach rcline $rc_struct {
	puts $file "[lindex $rcline 0] {$filename([lindex $rcline 0])}"
    }
    flush $file
    close $file
}

#
# edit the rcfile
#
proc edit_rc {} {
    global rc_struct filename env loggrc

    toplevel .edit_rc
    set i 1
    frame .edit_rc.cmds
    button .edit_rc.cmds.exit -text Close -command {
	destroy .edit_rc
    }
    button .edit_rc.cmds.save -text Save -command {
	set svar [tk_messageBox -message "Save changes to $loggrc" -type yesno\
	  -icon question]
	switch -- $svar {
	yes {
		save_rc
	    }
	}
    }
    pack .edit_rc.cmds.save .edit_rc.cmds.exit -in .edit_rc.cmds -side left\
      -fill both
    pack .edit_rc.cmds -in .edit_rc -side top
    frame .edit_rc.left
    frame .edit_rc.right
    foreach rcline $rc_struct {
	frame .edit_rc.$i
	label .edit_rc.$i.l -text [lindex $rcline 0] -width 15
	entry .edit_rc.$i.e -textvariable filename([lindex $rcline 0])\
	  -relief sunken -width 50
	pack .edit_rc.$i.l .edit_rc.$i.e -in .edit_rc.$i -side left
	if {$i <= 19} {
	pack .edit_rc.$i -in .edit_rc.left -side top
	} else {
	pack .edit_rc.$i -in .edit_rc.right -side top
	}
	incr i
    }
    pack .edit_rc.left .edit_rc.right -in .edit_rc -side left
}

proc edit_entry {} {
    global logstructure listi log_index edit_line val do_edit write_log

    destroy .edit_entry
    toplevel .edit_entry
    frame .edit_entry.cmds
    button .edit_entry.cmds.exit -text Close -command {
	destroy .edit_entry
    }
    button .edit_entry.cmds.save -text Save -command {
	set newentry {}
	foreach i $logstructure {
	    lappend newentry $edit_line($log_index($i))
	}
	set listi($val(Num)) $newentry
	write_log
    }
    button .edit_entry.cmds.del -text Delete -activebackground red -command {
	set svar [tk_messageBox -message "Delete entry: $val(Num)" -type yesno\
	  -icon question]
	switch -- $svar {
	yes {
		do_edit $val(Num) DEL $val(Call)
		write_log
	    }
	}
    }
    pack .edit_entry.cmds.save .edit_entry.cmds.exit .edit_entry.cmds.del\
      -in .edit_entry.cmds -side left -fill both
    pack .edit_entry.cmds -in .edit_entry -side top
    set i 0
    frame .edit_entry.left
    frame .edit_entry.right
    set editline $listi($val(Num))
    foreach line $logstructure {
	frame .edit_entry.$i
	set edit_line($i) [lindex $editline $i]
	label .edit_entry.$i.l -text $line -width 15
	entry .edit_entry.$i.e -textvariable edit_line($i) -relief sunken
	pack .edit_entry.$i.l .edit_entry.$i.e -in .edit_entry.$i -side left
	if {$i <=16} {
	pack .edit_entry.$i -in .edit_entry.left -side top
	} else {
	pack .edit_entry.$i -in .edit_entry.right -side top
	}
	incr i
    }
    pack .edit_entry.left .edit_entry.right -in .edit_entry -side left
}

#
# edit the CABBRILLO header
#
proc edit_cab {} {
    global cab_struct filename env loggrc cab_header

    toplevel .cab_h
    set i 1
    frame .cab_h.cmds
    button .cab_h.cmds.exit -text Close -command {
	destroy .cab_h
    }
    pack .cab_h.cmds.exit -in .cab_h.cmds -side left -fill both
    pack .cab_h.cmds -in .cab_h -side top
    set cab_header(CALLSIGN) $filename(CALLSIGN)
    set cab_header(NAME) $filename(NAME)
    set cab_header(ADDRESS) $filename(ADDRESS)
    foreach hline $cab_struct {
	frame .cab_h.$i
	label .cab_h.$i.l -text $hline -width 15
	entry .cab_h.$i.e -textvariable cab_header($hline) -relief sunken
	pack .cab_h.$i.l .cab_h.$i.e -in .cab_h.$i -side left
	pack .cab_h.$i -in .cab_h -side top
	incr i
    }
}

#
# send
#
#
# send_cmd, the command to K2 using the serial port
#
if {[info procs send_cmd] == {}} {
    proc send_cmd {command} {
	global serial_port ready f log serial_busy
        
	if {$serial_busy} return 1
	set wordslist [split $command]
	foreach word $wordslist {
	    puts $serial_port "[subst $word]"
	    update
	}
    }
}

#
# send, the message to K2 keyer using the serial port
#
if {[info procs send_mess] == {}} {

    proc send_live {message} {
	global serial_port serial_busy

	if {$serial_busy} return 1
	puts $serial_port "KY $message;"
	if {[winfo exists .t.wins]} {
	    .t.wins.s insert end "$message"
	    .t.wins.s see end
	    update
	}
    }
    proc send_mess {message} {
	global serial_port .wins ready f log serial_busy

	if {$serial_busy} return 1
	set wordslist [split $message]
	foreach word $wordslist {
	    puts $serial_port "KY [subst $word] ;"
	    if {[winfo exists .t.wins]} {
		.t.wins.s insert end "[subst $word] "
		.t.wins.s see end
		update
	    }
	}
    }
}

#
# get the rig_info, from K2
#

proc rig_info {} {
    global log filename serial_port inn inline ant xfil xfil_bw dxcc_gluggi
    global f freq vfo mode splitmode speed tx_pwr PA serial_busy
    array set RMODES {1 LSB 2 USB 3 CW 6 RTTY 7 CW-REV 9 RTTY-REV}
    array set VFO {0 A 1 B}
    array set BANDS {1 160m 3 80m 7 40m 10 30m 14 20m 18 17m 21 15m 24 12m 28\
      10m 29 10m 54 6m}
    array set MODES {1 LSB 2 USB 3 CW 6 RTTY}

    if {$serial_busy} return 1
    after 200
    append inn [read $serial_port]
    if {[string index $inn end] == {;}} {
	set inline [string trimright $inn {;}]
	set inn {}
    } else {
	return 1
    }
    set svar [split $inline {;}]
    foreach inline $svar {
	switch [string range $inline 0 1] {
	"IF" {
		set vfo $VFO([string index $inline 30])
		set ifreq [string trimleft [string range $inline 5 12] 0]
		set freq($vfo) [format "%.3f" [expr {$ifreq/1000.0}]]
		set MHz [expr {$ifreq/1000000}]
		set mode $RMODES([string index $inline 29])
		set splitmode [string index $inline 32]
		if {[info exists BANDS($MHz)]} {
		    set band $BANDS($MHz)
		} else {
		    set band "[expr {300/$MHz}]m"
		}
		set log(BAND) $band
		set log(MODE) $mode
		set log(FREQ) $freq($vfo)
	    }
	"FR" {
		set vfo $VFO([string index $inline 2])
		set log(FREQ) $freq($vfo)
	    }
	"FA" {
		set ifreq [string trimleft [string range $inline 5 12] 0]
		set freq(A) [format "%.3f" [expr {$ifreq/1000.0}]]
		set MHz [expr {$ifreq/1000000}]
	    }
	"FB" {
		set ifreq [string trimleft [string range $inline 5 12] 0]
		set freq(B) [format "%.3f" [expr {$ifreq/1000.0}]]
		set MHz [expr {$ifreq/1000000}]
	    }
	"MD" {
		set mode $RMODES([string index $inline 2])
	    }
	"AN" {
		set ant [string index $inline 2]
	    }
	"FW" {
		set xfil [string index $inline 6]
		set xfil_bw [string trimleft [string range $inline 2 5] 0]
	    }
	"PC" {
		set tx_pwr [string range $inline 2 4]
		if {[string index $inline 5] == 1} {
		    set log(TX_PWR) [string range $inline 2 4]
		    set PA 1
		} else {
		    set log(TX_PWR) "[string range $inline 2 3].[string index\
		      $inline 4]"
		    set PA 0
		}
		set log(TX_PWR) [string trimleft $log(TX_PWR) 0]
	    }
	"KS" {
		set speed [string range $inline 2 4]
	    }
	"?;" {
		puts stderr Busy
	    }
	"K2" {
		$dxcc_gluggi delete 1.0 end
		$dxcc_gluggi insert end "Connected to Elecraft -- K2\n"
		$dxcc_gluggi insert end "Using Auto-Info Mode 2\n"
	    }
	default {
		#puts stderr $inline
	    }
	}
    }
    return 0
}

#
# 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
    }
    #puts stderr [fconfigure $serial_port]
    fileevent $serial_port readable rig_info
    return 0
}

#
# start and stop the rig_info
#
proc rig_start {} {
    global serial_port rig_initstring serial_busy
    set serial_busy [init_serial]
    send_cmd $rig_initstring
}

proc rig_stop {} {
    global serial_port
    send_cmd "K22;AI0;"
}

#
# and now the GUI
#

frame .top

#
# The qso date entry
#
frame .day
label .day.dag_l -text $box_date($lang) -width 8 -relief sunken
entry .day.dag -textvariable log(QSO_DATE) -width 8 -relief sunken -background #bedcaa -foreground darkblue
pack .day.dag_l .day.dag -side top
bind .day.dag <Button-1> {
    set tmode $b_text_manual($lang)
}
bind .day.dag <KeyRelease> {
    if {([string length $log(QSO_DATE)] == "8")} {
	focus .tim.time
    }
}

#
# The QSO start time entry
#
frame .tim
label .tim.time_l -text $box_time($lang) -width 5 -relief sunken
entry .tim.time -textvariable log(TIME_ON) -width 4 -relief sunken -background #bedcaa -foreground darkblue
pack .tim.time_l .tim.time -side top
bind .tim.time <Button-1> {
    set tmode $b_text_manual($lang)
}
bind .tim.time <KeyRelease> {
    if {([string length $log(TIME_ON)] == "4")} {
	focus .call.stod
    }
}

#
# The station call entry
#
frame .call
label .call.stod_l -text $box_station($lang) -width 10 -relief sunken
entry .call.stod -textvariable log(CALL) -width 10 -relief sunken
pack .call.stod_l .call.stod -side top
bind .call.stod <KeyRelease> {
    set log(CALL) [string toupper $log(CALL)]
    update
    check_entry $c_sel $log(CALL) "CALL"
    set year [string range $log(QSO_DATE) 0 3]
    check_country $log(CALL) $year
}
bind .call.stod <Button-3> {
    check_entry $c_sel $log(CALL) "CALL"
    }
bind .call.stod <KeyPress-Tab> {
    set tfreeze 1
    if {($tmode == $b_text_auto($lang)) ||($log(CONTEST_ID) != "QSO")} {
	do_time
	qrz $log(CALL)
    }
}

#
# The band entry
#
frame .bnd
label .bnd.m -text $box_band($lang) -width 5 -relief sunken
menubutton .bnd.m_l -relief sunken -textvariable log(BAND) -menu .bnd.m_l.sel\
  -width 3 -pady 2 -background #bedcaa -foreground darkblue
menu .bnd.m_l.sel
foreach bnd $filename(BAND) {
    .bnd.m_l.sel add radio -label $bnd -variable log(BAND) -value $bnd
}
pack .bnd.m .bnd.m_l -side top
bind .bnd.m <Button-1> {send_cmd "SW01;"}
bind .bnd.m <Button-3> {send_cmd "SW03;"}

#
# The frequency entry
#
frame .freq
label .freq.tidni_l -text $box_freq($lang) -width 9 -relief sunken
label .freq.tidni -textvariable log(FREQ) -width 9 -relief sunken\
  -background #bedcaa -foreground darkblue
pack .freq.tidni_l .freq.tidni -side top
bind .freq.tidni_l <Button-1> {
    send_cmd $rig_initstring
    $dxcc_gluggi delete 1.0 end
    $dxcc_gluggi insert end "Rig info On"

}
bind .freq.tidni_l <Button-3> {
    send_cmd "AI0;"
    $dxcc_gluggi delete 1.0 end
    $dxcc_gluggi insert end "Rig info Off"
}
bind .freq.tidni_l <Button-4> {send_cmd "DN2;"}
bind .freq.tidni_l <Shift-Button-4> {send_cmd "DN4;"}
bind .freq.tidni_l <Control-Button-4> {send_cmd "DN1;"}
bind .freq.tidni_l <Button-5> {send_cmd "UP2;"}
bind .freq.tidni_l <Shift-Button-5> {send_cmd "UP4;"}
bind .freq.tidni_l <Control-Button-5> {send_cmd "UP1;"}

#
# The mode entry
#
frame .mode
label .mode.mode_l -text $box_mode($lang) -width 6 -relief sunken
menubutton .mode.mode -relief sunken -textvariable log(MODE)\
  -menu .mode.mode.mode -width 4 -pady 2 -background #bedcaa\
  -foreground darkblue
menu .mode.mode.mode
foreach mo $filename(MODE) {
    .mode.mode.mode add radio -label $mo -variable log(MODE) -value $mo
}
pack .mode.mode_l .mode.mode -side top
bind .mode.mode_l <Button-1> {send_cmd "SW08;"}

#
# The RST sent entry
#
frame .rsts
label .rsts.rst_sent_l -text $box_rst_sent($lang) -width 10 -relief sunken
entry .rsts.rst_sent -textvariable log(RST_SENT) -width 4 -relief sunken
entry .rsts.rst_sx -textvariable log(STX) -width 5 -relief sunken
pack .rsts.rst_sent_l -side top
pack .rsts.rst_sent .rsts.rst_sx -side left
bind .rsts.rst_sent <KeyRelease> {
    if {!(($log(MODE) == "CW") ||($log(MODE) == "BPSK31") ||($log(MODE) ==\
      "QPSK31") ||($log(MODE) == "MFSK16") ||($log(MODE) ==\
      "RTTY") ||($log(MODE) == "SSTV")) &&([string length $log(RST_SENT)] ==\
      "2") ||([string length $log(RST_SENT)] == "3")} {
	if {$log(CONTEST_ID) == "QSO"} {
	    focus .rstr.rst_rcvd
	} else {
	    focus .rstr.rst_rx
	}
    }
}
bind .rsts.rst_sx <FocusIn> {
	if {$log(CONTEST_ID) == "QSO"} {
	    focus .rstr.rst_rcvd
	}
	}
#
# The RST received entry
#
frame .rstr
label .rstr.rst_rcvd_l -text $box_rst_rcvd($lang) -width 10 -relief sunken
entry .rstr.rst_rcvd -textvariable log(RST_RCVD) -width 4 -relief sunken
entry .rstr.rst_rx -textvariable log(SRX) -width 5 -relief sunken
pack .rstr.rst_rcvd_l -side top
pack .rstr.rst_rcvd .rstr.rst_rx -side left
bind .rstr.rst_rcvd <KeyRelease> {
    if {!(($log(MODE) == "CW") ||($log(MODE) == "BPSK31") ||($log(MODE) ==\
      "QPSK31") ||($log(MODE) == "MFSK16") ||($log(MODE) ==\
      "RTTY") ||($log(MODE) == "SSTV")) &&([string length $log(RST_RCVD)] ==\
      "2") ||([string length $log(RST_RCVD)] == "3")} {
	if {$log(CONTEST_ID) == "QSO"} {
	    focus .name.nafn
	} else {
	    focus .rstr.rst_rx
	}
    }
}
bind .rstr.rst_rx <FocusIn> {
	if {$log(CONTEST_ID) == "QSO"} {
	    focus .name.nafn
	}
	}

bind .rstr.rst_rx <KeyRelease> {
    set log(SRX) [string toupper $log(SRX)]
}

bind .rstr.rst_rx <KeyPress-Tab> {
    set log(SRX) [string toupper $log(SRX)]
    append_info
    append_log
    write_log
}

#
# The QSL entry
#
frame .qsl
label .qsl.qsl_l -text $box_qsl($lang) -width 5 -relief sunken
menubutton .qsl.qsl_rq -relief sunken -textvariable log(QSL_SENT)\
  -menu .qsl.qsl_rq.mode -width 1 -pady 2
menu .qsl.qsl_rq.mode
.qsl.qsl_rq.mode add radio -label "Ignore" -variable log(QSL_SENT) -value I
.qsl.qsl_rq.mode add radio -label "Requested" -variable log(QSL_SENT) -value R
menubutton .qsl.qsl_se -relief sunken -textvariable log(QSL_RCVD)\
  -menu .qsl.qsl_se.mode -width 1 -pady 2
menu .qsl.qsl_se.mode
.qsl.qsl_se.mode add radio -label "Ignore" -variable log(QSL_RCVD) -value I
.qsl.qsl_se.mode add radio -label "Requested" -variable log(QSL_RCVD) -value R
pack .qsl.qsl_l -side top
pack .qsl.qsl_rq .qsl.qsl_se -side left

#
# The OP name entry
#
frame .name
label .name.nafn_l -text $box_name($lang) -width 10 -relief sunken
entry .name.nafn -textvariable log(NAME) -width 10 -relief sunken
pack .name.nafn_l .name.nafn -side top
bind .name.nafn <Button-3> {
check_entry $c_sel $log(NAME) "NAME"
}
bind .name.nafn <FocusIn> {
    if {$log(CONTEST_ID) != "QSO"} {
	focus .call.stod
    }
}


#
# The QTH, etc  entry
#
frame .qthe
label .qthe.qth_l -text $box_qth($lang) -width 30 -relief sunken
entry .qthe.qth -textvariable log(QTH) -width 30 -relief sunken
pack .qthe.qth_l .qthe.qth -side top
bind .qthe.qth <Button-3> {
   check_entry $c_sel $log(QTH) "QTH"
}

#
# The rig used entry
#
frame .rig
label .rig.rig_l -text $box_rig($lang) -width 7 -relief sunken
menubutton .rig.rig -relief sunken -textvariable log(RIG) -menu .rig.rig.sel\
  -width 6 -pady 2
menu .rig.rig.sel
.rig.rig.sel add cascade -label "Rig" -menu .rig.rig.rig
menu .rig.rig.rig
foreach rig $filename(RIG) {
    .rig.rig.rig add radio -label $rig -variable log(RIG) -value $rig
}
.rig.rig.sel add separator
.rig.rig.sel add cascade -label "Power" -menu .rig.rig.pwr
menu .rig.rig.pwr
foreach pwr $filename(TX_PWR) {
    .rig.rig.pwr add radio -label $pwr -variable log(TX_PWR) -value $pwr
}
.rig.rig.sel add separator
.rig.rig.sel add cascade -label "Antenna" -menu .rig.rig.ant
menu .rig.rig.ant
foreach antenna $filename(ANT) {
    .rig.rig.ant add radio -label $antenna -variable log(ANT) -value $antenna
}
pack .rig.rig_l .rig.rig -side top
bind .rig.rig.sel <Leave> {
    switch -- $log(RIG) {
    K2 {set log(TX_PWR) 100}
    K2/QRP {set log(TX_PWR) 5}
    }
}

#
# NOTES entry
#
frame .notese
label .notese.notes_l -text $box_notes($lang) -width 10 -relief sunken
entry .notese.notes -textvariable log(NOTES) -width 10 -relief sunken
pack .notese.notes_l .notese.notes -side top

#
# The QSO end time entry
#
frame .tim_e
label .tim_e.time_l -text $box_time_off($lang) -width 5 -relief sunken
entry .tim_e.time -textvariable log(TIME_OFF) -width 4 -relief sunken
pack .tim_e.time_l .tim_e.time -side top

pack .day .tim .call .bnd .freq .mode .rsts .rstr .qsl .name .qthe .rig .tim_e\
  -in .top -side left

#pack .day .tim .call .bnd .mode .rsts .rstr .qsl .name .qthe .rig .notese\
#  .tim_e -in .top -side left

frame .bot

#
# Normal QSO or Contest mode
#
# label .logmode_l -text "Logmode"
menubutton .logmode -relief sunken -textvariable log(CONTEST_ID)\
  -menu .logmode.mode -width 10
menu .logmode.mode
foreach cid $filename(CONTEST_ID) {
    .logmode.mode add radio -label $cid -variable log(CONTEST_ID) -value $cid
}
bind .logmode.mode <Leave> {
    if {$log(CONTEST_ID) == "ARRL-10"} {
	set log(BAND) 10m
    }
    if {$log(CONTEST_ID) == "ARRL-160" || $log(CONTEST_ID) == "CQ-160"} {
	set log(BAND) 160m
    }
    set save_call $log(CALL)
    upphaf 0
    set log(CALL) $save_call
}


menubutton .timemode -relief sunken -textvariable tmode -menu .timemode.mode\
  -width 5
menu .timemode.mode
.timemode.mode add radio -label $b_text_auto($lang) -variable tmode\
  -value $b_text_auto($lang)
.timemode.mode add radio -label $b_text_manual($lang) -variable tmode\
  -value $b_text_manual($lang)

#
# Button for setting the QSO start time to current time
#
button .s_time -text $b_text_time($lang) -command {
    do_time
}
bind . <KeyPress-F11> {do_time}

#
# Button for setting the QSO end time to current time
#
button .e_time -text $b_text_time_off($lang) -command {
    set log(TIME_OFF) [clock format [clock seconds] -format %H%M]
}

#
# Button for clearing the entries
#
button .clear -text $b_text_clear($lang) -command {
    set infoentry $listi(0)
    set val(Num) 0
    set val(Call) {}
    upphaf 0
}

bind . <KeyPress-F12> {
    set infoentry $listi(0)
    set val(Num) 0
    set val(Call) {}
    upphaf 0
}

#
# Button for logging the enterd QSO
#
button .log -text $b_text_log($lang) -command {
    append_info
    append_log
    write_log
}

bind . <KeyPress-F9> {
    append_info
    append_log
    write_log
}

#
# Button for file operations and quit
#
menubutton .quit -text $b_text_file($lang) -menu .quit.e -relief raised\
  -padx .5c -pady .1c
set exitmenu [menu .quit.e]
set exportmenu [menu .quit.exp]
.quit.e add cascade -label "Export" -menu .quit.exp
.quit.exp add command -label "Export file as CBR" -command {
    edit_cab
    cbr $c_sel $num
}
.quit.exp add command -label "Export file as ADIF" -command {
    adif $c_sel $num
}
.quit.exp add command -label "Export ADIF for eQSL" -command {
    set c_sel $filename(EQSL)
    adif $c_sel $num
    set filename(EQSL) $num
    save_rc
    set c_sel $filename(OFFSET)
}
.quit.exp add command -label "Export file as ASCII" -command {
    ascii $c_sel $num
}
.quit.exp add command -label "Export file as TAB limited ASCII" -command {
    convert_log $logdir $filename(LOGFILE) $filename(CALLSIGN)
}
set importmenu [menu .quit.imp]
.quit.e add cascade -label "Import" -menu .quit.imp
.quit.imp add command -label "Import ADIF file" -command {
    set adif_file [tk_getOpenFile -initialdir $logdir -filetypes {{adif .adi}\
      {adif .adif}}]
    if {$adif_file != ""} {lesa_adif $adif_file}
}
set rangemenu [menu .quit.range]
.quit.e add cascade -label "Range" -menu .quit.range
.quit.range add command -label "Set Range from QSO#" -command {set c_sel\
  $val(Num)}
.quit.range add command -label "Set Range from 0" -command {set c_sel 0}
.quit.range add command -label "Set Range from OFFSET#" -command {set c_sel\
  $filename(OFFSET)}
#.quit.e add radio -label "No-Lookup" -variable qrz_lookup -value 0
.quit.e add check -label "QRZ Lookup" -variable qrz_lookup -onvalue 1 -offvalue 0
.quit.e add command -label "Edit $loggrc" -command {
    edit_rc
}
.quit.e add command -label "About $programname" -command {
    $country_gluggi delete 1.0 end
    $country_gluggi insert end $Credit
    $country_gluggi insert end $Help
    update
}
.quit.e add command -label "MATerm" -command {if {[info procs morse] == {}}\
  {source /usr/local/bin/MATerm} else {morse}}
.quit.e add separator
.quit.e add command -label "Quit program" -activebackground red -command {
    if {$block == 0} {
	set block 1
    }
    rm_lock
    exit
}

frame .edit

label .edit.fill1 -width 5
label .edit.fill2 -width 5
label .edit.qsl -text QSL -width 5
label .edit.val -textvariable val(Call) -width 11 -relief sunken -anchor w -background lightyellow

button .edit.qsl_s -text $b_text_sent($lang) -command {
    do_edit $val(Num) QSLS $val(Call)
    write_log
    prenta $val(Num) $val(Call)
}
button .edit.qsl_r -text $b_text_recvd($lang) -command {
    do_edit $val(Num) QSLR $val(Call)
    write_log
}
button .edit.qsl_p -text SWL -command {
    get_swl
}

label .edit.log -text $logbook($lang) -width 10

button .edit.upd -text $b_text_upd($lang) -command {
    $country_gluggi delete 1.0 end
    $country_gluggi insert end "Processing the logfile -- please wait"
    update
    add_info $c_sel 0
    get_info $c_sel
    write_log
}

button .edit.edit -text $b_text_edit($lang) -command {
    edit_entry
}
pack .edit.fill1 .edit.qsl .edit.val .edit.qsl_s .edit.qsl_r .edit.qsl_p\
  .edit.fill2 .edit.log .edit.upd -side left
#.logmode_l 
#.timemode_l 
pack .quit -in .bot -side left -pady .1c -padx .25c
pack .logmode -in .bot -side left -pady .1c -padx .25c
pack .s_time .log .clear .e_time -in .bot -side left -pady .1c -padx .25c
pack .edit -in .bot -side left -pady .1c -padx .25c

pack .top .bot -side top -expand y

frame .last
label .last.label -text $b_text_last($lang)
label .last.num -textvariable val(Num) -width 5 -relief sunken -background lightyellow
label .last.inf -text $b_text_info($lang)
label .last.qso -textvariable infoentry -width 115 -relief sunken -anchor w -background lightyellow
bind .last.qso <Double-ButtonRelease-1> {
    edit_entry
}

pack .last.label .last.num .last.inf .last.qso -side left
pack .last -side top -fill both -expand true


#
# Here is the display of old QSO's with the station
#
frame .info
set info_gluggi [listbox .info.sambond -height 17 -width 70\
  -yscrollcommand {.info.scroll set} -setgrid true -font $font]
scrollbar .info.scroll -command {.info.sambond yview}
pack .info.scroll -side right -fill y
pack .info.sambond -side left -fill both -expand true
bind .info.sambond <ButtonRelease-1> {
    set sel_lina [$info_gluggi get [$info_gluggi nearest %y]]
    set value [lindex [split $sel_lina] 0]
    if {[regexp -nocase {[A-Z]} $value] || [string length $value] == 0} {
	check_country $value 1966
    } else {
	set val(Num) $value
	if {[info exists listi($val(Num))]} {
	    set val(Call) [lindex [split $sel_lina] 6]
	    set val(Date) [lindex [split $sel_lina] 4]
	    check_country $val(Call) $val(Date)
	    set infoentry $listi($val(Num))
	}
    }
}
bind .info.sambond <Double-ButtonRelease-1> {
    set sel_lina [$info_gluggi get [$info_gluggi nearest %y]]
    set value [lindex [split $sel_lina] 0]
    if {[info exists listi($value)]} {
       set val(Num) $value
       edit_entry
    } else {
       check_entry $c_sel $value "DXCC" 
    }
}
bind .info.sambond <Double-ButtonRelease-3> {
    set sel_lina [$info_gluggi get [$info_gluggi nearest %y]]
    set value [lindex [split $sel_lina] 0]
    set val(Num) $value
    if {[info exists listi($value)]} {
       check_entry $c_sel $value "DATE" 
    }
}

frame .haegri

frame .dxcc
set dxcc_gluggi [text .dxcc.country -wrap word -height 1 -width 50\
  -yscrollcommand { .dxcc.scroll set} -setgrid true]
scrollbar .dxcc.scroll -command {.dxcc.country yview}
pack .dxcc.scroll -side right -fill y
pack .dxcc.country -side left -fill both -expand true

#
# Here is the display of the dxcc country list
#
frame .lookup
set country_gluggi [text .lookup.country -wrap word -height 7 -width 50\
  -yscrollcommand { .lookup.scroll set} -setgrid true]
scrollbar .lookup.scroll -command {.lookup.country yview}
pack .lookup.scroll -side right -fill y
pack .lookup.country -side left -fill both -expand true

#pack .info .lookup -side left -fill both -expand true

#
# Here is the display of last 10 entries
#
frame .lastten
set last_gluggi [text .lastten.log -wrap none -height 10 -width 50\
  -yscrollcommand { .lastten.scroll set} -setgrid true]
scrollbar .lastten.scroll -command {.lastten.log yview}
pack .lastten.scroll -side right -fill y
pack .lastten.log -side left -fill both -expand true

pack .dxcc .lookup .lastten -in .haegri -side top -fill both -expand true

pack .info .haegri -side left -fill both -expand true



#
# CW terminal, quick keys, send N and T for 9 and 0
#
proc cw_term {} {
    global cursor_pos pre_cursor_pos cw_word live_key

    destroy .cwterm
    toplevel .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 40 -height 5 -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"} {
		    #    if {[info exists cw_word]} {send_mess "$cw_word "}
		    if {[info exists cww_word]} {send_mess "$cww_word "}
		    set cw_word {}
		    set cww_word {}
		}
		append cww_word $key
	    } 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
    focus .cwterm.t
}

proc rst_stx {rst stx} {
    set y [format "%3u %03u" $rst $stx]
    #regsub -all "0" $y "T" y
    #regsub -all "9" $y "N" y
    send_mess $y
}

bind all <F1> {
    if {$log(CONTEST_ID) == "QSO"} {
	#send_mess "CQ CQ CQ de $filename(CALLSIGN) k"
	send_mess "[subst $filename(F1_QSO)]"
    } else {
	#send_mess "Test de $filename(CALLSIGN) k"
	send_mess "$filename(F1_CONTEST)"
    }
}

bind all <F2> {
    if {$log(CONTEST_ID) == "QSO"} {
	send_mess "[subst $filename(F2_QSO)]"
    } else {
	send_mess "$filename(F2_CONTEST)"
    }
}
bind all <F3> {
    if {$log(CONTEST_ID) == "QSO"} {
	send_mess "[subst $filename(F3_QSO)]"
    } else {
	send_mess "$filename(F3_CONTEST)"
    }
}
bind all <F4> {send_mess "$filename(F4)"}
bind all <F5> {send_mess "$filename(F5)"}
bind all <F6> {send_mess "$filename(F6)"}
bind all <F7> {send_mess "$filename(F7)"}
bind all <F8> {send_mess "$filename(F8)"}

bind all <Escape> {send_mess "@"}

bind all <F10> {cw_term}

#
# Initialize the time and othe things
#
do_time

update
check_lock
#
# start by reading in the information in the 
# all the logfiles and country list files
#
lesa_inn
upphaf 1
dxcc_inn
mkreg
mklist
tail_log
get_info $c_sel
focus .call.stod

#
# process command line arguments
#
foreach arg $argv {
    switch -regexp -- $arg {
    -h {
	    puts stderr "Options: --h help"
	    puts stderr "Options: --u update country information in the logfile"
	}
    -u {
	    puts stderr "Updating country info in logfile: $filename(LOGFILE)\
	      ---please wait"
	    add_info 0 1
	    write_log
	    puts stderr "Done"
	    rm_lock
	    exit
	}
    }
}

update
focus .call.stod
if {[info exists invoke_rc]} {
    edit_rc
}

#
# initialize the rig_info, if the serialport is not busy
#

update
rig_start

#
# the main program loops forever......
#

while {$block == 1} {
    after $refresh
    if {($tmode == $b_text_auto($lang)) &&($tfreeze == 0)} {
	do_time
    }
    update
}

