#!/bin/sh
# This line makes the next one a comment in Tcl \
exec wish "$0" -- ${1+"$@"}

# eTKTab by Jason Sonnenschein jes_jm@yahoo.com
# based on:

# TkTab by Giovanni Chierico, chierico@writeme.com
# You can do whatever you want with the code, as long as you leave my name and email address in it. Thanks


#######################################
### SET CONSTANTS:
###

# create necessary root namespaces
namespace eval WIN {}
namespace eval defaults {}

#directories... what was the user's working directory when the program
#was started, and where is the program located
set program_dir [ file dirname [ info script ] ]
set cwd [pwd]

# move next line to initialization code when program pulls up new windows
set version "2.5"
set webpage {http://etktab.sourceforge.net}
set author {Jason Sonnenschein (jes_jm@yahoo.com)}

# some O/S dependent stuff
switch -- $tcl_platform(platform) {
    {macintosh} {
        set commandkey Command
        set altkey Option
        # Cloverleaf symbol in Chicago Font is ASCII 17 (HEX 11)
        set displaycmd "\x11"
        set displayalt Opt
        set keynext Next
        set keyprior Prior
        set prefs_filename [file join $env(PREF_FOLDER) eTktab]
    }
    {windows} {
        set altkey Alt
        set commandkey Control
        set displayalt Alt
        set displaycmd Ctrl
        set keynext Next
        set keyprior Prior
        set prefs_filename {HKEY_CURRENT_USER\Software\eTktab} 
    }
    default {
        # Unix
        set altkey Alt
        set commandkey Control
        set displayalt Alt
        set displaycmd Ctrl
        set keynext Page_Down
        set keyprior Page_Up
        set prefs_filename [file join $env(HOME) .eTktabrc]
    }
}

# number of redo/undo steps kept
set histsteps 10

# all possible notes
set chromatic {D# {D } Db C# {C } {B } Bb A# {A } Ab G# {G } Gb F# {F } {E } Eb}

# basefret stuff
set maxbasefret 21

# what embellishments are there
array set embellish { 0 - 1 h 2 p 3 ^ 4 ~ 5 / 6 "\\" 7 s 8 b 9 r 10 t 20 x }

# what non-fret symbols are there
array set tab_symbols { -1 --- -2 -|- -6 o|- -10 -|o -14 o|o }

# width of guitar tuning in chars
set initial_col 3

# chars per column of tab
set col_width 3

# font sizes and types to be made available in prefs
set font_sizes { 6 7 8 9 10 12 14 18 24 }
array set font_weights {regular {} bold bold italic italic bold_italic {bold italic}}

# appearance of main window and statusbar
array set default_prefs {color_tab_bg_default black color_tab_bg_sel grey60 color_tab_fg_default white color_tab_fg_currpos red color_tab_fg_currstring green font_help {Courier 10} font_tab {Courier 12} font_statusbar {Times 10 bold} color_menu_fg_left blue color_menu_fg_right green color_menu_bg black color_help_fg black color_help_bg lightgrey num_strings 6 row_sep_lines 3 score_width 75 window_height 40 window_width 80}

if {$tcl_platform(platform)=="windows"} {
    # Courier 12 looks too big in main tab window under MS Windows
    set default_prefs(font_tab) {Courier 10}
} elseif {$tcl_platform(platform)=="macintosh"} {
    # Some macOS versions don't like certain colors and fonts being changed
    array set default_prefs {color_menu_fg_left black color_menu_fg_right black color_menu_bg lightgrey}
    set tabwin_options(*background) $default_prefs(color_menu_bg)
}

# set up tk defaults for widgets
array set tabwin_options "*Menubutton.relief raised *Menubutton.indicatorOn 1 *Menu.TearOff 0 *Dialog.msg.wrapLength 4i *Dialog.Button.underline 0 *Textwin.Text.setGrid 1 *Textwin.Text.wrap none *Textwin.Text.cursor left_ptr"

# stuff related to number of strings
set valid_numstrings "6 5 4"
set default_prefs(tuning_4) { 0 {G } 1 {D } 2 {A } 3 {E } }
set default_prefs(tuning_5) { 0 {D } 1 {B } 2 {G } 3 {D } 4 {G }}
set default_prefs(tuning_6) { 0 {E } 1 {B } 2 {G } 3 {D } 4 {A } 5 {E } }
# fill in numstring dependent stuff that doesn't need messages array
set menu_ns 0
foreach ns $valid_numstrings {
    set gui_label(menu:${ns}string) "{msg_frame.left_file.menu.new $menu_ns} {msg_frame.left_edit.menu.option.numstrings $menu_ns} {msg_frame.left_edit.menu.option.tuning $menu_ns}"
    set ext($ns) ".et$ns"
    set macext($ns) "eTk$ns"
    set blank_tab($ns) " { [lrange { -1 -1 -1 -1 -1 -1 -1 -1 } 0 [ expr $ns -1 ] ] } "
    incr menu_ns
}

# back end commands for keybindings:

array set keybind_funcs {
    back back
    forward forward
    up_string up_string
    down_string down_string
    up_score up_score
    down_score down_score
    home home
    end end
    inc_base inc_basefret
    dec_base dec_basefret
    new new_tab
    open open_dialog
    save save_tab
    export export_tab
    close close_tab
    quit_safe quit_safe
    exit __exit_now
    redraw redraw_full
    help help
    mode toggle_insert_mode
    mark toggle_mark
    select_all select_all
    copy copy_tab
    cut {cut_tab -history -redraw}
    paste paste_tab
    undo history_undo
    redo history_redo
    del_note del_note
    del_pos {del_pos -history}
    backspace backspace
    tuning {tuning_win current}
    space_before {add_blank -history -redraw}
    space_after {add_blank -advance -history -redraw}
    space_to_endline {force_newline}
    bar bar
    repeat {toggle_repeat}
}
    
# widget names for each lang-specific message

array set gui_text {
    string:mode msg_frame.right_chord_lead_legend
    string:basefret msg_frame.right_basefret_legend
    button:help msg_frame.left_help
    button:tuning msg_frame.right_tuning
    menu:file msg_frame.left_file
    menu:edit msg_frame.left_edit
}

array set gui_label {
    string:chord {{msg_frame.right_chord_lead.menu 0}}
    string:lead {{msg_frame.right_chord_lead.menu 1}}
    menu:new {{msg_frame.left_file.menu 0}}
    string:open {{msg_frame.left_file.menu 1}}
    string:save {{msg_frame.left_file.menu 2}}
    menu:save_as {{msg_frame.left_file.menu 3}}
    string:export {{msg_frame.left_file.menu 4}}
    menu:close {{msg_frame.left_file.menu 5}}
    menu:quit {{msg_frame.left_file.menu 6}}
    menu:undo {{msg_frame.left_edit.menu 0}}
    menu:redo {{msg_frame.left_edit.menu 1}}
    menu:cut {{msg_frame.left_edit.menu 3}}
    menu:copy {{msg_frame.left_edit.menu 4}}
    menu:clear {{msg_frame.left_edit.menu 5}}
    menu:paste {{msg_frame.left_edit.menu 6}}
    menu:select_all {{msg_frame.left_edit.menu 7}}
    menu:format {{msg_frame.left_edit.menu 9}}
    menu:options {{msg_frame.left_edit.menu 10}}
    string:keybind {{msg_frame.left_edit.menu.option 0}}
    string:language {{msg_frame.left_edit.menu.option 1}}
    menu:font {{msg_frame.left_edit.menu.option 2}}
    menu:color {{msg_frame.left_edit.menu.option 3}}
    menu:default_numstrings {{msg_frame.left_edit.menu.option 5}}
    menu:default_tuning {{msg_frame.left_edit.menu.option 6}}
    menu:default_format {{msg_frame.left_edit.menu.option 7}}
    menu:revert {{msg_frame.left_edit.menu.option 9}}
}

# menu accelerator keys
array set gui_accel {
    open {msg_frame.left_file.menu 1}
    save {msg_frame.left_file.menu 2}
    export {msg_frame.left_file.menu 4}
    close {msg_frame.left_file.menu 5}
    quit_safe {msg_frame.left_file.menu 6}
    undo {msg_frame.left_edit.menu 0}
    redo {msg_frame.left_edit.menu 1}
    cut {msg_frame.left_edit.menu 3}
    copy {msg_frame.left_edit.menu 4}
    paste {msg_frame.left_edit.menu 6}
    select_all {msg_frame.left_edit.menu 7}
}

#######################################
### INITIALIZE GLOBALS THAT DON'T GET RESET WITH NEW DOCUMENT
###

set newwin 0
# clear out the paste buffer
set pastebuf ""
set settings_file_failures ""

#######################################
### GLOBAL FUNCTIONS:
###

# doing this to have save queries come up when using Quit from mac menus
rename exit __exit_now
proc exit {} {quit_safe}

# there are equivalents to the next 2 procs in extended tcl/tk, but we're not 
# going to assume we're running under that

# return minimum of 2 vals
proc calc_min {arg1 arg2} {
    if { $arg1 < $arg2} {
        return $arg1
    } else {
        return $arg2
    }
}
# return maximum of 2 vals
proc calc_max {arg1 arg2} {
    if { $arg1 > $arg2} {
        return $arg1
    } else {
        return $arg2
    }
}

# also similar to some extended tcl procs

# add a new element to the beginning of a list, but limit its length
proc listshift {arrayname index limit new_item} {
    upvar $arrayname arr

    set arr($index) [ linsert [lrange $arr($index) 0 [expr $limit - 2 ] ] 0 "$new_item" ]
}
# return the first element from a list, and remove it from the list
proc listpop {arrayname index} {
    upvar $arrayname arr

    set popped [ lindex $arr($index) 0 ]
    set arr($index) [ lreplace $arr($index) 0 0 ]
    return "$popped"
}


# create new window
proc new_tab {args} { 
    global newwin
    global prefs
    global messages
    global settings_file_failures

    array set data $args
    # new tab defaults to default numstrings in prefs
    set requested_strings $prefs(num_strings) 
    if { [array names data {?strings} ] != "" } {
        set requested_strings $data(-strings)
    }
    
    # set up a new variable space for the window
    incr newwin
    set new_namespace ::WIN::$newwin
    namespace eval $new_namespace {}
    set ${new_namespace}::num_strings $requested_strings
    set ${new_namespace}::name ""
    if { [array names data {?file} ] != "" } {
        set ${new_namespace}::name $data(-file)
    }
    initialize_vars $new_namespace

    # create the new window
    build_gui $new_namespace

    # initialize the contents of the tablature
    redraw_full
    # let Tk draw the window, so transients of it will appear correctly
    update idletasks
    if { [array names data {?file} ] != "" } {
        open_tab
    }
    # need to post settings file load failures after first tab window 
    # is opened (due to it being a transient)
    foreach filename $settings_file_failures {
        my_dialog $messages(title:open_fail)  [subst -nocommands -nobackslashes $messages(dialog:open_fail) ] error 0 $messages(button:ok)
    }
    set settings_file_failures ""
}

# perform function for each tab window
proc each_namespace {cmd} {
    global curr_namespace
        
    set orig_namespace $curr_namespace
    foreach curr_namespace [ namespace children ::WIN ] {
        eval $cmd
    }
    set curr_namespace $orig_namespace
}

# generic proc to load settings files
proc read_settings_file {filename} {
    global settings_file_failures

    catch { set settings_file [open "$filename" r] }
    # file open failed
    if { ! ( [ info exists settings_file ] ) } {
        lappend settings_file_failures $filename
        return ""
    }

    set cont_line 0
    while { [gets $settings_file file_line ] != -1 } {
        # ignore lines beginning with '#'
        if { [string first {#} $file_line] == 0 } {
            set cont_line 0
            continue
        # add on to prev. line if last line ended in '\'
        } elseif { $cont_line == 1 } {
            if { [string range $file_line end end ] == "\\"} {
                set file_line [ string range $file_line 0 [ expr [string length $file_line ] - 2 ] ]\n
            } else {
                set cont_line 0
            }
            append array_value "${file_line}"
        # look for <word> = <whatever> format
        } elseif { [regexp {([a-zA-Z0-9\-_\.\,\:]+)\ *=\ *(.+)} $file_line full p1 p2] } {
            if { [string range $p2 end end ] == "\\"} {
                set p2 [ string range $p2 0 [ expr [string length $p2 ] - 2 ] ]\n
                set cont_line 1
            }
            set array_key $p1
            set array_value $p2
        # ignore lines that don't match above criteria
        } else {
            continue
        }
        if { $cont_line == 0 } {
            set return_array($array_key) $array_value
        }
    }
    close $settings_file
    return [array get return_array]
}

#look for eTktab user preferences in OS appropriate location
proc load_prefs {} {
    global default_prefs
    global prefs
    global prefs_filename
    global tabwin_options
    global settings_file_failures

    #load defaults
    array set prefs [ array get default_prefs ]

    if { [string first HKEY_ $prefs_filename ] == 0 } {
        #ms-windows: look for user-specific registry entries
        catch { set registry_values [ registry values $prefs_filename ] }
        if { [ info exists registry_values ] } {
            foreach curr_registry $registry_values {
                set curr_value [ registry get $prefs_filename $curr_registry ] 
                set prefs($curr_registry) $curr_value
            }
        }
    } else {
        # read in prefs file, if it exists
        array set prefs [ read_settings_file $prefs_filename ]
        # don't keep info. on failing to read the user's prefs...
        # they don't have to have a preferences file
        set settings_file_failures ""
    }
    # load in keybindings and natural language support
    load_language_support
    load_keybindings
}

# save user's prefs
proc save_prefs {} {
    global prefs
    global prefs_filename
    global messages

    set filename $prefs_filename
    if { [string first HKEY $prefs_filename ] == 0 } {
        #ms-windows: set user-specific registry entries
        foreach prefs_key [array names prefs] {
             registry set $prefs_filename $prefs_key $prefs($prefs_key)
        }
    } else {
        # mac/unix put prefs in user dotfile or mac preferences file
        # on failed file operation, does user want to retry?
        set success 0
        while { ! ($success) } {
            catch { set prefs_filehandle [open "$prefs_filename" w] }
            if { [info exists prefs_filehandle] } {
                set success 1
            } elseif { [my_dialog  $messages(title:save_fail)  [subst -nocommands -nobackslashes $messages(dialog:save_fail)] error "" $messages(button:retry) $messages(button:cancel) ] == "1" } {
                    return
            }
        }
    
        # write prefs to file
        foreach prefs_key [ lsort [array names prefs] ] {
            puts $prefs_filehandle "$prefs_key = $prefs($prefs_key)"
        }
        close $prefs_filehandle

    }

}

#open keybindings file and read its contents into keybind array
proc load_keybindings {} {
    global prefs
    global keybindings
    global keynames
    global altkey
    global commandkey
    global keynext
    global keyprior
    global messages
    global displayalt
    global displaycmd

    # Load in defaults
    array set unparsed_bindings [ default_keybindings ]
    # Did the user specify a keybindings file in the prefs?
    if { [array names prefs keybindings] != "" } {
        # Read in the file
        array set unparsed_bindings [ read_settings_file $prefs(keybindings)]
    }

    # Parse raw bindings
    foreach p1 [array names unparsed_bindings ] {
        set p2 $unparsed_bindings($p1)
        set new_keybind ""
        set new_keyname ""
        # Substitute for OS-specific keynames
        regsub -all {PGUP} $p2 $keyprior p2
        regsub -all {PGDN} $p2 $keynext p2
        # escape backslashes
        regsub -all {\\} $p2 {\\\\} p2
        foreach curr_key $p2 {
            # parse 'keysym(help_screen)' lines
            if { ! ( [regexp {([^\(]+)\-\>\((.*)\)} $curr_key full actual display ] ) } {
                set actual $curr_key
                set display $curr_key
            }
            lappend new_keybind $actual
            if {$display != ""} {
                lappend new_keyname $display
            }
        }
        # more os-dependent substitutions
        regsub -all CMD $new_keybind $commandkey new_keybind
        regsub -all CMD $new_keyname $displaycmd new_keyname
        regsub -all {ALT} $new_keyname $displayalt new_keyname
        regsub -all {ALT} $new_keybind $altkey new_keybind
        set new_keyname [join $new_keyname " $messages(string:or) "]
        if { [ string first {note} $p1 ] != 0 } {
            set new_keyname [format {%-18s} $new_keyname ]
        }
        set keybindings($p1) $new_keybind
        set keynames($p1) $new_keyname
    }
}

# default (qwerty keyboard) keybindings
proc default_keybindings {} {
    return {
        back Left
        forward Right
        up_string Up
        down_string Down
        up_score PGUP->(Page_Up)
        down_score PGDN->(Page_Down)
        home Home
        end End
        inc_base {plus->(+) equal->()}
        dec_base {minus->(-) underscore->()}
        new CMD-n
        open CMD-o
        save CMD-s
        export CMD-e
        close CMD-w
        quit_safe {CMD-q Escape->(Esc)}
        exit CMD-backslash->(CMD-\\)
        redraw CMD-l
        help {question->(?) CMD-h}
        mode Key-Tab->(Tab)
        mark CMD-m
        select_all CMD-a
        copy CMD-c
        cut CMD-x
        paste CMD-v
        undo CMD-u
        redo CMD-r
        del_note Delete
        del_pos Shift-Delete
        backspace BackSpace
        tuning {semicolon->(;) colon->()}
        space_before Insert
        space_after space
        space_to_endline Return
        bar {bar->(|) backslash->()}
        repeat {ALT-semicolon->(ALT-;) ALT-colon->()}
        mod:0 ALT-minus->(ALT--)
        mod:1 ALT-h
        mod:2 ALT-p
        mod:3 ALT-Key-6->(ALT-6)
        mod:4 ALT-quoteleft->(ALT-`)
        mod:5 ALT-slash->(ALT-/)
        mod:6 ALT-backslash->(ALT-\\)
        mod:7 ALT-s
        mod:8 ALT-b
        mod:9 ALT-r
        mod:10 ALT-t
        mod:20 ALT-x
        note:E.o exclam->(!)
        note:A.o at->(@)
        note:D.o numbersign->(#)
        note:G.o dollar->($)
        note:B.o percent->(%)
        note:e.o asciicircum->(^)
        note:E.0 Key-1->(1)
        note:A.0 Key-2->(2)
        note:D.0 Key-3->(3)
        note:G.0 Key-4->(4)
        note:B.0 Key-5->(5)
        note:e.0 Key-6->(6)
        note:E.1 q
        note:A.1 w
        note:D.1 e
        note:G.1 r
        note:B.1 t
        note:e.1 y
        note:E.2 a
        note:A.2 s
        note:D.2 d
        note:G.2 f
        note:B.2 g
        note:e.2 h
        note:E.3 z
        note:A.3 x
        note:D.3 c
        note:G.3 v
        note:B.3 b
        note:e.3 n
    }
}

#open natural-language support file and read its contents into messages array
proc load_language_support {} {
    global prefs
    global messages
    global valid_numstrings
    global save_types
    global open_types
    global export_types
    global language_types
    global keybind_types
    global ext
    global macext

    # load in defaults
    array set messages [ default_language_support ]
    # did user specify message file in prefs?
    if { [array names prefs language] != "" } {
        # read in the file
        array set messages [ read_settings_file $prefs(language) ]
    }

    # fill in constants that need messages array
    set export_types "
        {{$messages(string:file_tab)}	{.tab}	}
        {{$messages(string:file_tab)}	{}  TEXT}
    "
    set keybind_types "
        {{$messages(string:keybind)}	{.etk}	}
    "
    set language_types "
        {{$messages(string:language)}	{.etl}	}
    "

    foreach ns $valid_numstrings {
        set filetype($ns) [ subst -nocommands -nobackslashes $messages(string:file_etx) ]
        set messages(menu:${ns}string) [ subst -nocommands -nobackslashes $messages(menu:xstring) ]
    }
    foreach ns $valid_numstrings {
        set save_types($ns) "
            {{$filetype($ns)}       {$ext($ns)}       }
            {{$filetype($ns)}       {}    $macext($ns)}
        "
        # put current type at top, followed by the other valid ones
        set open_types($ns) "
            {{$filetype($ns)}       {$ext($ns)}       }
            {{$filetype($ns)}       {}    $macext($ns)}"
        foreach non_ns $valid_numstrings {
            if {$non_ns != $ns} {
                append open_types($ns) "
                    {{$filetype($non_ns)}       {$ext($non_ns)}       }
                    {{$filetype($non_ns)}       {}    $macext($non_ns)}"
            }
        }
    }
}

# default (American English) language support
proc default_language_support {} {
    return {
        string:open Open
        string:save Save
        string:export Export
        string:close Close
        string:untitled Untitled
        string:mode Mode
        string:lead Lead
        string:chord Chord
        string:lead Lead
        string:chord Chord
        string:basefret {Base Fret}
        string:or or
        string:color_menu_fg_left {Left Side Menu Foreground}
        string:color_menu_fg_right {Right Side Menu Foreground}
        string:color_menu_bg {Menu/Button Background}
        string:color_tab_fg_default {Tablature Default Foreground}
        string:color_tab_fg_currpos {Tablature Current Position Foreground}
        string:color_tab_fg_currstring {Tablature Current String Foreground}
        string:color_tab_bg_default {Default Tablature Background}
        string:color_tab_bg_sel {Selected Tablature Background}
        string:color_help_fg {Help Text Foreground}
        string:color_help_bg {Help Text Background}
        string:font_help {Help Font}
        string:font_tab {Tablature Font}
        string:font_statusbar {Statusbar Font}
        string:separation {Tab Spacing}
        string:width {Tab Width}
        string:window_width = {Window Width}
        string:window_height = {Window Height}
        string:regular Regular
        string:bold Bold
        string:italic Italic
        string:bold_italic Bold+Italic
        string:string_name {String $cs}
        string:file_tab {ASCII Tab}
        string:keybind Keybindings
        string:language Language
        string:file_etx {eTktab $ns String}
        string:usage {Usage: $argv0 [tablature file]
}
        title:help {Help: eTktab$version}
        title:tuning {Set Instrument Tuning}
        title:about {About eTktab}
        title:save_fail {Save Failed}
        title:open_fail {Open Failed}
        title:file_bad {File Format Bad}
        title:close_verify {File not Saved!}
        title:color {Choose Colors}
        dialog:about {eTktab $version by $author
$webpage}
        dialog:save_fail {Save operation failed for file:  $filename}
        dialog:open_fail {Open operation failed for file:  $filename}
        dialog:file_bad {eTktab$version cannot read the file format of $filename}
        dialog:close_verify {$filename has been modified.  Do you want to save before closing?}
        button:tuning Tuning
        button:help Help
        button:ok OK
        button:cancel Cancel
        button:yes Yes
        button:no No
        button:retry Retry
        menu:file File
        menu:new New
        menu:save_as {Save As}
        menu:close Close
        menu:quit Quit
        menu:edit Edit
        menu:undo {Undo $undo_menu}
        menu:redo {Redo $redo_menu}
        menu:cut Cut
        menu:copy Copy
        menu:clear Clear
        menu:paste Paste
        menu:select_all {Select All}
        menu:options Preferences
        menu:default_numstrings {New Document Default}
        menu:default_tuning {Default Tuning}
        menu:format {Document Formatting}
        menu:default_format {Default Formatting}
        menu:font Fonts
        menu:color Colors
        menu:revert {Revert to Defaults}
        menu:xstring {$ns string}
        history:note {Insert Note}
        history:tuning {Change Tuning}
        history:delete Delete
        history:del_note {Delete Note}
        history:space {Insert Space}
        history:cut Cut
        history:clear Clear
        history:paste Paste
        history:expression {Expression Mark}
        history:repeat {Toggle Repeat Symbol}
        history:bar {Insert Bar}
        history:newline {New Line}
        help:start {This help document describes the eTktab keybindings.  For a more general
explanation of how the program works, please see the 'README.html' file that 
comes with the program. 

Inserting notes:

Chord mode does not advance the cursor after each inserted note, lead mode 
does.  This mode may be changed via pulldown menu or keys in the Misc. section


          STRING (guitar)             STRING (banjo)            STRING (bass)

            E A D G B E                  G B G B D                  E A D G
          +-------------+              +-----------+              +---------+
F  base+0 | $keynames(note:E.0) $keynames(note:A.0) $keynames(note:D.0) $keynames(note:G.0) $keynames(note:B.0) $keynames(note:e.0) |    F  base+0 | $keynames(note:E.0) $keynames(note:A.0) $keynames(note:D.0) $keynames(note:G.0) $keynames(note:B.0) |    F  base+0 | $keynames(note:E.0) $keynames(note:A.0) $keynames(note:D.0) $keynames(note:G.0) |
R  base+1 | $keynames(note:E.1) $keynames(note:A.1) $keynames(note:D.1) $keynames(note:G.1) $keynames(note:B.1) $keynames(note:e.1) |    R  base+1 | $keynames(note:E.1) $keynames(note:A.1) $keynames(note:D.1) $keynames(note:G.1) $keynames(note:B.1) |    R  base+1 | $keynames(note:E.1) $keynames(note:A.1) $keynames(note:D.1) $keynames(note:G.1) |
E  base+2 | $keynames(note:E.2) $keynames(note:A.2) $keynames(note:D.2) $keynames(note:G.2) $keynames(note:B.2) $keynames(note:e.2) |    E  base+2 | $keynames(note:E.2) $keynames(note:A.2) $keynames(note:D.2) $keynames(note:G.2) $keynames(note:B.2) |    E  base+2 | $keynames(note:E.2) $keynames(note:A.2) $keynames(note:D.2) $keynames(note:G.2) |
T  base+3 | $keynames(note:E.3) $keynames(note:A.3) $keynames(note:D.3) $keynames(note:G.3) $keynames(note:B.3) $keynames(note:e.3) |    T  base+3 | $keynames(note:E.3) $keynames(note:A.3) $keynames(note:D.3) $keynames(note:G.3) $keynames(note:B.3) |    T  base+3 | $keynames(note:E.3) $keynames(note:A.3) $keynames(note:D.3) $keynames(note:G.3) |
 
   open   | $keynames(note:E.o) $keynames(note:A.o) $keynames(note:D.o) $keynames(note:G.o) $keynames(note:B.o) $keynames(note:e.o) |       open   | $keynames(note:E.o) $keynames(note:A.o) $keynames(note:D.o) $keynames(note:G.o) $keynames(note:B.o) |       open   | $keynames(note:E.o) $keynames(note:A.o) $keynames(note:D.o) $keynames(note:G.o) |

* base is shown in the status line and is changed via pulldown menu or the 
  keys listed in the 'Miscellaneous' section, below 
* bindings in the 'open' row are always at fret 0 (ignoring base fret)
________________________________________________________________________________
Cursor Movement:

$keynames(up_string)  up a string         $keynames(down_string)  down a string
$keynames(back)  left a position     $keynames(forward)  right a position
$keynames(up_score)  up a score          $keynames(down_score)  down a score

left mouse button click    unset mark (if any) and move to mouse position
________________________________________________________________________________
Insert/Delete:

$keynames(backspace)  delete previous position OR clear (*)
$keynames(del_note)  delete note under cursor OR clear (*)
$keynames(del_pos)  delete current position  OR clear (*)
$keynames(space_before)  insert a new position at cursor 
$keynames(space_after)  forward then add (chord mode) add then forward (lead mode)
$keynames(space_to_endline)  fill in empty positions to the end of the current line

    (*) if there is currently a highlighted area (if a mark is set) this key
        will clear that area instead of its usual function
________________________________________________________________________________
Note Alterations:

$keynames(mod:5)  slide up to note    $keynames(mod:6)  slide down to note
$keynames(mod:8)  bend                $keynames(mod:9)  release bend
$keynames(mod:1)  hammer-on           $keynames(mod:2)  pull-off
$keynames(mod:4)  vibrato (~)         $keynames(mod:3)  harmonic (^)
$keynames(mod:7)  slap/pop            $keynames(mod:10)  right-hand tapping
$keynames(mod:20)  muted               $keynames(mod:0)  remove alteration
________________________________________________________________________________
Cut/Paste:

$keynames(mark)  (un)set mark        $keynames(select_all)  select all
$keynames(copy)  copy highlighted tab
$keynames(cut)  cut highlighted tab $keynames(paste)  paste(*)
$keynames(undo)  undo                $keynames(redo)  redo

$keynames(del_note)/   $keynames(backspace)  SEE Insert/Delete section above

left mouse button click    unset mark (if any) and move to mouse position
left mouse button drag     highlight dragged over area}
        help:unix_mouse {
middle mouse button        paste(*)
right mouse button         move to mouse position; extend highlighted area}
        help:windows_mouse {
shift-left button click    move to mouse position; extend highlighted area
right mouse button         paste(*)}
        help:macintosh_mouse {
shift-left button click    move to mouse position; extend highlighted area
right mouse button         paste(*)
    NOTE:  'left button' bindings only, on a 1-button mouse}
        help:end {

    (*) if there is currently a highlighted area (if a mark is set) the paste
        function replaces the highlighted tab
________________________________________________________________________________
Miscellaneous:

$keynames(inc_base)  increase basefret   $keynames(dec_base)  decrease basefret
$keynames(mode)  toggle chord/lead   $keynames(tuning)  change guitar tuning
$keynames(bar)  add a bar           $keynames(repeat)  toggle repeat (*)

    (*) repeat symbols on bar lines... looking like this   |:   :|
________________________________________________________________________________
File I/O:

$keynames(help)  HELP                $keynames(redraw)  redraw screen
$keynames(quit_safe)  quit with save      $keynames(exit)  quit without save
$keynames(open)  open eTktab file    $keynames(save)  save eTktab file
$keynames(export)  export ascii tab    $keynames(new)  new tab   
$keynames(close)  close document

________________________________________________________________________________}
    }
}

# revert all preferences to defaults
proc pref_revert {} {
    global prefs
    global default_prefs
    global curr_namespace

    set old_keybindings [ array names prefs keybindings ]
    set old_language [ array names prefs language ]

    # reset all preferences
    unset prefs
    array set prefs [ array get default_prefs ]
    # save changes
    save_prefs

    # reload default keybindings and language support, if necessary
    if {$old_language != ""} {
        load_language_support
        each_namespace label_gui
    }
    if {$old_keybindings != ""} {
        load_keybindings
        each_namespace keybind_all
    }
    each_namespace color_gui
}

#set pref for default new tablature type
proc pref_numstrings {strings} {
    global prefs
    global curr_namespace

    save_prefs

    # change behavior of 'new tab' keybinding in each open tab window
    each_namespace keybind_all
}

# show user reqested color combinations in color prefs window
proc trycolor {} {
    global temp_colors

    foreach color_pref [ array names temp_colors] {
        switch -glob -- $color_pref {
            {*bg*} 
                {.color.test tag configure $color_pref -background $temp_colors($color_pref)}
            {*fg*} 
                {.color.test tag configure $color_pref -foreground $temp_colors($color_pref)}
        }
    }
}

# place transient window centered over its parent
proc place_transient {window} {
    global tcl_platform
    global curr_namespace
    variable ${curr_namespace}::tabwin

    wm withdraw $window
    set x [expr {[winfo screenwidth $window]/2 - \
        [winfo reqwidth $window]/2 - [winfo vrootx $tabwin]}]
    set y [expr {[winfo screenheight $window]/2 - \
        [winfo reqheight $window]/2 - [winfo vrooty $tabwin]}]
    wm geom $window +$x+$y
    wm resizable $window no no
    wm transient $window $tabwin
    wm deiconify $window

    #ms-windows doesn't seem to want to focus on our new toplevel windows
    if {$tcl_platform(platform)=="windows"} {
        update idletasks
        focus -force $window
    }
}

# lower and uppercase bindings of the first letter of a button's text
proc button_bind {args} {
    global altkey

    set prefix ""
    if {[lindex $args 0] == "-alt"} {
        set prefix ${altkey}-
        set args [lreplace $args 0 0]
    }
    set widget [lindex $args 0]
    set window [winfo toplevel $widget]
    set text [$widget cget -text]

    foreach i "tolower toupper" {
        bind $window "<${prefix}Key-[string $i [string index $text 0 ] ]>" "$widget invoke"
    }
}

# process 'shorthand' notation for creating a menubutton
proc my_menubutton {mb_name args} {
    set menu_items [lrange $args end end]
    set args [lreplace $args end end]
    eval "menubutton $mb_name -menu $mb_name.menu $args"
    eval "my_menu $mb_name.menu $menu_items"
}

# process 'shorthand' notation for creting a menu
proc my_menu {menu_name menu_items} {
    menu $menu_name
    foreach item $menu_items {
        switch -exact -- [lindex $item 0] {
            {command} 
                {set item [linsert $item [ expr [ llength $item ] - 1] -command]}
            {cascade} {
                my_menu $menu_name.[lindex $item 1] [lindex $item 2]
                set item [lreplace $item 1 2 -menu $menu_name.[lindex $item 1]] 
            }
        }
        eval "$menu_name add $item"
    }
}

# call standard tk color dialog, and change OK, Cancel button text
proc my_chooseColor {args} {
    global messages

    set frame .__tk__color.bot
    after idle "catch {$frame.ok configure -text $messages(button:ok)}"
    after idle "catch {button_bind -alt $frame.ok}"
    after idle "catch {$frame.cancel configure -text $messages(button:cancel)}"
    after idle "catch {button_bind -alt $frame.cancel}"
    return [ eval [ linsert $args 0 tk_chooseColor ] ]
}
# call standard tk file dialog, and change Open, Save, Cancel button text
proc my_filedialog {args} {
    global messages

    set w .__tk_filedialog
    set parent [ lsearch -exact $args -parent ]
    if {$parent > 0} {
        set w [ lindex $args [expr $parent + 1] ]$w
    }
    if { [ lindex $args 0 ] == "tk_getOpenFile" } {
        set text(f2.ok) $messages(string:open)
    } else {
        set text(f2.ok) $messages(string:save)
    }
    set text(f3.cancel) $messages(button:cancel)

    foreach widget [ array names text ] {
        after idle "catch {$w.$widget configure -text $text($widget)}"
        after idle "catch {button_bind -alt $w.$widget}"
    }
    return [ eval $args ]
}

# call standard tk dialog creation proc, and add keyboard bindings
proc my_dialog {args} {
    global curr_namespace
    variable ${curr_namespace}::tabwin

    set w "${tabwin}.dialog"
    for { set i 0 } { $i < [ expr [llength $args] - 4] } { incr i } {
        after idle button_bind ${w}.button$i
    }
    return [ eval [ linsert $args 0 tk_dialog $w ] ]
}

# proc to handle windows/mac documents dragged to eTktab
proc tkOpenDocument {args} {
    global used_dragdrop

    set used_dragdrop 1
    foreach file $args {
        new_tab -file $file
    }
}

# close all windows, checking if each document was saved
proc quit_safe {} {
    global curr_namespace

    each_namespace {
        set currwin [set [ string range $curr_namespace 2 end ]::tabwin] 
        if { [ focus ] != $currwin} {
            raise $currwin
            focus $currwin
        } 
        close_tab
    }
}

# about window
proc about {} {
    global author
    global version
    global webpage
    global messages

    if { [ basic_transient -nocancel .about $messages(title:about) ] == -1 } {
        return
    }

    label .about.text -text [subst -nobackslashes -nocommands $messages(dialog:about)]
    pack .about.text -side top -fill x
}

# help window
proc help {} {
    global prefs
    global tcl_platform
    global version
    global keynames
    global messages
    global keyprior
    global keynext
    global clover

    if { [ winfo exists .helpwin ] } {
        raise .helpwin
        focus .helpwin
        return
    }
    toplevel .helpwin -class Textwin
    wm title .helpwin [subst -nocommands -nobackslashes $messages(title:help) ]
    frame .helpwin.msg_frame -background $prefs(color_menu_bg)
    frame .helpwin.buttons -background $prefs(color_menu_bg)
    button .helpwin.buttons.can -background $prefs(color_menu_bg) -font $prefs(font_statusbar) -highlightbackground $prefs(color_menu_bg) -foreground $prefs(color_menu_fg_left) -text $messages(string:close) -default active -command {destroy .helpwin}

    text .helpwin.txt -font $prefs(font_help) -foreground $prefs(color_help_fg) -background $prefs(color_help_bg) -width 80 -height 40 -yscrollcommand ".helpwin.scrolly set" -xscrollcommand ".helpwin.scrollx set" 
    scrollbar .helpwin.scrollx -background $prefs(color_menu_bg) -highlightbackground $prefs(color_menu_bg) -activebackground $prefs(color_menu_bg) -orient horizontal -command ".helpwin.txt xview"
    scrollbar .helpwin.scrolly -background $prefs(color_menu_bg) -highlightbackground $prefs(color_menu_bg) -activebackground $prefs(color_menu_bg) -command ".helpwin.txt yview"
    
    #put actual help contents in window
    .helpwin.txt insert end [subst -nocommands -nobackslashes $messages(help:start)]
    .helpwin.txt insert end [subst -nocommands -nobackslashes $messages(help:$tcl_platform(platform)_mouse)]
    .helpwin.txt insert end [subst -nocommands -nobackslashes $messages(help:end)]
    
    .helpwin.txt configure -state disabled
    # some versions of macos won't allow us to change button bg color,font
    if {$tcl_platform(platform)!="macintosh"} {
        .helpwin.buttons.can configure -font $prefs(font_statusbar)
    } else {
       # change font of each cloverleaf char to 'Chicago'
       .helpwin.txt tag configure chicago -font "Chicago [lrange $prefs(font_help) 1 end]"
       set nextclover [.helpwin.txt search -forwards -exact -- "\x11" {1.0} end]
       while { $nextclover != ""} {
           .helpwin.txt tag add chicago $nextclover
           set nextclover "$nextclover + 1 chars"
           set nextclover [.helpwin.txt search -forwards -exact -- "\x11" $nextclover end]
       }
    }
    # keybindings
    bind .helpwin <Key-Return> ".helpwin.buttons.can invoke"
    bind .helpwin <Key-Left> ".helpwin.txt xview scroll -1 units"
    bind .helpwin <Key-Right> ".helpwin.txt xview scroll 1 units"
    bind .helpwin <Key-Up> ".helpwin.txt yview scroll -1 units"
    bind .helpwin <Key-Down> ".helpwin.txt yview scroll 1 units"
    bind .helpwin <Key-$keyprior> ".helpwin.txt yview scroll -1 pages"
    bind .helpwin <Key-$keynext> ".helpwin.txt yview scroll 1 pages"
    bind .helpwin <Key-Home> ".helpwin.txt yview moveto 0"
    bind .helpwin <Key-End> ".helpwin.txt yview moveto 1"

    pack .helpwin.buttons.can -pady 4 -side left

    grid rowconfig .helpwin.msg_frame 0 -weight 1 -minsize 0
    grid columnconfig .helpwin.msg_frame 0 -weight 1 -minsize 0
    grid .helpwin.txt -in .helpwin.msg_frame -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news
    grid .helpwin.scrolly -in .helpwin.msg_frame -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news
    grid .helpwin.scrollx -in .helpwin.msg_frame -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news
    
    pack .helpwin.buttons -side top -fill both
    pack .helpwin.msg_frame -side top -fill both -expand true
    #ms-windows doesn't seem to want to focus on our new toplevel windows
    if {$tcl_platform(platform)=="windows"} {
        update idletasks
        focus -force .helpwin
    }
}


#######################################
### FUNCTIONS THAT ACT ON CURRENTLY FOCUSED TAB WINDOW
###

#
# back end stuff, user doesn't call directly
#

# initialize all globals that do get reset at new document
proc initialize_vars {new_namespace} {
    global messages
    global prefs
    variable ${new_namespace}::basefret
    variable ${new_namespace}::col
    variable ${new_namespace}::create_newline
    variable ${new_namespace}::data_end
    variable ${new_namespace}::fret
    variable ${new_namespace}::insert_mode
    variable ${new_namespace}::mark
    variable ${new_namespace}::num_strings
    variable ${new_namespace}::pos
    variable ${new_namespace}::row
    variable ${new_namespace}::saved
    variable ${new_namespace}::string
    variable ${new_namespace}::tabula_rasa
    variable ${new_namespace}::tabwin
    variable ${new_namespace}::winnum
    variable ${new_namespace}::score_width
    variable ${new_namespace}::row_sep_lines

    # which window are we in?
    set winnum [ namespace tail $new_namespace ]
    set tabwin .tabwin$winnum

    # chord or note insertion type
    set insert_mode $messages(string:lead) 

    # where do we start on the fretboard?
    set fret 0
    set string 0            
    set basefret 0

    # starting afresh
    set tabula_rasa 1
    
    # erase any "mark"
    set mark -1
    
    # is the file saved ?
    set saved 1
              
    # current x position
    set col 0          
    
    # current score row
    set row 0
    
    # current position
    set pos 0
    
    set create_newline 1

    set data_end 0

    set score_width $prefs(score_width)

    # blank lines between scores
    set row_sep_lines $prefs(row_sep_lines)

    initialize_numstrings $new_namespace
}

proc initialize_numstrings {namespace} {
    global blank_tab
    global prefs
    variable ${namespace}::row_sep_lines
    variable ${namespace}::num_strings
    variable ${namespace}::row_height
    variable ${namespace}::tab_data
    variable ${namespace}::tuning

    array set tuning $prefs(tuning_$num_strings)

    # start with blank tablature
    set tab_data $blank_tab($num_strings)

    process_formatting $namespace
}

# empty the undo/redo buffers
proc history_clear {} {
    global curr_namespace
    variable ${curr_namespace}::redo
    variable ${curr_namespace}::undo

    foreach i {tab_data pos tuning mark last_action} {
            set undo($i) ""
            set redo($i) ""
    }
}

# add to the undo buffer
proc history_add {last_action} {
    global curr_namespace
    global histsteps
    global messages
    variable ${curr_namespace}::redo
    variable ${curr_namespace}::undo
    
    foreach i {tab_data pos mark last_action tuning} {
        if { $i != "last_action" } {
            variable ${curr_namespace}::$i
        }
        set redo($i) ""
        if { $i != "tuning" } {
            listshift undo $i $histsteps [set $i]
        } else {
            listshift undo tuning $histsteps [ array get tuning ]
        }
    } 
    set_saved 0
    ghost_menu normal menu:undo undo_menu $last_action
    ghost_menu disabled menu:redo redo_menu {}
}

# replace current tab with most recent in undo buffer
proc history_undo {} {
    global curr_namespace
    global histsteps
    global messages
    variable ${curr_namespace}::redo
    variable ${curr_namespace}::tuning
    variable ${curr_namespace}::undo

    if { $undo(pos) == "" } {
        return
    }

    listshift redo tuning $histsteps [ array get tuning ]
    array set tuning [ listpop undo tuning ]
    listshift redo last_action $histsteps [ listpop undo last_action ]
    foreach i {tab_data pos mark} {
        variable ${curr_namespace}::$i

        listshift redo $i $histsteps [set $i]
        set $i [ listpop undo $i ]
    }
    set_saved 0
    process_tuning $curr_namespace
    redraw_full
    ghost_menu normal menu:redo redo_menu [lindex $redo(last_action) 0]
    set undo_length [ llength $undo(pos) ] 
    if { $undo_length == 0 } {
        ghost_menu disabled menu:undo undo_menu {}
    } else {
        ghost_menu normal menu:undo undo_menu [lindex $undo(last_action) 0]
    }
}

# replace current tab with most recent in redo buffer
proc history_redo {} {
    global curr_namespace
    global histsteps
    global messages
    variable ${curr_namespace}::redo
    variable ${curr_namespace}::tuning
    variable ${curr_namespace}::undo

    if { $redo(pos) == "" } {
        return
    }

    listshift undo tuning $histsteps [ array get tuning ]
    array set tuning [ listpop redo tuning ]
    listshift undo last_action $histsteps [ listpop redo last_action ]
    foreach i {tab_data pos mark} {
        variable ${curr_namespace}::$i

        listshift undo $i $histsteps [set $i ]
        set $i [ listpop redo $i ]
    }
    set_saved 0
    process_tuning $curr_namespace
    redraw_full
    ghost_menu normal menu:undo undo_menu [lindex $undo(last_action) 0]
    set redo_length [ llength $redo(pos) ] 
    if { $redo_length == 0 } {
        ghost_menu disabled menu:redo redo_menu {}
    } else {
        ghost_menu normal menu:redo redo_menu [lindex $redo(last_action) 0]
    }
}

# put human readable copy of marked tablature in system's clipboard
proc update_clipboard {} {
    global curr_namespace
    global initial_col
    global col_width
    global clip
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::col
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::row_sep
    variable ${curr_namespace}::col_max

    set clip ""
    # do these three for each of min, max of pos,mark
    set col_marklow [ expr [calc_min $pos $mark ] % $col_max ]
    set row_marklow [ expr ([calc_min $pos $mark ] - $col_marklow) / $col_max ]
    set char_x_marklow [expr $col_marklow*$col_width+$initial_col]
    # grab tuning if they tried to grab the start of the line
    if {$char_x_marklow == $initial_col} {
        set char_x_marklow 0
    }
    set col_markhi [ expr [calc_max $pos $mark ] % $col_max ]
    set row_markhi [ expr ([calc_max $pos $mark ] - $col_markhi) / $col_max ]
    set char_x_markhi [expr ($col_markhi+1)*$col_width+$initial_col]

    for { set i $row_marklow } { $i <= $row_markhi } { incr i } {
        if { ( $i != $row_marklow ) && ( $i != $row_markhi ) } {
            set char_y [expr 1+$i*$row_height+$row_sep_lines]
	    append clip [ $tabwin.tablature get $char_y.0 [ expr $char_y + $num_strings ].0 ] 
        } else {
            if { $i == $row_marklow } {
                set leftedge $char_x_marklow
            } else {
                set leftedge 0
            }
            if { $i == $row_markhi } {
                set rightedge $char_x_markhi
            } else {
                set rightedge "end"
            }
    
            for { set j 0 } { $j < $num_strings } { incr j } {
                set char_y [expr $j+1+$i*$row_height+$row_sep_lines]
    	    append clip [ $tabwin.tablature get $char_y.$leftedge $char_y.$rightedge ] 
                append clip "\n"
            }
        }
        
        if { $i != $row_markhi } {
            append clip $row_sep
        }
    }

    selection own -selection "CLIPBOARD" .
    selection own -selection "PRIMARY" .
    selection own -selection "ETKTAB" .
    clipboard clear
    clipboard append $clip
}

# push out clipboard contents 
proc clipboard_dump {offset maxbytes} {
    global clip

    return [string range $clip $offset [expr $offset + $maxbytes ] ]
}
    
# push out paste buffer contents
proc pastebuf_dump {offset maxbytes} {
    global pastebuf

    return [string range $pastebuf $offset [expr $offset + $maxbytes ] ]
}

# change enable/disable (and/or text) of menu items
proc ghost_menu {state textkey args} {
    global curr_namespace
    global messages
    global gui_label
    variable ${curr_namespace}::tabwin

    # read in any variables necessary for variable substitution below
    array set data $args
    foreach varname [array names data] {
        set $varname $data($varname)
    }
    foreach widget $gui_label($textkey) {
        $tabwin.[lindex $widget 0] entryconfigure [lindex $widget 1] -state $state -label [subst -nocommands -nobackslashes $messages($textkey)]
    }
}

# change color of 'save' menu item
proc set_saved {status} {
    global curr_namespace
    global prefs
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::saved

    set saved $status
    if {$status == 1 } {
        set state disabled
    } else {
        set state normal
    }

    $tabwin.msg_frame.left_file.menu entryconfigure Save -state $state
}

# change appearance of mouse pointer
proc pointer {appearance} {
    global curr_namespace
    variable ${curr_namespace}::tabwin

    if {$appearance == "drag"} {
        set pointer_type xterm
    } else {
        set pointer_type left_ptr
    }
    $tabwin.tablature configure -cursor $pointer_type
}

# set values that depend on the text formatting values
proc process_formatting {namespace} {
    global initial_col
    global col_width
    variable ${namespace}::num_strings
    variable ${namespace}::score_width
    variable ${namespace}::col_max
    variable ${namespace}::row_sep
    variable ${namespace}::row_sep_lines
    variable ${namespace}::row_height

    # set last position possible on a line
    set col_max [ expr int ($score_width / $col_width) - $initial_col ]

    # blank lines between scores
    set row_sep ""
    for { set i 0 } { $i < $row_sep_lines } { incr i } {
        append row_sep "\n"
    }

    # lines per row of tab
    set row_height [ expr $num_strings + $row_sep_lines ]
    process_tuning $namespace
}

# take the array of the tuning and make something printable from it
proc process_tuning {namespace} {
    variable ${namespace}::row_sep
    variable ${namespace}::num_strings
    variable ${namespace}::processed_tuning
    variable ${namespace}::tuning

    set processed_tuning ""
    for { set i 0 } { $i < $num_strings } { incr i } {
        append processed_tuning $tuning($i) "|-\n"
    }
    append processed_tuning $row_sep
}

# finds the right col and row in function of pos
proc calc_rowcol {} {
    global curr_namespace
    variable ${curr_namespace}::col
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::col_max

    set col [ expr $pos % $col_max ]
    set row [ expr ($pos - $col) / $col_max ]
}    

# insert new score in tab window
proc newlines {} {
    global curr_namespace
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::row_sep
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::create_newline
    variable ${curr_namespace}::processed_tuning
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::tabula_rasa
    variable ${curr_namespace}::tabwin
    
    if { $tabula_rasa == 1 } {
	$tabwin.tablature insert 0.end $row_sep
        set tabula_rasa 0
    }
    
    set row_add [ expr ($data_end - ($data_end % $col_max)) / $col_max ]
    $tabwin.tablature insert [expr ( $row_add +1 ) * $row_height + 1+$row_sep_lines].end $processed_tuning
    set create_newline 0
}

# replaces notes on all strings with note sent as arg
proc replace_pos {fill} {
    global curr_namespace
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    for { set i 0 } { $i < $num_strings } { incr i } {
        set tab_data [ lreplace $tab_data $pos $pos [ lreplace [ lindex $tab_data $pos ] $i $i $fill ] ]
    }
}

# due to moving of $mark or $pos, need to recolor a range of tab
proc recolor_tab_full {} {
    global col_width
    global curr_namespace
    global initial_col
    global col_width
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::col
    variable ${curr_namespace}::row
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tabwin
    
    # this loop removes old color coding en masse
    foreach i "marked currpos currstring" {
        catch { $tabwin.tablature tag remove $i 0.0 end }
    }

    calc_rowcol
    # set color for marked area
    if {$mark!=-1} {
        set col_marklow [ expr [calc_min $pos $mark] % $col_max ]
        set row_marklow [ expr ([calc_min $pos $mark] - $col_marklow) / $col_max ]
        set char_x_marklow [expr $col_marklow*$col_width+$initial_col]
        set col_markhi [ expr [calc_max $pos $mark] % $col_max ]
        set row_markhi [ expr ([calc_max $pos $mark] - $col_markhi) / $col_max ]
        set char_x_markhi [expr ($col_markhi+1)*$col_width+$initial_col]

        for { set i $row_marklow } { $i <= $row_markhi } { incr i } {
            if { $i == $row_marklow } {
                set leftedge $char_x_marklow
            } else {
                set leftedge $initial_col
            }
            if { $i == $row_markhi } {
                set rightedge $char_x_markhi
            } else {
                set rightedge "end"
            }
    
            for { set j 0 } { $j < $num_strings } { incr j } {
                set char_y [expr $j+1+$i*$row_height+$row_sep_lines]
                $tabwin.tablature tag add marked $char_y.$leftedge $char_y.$rightedge
            }
        }
    }

    #set color for current position
    set char_x [expr $col*$col_width+$initial_col]
    set char_y [expr $string+1+$row*$row_height+$row_sep_lines]
    $tabwin.tablature tag add currstring $char_y.$char_x $char_y.[expr $char_x + $col_width]
    for { set i 0 } { $i < $num_strings } { incr i } {
        set char_y [expr $i+1+$row*$row_height+$row_sep_lines]
        $tabwin.tablature tag add currpos $char_y.$char_x $char_y.[expr $char_x + $col_width]
    }
    
    # make sure current position is visible
    see_currpos
}

# recolor a single position of tab
proc recolor_tab_pos {pos_todraw} {
    global curr_namespace
    global initial_col
    global col_width
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::string
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::row_sep_lines

    set col_todraw [ expr $pos_todraw % $col_max ]
    set row_todraw [ expr ($pos_todraw - $col_todraw) / $col_max ]
    set char_x [expr $col_todraw*$col_width+$initial_col]

    # pick the color for the text based on whether we're in a cut/paste 
    # selection zone or not, and whether or not we're under the cursor
    array set tag {marked remove currpos remove}
    if { ($mark != -1) && ($pos_todraw >= [ calc_min $mark $pos ]) && ($pos_todraw <= [ calc_max $mark  $pos ]) } {
        set tag(marked) add
    }
    if { $pos == $pos_todraw } {
        set tag(currpos) add
    }
    for { set i 0 } { $i < $num_strings } { incr i } {
        set tag(currstring) remove
        set char_y [expr $i+1+$row_todraw*$row_height+$row_sep_lines]
        # pick a color based on whether we're at the exact string and
        #  position of the cursor 
        if { ($i == $string)&&($pos == $pos_todraw) } { 
            set tag(currstring) add
        }
        foreach j "marked currpos currstring" {
	    catch { $tabwin.tablature tag $tag($j) $j $char_y.$char_x $char_y.[expr $char_x+$col_width] }
        }
    }
    calc_rowcol
    see_currpos
}
    
# redraw without erasing everything. A LOT more efficient than redraw_full
# you pass the position from which you want to redraw
proc redraw_toend { data_pos_redraw } {
    global col_width
    global curr_namespace
    global initial_col
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::row_sep
    variable ${curr_namespace}::create_newline
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::col_max
    
    set data_end [expr [llength $tab_data]  - 1 ]
    
    # allow writes to the window
    $tabwin.tablature configure -state normal
    # redraw the tab from data_pos_redraw on
    for { set i $data_pos_redraw } { $i <= $data_end  } { incr i } {
	draw_pos $i 
    }
    if { $pos < $data_pos_redraw } { redraw_pos $pos }

    # calate coords for the last position 
    set col_endtab [ expr $data_end % $col_max ]
    set row_endtab [ expr ($data_end - $col_endtab) / $col_max ]

    $tabwin.tablature configure -state normal
    
    #delete everything after the end of the lines of the last position
    for { set i 0 } { $i < $num_strings } { incr i } {
	$tabwin.tablature delete [expr $i+1+$row_endtab*$row_height+$row_sep_lines].[expr ($col_endtab+1)*$col_width+$initial_col] [expr $i+1+$row_endtab*$row_height+$row_sep_lines].end
    }

    
    # delete everything under the last row, like old rows
    $tabwin.tablature delete [expr $num_strings+$row_endtab*$row_height+$row_sep_lines].end end
    $tabwin.tablature insert [expr $num_strings+$row_endtab*$row_height+$row_sep_lines].end "\n$row_sep"

    calc_rowcol
    recolor_tab_full
    # re-disable writes to window, so user can't type arbitrary text
    $tabwin.tablature configure -state disabled
}


# delete and then redraw the whole tablature. 
proc redraw_full {} {
    global curr_namespace
    variable ${curr_namespace}::create_newline
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::tabula_rasa
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::col_max


    # allow writes to the window
    $tabwin.tablature configure -state normal
    $tabwin.tablature delete 1.0 end

    set tabula_rasa 1
    
    set data_end [expr [llength $tab_data] - 1 ]
   
    for { set i 0 } { $i <= $data_end  } { incr i } { 
	if { [ expr $i % $col_max ] == 0 } { set create_newline 1 }
	draw_pos $i 
    }
    calc_rowcol
    recolor_tab_full
    # re-disable writes to window, so user can't type arbitrary text
    $tabwin.tablature configure -state disabled
}

# redraw single position of tablature
proc redraw_pos {pos_todraw} {
   global curr_namespace
   variable ${curr_namespace}::tabwin
   variable ${curr_namespace}::pos

   # allow writes to the window
   $tabwin.tablature configure -state normal
   draw_pos $pos_todraw
   recolor_tab_pos $pos_todraw
   # re-disable writes to window, so user can't type arbitrary text
   $tabwin.tablature configure -state disabled
}

# make sure a position is visible in the tablaure
proc see_currpos {} {
    global curr_namespace
    global initial_col
    global col_width
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::col
    variable ${curr_namespace}::row
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tabwin

    set char_x [expr $col*$col_width+$initial_col]
    set char_y [expr $string+1+$row*$row_height+$row_sep_lines]

    $tabwin.tablature see [expr $char_y - $num_strings - 1 ].$char_x
    $tabwin.tablature see [expr $char_y + 2].$char_x
    # added the following because xview stuff doesn't work in 'see?'
    set xvisible [$tabwin.tablature xview]
    if {[lindex $xvisible 1] < 1} {
        # * 1.0 means give me a floating point, not an integer
        $tabwin.tablature xview moveto [expr $col * 1.0 / $col_max ]
    }
}


# prints out the tab. This is the procedure that writes stuff out to the screen
proc draw_pos {pos_todraw} {
    global curr_namespace
    global embellish
    global initial_col
    global col_width
    global tab_symbols
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::create_newline
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::tabwin
    
    set col_todraw [ expr $pos_todraw % $col_max ]
    set row_todraw [ expr ($pos_todraw - $col_todraw) / $col_max ]
    set char_x [expr $col_todraw*$col_width+$initial_col]

    if { $create_newline == 1} { newlines }
    for { set i 0 } { $i < $num_strings } { incr i } {
        set char_y [expr $i+1+$row_todraw*$row_height+$row_sep_lines]
	$tabwin.tablature delete $char_y.$char_x $char_y.[expr $char_x+$col_width]
	set fret_todraw [string trim [ lindex [ lindex $tab_data $pos_todraw ] $i ] ]
        if { $fret_todraw < 0 } {
            # empty tab, bars, repeats on bars
            $tabwin.tablature insert $char_y.$char_x $tab_symbols($fret_todraw)
        } elseif { $fret_todraw < 2000} {
            # modifier is 100's digit
            set modnum [ expr int ( $fret_todraw / 100 ) ]
            # fret is 1's and 10's
            set fretnum [ expr $fret_todraw % 100 ]
            # if fret < 10, add in a '-' to fill the 'empty' spot
            set filler [ lindex { - {} } [ expr $fretnum > 9 ] ]
            $tabwin.tablature insert $char_y.$char_x "$embellish($modnum)${fretnum}$filler"
        } elseif { $fret_todraw < 2100} {
            $tabwin.tablature insert $char_y.$char_x "-x-"
	} 
    }
	
}


#export tablature
proc export_tab {} {
    global curr_namespace
    global version
    global export_types
    global tcl_platform
    global cwd
    global messages
    variable ${curr_namespace}::name
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::winnum
    
    # what do we do if we don't yet have a filename?
    if { $name == "" } {
        set basename $messages(string:untitled)$winnum
    } else {
        set basename [ file rootname [ lindex [ file split $name ] end ] ]
    }

    # pull up the file dialog window
    if {$tcl_platform(platform)=="macintosh"} {
        set filename [my_filedialog tk_getSaveFile \
            -title $messages(string:export) -parent $tabwin \
            -initialfile $basename -initialdir $cwd -defaultextension .tab ]
    } else {
        set filename [my_filedialog tk_getSaveFile -filetypes $export_types \
            -title $messages(string:export) -parent $tabwin \
            -initialfile $basename -initialdir $cwd -defaultextension .tab ]
    }

    # did user close file dialog without choosing a file?
    if { $filename == "" } {
        return
    }

    set cwd [ file dirname $filename ]
    # on failed file operation, does user want to retry?
    set success 0
    while { $success == 0 } {
        catch { set myfile [open "$filename" w] }
        if { [info exists myfile] } {
            set success 1
        } elseif { [my_dialog  $messages(title:save_fail)  [subst -nocommands -nobackslashes $messages(dialog:save_fail)] error "" $messages(button:retry) $messages(button:cancel) ] == "1" } {
                return
        }
    }

    # dump data into the file
    # according to fconfigure manpage, end-of-line chars will be translated
    # appropriately for each OS
    puts -nonewline $myfile [$tabwin.tablature get 1.0 end]
    close $myfile
    if { $tcl_platform(platform) == "macintosh" } {
        file attributes $filename -creator ttxt -type TEXT
    }
}

#save tablature
proc save_tab {args} {
    global curr_namespace
    global version
    global save_types
    global ext
    global macext
    global tcl_platform
    global cwd
    global messages
    variable ${curr_namespace}::name
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::saved
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::winnum
    variable ${curr_namespace}::tuning
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::score_width
    
    set save_as 0
    if { [lsearch -exact $args -as] >= 0 } {
        set save_as 1
    }
    # nothing to do if file is already saved, and user isn't doing save_as
    if { ($saved == 1)&&($save_as == 0) } {
        return
    }
    # what do we do if we don't yet have a filename?
    if { $name == "" } {
        set basename $messages(string:untitled)$winnum
        set save_as 1
    } else {
        set basename [ file rootname [ lindex [ file split $name ] end ] ]
    }

    # pull up the file dialog window
    if {$save_as == 1} {
        if {$tcl_platform(platform)=="macintosh"} {
            set filename [my_filedialog tk_getSaveFile -parent $tabwin \
                -title $messages(string:save) -initialfile $basename \
                -defaultextension $ext($num_strings) -initialdir $cwd ]
        } else {
            set filename [my_filedialog tk_getSaveFile -parent $tabwin \
                -title $messages(string:save) -initialfile $basename \
                -defaultextension $ext($num_strings) -initialdir $cwd \
                -filetypes $save_types($num_strings) ]
        }

        # did user close file dialog without choosing a file?
        if { $filename == "" } {
            return
        }
        set cwd [ file dirname $filename ]
        set name $filename
    }

    # on failed file operation, does user want to retry?
    set success 0
    while { $success == 0 } {
        catch { set myfile [open "$name" w] }
        if { [info exists myfile] } {
            set success 1
        } elseif { [my_dialog  $messages(title:save_fail)  [subst -nobackslashes -nocommands $messages(dialog:save_fail)] error "" $messages(button:retry) $messages(button:cancel) ] == "1" } {
                return
        }
    }

    # dump data into the file
    puts $myfile "#eTktab$version tablature file"
    puts $myfile "#*formatting: score_width $score_width row_sep_lines $row_sep_lines"
    for { set i 0 } { $i < $num_strings } { incr i } {
        puts $myfile $tuning($i)
        # windows wants us to flush when we write in multiple statements
        flush $myfile
    }
    puts -nonewline $myfile $tab_data 
    close $myfile
    if { $tcl_platform(platform) == "macintosh" } {
        file attributes $name -creator eTkt -type $macext($num_strings)
    }

    # update window 
    wm title $tabwin "eTktab$version - $name" 
    set_saved 1
}

#load tablature 
proc open_tab {} {
    global curr_namespace
    global tcl_platform
    global version
    global chromatic
    global messages
    global default_prefs
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::name
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::saved
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::tuning
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::score_width
    
    array set new_tuning [ array get tuning ]
    set filename $name

    # on failed file operation, does user want to retry?
    set success 0
    while { $success == 0 } {
        catch { set myfile [open "$name" r] }
        if { [info exists myfile] } {
            set success 1
        } elseif { [my_dialog  $messages(title:open_fail)  [subst -nocommands -nobackslashes $messages(dialog:open_fail) ] error "" $messages(button:retry) $messages(button:cancel) ] == "1" } {
                return
        }
    }

    # as of version 2.0, there's a line at the top to identify it's a
    # eTktab file
    # according to fconfigure tcl manpage, we don't have to worry about
    # which OS the file was made on (what end-of-line char is used)
    # as tcl will translate automatically for us!
    set i 0
    while { [ info exists tab_data_new ] == 0 } {
        gets $myfile next_line
        # comments and formatting info
        if { [ string index "$next_line" 0 ] == "#" } {
            # is it formatting... not really a comment line?
            regexp {^#\*formatting: *score_width *([0-9]+) *row_sep_lines *([0-9]+)} $next_line full score_width_new row_sep_lines_new
        } elseif { [lsearch -exact $chromatic $next_line] > -1 } {
            # tuning
            set new_tuning($i) $next_line
            incr i
        } else {
            # tab
            set num_strings_new $i
            set tab_data_new $next_line
        }
    }
    close $myfile

    # tab looks valid?
    if { ( [ llength [ lindex $tab_data_new 0 ] ] != $num_strings_new ) || (($num_strings_new < 4)||($num_strings_new > 6)) } {
        my_dialog  $messages(title:file_bad) [subst -nocommands -nobackslashes $messages(dialog:file_bad) ] error 0 $messages(button:ok)
        return
    } 

    set num_strings $num_strings_new
    if { [info exists row_sep_lines_new] } {
        set row_sep_lines $row_sep_lines_new
    } else {
        set row_sep_lines $default_prefs(row_sep_lines)
    }
    if { [info exists score_width_new] } {
        set score_width $score_width_new
    } else {
        set score_width $default_prefs(score_width)
    }
    initialize_numstrings $curr_namespace
    keybind_numstrings
    array set tuning [ array get new_tuning ]
    set tab_data $tab_data_new
    set data_end [ expr [llength $tab_data] -1 ]
    set pos $data_end
    set mark -1
    redraw_full
    wm title $tabwin "eTktab$version - $name"

    set_saved 1
    history_clear
}

# close window... if unsaved, ask user what to do
proc close_tab {} { 
    global curr_namespace
    global messages
    variable ${curr_namespace}::name
    variable ${curr_namespace}::saved
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::winnum

    if { $saved == 0 } {
        if { $name == "" } {
            set filename $messages(string:untitled)$winnum
        } else {
            set filename $name
        }

        set response [my_dialog  $messages(title:close_verify) [subst -nocommands -nobackslashes $messages(dialog:close_verify)] warning "" $messages(button:yes) $messages(button:no) $messages(button:cancel) ]
        if {$response == 0} {
            save_tab
        } elseif {($response != 1)} {
            return
        }
    } 
    # closing the last window means quitting the program
    if { [ llength [ namespace children ::WIN ] ] == 1 } {
        __exit_now
    } else {
        destroy $tabwin
        namespace delete $curr_namespace
    }
}

#
# Pull up transient windows for user input
#

#set which file to look to for natural language support strings
proc pref_language {} {
    global curr_namespace
    global prefs
    global messages
    global program_dir
    global curr_namespace
    global language_types
    global settings_file_failures
    variable ${curr_namespace}::tabwin

    # call up file dialog to find natural language file
    set filename [my_filedialog tk_getOpenFile -parent $tabwin \
        -title $messages(string:language)  -filetypes $language_types \
        -initialdir $program_dir -defaultextension .etl ]
    # did the user give a filename?
    if { $filename == "" } {
        return
    }

    # alter prefs and load in file
    set prefs(language) $filename
    load_language_support

    # did load fail?
    if { $settings_file_failures != "" } {
        my_dialog $messages(title:open_fail)  [subst -nocommands -nobackslashes $messages(dialog:open_fail) ] error 0 $messages(button:ok)
        set settings_file_failures ""
        return
    }

    #save all user prefs
    save_prefs

    # load lang. support strings into each open tab window
    each_namespace label_gui
    # kill and reopen help window
    if { [ winfo exists .helpwin ] } {
        destroy .helpwin
        help
    }
}

#set which file to look to for keybindings
proc pref_keybindings {} {
    global curr_namespace
    global prefs
    global messages
    global program_dir
    global curr_namespace
    global keybind_types
    global settings_file_failures
    variable ${curr_namespace}::tabwin

    # call up file dialog to find keybindings file
    set filename [my_filedialog tk_getOpenFile -filetypes $keybind_types \
        -title $messages(string:keybind) -parent $tabwin \
        -initialdir $program_dir -defaultextension .etk ]
    # did the user give a filename?
    if { $filename == "" } {
        return
    }

    # alter prefs and load in file
    set prefs(keybindings) $filename
    load_keybindings

    # did load fail?
    if { $settings_file_failures != "" } {
        my_dialog $messages(title:open_fail)  [subst -nocommands -nobackslashes $messages(dialog:open_fail) ] error 0 $messages(button:ok)
        set settings_file_failures ""
        return
    }

    #save all user prefs
    save_prefs

    # load bindings into each open tab window
    each_namespace keybind_all
    # kill and reopen help window
    if { [ winfo exists .helpwin ] } {
        destroy .helpwin
        help
    }
}

#build a generic transient window to fill in with whatever
proc basic_transient {args} {
    global messages

    set close cancel
    if {[lindex $args 0] == "-nocancel"} {
       set close ok
       set args [lreplace $args 0 0]
    }
    set w [ lindex $args 0 ]
    set title [ lindex $args 1 ]

    if { [ winfo exists $w ] } {
        raise $w
        focus $w
        return -1
    }

    toplevel $w
    wm title $w $title
    frame $w.buttons
    pack $w.buttons -side bottom -pady 2m
    button $w.buttons.ok -under 0 -text $messages(button:ok)
    pack $w.buttons.ok -side left -expand true -padx 2.5m
    button_bind $w.buttons.ok

    # do we have a both ok and cancel, or just ok?
    if { $close == "cancel" } {
        button $w.buttons.cancel -under 0 -text $messages(button:cancel) 
        pack $w.buttons.cancel -side left -expand true -padx 2.5m
        button_bind $w.buttons.cancel
    } else {
        $w.buttons.ok configure -default active
        bind $w <Key-Return> "$w.buttons.ok invoke"
    }
    $w.buttons.$close configure -command "
        grab release $w
        destroy $w
    "
    wm protocol $w WM_DELETE_WINDOW "$w.buttons.$close invoke"
}

#set color preferences
proc pref_colors {} {
    global curr_namespace
    global prefs
    global messages
    global temp_colors
    global tcl_platform

    if { [ basic_transient .color $messages(title:color) ] == -1 } {
        return
    }

    text .color.test -font {Courier 18} -height 7 -width 14
    pack .color.test -side right -fill y
    frame .color.settings
    pack .color.settings -side top -fill both -expand true
    
    .color.buttons.ok configure -command {
        array set prefs [ array get temp_colors ]
        #save all user prefs
        save_prefs

        # load colors into each open tab window
        # we'll skip the help window on this one pref. proc.
        each_namespace color_gui
        destroy .color
    }

    set attribute_old ""
    array set attrib_row {bg -1 fg -1}
    array set attrib_col {bg 1 fg 0}
    foreach setting [ lsort [ array names prefs {color*} ] ] {
        #some macos versions don't like font redef. in menus
        if {($tcl_platform(platform)=="macintosh")&&([string match {*menu*} $setting])} {
            continue
        }
        set temp_colors($setting) $prefs($setting)
        button .color.settings.$setting -font $prefs(font_statusbar) -text $messages(string:$setting) -command "
            set tc \[my_chooseColor -parent .color -title {$messages(string:$setting)} -initialcolor \$temp_colors($setting)\] 
            if {\$tc != \"\"} { 
                set temp_colors($setting) \$tc 
                trycolor 
            }
         "
        regexp {color_[a-z]+_([bf]g)} $setting full attribute
        if {($attribute != $attribute_old)&&($attribute == {bg})} {
                set lastrow [calc_max $attrib_row(bg) $attrib_row(fg)]
                array set attrib_row "fg $lastrow bg $lastrow"
        }
        incr attrib_row($attribute)
        grid .color.settings.$setting -row $attrib_row($attribute) -column $attrib_col($attribute) -pady 2m -sticky we
        set attribute_old $attribute
    }
    
    trycolor
    .color.test insert end "\n 0123ABCDabcd\n\n 0123ABCDabcd"
    .color.test tag add color_help_bg 2.0 3.0
    .color.test tag add color_help_fg 2.0 3.0
    # don't show menu color opts on mac
    if {$tcl_platform(platform)!="macintosh"} {
        .color.test insert end "\n\n 0123ABCDabcd"
        .color.test tag add color_menu_bg 4.0 5.0
        .color.test tag add color_menu_fg_left 4.0 4.7
        .color.test tag add color_menu_fg_right 4.7 5.0
        set lastrow 6
    } else {
        set lastrow 4
    }
    .color.test tag add color_tab_bg_default ${lastrow}.0 ${lastrow}.7
    .color.test tag add color_tab_bg_sel ${lastrow}.7 end
    .color.test tag add color_tab_fg_currpos ${lastrow}.0 ${lastrow}.3 ${lastrow}.7 ${lastrow}.9
    .color.test tag add color_tab_fg_currstring ${lastrow}.3 ${lastrow}.5 ${lastrow}.9 ${lastrow}.11
    .color.test tag add color_tab_fg_default ${lastrow}.5 ${lastrow}.7 ${lastrow}.11 end

    place_transient .color
}

#set font size/weight preferences... not family, because we want to force
#the user to a non-proportional tablature font, and it also makes this easier
proc pref_fonts {} {
    global curr_namespace
    global prefs
    global messages
    global font_sizes
    global font_weights
    global temp_font
    global tcl_platform

    if { [ basic_transient .font $messages(menu:font) ] == -1 } {
        return
    }

    .font.buttons.ok configure -command {
        array set prefs [ array get temp_font ]
        #save all user prefs
        save_prefs

        # load fonts into each open tab window
        each_namespace color_gui
        destroy .font
        # load fonts into any open help windows
        if { [ winfo exists .helpwin ] } {
            .helpwin.txt configure -font $prefs(font_help)
            .helpwin.buttons.can configure -font $prefs(font_statusbar)
        }
    }

    frame .font.pref
    pack .font.pref -side top -fill x -pady 2m
    set i -1
    foreach setting [ lsort [ array names prefs {font*} ] ] {
        #some macos versions don't like font redef. in menus
        if {($tcl_platform(platform)=="macintosh")&&([string match {*status*} $setting])} {
            continue
        }
        set prefix .font.pref.${setting}
        incr i
        set temp_font($setting) $prefs($setting)
        # get size and weight of fonts currently in use
        regexp {([0-9]+)} $prefs($setting) full size
        switch -glob -- $prefs($setting) {
            {*bold?italic*}
                {set weight bold_italic}
            {*bold*}
                {set weight bold}
            {*italic*}
                {set weight italic}
            default
                {set weight regular}
        }
        
        # Font name written in chosen font
        label ${prefix}_name -justify left -text $messages(string:$setting) -font $prefs($setting)

        # size choice menubutton
        menubutton ${prefix}_size -text $size -menu ${prefix}_size.menu
        menu ${prefix}_size.menu 
        foreach size_choice $font_sizes {
            ${prefix}_size.menu add radiobutton -indicatoron false -label $size_choice -command "
                regsub {(\[0-9\]+)} \$temp_font($setting) $size_choice temp_font($setting)
                ${prefix}_name configure -font \$temp_font($setting)
                ${prefix}_size configure -text $size_choice 
            "
        }

        # weight choice menubutton
        menubutton ${prefix}_weight -text $messages(string:$weight) -menu ${prefix}_weight.menu
        menu ${prefix}_weight.menu 
        foreach weight_choice [ lsort [ array names font_weights ] ] {
            ${prefix}_weight.menu add radiobutton -indicatoron false -label $messages(string:$weight_choice) -command "
                set temp_font($setting) \"\[lrange \$temp_font($setting) 0 1 \] \$font_weights($weight_choice)\"
                ${prefix}_name configure -font \$temp_font($setting)
                ${prefix}_weight configure -text $messages(string:$weight_choice)
            "
        }
        grid ${prefix}_name ${prefix}_size ${prefix}_weight -row $i -sticky we -pady 2m
    }

    place_transient .font
}
      
# set formatting of tablature
proc pref_format {variable} {
    global curr_namespace
    global messages
    global tcl_platform
    global col_width

    if {$variable == "current"} {
        set space $curr_namespace
        variable ${space}::temp_format
        variable ${space}::score_width
        variable ${space}::row_sep_lines
        variable ${space}::tabwin
        array set temp_format [list row_sep_lines $row_sep_lines score_width $score_width]
        set window $tabwin.format
        set title $messages(menu:format)
    } else {
        set space "::defaults"
        global prefs
        variable ${space}::temp_format
        array set temp_format [list row_sep_lines $prefs(row_sep_lines) score_width $prefs(score_width) window_width $prefs(window_width) window_height $prefs(window_height)]
        set window .format_defaults
        set title $messages(menu:default_format)
    }

    if { [ basic_transient $window $title ] == -1 } {
        return
    }

    if {$variable == "current"} {
        $window.buttons.ok configure -command "
            set ${space}::score_width \$${space}::temp_format(score_width)
            set ${space}::row_sep_lines \$${space}::temp_format(row_sep_lines)
           
            # load formatting into current tab window
            process_formatting $space
            redraw_full

            destroy $window
        "
    } else {
        $window.buttons.ok configure -command "
            array set prefs \[array get ${space}::temp_format \]
            save_prefs
            destroy $window
        "
    }

    frame $window.pref
    pack $window.pref -side top -fill x -pady 2m

    label $window.pref.rowsep_label -text $messages(string:separation)
    scale $window.pref.rowsep_scale -showvalue true -from 1 -to 10 -resolution 1 -orient vertical -variable ${space}::temp_format(row_sep_lines)
    grid $window.pref.rowsep_label -row 0 -column 0 -columnspan 2 -sticky e
    grid $window.pref.rowsep_scale -row 0 -column 2 -rowspan 2 -sticky w
    scale $window.pref.width_scale -showvalue true -from 45 -to 135 -resolution $col_width -label $messages(string:width) -orient horizontal -variable ${space}::temp_format(score_width)
    grid $window.pref.width_scale -row 1 -column 0 -columnspan 2 -sticky we -pady 2m
    if {$variable != "current"} {
        label $window.pref.spacer -text "   "
        label $window.pref.winheight_label -text $messages(string:window_height)
        scale $window.pref.winheight_scale -showvalue true -from 20 -to 80 -resolution 1 -orient vertical -variable ${space}::temp_format(window_height)
        grid $window.pref.spacer -row 1 -column 3
        grid $window.pref.winheight_label -row 0 -column 4 -columnspan 2 -sticky e
        grid $window.pref.winheight_scale -row 0 -column 6 -rowspan 2 -sticky w
        scale $window.pref.winwidth_scale -showvalue true -from 50 -to 140 -label $messages(string:window_width) -orient horizontal -variable ${space}::temp_format(window_width)
        grid $window.pref.winwidth_scale -row 1 -column 4 -columnspan 2 -sticky we -pady 2m
    }

    place_transient $window
}
      
# pulldown menus to change tuning of individual strings
proc tuning_win {variable} {
    global chromatic
    global curr_namespace
    global messages
    global prefs
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tabwin

    if {$variable == "current"} {
        set space $curr_namespace
        variable ${space}::num_strings
        variable ${space}::tuning
        variable ${space}::temp_tuning
        set ns $num_strings
        array set temp_tuning [ array get tuning ]
        set window $tabwin.tuning
        set title $messages(title:tuning)
    } else {
        regexp {tuning_([0-9])} $variable full ns
        set space ::defaults
        variable ${space}::temp_tuning
        array set temp_tuning $prefs($variable)
        set window .tuning_defaults
        set title $messages(menu:default_tuning)
    }

    if { [ basic_transient $window $title ] == -1 } {
        return
    }

    grab $window
    frame $window.body
    pack $window.body -expand 1 -fill both -side top

    for { set i 0 } { $i < $ns } { incr i } {
        set cs [ expr $i + 1 ]
        menubutton $window.body.${i}_button -textvariable ${space}::temp_tuning($i) -menu $window.body.${i}_button.menu -direction right
        menu $window.body.${i}_button.menu 
        foreach j $chromatic {
            $window.body.${i}_button.menu add radiobutton -label $j -variable ${space}::temp_tuning($i) 
        }
        $window.body.${i}_button.menu entryconfigure 9 -columnbreak 1
        label $window.body.${i}_label -justify left -text [ subst -nobackslashes -nocommands $messages(string:string_name) ]
        grid $window.body.${i}_label $window.body.${i}_button -row $i -sticky we -pady 1m -padx 1m
    }

    if {$variable == "current"} {
        $window.buttons.ok configure -command "
            history_add {$messages(history:tuning)}
            array set ${curr_namespace}::tuning \[ array get ${space}::temp_tuning \]
            process_tuning $curr_namespace
            redraw_full 
            grab release $window 
            destroy $window
        "
    } else {
        $window.buttons.ok configure -command "
            set prefs($variable) \[array get ${space}::temp_tuning \]
            save_prefs
            grab release $window 
            destroy $window
        "
    }

    label $window.body.spacer -text ""
    grid $window.body.spacer -row $ns 

    place_transient $window
}

# file open/save/export window
proc open_dialog {} {
    global curr_namespace
    global ext
    global open_types
    global blank_tab
    global cwd
    global messages
    global prefs
    variable ${curr_namespace}::name
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::tab_data

    set filename [my_filedialog tk_getOpenFile -title $messages(string:open) \
        -parent $tabwin -defaultextension $ext($prefs(num_strings)) \
        -initialdir $cwd -filetypes $open_types($prefs(num_strings)) ]

    if { $filename == "" } {
        return
    }

    set cwd [ file dirname $filename ]
    # get new window for tab, unless current tab window is empty
    if { $tab_data == $blank_tab($prefs(num_strings)) } {
        set name $filename
        open_tab
    } else {
        new_tab -file $filename
    }
}


#
# functions mapped to keypresses by end user
#

# **functions that affect overall mode

# toggle chord/note mode
proc toggle_insert_mode {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::insert_mode

    if { $insert_mode == $messages(string:chord) } { 
	set insert_mode $messages(string:lead)
    } else {
	set insert_mode $messages(string:chord)
    }
}

# move the base fret up 1
proc inc_basefret {} {
    global curr_namespace
    global maxbasefret
    variable ${curr_namespace}::basefret

    if { $basefret < $maxbasefret } {
      incr basefret
    }
}

# move the base fret down 1
proc dec_basefret {} {
    global curr_namespace
    variable ${curr_namespace}::basefret
    variable ${curr_namespace}::pos

    if { $basefret > 0 } {
      incr basefret -1
    }
}
    
# **cursor movement

# move back a position in the tab
proc back {} {
    global curr_namespace
    variable ${curr_namespace}::col
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::col_max

    if { $pos > 0 } {
        set old_pos $pos
	incr pos -1
	recolor_tab_pos $old_pos
	recolor_tab_pos $pos
    }
}

# move forward a position in the tab
proc forward {} {
    global curr_namespace
    variable ${curr_namespace}::col
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::col_max

    if { $pos < $data_end } {
	set old_pos $pos
	incr pos
	recolor_tab_pos $old_pos
	recolor_tab_pos $pos
    }
}

# move up a string
proc up_string {} {
    global curr_namespace
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::string

    if { $string > 0 } {
        incr string -1
        recolor_tab_pos $pos
    }
}

# move down a string
proc down_string {} {
    global curr_namespace
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::string

    if { $string < [expr $num_strings - 1] } {
        incr string
        recolor_tab_pos $pos
    }
}


# move up a score
proc up_score {} {
    global curr_namespace
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::col_max

    set pos_new [ expr $pos - $col_max ]
    if { $pos_new >= 0 } {
        set pos_old $pos
        set pos $pos_new
        if { $mark == -1 } {
            recolor_tab_pos $pos_old
            recolor_tab_pos $pos
        } else {
            recolor_tab_full
        }
    }
}

# move down a score
proc down_score {} {
    global curr_namespace
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::col_max

    set pos_old $pos
    set pos_new [ expr $pos + $col_max ]
    if { $pos_new <= $data_end } {
        set pos $pos_new
    } else {
        set pos_new [ expr ( $row + 1 ) * $col_max ]
        if { $pos_new <= $data_end } {
            set pos $data_end
        }
    }
    if { $pos != $pos_old } {
        if { $mark == -1 } {
            recolor_tab_pos $pos_old
            recolor_tab_pos $pos
        } else {
            recolor_tab_full
        }
    }
}

# move to start of score
proc home {} {
    global curr_namespace
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos

    set pos_old $pos
    set pos 0
    if { $mark == -1 } {
        recolor_tab_pos $pos_old
        recolor_tab_pos $pos
    } else {
        recolor_tab_full
    }
}

# move to end of score
proc end {} {
    global curr_namespace
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos

    set pos_old $pos
    set pos $data_end
    if { $mark == -1 } {
        recolor_tab_pos $pos_old
        recolor_tab_pos $pos
    } else {
        recolor_tab_full
    }
}

# absolute position set via mouse click
proc absolute_pos {pointer_x pointer_y need_fullredraw} {
    global curr_namespace
    global initial_col
    global col_width
    variable ${curr_namespace}::col_max
    variable ${curr_namespace}::row_sep_lines
    variable ${curr_namespace}::score_width
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::row_height
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tabwin
    
    set char_x [ lindex [ split [ $tabwin.tablature index @$pointer_x,$pointer_y ] . ]  1 ]
    set char_y [ lindex [ split [ $tabwin.tablature index @$pointer_x,$pointer_y ] . ]  0 ]

    set row_new [ expr int( ( $char_y - 1 - $row_sep_lines ) / $row_height ) ]
    set string_new [ expr ( $char_y -1 - $row_sep_lines ) % $row_height ]
    set col_new [ expr int ( ( $char_x - $initial_col ) / $col_width ) ]
    set pos_new [ expr $row_new * $col_max + $col_new ]
    if { ($col_new<$col_max)&&($col_new>=0)&&($string_new>=0)&&($string_new<$num_strings)&&($pos_new>=0)&&($pos_new<=$data_end) } {
        set pos_old $pos
        set pos $pos_new
        set string $string_new
        if { $mark == -1 } {
            recolor_tab_pos $pos_old
            recolor_tab_pos $pos
        } else {
            recolor_tab_full
        }
    }
}

# **insert/delete related functions

# delete note cursor is over, but leave the rest of this position intact
proc del_note {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::col
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tab_data

    if { $mark != -1 } {
        history_add $messages(history:delete)
        cut_tab -redraw
    } elseif { [ lindex [ lindex $tab_data $pos ] $string ] > -1 } {
        history_add $messages(history:del_note)
        set tab_data [ lreplace $tab_data $pos $pos [ lreplace [ lindex $tab_data $pos ] $string $string -1 ] ]
        redraw_pos $pos
    }
}

# delete position behind cursor
proc backspace {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos

    history_add $messages(history:delete)
    if { $mark != -1 } {
        cut_tab -redraw
    } else {
        # don't do backspace functionality if already at beginning of tab
        if { $pos > 0 } {
            back
            del_pos
        }
    }
}


# delete whole position
proc del_pos {args} {
    global blank_tab
    global curr_namespace
    global messages
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    if { [lsearch -exact $args -history] >= 0 } {
        history_add $messages(history:delete)
    }
    if { $mark != -1 } {
        cut_tab -redraw
    } elseif { $pos > 0 } { 
        set tab_data [ lreplace $tab_data $pos $pos ]
	incr data_end -1
        if { $pos > $data_end } {
            incr pos -1
        }
	redraw_toend $pos 
    } elseif { $tab_data != $blank_tab($num_strings) } {
        set tab_data [ lreplace $tab_data $pos $pos ]
        if { $data_end == 0 } {
            set tab_data [ concat $tab_data $blank_tab($num_strings) ]
	    redraw_pos $pos
	} else {
	    redraw_toend $pos
        }
    }
}

# add blank spaces to the end of the current line
proc force_newline {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::col
    variable ${curr_namespace}::col_max

    set pos_old $pos
    history_add $messages(history:newline)

    for { set i $col } { $i < $col_max } { incr i } {
        add_blank -advance
    }

    redraw_toend $pos_old
}

# insert new position
proc add_blank {args} {
    global blank_tab
    global curr_namespace
    global messages
    variable ${curr_namespace}::create_newline
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::insert_mode
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::col_max

    set advance 0
    if { [lsearch -exact $args -advance] >= 0 } {
        set advance 1
    }
    if { [lsearch -exact $args -history] >= 0 } {
        history_add $messages(history:space)
    }
    set exception 0
    if { $mark != -1 } {
        cut_tab
        if { $insert_mode == $messages(string:chord) } { 
            set exception 1 
        }
    }
    if { ( $insert_mode == $messages(string:chord)) && ( $exception == 0 ) && ( $advance == 1 ) } {
        set before [ lrange $tab_data 0 $pos ]
        if { $pos == $data_end } {
            set after ""
        } else {
            set after [ lrange $tab_data [ expr $pos + 1 ] end ]
        }
        set tab_data [ concat $before $blank_tab($num_strings) $after ]
        incr pos 
    } else {
        set before [ lrange $tab_data 0 [ expr $pos - 1 ]]
        set after [ lrange $tab_data $pos end ]
        set tab_data [ concat $before $blank_tab($num_strings) $after ]
    }

    incr data_end
    if { [ expr $data_end  % $col_max ] == 0 } {
        set create_newline 1
    }
    if { ( $advance == 1 ) && ( $insert_mode == $messages(string:lead) ) } {
        incr pos
    }

    if { [lsearch -exact $args -redraw] >= 0 } {
        redraw_toend [ expr $pos - 1 ]
    }
}

# remove mark
proc clear_mark {} {
    global curr_namespace
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos

    if { $mark != -1 } {
        set mark -1
        recolor_tab_full
        foreach item {cut copy paste} {
            ghost_menu disabled menu:$item
        }
    }
}

# place mark
proc set_mark {} {
    global curr_namespace
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos

    if { $mark == -1 } {
        set mark $pos
        redraw_pos $pos
        foreach item {cut copy paste} {
            ghost_menu normal menu:$item
        }
    } 
}

# toggle mark on/off
proc toggle_mark {} {
    global curr_namespace
    variable ${curr_namespace}::mark

    if { $mark == -1 } {
        set_mark 
    } else {
        clear_mark
    }
}

# select all of tablature
proc select_all {} {
    global curr_namespace
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::data_end

    set mark 0
    set pos_old $pos
    set pos $data_end
    foreach item {cut copy paste} {
        ghost_menu normal menu:$item
    }
    recolor_tab_full
}

# copy tab into paste buffer
proc copy_tab {} {
    global curr_namespace
    global pastebuf
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    if { $mark != -1 } {
        update_clipboard
        set pastebuf [ lrange $tab_data [ calc_min $pos $mark ] [calc_max $pos $mark ] ]
        clear_mark
    }
}

# cut tab from screen into paste buffer
proc cut_tab {args} {
    global blank_tab
    global curr_namespace
    global pastebuf
    global messages
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    if { $mark != -1 } {
        if { [lsearch -exact $args -history] >= 0 } {
            history_add $messages(history:cut)
            update_clipboard
            set pastebuf [ lrange $tab_data [ calc_min $pos $mark ] [calc_max $pos $mark ] ]
        }
        set tab_data [ lreplace $tab_data [ calc_min $pos $mark ] [ calc_max $pos $mark ] ]
        set pos [ calc_min $pos $mark ]
        set data_end [expr [llength $tab_data] -1 ]
        if { $data_end < 0 } {
            set tab_data [ concat $tab_data $blank_tab($num_strings) ]
            set data_end 0
        }
        if { $pos > $data_end } {
            set pos $data_end
        } 
        set mark -1
        foreach item {cut copy paste} {
            ghost_menu disabled menu:$item
        }
        if { [lsearch -exact $args -redraw] >= 0 } {
            redraw_toend $pos
        }
    }
}

# cut with addition to history buffer, but not to paste buffer
proc clear_tab {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::mark

    if { $mark != -1 } {
        history_add $messages(history:clear)
        cut_tab -redraw
    }
}

# paste from paste buffer
proc paste_tab {} {
    global curr_namespace
    global pastebuf
    global messages
    global tcl_platform
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    # on Unix, grab the paste data from primary eTktab window
    # even if it's in another eTktab process
    catch {set x_selection [selection get -selection ETKTAB]}
    if { ($tcl_platform(platform) == "unix") && ([info exists x_selection]) } {
        set pastebuf $x_selection
    }
    # do nothing if paste buffer is empty, or paste tab is mismatch 6/5/4 string
    if { $pastebuf == "" } {
        return
    }
    if { [ llength [ lindex $pastebuf 0 ] ] != $num_strings } {
        return
    }

    history_add $messages(history:paste)
    if { $mark != -1 } { 
        cut_tab
    }
    set before [ lrange $tab_data 0 [ expr $pos - 1 ]]
    set after [ lrange $tab_data $pos end ]
    set tab_data [ concat $before $pastebuf $after ]
    redraw_full
}

#insert note requested from keyboard bindings
proc ins_note {askstring askfret} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::basefret
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::fret
    variable ${curr_namespace}::insert_mode
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::row
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tab_data
    variable ${curr_namespace}::col_max
	
    
    history_add $messages(history:note)
    if { ( $mark != -1 ) || ( $insert_mode == $messages(string:lead) ) } {
        add_blank
    } 

    # user asked for 'open' string, or number above basefret?
    if { $askfret == "o" } {
        set fret 0
    } else {
        set fret [expr $basefret + $askfret ]
    }

    set string $askstring
    set fret_old [ lindex [ lindex $tab_data $pos ] $string ]
    if { $fret_old == -2 } {
        replace_pos {-1}
    }
    
    set fret [ expr ( 100 * int ( abs ( $fret_old ) / 100 ) ) + $fret ]
    set tab_data [ lreplace $tab_data $pos $pos [ lreplace [ lindex $tab_data $pos ] $string $string $fret ] ]

    if { $insert_mode == $messages(string:lead) } {
        if { $pos == $data_end } {
            add_blank -advance
        } else {
            forward
        }
        redraw_toend [ expr $pos - 1 ]
    } else {
        redraw_pos $pos
    }
}

# add or remove embellishments (hammer-on, pull-off, etc.)
proc modifier {modnum} {
    global curr_namespace
    global embellish
    global messages
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::string
    variable ${curr_namespace}::tab_data

    set fret_old [ lindex [ lindex $tab_data $pos ] $string ]
    if { $fret_old > -1 } {
        history_add $messages(history:expression)
        set newfret  [ expr ( $fret_old % 100 ) + ( $modnum * 100 ) ]
        set tab_data [ lreplace $tab_data $pos $pos [ lreplace [ lindex $tab_data $pos ] $string $string $newfret ] ]

         if { $mark != -1 } {
             clear_mark
         }
         redraw_pos $pos
    }
}

# add or remove repeat marks from measure bar
proc toggle_repeat {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    set fret_old [ lindex [ lindex $tab_data $pos ] 1 ]
    if { $fret_old > -2 } {
        return
    }

    history_add $messages(history:repeat)
    set bar_values {-2 -10 -6 -14}
    set newfret [ lindex $bar_values [ expr ([ lsearch -exact $bar_values [string trim $fret_old] ] + 1) % 4 ] ]

    set second [ expr $num_strings - 2 ]
    set tab_data [ lreplace $tab_data $pos $pos [ lreplace [ lreplace [ lindex $tab_data $pos ] 1 1 $newfret ] $second $second $newfret ] ]

     if { $mark != -1 } {
         clear_mark
     }
     redraw_pos $pos
}

# replace contents of current position with a bar
proc bar {} {
    global curr_namespace
    global messages
    variable ${curr_namespace}::data_end
    variable ${curr_namespace}::fret
    variable ${curr_namespace}::insert_mode
    variable ${curr_namespace}::mark
    variable ${curr_namespace}::pos
    variable ${curr_namespace}::tab_data

    set fret_old [ lindex [ lindex $tab_data $pos ] 0 ]
    # don't need <= other neg numbers for repeat symbols only on two strings
    # (not on string 0)
    if { $fret_old == -2 } {
        return
    }

    history_add $messages(history:bar)
    if { ( $mark != -1 ) || ( $insert_mode == $messages(string:lead) ) } {
        add_blank
    } 

    # if the value is -2 it means there's the bar
    replace_pos {-2}

    if { $insert_mode == $messages(string:lead) } {
        if { $pos == $data_end } {
            add_blank -advance
        } else {
            forward
        }
        redraw_toend [ expr $pos - 1 ]
    } else {
        redraw_pos $pos
    }
}




#######################################
### BUILD THE GUI
###

proc build_gui {new_namespace} {
    global curr_namespace
    global ext
    global maxbasefret
    global prefs
    global tcl_platform
    global version
    global embellish
    global messages
    global valid_numstrings
    variable ${new_namespace}::tabwin
    variable ${new_namespace}::winnum
    variable ${new_namespace}::score_width

    toplevel $tabwin -class Textwin
    bind $tabwin <FocusIn> "set ::curr_namespace $new_namespace"
        frame $tabwin.tab_frame 
            scrollbar $tabwin.scrollx -orient horizontal -command "$tabwin.tablature xview" 
            scrollbar $tabwin.scrolly -command "$tabwin.tablature yview" 
            text $tabwin.tablature -xscrollcommand "$tabwin.scrollx set" -yscrollcommand "$tabwin.scrolly set" -width $prefs(window_width) -height $prefs(window_height) -state disabled -exportselection false -selectborderwidth 0 
    
        frame $tabwin.msg_frame 
            label $tabwin.msg_frame.right_chord_lead_legend 
            my_menubutton $tabwin.msg_frame.right_chord_lead -textvariable ${new_namespace}::insert_mode "
                {radiobutton -variable ${new_namespace}::insert_mode -label $messages(string:chord)}
                {radiobutton -variable ${new_namespace}::insert_mode -label $messages(string:lead)}
            "
    
            label $tabwin.msg_frame.right_basefret_legend
            for { set i 0 } { $i <= $maxbasefret } { incr i } {
                lappend basefret_entries "radiobutton -label $i -variable ${new_namespace}::basefret" 
            }
            my_menubutton $tabwin.msg_frame.right_basefret -textvariable ${new_namespace}::basefret $basefret_entries
            $tabwin.msg_frame.right_basefret.menu entryconfigure 12 -columnbreak 1
    
            button $tabwin.msg_frame.right_tuning -command "tuning_win current"
    
            foreach ns $valid_numstrings {
                lappend newtab_entries "command {new_tab -strings $ns}"
                lappend stringpref_entries "radiobutton -variable prefs(num_strings) -value $ns -command {pref_numstrings $ns}"
                lappend tunpref_entries "command {tuning_win tuning_$ns}"
            }
            my_menubutton $tabwin.msg_frame.left_file "
                {cascade new {$newtab_entries}}
                {command open_dialog}
                {command -state disabled save_tab}
                {command {save_tab -as}}
                {command export_tab}
                {command close_tab}
                {command quit_safe}
            "
    
    
        my_menubutton $tabwin.msg_frame.left_edit "
            {command -state disabled history_undo}
            {command -state disabled history_redo}
            separator
            {command -state disabled {cut_tab -history -redraw}}
            {command -state disabled copy_tab}
            {command -state disabled clear_tab}
            {command paste_tab}
            {command select_all}
            separator
            {command {pref_format current}}
            {cascade option {
                {command pref_keybindings}
                {command pref_language}
                {command pref_fonts}
                {command pref_colors}
                separator
                {cascade numstrings {$stringpref_entries}}
                {cascade tuning {$tunpref_entries}}
                {command {pref_format default}}
                separator
                {command pref_revert}
            }}
        "
    
        button $tabwin.msg_frame.left_help -command help
    
    grid rowconfig $tabwin.tab_frame 0 -weight 1 -minsize 0
    grid columnconfig $tabwin.tab_frame 0 -weight 1 -minsize 0
    grid $tabwin.tablature -in $tabwin.tab_frame -row 0 -column 0 -sticky news
    grid $tabwin.scrolly -in $tabwin.tab_frame -row 0 -column 1 -sticky news
    grid $tabwin.scrollx -in $tabwin.tab_frame -row 1 -column 0 -sticky news
    
    pack $tabwin.msg_frame.right_tuning $tabwin.msg_frame.right_chord_lead $tabwin.msg_frame.right_chord_lead_legend $tabwin.msg_frame.right_basefret $tabwin.msg_frame.right_basefret_legend -side right -anchor e -ipady 2
    pack $tabwin.msg_frame.left_file $tabwin.msg_frame.left_edit $tabwin.msg_frame.left_help -side left -anchor w -ipady 2
    
    pack $tabwin.msg_frame -side top -fill both
    pack $tabwin.tab_frame -fill both -expand true
    
    wm protocol $tabwin WM_DELETE_WINDOW "set ::curr_namespace $new_namespace ; close_tab"
    wm title $tabwin "eTktab$version - $messages(string:untitled)$winnum"
    #ms-windows doesn't seem to want to focus on our new toplevel windows
    if {$tcl_platform(platform)=="windows"} {
        update idletasks
        focus -force $tabwin
    }

    set curr_namespace $new_namespace

    history_clear
    label_gui
    color_gui
    keybind_all
}

# put strings in each widget (buttons, menus, etc.)
proc label_gui {} {
    global curr_namespace
    global gui_text
    global gui_label
    global messages
    variable ${curr_namespace}::tabwin
    variable ${curr_namespace}::undo
    variable ${curr_namespace}::redo

    # labels and buttons
    foreach text_key [ array names gui_text ] {
        foreach widget $gui_text($text_key) {
            ${tabwin}.$widget configure -text $messages($text_key)
        }
    }

    # prepare for undo and redo menu entries
    set undo_menu $undo(last_action)
    set redo_menu $redo(last_action)

    # most menu entries
    foreach text_key [ array names gui_label ] {
        foreach widget $gui_label($text_key) {
            ${tabwin}.[lindex $widget 0] entryconfigure [lindex $widget 1] -label [ subst -nocommands -nobackslashes $messages($text_key) ]
        }
    }
}

# assign fonts and colors to tab window
proc color_gui {} {
    global curr_namespace
    global prefs
    global tcl_platform
    variable ${curr_namespace}::tabwin


    #all other widgets... 
    foreach widget [info commands $tabwin.* ] {
        switch -glob -- $widget {
            {*.tablature} {
                $tabwin.tablature configure -background $prefs(color_tab_bg_default) -foreground $prefs(color_tab_fg_default) -font $prefs(font_tab) -selectbackground $prefs(color_tab_bg_default) -selectforeground $prefs(color_tab_fg_default) 
                $tabwin.tablature tag configure marked -background $prefs(color_tab_bg_sel)
                $tabwin.tablature tag configure currpos -foreground $prefs(color_tab_fg_currpos)
                $tabwin.tablature tag configure currstring -foreground $prefs(color_tab_fg_currstring)
            }
            {*.msg_frame.left*} {
                $widget configure -background $prefs(color_menu_bg) -foreground $prefs(color_menu_fg_left) 
                catch { $widget configure -highlightbackground $prefs(color_menu_bg) }
            }
            {*.msg_frame.right*} {
                #certain widgets can't have diff colors/fonts macos
                $widget configure -background $prefs(color_menu_bg) -foreground $prefs(color_menu_fg_right) 
                catch { $widget configure -highlightbackground $prefs(color_menu_bg) }
            }
            {*.scrollx}
                -
            {*.scrolly}
                {$widget configure -background $prefs(color_menu_bg) -highlightbackground $prefs(color_menu_bg) -activebackground $prefs(color_menu_bg)}
            default
                {$widget configure -background $prefs(color_menu_bg)}
        }
       #certain widgets can't have diff fonts macos
       if {($tcl_platform(platform)!="macintosh")&&([string match {*.msg_frame.*} $widget])} {
           $widget configure -font $prefs(font_statusbar)
       }
    }
}

# do non-stringnum-specific keybindings, then call keybind-secific proc
proc keybind_all {} {
    global curr_namespace
    global keybindings
    global keybind_funcs
    global keynames
    global tcl_platform
    global embellish
    global gui_accel
    global prefs
    global valid_numstrings
    variable ${curr_namespace}::tabwin

    # bulk of the keybindings
    foreach func_name [ array names keybind_funcs ] {
        foreach keypress $keybindings($func_name) {
            bind $tabwin "<${keypress}>" $keybind_funcs($func_name)
        }
    }
    # modifiers
    foreach modnum [ array names embellish ] {
        foreach keypress $keybindings(mod:$modnum) {
            bind $tabwin "<${keypress}>" "modifier $modnum"
        }
    }
    # Put mousebindings in place
    bind $tabwin.tablature <ButtonPress-1> "clear_mark ; absolute_pos %x %y 0"
    bind $tabwin.tablature <Button1-Motion> "set_mark ; pointer drag"
    bind $tabwin.tablature <ButtonRelease-1> "absolute_pos %x %y 1 ; pointer norm"
    if {$tcl_platform(platform)=="unix"} {
        bind $tabwin.tablature <ButtonPress-2> "clear_mark ; absolute_pos %x %y 0"
        bind $tabwin.tablature <ButtonRelease-2> "paste_tab"
        bind $tabwin.tablature <ButtonRelease-3> "absolute_pos %x %y 0"
    } else {
        bind $tabwin.tablature <ButtonPress-3> "clear_mark ; absolute_pos %x %y 0"
        bind $tabwin.tablature <ButtonRelease-3> "paste_tab"
        bind $tabwin.tablature <Shift-ButtonPress-1> "set bupkes 0"
        bind $tabwin.tablature <Shift-Button1-Motion> "set bupkes 0"
        bind $tabwin.tablature <Shift-ButtonRelease-1> "absolute_pos %x %y 1 ; pointer norm"
    }

    # load keybindings that are diff for 4/5/6-string modes
    keybind_numstrings

    # put text version of keystrokes into menu text
    foreach widget [ array names gui_accel ] {
        ${tabwin}.[lindex $gui_accel($widget) 0] entryconfigure [lindex $gui_accel($widget) 1] -accelerator [lindex $keynames($widget) 0]
    }
    # add accel for 'new' to our preferred numstrings for new tab
    foreach ns $valid_numstrings {
        if { $ns == $prefs(num_strings) } {
            $tabwin.msg_frame.left_file.menu.new entryconfigure "${ns}*" -accelerator [lindex $keynames(new) 0]
        } else {
            $tabwin.msg_frame.left_file.menu.new entryconfigure "${ns}*" -accelerator ""
        }
    }
}

### KEYBINDINGS FOR EMACS TAB MODE EMULATION
proc keybind_numstrings {} {
    global curr_namespace
    global keybindings
    variable ${curr_namespace}::num_strings
    variable ${curr_namespace}::tabwin

    set string_set "E A D G B e"
    set string_num $num_strings
    foreach bind_string $string_set {
       incr string_num -1
       foreach bind_fret "o 0 1 2 3" {
           foreach keypress $keybindings(note:${bind_string}.${bind_fret}) {
               # blank out some keybindings in 4/5-string mode
               if { $string_num < 0} {
                   bind $tabwin "<${keypress}>" {}
               } else {
                   bind $tabwin "<${keypress}>" "ins_note $string_num $bind_fret"
               }
           }
       }
    }
}

    
#######################################
### MAIN:
### READ COMMAND LINE AND PREFS; INITIALIZE CONTENTS OF MAIN WINDOW 
### 

# set up tk defaults for widgets
foreach i [ array names tabwin_options ] {
    option add $i $tabwin_options($i) 50
}
# designate handlers for clipboard access from X-Windows
selection handle -selection "CLIPBOARD" . clipboard_dump
selection handle -selection "PRIMARY" . clipboard_dump
selection handle -selection "ETKTAB" . pastebuf_dump
# undo standard Tk bindings that conflict with program bindings
bind all <Alt-KeyPress> {}
bind all <Key-Tab> {}
# load in preferences
load_prefs

# OS Specific stuff
switch $tcl_platform(platform) {
    {macintosh} {
        # tkOpenDocument doesn't work correctly on mac no windows are mapped
        # so we make the window appear offscreen, instead
        wm geometry . 1x1-25000-25000
        . configure -menu .mac_menus
        menu .mac_menus 
            .mac_menus add cascade -menu .mac_menus.apple
                menu .mac_menus.apple
                .mac_menus.apple add command -label $messages(title:about) -command about
            .mac_menus add cascade -menu .mac_menus.help
                menu .mac_menus.help
                .mac_menus.help add command -label [subst -nocommands -nobackslashes $messages(title:help)] -command help
        # hide the tcl/tk console window, but add shortcut so programmer
        # can use it for debugging ;-)
        console hide
        bind all <Control-Option-ButtonPress> {console show}
    }
    {windows} {
        # figure out if there's already a running eTktab
        if { [dde services TclEval eTktab] == "" } {
            # register as a dde server
            dde servername eTktab
        } else {
            # already a copy running... tell it to open a new window and quit
            dde execute TclEval eTktab {new_tab}
            exit
        }
        wm withdraw .
        . configure -menu .win_menus
        menu .win_menus 
            .win_menus add cascade -menu .win_menus.system
                menu .win_menus.system
                .win_menus.system add command -label $messages(title:about) -command about
        # add shortcut to pull up console window so programmer
        # can use it for debugging ;-)
        bind all <Control-Alt-ButtonPress-1> {console show}
    }
    default {
        #Unix
        wm withdraw .
        # give usage statement.  -b no longer allowed; replaced by preferences
        if { [ string index [lindex $argv 0] 0 ] == "-" } {
            puts [subst -nocommands -nobackslashes $messages(string:usage)]
            __exit_now
        }
    }
}

set req_file ""
set used_dragdrop 0
# In windows installation program, we're setting the registry to send us
# __dde__ on the command line when the program isn't running, but the user
# double-clicked a document
if { [ lindex $argv 0 ] == "__dde__" } {
    set used_dragdrop 1
} elseif { $argv != "" } {
    # initial filename on command line?
    foreach i  [list "${cwd}/" "" ] {
        if { $used_dragdrop } {
            break
        }
        foreach j [concat {{}} $open_types($prefs(num_strings))] {
            if {$j != ""} {
                set j [ lindex $j 1]
                if { ! ([string match {.et*} $j]) } {
                    continue
                }
            }
            # if filename is valid, open it
            if { [ file exists ${i}[lindex $argv 0]${j} ] } {
                set cwd [ file dirname $req_file ]
                set used_dragdrop 1
                new_tab -file ${i}[lindex $argv 0]${j} 
                break
            }
        }
    }
}

# look for incoming mac drag/drop events
update

# on mac/win the following will check if we started via drag & drop
# If we did, we don't need to create an initial window, because it will
# be created for us via the tkOpenDocument proc
if { $used_dragdrop == 0 } {
    # Initialize empty window
    new_tab
}

