#!/bin/sh
#-*- mode: Tcl;time-stamp-start:"TimeStamp[ 	]+\\\\?[\"<]+";-*-
# the next line restarts using wish \
exec tclsh $0 $@
set TimeStamp "2008-12-13 23:17:53 poser"
#
# Copyright (C) 2005-2008 William J. Poser (billposer@alum.mit.edu)
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 3 of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is contained in the
# procedure "License" in this file.
# If it is not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# or go to the web page:  http://www.gnu.org/licenses/gpl.txt.

set Version "3.3"
set SegmenterVersion "0.85"
set DebugP 0
set SegmenterP 0
set IwidigetsAvailableP 0
set InteractiveP 0
set SynchJournalP 1;
set BatchModeP  0;   
set JournalHomeP 0;
set ReadScriptFileP 0
set ReadSegmentFileP 0
set ReadInitFileP 1;
set ScriptFileName "";
set SegmentList [list]
package require math::statistics
package require msgcat
proc _ {s} {return [::msgcat::mc $s]};	# Define shorthand for gettext

proc dmsg {msg} {
    if {$::DebugP} {
	puts $msg;
    }
}

proc putstd {s} {
    if {$::System eq "Unix"} {
	puts $s
    }
}

proc puterr {s} {
    if {$::System eq "Unix"} {
	puts stderr $s
    }
}

proc Usage {} {
    putstd {Usage: SndBite [options] (<audio file>)};
    putstd [_ "    -b              run in batch mode"];
    putstd [_ "    -d              set debug flag"];
    putstd [_ "    -f <file name>  execute commands from file <file name>"]
    putstd [_ "    -h              help"];
    putstd [_ "    -i              do not read init file"];
    putstd [_ "    -v              version"];
}

if {[catch {package require Iwidgets} ] != 0} {
    set IwidgetsAvailableP 0
} else {
    set IwidgetsAvailableP 1
}

proc argshift {k} {
    set ::argv [lrange $::argv $k end];
    dmsg "argcnt = [llength $::argv]"
}

#Handle command line arguments
while {[string match -* [lindex $argv 0]]} {
    switch -regexp -- [lindex $argv 0] {
	--?b.* {
	    set BatchModeP 1;
	    argshift 1;
	}
	--?d.* {
	    set DebugP 1;
	    argshift 1;
	}
	--?f.* {
	    set ReadScriptFileP 1;
	    set ScriptFileName [lindex $argv 1];
	    argshift 2
	}
	--?h.* {
	    Usage;
	    exit 0;
	}
	--?i.* {
	    set ReadInitFileP 0;
	    argshift 1;
	}
	--?v.* {
	    puts "SndBite $Version";
	    exit 0;
	}
	default {
	    puts [format [_ "Command line option %s not recognized."] [lindex $argv 0]];
	    Usage;
	    exit 0;
	}
    }
}

set PauseCommandName pause
package require Tk
package require snack

set InitFile     ".sbrc";
set JournalFile  "SndBite.log";
set NonBinPath [file join /usr share SndBite];


#If this is 0, only characters with glyphs in Code2000, Everson Mono, and SIL Doulos IPA
#are included. If this is 1, additional characters are included which, if no glyphs are
#available, will make the chart look crummy. 
set UseNoGlyphs 0

#Portability
#Figure out what system we are running on
if {[string equal $tcl_platform(platform) windows]} {
    set System MSWindows;
    dmsg "Running under MS Windows";
} elseif {[string equal $tcl_platform(platform) unix]} {
    if {[string equal $tcl_platform(os) Darwin]} {
	set System MacOSX;
	dmsg "Running under Mac OS X";
    } else {
	set System Unix;
	dmsg "Running under Unix";
    }
}

proc SetupEvents {sys} {
    switch $sys {
	Unix {
	    event add <<B3>> <ButtonPress-3>
	    event add <<B3Release>> <ButtonRelease-3>
	}
	MacOSX {
	    event add <<B3>> <Control-ButtonPress-1>
	    event add <<B3Release>> <Control-ButtonRelease-1>
	}
	MSWindows {
	    event add <<B3>> <ButtonPress-3>
	    event add <<B3Release>> <ButtonRelease-3>
	}
    }
}

proc DetermineGraphicsSystem {} {
    global AquaP
    global System

    if {[string match X11*  [winfo server .]]} {
	set AquaP 0
	set ::Pars(WindowSystem) X11
    } else {
	if {[string match $System MSWindows]} {
	    set AquaP 0;
	    set ::Pars(WindowSystem) MSWindows;
	}
	if {[string match $System MacOSX]} {
	    set AquaP 1
	    set ::Pars(WindowSystem) Aqua
	}
    }
}

proc CheckTkEightFivePlusOnX11 {} {
    set VLevelList [split [info patchlevel] "."]
    set Major [lindex $VLevelList 0]
    set Minor [lindex $VLevelList 1]
    if {$::Pars(WindowSystem) eq "X11"} {
	if {$Major > 8} {
	    return 1
	} else {
	    if {($Major == 8) && ($Minor >= 5)} {
		return 1
	    }
	} 
    }
    return 0
}


if {[info exists ::env(TMP)]} {
    set TempDir $::env(TMP);
} elseif {[info exists ::env(TEMP)]} {
    set TempDir $::env(TEMP);
} else {
    if { $tcl_platform(platform) == "windows"} {
	set TempDir "C:\tmp";
    } else {
	set TempDir "/tmp";
    }
}

if {[string match $System MSWindows]} {
    set NonBinPath [file dirname [info script]];
    set ::env(CYGWIN) "";
    set InitFile "SndBiteInit";
    set JournalFile "SndBiteLog";
}

set ExpansionFactor 1.0;#Ratio of actual width of main windows to initial width.
set PrompterList [list];# entries consist of uid, headword, begin and end in samples
set PrompterListHeight 5
set SegmentListHeight 5

set AmplitudeModeP     0;
set CurrentPrompterIndex -1
set CurrentSegmentIndex -1
set DrawCutMarksP      1;
set DisplayCloseupsP   1;
set DisplayDeltaBarP   0
if {$SegmenterP} {
    set DisplaySegmentBarP 1
    set UsePauseP 0
} else {
    set DisplaySegmentBarP 0
}
set DisplayHistoryPopupP 0
set DisplayPlayBarP    1
set DisplaySilenceBarP 1
set DisplayWriteBarP 1
set DisplayZeroCrossingButtonsP 1;
set AutoScaleSoundPDefault    1;
set WhichFontToSet MainFont  
set OutFileNameList [list]
set PauseAvailableP 0;
set UsePauseP 0;
set WriteCnt 0
set WriteMargin 0.0;			# Amount written preceding and following actual window
					# For use in batch mode.
set MainWindowWidth 680
set MainWindowHeight 80;
set InfoHeight 250
set InfoWidth  250
set CloseupHeight 60;
set CloseupWidth [expr ($MainWindowWidth - 10) /2]
set CutMargin [expr $CloseupWidth / 2];
set WavebarHeight 45;
set NeighborhoodWindowRatio 2;
set NeighborhoodChangeThresholdFraction 0.15;
set PanelChartPerRow 8
set SilenceListHeight 5;

set OV    .ov
set C     .c
set CLUPL .clup.l.canvas
set CLUPR .clup.r.canvas
set MSG     .msg;
set SILI  .info.sili 

#set ColorSpecs(BalloonHelp,Background) \#FFD8B1
set ColorSpecs(BalloonHelp,Background) \#FA4
set ColorSpecs(BalloonHelp,Foreground) black
set ColorSpecs(CharacterEntry,Background)		"\#FFFFFF";
set ColorSpecs(CharacterEntry,Foreground)		"\#000000";
set ColorSpecs(Closeup,Background)		\#FFD8B1
set ColorSpecs(CloseupCursor,Background)              "\#00FF99";
set ColorSpecs(CloseupCursor,Foreground)              "\#FF0000";
set ColorSpecs(CloseupRegionMarker,Foreground)       green
set ColorSpecs(CloseupRegionWidth,Background)              "\#33DDBB";
set ColorSpecs(CloseupRegionWidth,Foreground)              "\#FF0000";
set ColorSpecs(CloseupWaveform,Foreground)           blue
set ColorSpecs(ConfirmationDialogButton,Background)	 		"\#DFC0C0";
set ColorSpecs(ConfirmationDialogMain,Background)	 		"\#c36176";
set ColorSpecs(ConfirmationDialogMain,Foreground)	"\#DFC0C0";
set ColorSpecs(ConfirmationDialogText,Background)	 		"\#c36176";
set ColorSpecs(Control,Background)	        \#BEBAD5
set ColorSpecs(CutMark,Foreground)			"\#FF0066";
set ColorSpecs(Default,Background) \#FFD8B1
set ColorSpecs(DefaultActive,Background)	"\#d4e4fe";
set ColorSpecs(DeltaButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(DeltaButton,ActiveForeground) 	blue
set ColorSpecs(DeltaButton,Background) 		\#D8A7FF
set ColorSpecs(DeltaButton,Foreground) 		black
set ColorSpecs(DeltaButton,Highlight)	 	blue
set ColorSpecs(DeltaButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(HistoryList,AltBackground)	"\#C1FFC1"
set ColorSpecs(HistoryList,AltForeground)	blue
set ColorSpecs(HistoryList,Background)		"\#FFCDB6"
set ColorSpecs(HistoryList,Foreground)		black
set ColorSpecs(IPAHeadings,Background)		"\#09ffb2";
set ColorSpecs(InfoPopup,Background)	 	\#58C480
set ColorSpecs(InfoPopup,Foreground)	 	black
set ColorSpecs(LabelText,Foreground)		"\#d4e4fe";
set ColorSpecs(LazySusan,Background)	        \#BEBAD5
set ColorSpecs(LeftSilenceHighlight,Foreground)	\#FF7F6D
set ColorSpecs(MainFrame,Background)		coral
set ColorSpecs(Menu,ActiveBackground)		salmon
set ColorSpecs(Menubar,ActiveBackground)	"\#50E4A5";
set ColorSpecs(Menubar,Background)	 	"\#c36176";
set ColorSpecs(Menubar,Foreground)		"\#fee4a9";
set ColorSpecs(MessageRegion,Background) 	"\#e9c4dc";
set ColorSpecs(MessageRegion,Foreground) 	"\#000000";
set ColorSpecs(Neighborhood,Background)		\#FFD8B1;
set ColorSpecs(NeighborhoodCursor,Background)              "\#00FF99";
set ColorSpecs(NeighborhoodCursor,Foreground)              "\#FF0000";
set ColorSpecs(NeighborhoodWaveform,Foreground)      blue
set ColorSpecs(NeighborhoodWindowWaveform,Foreground)      red
set ColorSpecs(PanelCharacterChartButton,Background)		white
set ColorSpecs(PanelCharacterChartButton,Foreground)		black
set ColorSpecs(PanelCharacterChartEmpty,Background)		NavajoWhite
set ColorSpecs(PanelCharacterChartTitle,Background)		NavajoWhite
set ColorSpecs(PanelCharacterChartTitle,Foreground)		black
set ColorSpecs(PanelCloseupResolutionMain,Background)		\#E09896
set ColorSpecs(PanelCloseupResolutionMain,Foreground)		black
set ColorSpecs(PanelCloseupResolutionMain,Selected)		red
set ColorSpecs(PanelCloseupResolutionTitle,Background)	NavajoWhite
set ColorSpecs(PanelCloseupResolutionTitle,Foreground)	black
set ColorSpecs(PanelFileNameEntry,Background) white
set ColorSpecs(PanelFileNameEntry,Foreground) black
set ColorSpecs(PanelFileNameMain,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelFileNameMain,Background)		SkyBlue1
set ColorSpecs(PanelFileNameMain,Foreground)		black
set ColorSpecs(PanelFileNameMain,Highlight)	 	blue
set ColorSpecs(PanelFileNameMain,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelFileNameMain,Selected)		red
set ColorSpecs(PanelFileNameMain,Trough)		\#58C4FF
set ColorSpecs(PanelFileNameTitle,Background)	NavajoWhite
set ColorSpecs(PanelFileNameTitle,Foreground)	black
set ColorSpecs(PanelNeighborhoodRatioMain,Background)		DarkSeaGreen
set ColorSpecs(PanelNeighborhoodRatioMain,Foreground)		black
set ColorSpecs(PanelNeighborhoodRatioMain,Selected)		red
set ColorSpecs(PanelNeighborhoodRatioTitle,Background)	NavajoWhite
set ColorSpecs(PanelNeighborhoodRatioTitle,Foreground)	black
set ColorSpecs(PanelNotePadButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelNotePadButton,ActiveForeground) 	blue
set ColorSpecs(PanelNotePadButton,Background) 		\#58C480
set ColorSpecs(PanelNotePadButton,Foreground) 		black
set ColorSpecs(PanelNotePadButton,Highlight)	 	blue
set ColorSpecs(PanelNotePadButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelNotePadEntry,Background) white
set ColorSpecs(PanelNotePadEntry,DisabledBackground) gray
set ColorSpecs(PanelNotePadEntry,DisabledForeground) black
set ColorSpecs(PanelNotePadEntry,Foreground) black
set ColorSpecs(PanelNotePadMain,Background)		\#8844CC
set ColorSpecs(PanelNotePadMain,Foreground)		black
set ColorSpecs(PanelNotePadTitle,Background)	NavajoWhite
set ColorSpecs(PanelNotePadTitle,Foreground)	black
set ColorSpecs(PanelPauseParametersButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelPauseParametersButton,ActiveForeground) 	blue
set ColorSpecs(PanelPauseParametersButton,Background) 		\#58C480
set ColorSpecs(PanelPauseParametersButton,Foreground) 		black
set ColorSpecs(PanelPauseParametersButton,Highlight)	 	blue
set ColorSpecs(PanelPauseParametersButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelPauseParametersEntry,Background) white
set ColorSpecs(PanelPauseParametersEntry,DisabledBackground) gray
set ColorSpecs(PanelPauseParametersEntry,DisabledForeground) black
set ColorSpecs(PanelPauseParametersEntry,Foreground) black
set ColorSpecs(PanelPauseParametersMain,Background)		\#44CC88
set ColorSpecs(PanelPauseParametersMain,Foreground)		black
set ColorSpecs(PanelPauseParametersTitle,Background)	NavajoWhite
set ColorSpecs(PanelPauseParametersTitle,Foreground)	black

set ColorSpecs(PanelPrompterListEntry,Background) white
set ColorSpecs(PanelPrompterListEntry,DisabledBackground) gray
set ColorSpecs(PanelPrompterListEntry,DisabledForeground) black
set ColorSpecs(PanelPrompterListEntry,Foreground) black
set ColorSpecs(PanelPrompterListMain,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelPrompterListMain,Background)		chartreuse3
set ColorSpecs(PanelPrompterListMain,Foreground)		black
set ColorSpecs(PanelPrompterListMain,Highlight)	 	blue
set ColorSpecs(PanelPrompterListMain,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelPrompterListMain,Selected)		red
set ColorSpecs(PanelPrompterListMain,Trough)		\#58C4FF
set ColorSpecs(PanelPrompterListTitle,Background)	NavajoWhite
set ColorSpecs(PanelPrompterListTitle,Foreground)	black

set ColorSpecs(PanelSegmentListEntry,Background) white
set ColorSpecs(PanelSegmentListEntry,DisabledBackground) gray
set ColorSpecs(PanelSegmentListEntry,DisabledForeground) black
set ColorSpecs(PanelSegmentListEntry,Foreground) black
set ColorSpecs(PanelSegmentListMain,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelSegmentListMain,Background)		chartreuse3
set ColorSpecs(PanelSegmentListMain,Foreground)		black
set ColorSpecs(PanelSegmentListMain,Highlight)	 	blue
set ColorSpecs(PanelSegmentListMain,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelSegmentListMain,Selected)		red
set ColorSpecs(PanelSegmentListMain,Trough)		\#58C4FF
set ColorSpecs(PanelSegmentListTitle,Background)	NavajoWhite
set ColorSpecs(PanelSegmentListTitle,Foreground)	black

set ColorSpecs(PanelSilenceListEntry,Background) white
set ColorSpecs(PanelSilenceListEntry,DisabledBackground) gray
set ColorSpecs(PanelSilenceListEntry,DisabledForeground) black
set ColorSpecs(PanelSilenceListEntry,Foreground) black
set ColorSpecs(PanelSilenceListMain,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelSilenceListMain,Background)		chartreuse3
set ColorSpecs(PanelSilenceListMain,Foreground)		black
set ColorSpecs(PanelSilenceListMain,Highlight)	 	blue
set ColorSpecs(PanelSilenceListMain,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelSilenceListMain,Selected)		red
set ColorSpecs(PanelSilenceListMain,Trough)		\#58C4FF
set ColorSpecs(PanelSilenceListTitle,Background)	NavajoWhite
set ColorSpecs(PanelSilenceListTitle,Foreground)	black
set ColorSpecs(PanelSilencesEntry,Background) white
set ColorSpecs(PanelSilencesEntry,DisabledBackground) gray
set ColorSpecs(PanelSilencesEntry,DisabledForeground) black
set ColorSpecs(PanelSilencesEntry,Foreground) black
set ColorSpecs(PanelSilencesMain,Background)		salmon
set ColorSpecs(PanelSilencesMain,Foreground)		black
set ColorSpecs(PanelSilencesTitle,Background)	NavajoWhite
set ColorSpecs(PanelSilencesTitle,Foreground)	black
set ColorSpecs(PanelSoundFileMain,Background)		\#44CC88
set ColorSpecs(PanelSoundFileMain,Foreground)		black
set ColorSpecs(PanelSoundFileTitle,Background)		NavajoWhite
set ColorSpecs(PanelSoundFileTitle,Foreground)		black
set ColorSpecs(PanelWavebarMain,Foreground)			black
set ColorSpecs(PanelWavebarResolution,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelWavebarResolution,Background) 		\#3A993A
set ColorSpecs(PanelWavebarResolution,Foreground) 		black
set ColorSpecs(PanelWavebarResolution,Highlight)	 	blue
set ColorSpecs(PanelWavebarResolution,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelWavebarResolution,Trough)	 		\#58C4FF
set ColorSpecs(PanelWavebarResolutionTitle,Background) 		NavajoWhite
set ColorSpecs(PanelWavebarResolutionTitle,Foreground) 		black
set ColorSpecs(PanelWindowBoundariesButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(PanelWindowBoundariesButton,ActiveForeground) 	blue
set ColorSpecs(PanelWindowBoundariesButton,Background) 		\#58C480
set ColorSpecs(PanelWindowBoundariesButton,Foreground) 		black
set ColorSpecs(PanelWindowBoundariesButton,Highlight)	 	blue
set ColorSpecs(PanelWindowBoundariesButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(PanelWindowBoundariesEntry,Background) white
set ColorSpecs(PanelWindowBoundariesEntry,DisabledBackground) gray
set ColorSpecs(PanelWindowBoundariesEntry,DisabledForeground) black
set ColorSpecs(PanelWindowBoundariesEntry,Foreground) black
set ColorSpecs(PanelWindowBoundariesMain,Background)		\#FF9345
set ColorSpecs(PanelWindowBoundariesMain,Foreground)		black
set ColorSpecs(PanelWindowBoundariesMain,Selected)		bisque
set ColorSpecs(PanelWindowBoundariesTitle,Background)	NavajoWhite
set ColorSpecs(PanelWindowBoundariesTitle,Foreground)	black
set ColorSpecs(PanelWindowDeltaEntry,Background) white
set ColorSpecs(PanelWindowDeltaEntry,DisabledBackground) gray
set ColorSpecs(PanelWindowDeltaEntry,DisabledForeground) black
set ColorSpecs(PanelWindowDeltaEntry,Foreground) black
set ColorSpecs(PanelWindowDeltaMain,Background)		PaleGreen2
set ColorSpecs(PanelWindowDeltaMain,Foreground)		black
set ColorSpecs(PanelWindowDeltaMain,Selected)		red
set ColorSpecs(PanelWindowDeltaTitle,Background)	NavajoWhite
set ColorSpecs(PanelWindowDeltaTitle,Foreground)	black
set ColorSpecs(PlayButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(PlayButton,ActiveForeground) 	blue
set ColorSpecs(PlayButton,Background) 		\#58C4FF
set ColorSpecs(PlayButton,Foreground) 		black
set ColorSpecs(PlayButton,Highlight)	 	blue
set ColorSpecs(PlayButton,HighlightBackground) 	NavajoWhite

set ColorSpecs(PrompterHighlight,Foreground)	\#FF7F6D

set ColorSpecs(RightSilenceHighlight,Foreground)	\#CAA7D4
set ColorSpecs(SegmentButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(SegmentButton,ActiveForeground) 	blue
set ColorSpecs(SegmentButton,Background) 		\#D8A7FF
set ColorSpecs(SegmentButton,Foreground) 		black
set ColorSpecs(SegmentButton,Highlight)	 	blue
set ColorSpecs(SegmentButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(SegmentHighlight,Foreground)	\#FF7F6D
set ColorSpecs(SilenceButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(SilenceButton,ActiveForeground) 	blue
set ColorSpecs(SilenceButton,Background) 		\#58C480
set ColorSpecs(SilenceButton,Foreground) 		black
set ColorSpecs(SilenceButton,Highlight)	 	blue
set ColorSpecs(SilenceButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(UserTextEntry,Background)	"\#FFFFFF";
set ColorSpecs(UserTextEntry,Foreground)	black
set ColorSpecs(Volume,Trough)			salmon
set ColorSpecs(Wavebar,Background)		\#FFD8B1
set ColorSpecs(WavebarCursor,Background)              "\#00FF99";
set ColorSpecs(WavebarCursor,Foreground)              "\#FF0000";
set ColorSpecs(WavebarPlayMarker,Foreground)			\#44DFB0
set ColorSpecs(WavebarScrollbar,Scrollbar)	\#FFD8B1
set ColorSpecs(WavebarScrollbar,Trough)		\#00D0A0
set ColorSpecs(WavebarWaveform,Foreground)		"\#0000FF";
set ColorSpecs(WavebarWindowWaveform,Foreground)	red
set ColorSpecs(WindowCoordinates,Background)              "\#00CC99";
set ColorSpecs(WindowCoordinates,Foreground)              "\#000000";
set ColorSpecs(WriteButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(WriteButton,ActiveForeground) 	blue
set ColorSpecs(WriteButton,Background) 			\#FF9345
set ColorSpecs(WriteButton,Foreground) 		black
set ColorSpecs(WriteButton,Highlight)	 	blue
set ColorSpecs(WriteButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(WritePreviousButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(WritePreviousButton,ActiveForeground) 	blue
set ColorSpecs(WritePreviousButton,Background) 	\#FF8A97
set ColorSpecs(WritePreviousButton,Foreground) 		black
set ColorSpecs(WritePreviousButton,Highlight)	 	blue
set ColorSpecs(WritePreviousButton,HighlightBackground) 	NavajoWhite
set ColorSpecs(ZeroCrossingButton,ActiveBackground) 	NavajoWhite
set ColorSpecs(ZeroCrossingButton,ActiveForeground) 	blue
set ColorSpecs(ZeroCrossingButton,Background) 		\#F5C41D
set ColorSpecs(ZeroCrossingButton,Foreground) 		black
set ColorSpecs(ZeroCrossingButton,Highlight)	 	blue
set ColorSpecs(ZeroCrossingButton,HighlightBackground) 	NavajoWhite

set AutoPlayP 1;
set AutoPlayWritesP 0;
set AutoComputeSilencesP 1;
set BalloonHelpP 1;
set DeferWritesP 0; #Generate region list rather than actually writing out audio files
set SegmentsInSecondsP 1;
set SilencesInSecondsP 1;
set UseScrollbarsP 0;
set SetLeftEdgeOverviewImmediateP 0;
set UseOutFileNameListP 0;
set AutoLoadOutFileNamesP 0;

set SilenceFileNameTxt [_ "None"]
set LastSegmentFileWritten [_ "None Written Yet"]
set SavedLeftScrollSilenceNumber -1;
set SavedRightScrollSilenceNumber -1;

set WindowLeftEdge  0;			# In samples
set WindowRightEdge 0;			# In samples
set NeighborhoodLeftEdge 0;
set NeighborhoodRightEdge 0;
set DeltaSeconds 0.05;
set DeltaSamples 500;
set LeftCutWaveform "";
set RightCutWaveform "";
set LeftCutMark "";
set RightCutMark "";
set Volume 50;
#This is indexed on the name of the canvas and the property.
array set  WaveformInfo {};
set WaveformInfo(.ov,wf) "";
set WaveformInfo(.c,wf) "";
set WaveformInfo($CLUPL,wf) "";
set WaveformInfo($CLUPR,wf) "";
set WaveformInfo($CLUPL,zxlist) [list]
set WaveformInfo($CLUPR,zxlist) [list]
set WavebarPixelsPerSecond 50;
set WaveformInfo($CLUPL,CloseupRegionWidth) "";
set WaveformInfo($CLUPR,CloseupRegionWidth) "";

set WindowSetSecondsP 1
set PanelsToShow 3;
#Pause arguments
set DefaultPauseFrameSize	0.01;	# Positive real seconds
set DefaultPauseMinimumDuration 50.0;	# Non-negative real milliseconds
set DefaultPauseThreshold       200;	# Positive integer amplitude units
set PauseParameters(FrameSize) $DefaultPauseFrameSize
set PauseParameters(MinimumDuration) $DefaultPauseMinimumDuration
set PauseParameters(Threshold) $DefaultPauseThreshold
set CloseupSamplesPerPixel 10;

#Initialize the following just so nothing goes wrong before we load a sound file.
set SoundFileName "";
set WavebarLeftEdgeFraction 0;
set WavebarCoordsID 0
set WaveformInfo(.ov,PixelsPerSample) 2;
set WaveformInfo(.ov,PixelsInWaveform) 2;
set WaveformInfo(.c,PixelsPerSample) 2;
set WaveformInfo(.c,PixelsInWaveform) 2;
set WaveformInfo(Closeup,PixelsPerSample) 2;
set WaveformInfo($CLUPL,PixelsPerSample) 2;
set WaveformInfo($CLUPR,PixelsPerSample) 2;
set WaveformInfo($CLUPL,PixelsInWaveform) 2;
set WaveformInfo($CLUPR,PixelsInWaveform) 2;
set WaveformInfo(.ov,FirstSample) 0;
set WaveformInfo(.c,FirstSample) 0;
set WaveformInfo($CLUPL,FirstSample) 0;
set WaveformInfo($CLUPR,FirstSample) 0;
set WaveformInfo(.ov,ZeroHeight) 100;
set WaveformInfo(.c,ZeroHeight) 100;
set WaveformInfo($CLUPL,ZeroHeight) 100;
set WaveformInfo($CLUPR,ZeroHeight) 100;
set SamplingRate 22050
set SoundSeconds  0.0
set SoundSamples 0;
set SoundSamplesText "0"
set SoundLastSample 0;
set SoundChannels 1;
set SoundEncoding Lin16;
set SoundFileFormat .wav;
set SampleStrLen 5;
set MSDelta 0;
set WhichList Active

#package require Tk
set PlayCommand window;

proc min {a b} {
    if {$a < $b} {
	return $a
    } else {
	return $b
    }
}

#Convert seconds to integral hours, minutes, and seconds
proc SecondsToHMS {t} {
    set Hours   [expr int($t / 3600.0)];
    set Minutes [expr (int(($t  - ($Hours * 3600)) / 60.0))];
    set Seconds [expr round($t  - ($Hours * 3600) - ($Minutes * 60))];
    return [format "%d:%02d:%02d" $Hours $Minutes $Seconds]
}

#Convert seconds to minutes and fractional seconds
proc SecondsToMSF {t} {
    set Minutes [expr (int($t / 60.0))]
    set SecondsInMinutes [expr {$Minutes * 60.0}]
    set Seconds [expr {$t  - $SecondsInMinutes}]
    return [format "%02d:%05.2f" $Minutes $Seconds]
}

proc MinimizeFileName {s} {
    set cwd [pwd];
    set sdir [file dirname $s]
    if {[string equal $cwd $sdir]} {
	return [file tail $s]
    } else {
	return $s;
    }
}

trace add variable WaveformInfo(Closeup,PixelsPerSample) write SetCLPixelsPerSample

proc SetCLPixelsPerSample {n e o} {
    set ::WaveformInfo($::CLUPL,PixelsPerSample) $::WaveformInfo(Closeup,PixelsPerSample);
    set ::WaveformInfo($::CLUPR,PixelsPerSample) $::WaveformInfo(Closeup,PixelsPerSample);
}

set ScrollbarList [list];
#This array is indexed on window names
#and holds the commands necessary to pack them.
array set PackCommand {}

array set InfoBar {};
set InfoBar($OV) "0.0"
set InfoBar($C) "0.0"

set OutFilePrefix  "frag";
set OutFileSuffix  "seg";
set OutFileExtension ".wav";
set OutFileIndex    1;

#Indexed on canvases.
set UseSecondsP($OV) 1;
set UseSecondsP($C) 1;
set UseSecondsP($CLUPL) 1;
set UseSecondsP($CLUPR) 1;

set IPACIsDisplayedP 0;
set IPADIsDisplayedP 0;
set IPAVIsDisplayedP 0;
set IPAAIsDisplayedP 0;
set CharEntryByCodeIsDisplayedP 0;

#This provides an addition to the default methods of the scale
#widget. The default method, bound to <B1>, #increments or decrements
#the value by the resolution, by default 1. If you want a larger
#increment, you can use a larger resolution, but sometimes it is
#convenient to have a finer resolutio available while also being
#able to move in larger increments. A solution is to bind to
#<B3>, or some other event if you wish, a larger movement.
#This procedure moves by the specified multiplier k times
#the resolution of the scale. 

#The coordinates x and y are supplied by
#Tk when the binding is triggered. w and k are,
#from the point of view of the individual binding,
#CONSTANTS. They represent the scale widget and
#the desired resolution multiplier. You supply
#them when you create the bindng. A typical
#binding might look like this:
#bind .play.vol <<B3>> {ScaleMoveBigIncrement .play.vol 5 %x %y};

proc ScaleMoveBigIncrement {w k x y} {
    set part [$w identify $x $y]
    set inc 0;
    switch -exact -- $part {
	trough1 {
	    set dir -1;
	}
	trough2 {
	    set dir  1;
	}
	default {
	    return ;
	}
    }
    set Resolution [$w cget -resolution]
    set CurrentValue [$w get]
    set Delta [expr $dir * $k * $Resolution]
    $w set [expr $CurrentValue + $Delta]
}

snack::sound snd -precision single;

#Shut down gracefully.
proc ShutDown {} {
    global BrowserPIDS;
    WriteJournal [format [_ "Session ended:   %s"] [clock format [clock seconds]]];
    WriteJournal "--------------------"
    CloseJournal;
    #Shutdown child browsers
    foreach pid $BrowserPIDS {
	catch {exec kill $pid};
    }
    exit 0;
}

proc PopupDown {n} {
    global PopupList;
    if {[info exists PopupList($n)]} {
	if {[winfo exists $PopupList($n)]} {
	    destroy $PopupList($n);
	    return 1;
	}
    }
    return 0;
}

proc WriteJournal {msg} {
    global JournalHandle;
    global SynchJournalP;
    puts $JournalHandle $msg;
    if {$SynchJournalP} {
	FlushJournal;
    }
}

proc CloseJournal {} {
    close $::JournalHandle;
}

proc FlushJournal {} {
    global JournalHandle;
    flush $JournalHandle;
}

proc ShowMessage {msg} {
    if {$::BatchModeP} {
	WriteJournal $msg;
	puterr $msg;
    } else {
	if {[winfo exists $::MSG]} {
	    $::MSG configure -state normal;
	    $::MSG delete 1.0 end;
	    $::MSG insert 1.0 $msg;
	    $::MSG configure -state disabled;
	}
    }
}

proc ClearMessageWindow {} {
    if {[winfo exists $::MSG]} {
	$::MSG configure -state normal;
	$::MSG delete 1.0 end;
	$::MSG configure -state disabled;
    }
}

proc LoadMessageCatalog {} {
    global DebugP;

    if { $DebugP } {
	if { [::msgcat::mcload "msgs"] == 0} {
	    puts "No message catalog loaded."
	} else {
	    putstd "Message catalog loaded."
	}
    } else  {
	::msgcat::mcload [file join [file dirname [info script]] msgs];
    }
}

proc PauseAvailableQ {} {
    if {[string length [auto_execok $::PauseCommandName]]} {
	set ::PauseVersion [FindoutPauseVersion];
	dmsg "Pause version = $::PauseVersion"
	return 1;
    }
    set ::PauseVersion none
    return 0;
}

proc FindoutPauseVersion {} {
    set TmpFile [file join $::TempDir "sndbite.txt"]
    catch {[exec $::PauseCommandName -v 2> $TmpFile]}
    if {[catch {open $TmpFile "r"} TmpHandle ] != 0} {
	ShowMessage [format [_ "Mysterious failure to open temporary file %s."] $TmpFile];
	return ;
    }
    if {[gets $TmpHandle vline] > 0} {
	return [lindex [split $vline] 1]
    }
    return [_ "unknown"]
}

proc SetupImages {} {
    global GrassImage;
    global LeftArrowImage;

    set LeftArrowImage [image create photo -data {
	R0lGODlhFAAUAIAAAAAAAL+/vyH5BAEAAAEALAAAAAAUABQAAAIqjI+py43gGIAxTVrNxXVz
	54WTIopWGZ7oRq7X4o4wm2lvbX+ZjGv9/ysAADs=
    }]

    set GrassImage [image create photo -data {
	R0lGODlh4gAoAOcAAABCAABrAAiUABC1CBjGECGUCCmtCDFrCDFrGDGUGDGlMTG1ITHGITm1MTnO
	MTnnMUqUIUrOUlK9KVqUOVq1Slq9WlrOIVrnUmPOOWutWmu1OXNCIXO9SnPOSnPWa3PeUnPee3uc
	Qnu9WnvGtYxzUoy1e4zWWozWe4zvjJS9e5TWnJTvEJy1jJzee6WlpaW9lKXW1qXenK2tra3vpbUh
	MbW1tbXWpbXW77XnpbX3rb29vb3Gvb3nvb3vhL3/vcZzhMbexsbnpcbv58b/zs7Ozs7evc7vvc73
	rc73xs73ztZKhNalpda1pda9pdbeztbnId57jN7Gvd7nzt7n3t7vSt73xt7/1uetvefWxufn5+fv
	9+f3zuf33uf/5+f/7+f//+/Oa+/O1u/W1u/e3u/e7+/vte/v5+/v7+/3Uu/3Y+/3jO/35+/37+//
	1u//3vecrfe1zvfGxvfenPfn1vfn3vfvWvfv7/f3c/f3zvf35/f39/f/zvf/7/8hWv85c//WOf/n
	1v/n5//ve//v3v/3EP/3Mf/3Uv/3Y//3a//3lP/35//3////Y///pf//vf//3v//////////////
	////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////ywAAAAA4gAoAAAI/gAhCRxI
	sKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjyBDihxJsqTJkyhTqlzJsqVLhWdinpki86XN
	mzglypwyJQuRn0R2/Ox5JqfRozdlzpw5BejPHTp0CP2ZpShSozUd7uTJM+ZDpTSVZs0olqZZrk2d
	BAVaQ0eNGjLiypWhY6jVq5Bioh2bUOxdrUyJqN0LlmmWpoKd7nCSpepAv2edSg6q1knanodpMtzp
	U+3TyUTatpUBd66LuC5Sx21LpCdegTMTWybalylhwIgl78jM83BiyW2j1iXSeGtm30ChRn0bdern
	p4wP/zW406lU4cJXlzYtI7V31afp/gp1fPWMT+XDiWsuGBto3fFhYfIMrUP7W+f03QZf/pb5VN+e
	rXXdW3NxJxdc/bW1w39hgdUYW/UViFp3p1XoHYXffdcdacOtd1RsUO03FHmwzcecW0Lt0Jt5ShFk
	HhFRyRXeiW7pRxqCCfaXnhMBimajjBhuWOGEqwkX1GFV9cTVVG4BaSGGGbpwA5RRDlnDeCTmFFuM
	pbGm3kyHCdXfXM0p5pmSD0KFmobhTdjmjTcm2NxyEgpZ5Z0Xtqngcz+JVhqeGcbExRowvMHEG1GM
	ceeGHLbWIF8stbfdgcM5R6CTc+EoonMRUmkhm4zWSdqoa1LoKaBVBqkdlwWCl1oW/nys4QIXZ6wR
	ExI24DDDCFDQQAINUCwxCKBFOleZo16t9KKa4c1Yo3J/ZihkgTpe1+Sp3z2yRxmO7PHIk82Gaqe0
	qJYLHpBOujprG4C0MQYXg5yRRBK5nqDCCCb0+ocSYJyBJ6N7TtZbgx+d4cjBZXhb4oI6fDpkq9iy
	6UJVZ7ChlJvexcSHvy7w0YggjBwiSBkS38lHG1VUkYQVZdxxhyBqODIFynhUwQUXVWWxKJ568JEF
	HoCMMQcWWAziiBqCpAFzEEFYkQQPUPNAhQlPUGE1FC1AYYMTZhCrGqmjiggdZlla5IggghzysiML
	h7ZmansIUochhgiyh7neZcHG/hpIIFFFGY2oUUYbXHTHRRuOtIEHHok7sgUegb+cSBk6R8luGz+7
	sUcVR3QexAxpoEEFGnWXoUYPLaDQQw9BHFFFGxyjykcgQrdhxtBzDI3FHHLU8QcVT5jQwgwzqKCC
	vSqYQMgThVSNggAqoMBDEpXv/Om0mQYHVNkUnS0IIogI4gjFUzgxGpRlHFLI+oeQjLcLtVrhgw9B
	pGG14LQ+UgYTTEARRRRSwEMbFMc4bjmiDFzIUBYeYYc85IEPJ5sXD2xgAxS0wGpWS8MdiHeCD1Tg
	gzZonc3OwAdUZSEQcyiDCuMwhzjE4Q1vWMIbwPCEJ4RABPY6AQpUkDoUAK+G/lUDgQA8oIIZTM8O
	dngfqPR0JSxZRCl72JYjAjAoJ0hBCyF6mxHkcAdDkE4QTIgCosQgBSlgwWex847TjJCDHFzQfnVQ
	A/X28AZ9KUEJS3DBAEuYGgHsQXHeGSDmHpEHPLihDU4QAgx4MIIRnIADVBNBAFrQAhN4oAIaoAAE
	IKCBErQgCDjYXBu+Q7GbOQEJULMB645QhjrSgAb7gsIlOSABCnywAxXwgC49kAEgmsAEAoiAB0Cg
	ghjMK4FKTFVcoiIY7m2mPUKJCRucFgB64SAJXijNAh8RBxFAQQ5RCIAAoNArWEKBaU0wQhGSEARF
	eUcKqjSeB6ZGhRTMIAhc/igDGP7AT36+AQ97KGDiBNAIFdYsZVWoGRKKwDQKqsAGxlOBCCQAAQ6s
	AAAf6IAJMMABC1AUAgnQAAhaUIcMBsEGE0ReC0QQA3uxoAIlEIENYiACEvShD0+gQQg0gAEISGAB
	C6BABC5AtRquwKhP4EAwJRCBCKAAB9fUgne0cIYvvM9U2nPCdLSSGx3IhAtPAwAOepCGFtyBC2Yw
	AyKdIAcRcMBQAQgAFEjwh1eCgYIhDEIRimCEMmChjEGg6QlO4AEOCJGYKAiCGqjQTzCAAYFnUKEK
	qyAANVg2BxTEQQtQyoNFUhCHJQBBBjKgAQlI4AABkIAFLFpDDEjAAAZo/oAwMWi/HugSph+M6QeH
	CVMBgOAEJQCmADZggkw2oAEJWMBxHWCBJ6zgqEB8Ak8F8IAGCJWYKuhJarTwBS1kQapes1ITiZMF
	nTRFTTI4gxWswIMc6JKeGHzoSt0aAhOUIAQkCMEfahiCFYgUBLo0AQgo2AMmrK4FIUjwDTkAgOB6
	4AQXNEEd6lBZNbSOaTOgYAsIewIBN5UCHCCiCmAQAxio4IMRoIAFLICBGpbWARIo6lEVQAACLECY
	EQ6eCUxr2qZioAM89UBRfalUAeyUBEyNQAUo4AAGLKDF0U2qjQnAgAYw4MoRGKwRjcCDGwjBy0Jw
	gh1stQZb6Uxc2qNK/nkj8iIYoUa9VgACD3KpAQ1QgXWMPAEF6kyBD9R0A3Xdbw1N0ADTcqAEGmgA
	BErAgejq9JW/IsGvOHDoBw8Tejxs6S6bWoGmNvW4DxBqA0CA3RHc68QYgPIKOODaCLC4tK+FrWxv
	XGXlOnkBTnaAA258AQlcoNHRxYADBCAACWwgBCW+AQxGQIEBFOAAxKUapQ3AACoTYAAMiAAITG28
	EbyAmEBAqfFsMANdGXFeejiDkRZDtq1qRS1NOs16kzADD1BAkyVQQWdPrIDjQuDHIXh0CKT7hJ+a
	VgM7vbedawi8gCcYljpdwQQ66QEcekAAlESBLpvqgAg8wNMgV60E/nRtXQ+MwMQw8MBxOZrUnyrA
	ADQOwAAEkIAEwDYBNk5uAQggAAIkoONKbupPoQzEkRO7AQVAtrJvoIIIHKAAUEcAAp4N2wHU+OoV
	MDUMTHw8ELBABUOMntiJt+Uk2CFFSHImRNp8rbh4wQj3amTcR4CCRtodBPdO8AZWAIFiF+CjmUzy
	nhttggyEYAOS3oBON2ABoX6w0xQIZoojQHJdp7gDGeXABS6AAaAuoN8KoIDJVWDvmgM1Aa8FvQEW
	AABFwxYBBqh5AQYwANkGPet2VwEFcH31nr+W2MY+dESHn4IQbJLYM6/21Qmg7WWPgJgV0KFvf6vL
	E4AABSiA8PSS/oAZdzekOFXhgheyYAWwJkHOPmjjDHZ48kZevABZH/Gyda9kYXOgAcGsKKURTelM
	VnQAdYZwz2UCNxQCJfABAOYBniYA9zZUGBABhRYBD8h5H5Box0UAq6cAQCUABfB5CzB7tfd5hUYB
	1kWCAYABCmBa1tUAN6Zc8icEpkZqxiMCIbBcMCYADiBbqRYCHeVTwXQCIwA1LPABcYV/AsAATUYA
	DoBtInh0HxYBktdUuzRYO7R9F0ExazBvUdNeEBU92HcCFYBdpBcBCzAAEXBqEbVnEcBnDFhLGkBp
	FZBgpeVTExBMCGdfJZACBNgCiJZiH5dtONhx2WYBD4ABHhWA/qV1XAngUz/ledfmebQngq6VSSlW
	S7V0bxXwUyS4aycHAzfAdJgoAPdVWhpgAbkkABXgQRXAao3HAALQAMjjSBVActQViLn2ildGbDnI
	aagIYCmwS6QGAjNwTE+UhVbAZTmwftEzTAmogE2lAAVQcwKwegmAgw0AdEqmAZgUeAJgAUMVeiTY
	ABNwXCyYAGRoiUJHghIwAQawaw5wbQKgXFamax0nAQ2AAQjHgzsVgB1lWhfQAFWHf1D3iqgnAQxg
	cEh4XJ4HVNSIivdiYhWwgbJVZyKwAjtVAaioASIgAh0gVLsnWx7ZgBsnALR3cVAIclCIirokRF+4
	Q9lXROdG/isXMS8SlIzZd33NuEsqd1wRkG0OkFxOhoRYlm1JRo9CmYNWZmVVVmUEwIK1BlumtXok
	SXsDkAAzB1ur94ELkFwKoH8fYAId0H8coI2c52sGSW0L2QBNaWvHtZS1Z2U0Zo9LeVyvmGJ7VmcK
	qIB7VgH/Fo6UR4ILUI9Q+AAfRGq6hAKk5lsraX3ZdwIxgAKYlQNQkwRGAARIkATetWYYERNO8zQ5
	UEQap3EAloBNBQKdBnKfp2tIyHEpZnuW12RNBlS55pRAxYLIVWgSUAAQ0IFW2XO0VwA0F4m8KYm9
	xmIUYFqpJgEYgIQWUHkLcHW4FphXVnlBWWPV9lPUNp34/ndlB6ecF+BpTBaOSHmNuIaETOZpHwCM
	1ndpiOkBLkluRsQDTmN+60UTeuARnOk0UDMDMaCM2PeSX/hbhrlxp8kBj3cBqchxTKaaTYaEsEmP
	HcdJ6wh1FLWO5WllVAZUNdZk10iPQuUAH4eN9AiBQnllJjqdVHaiQpmi1aai08lcTEWPnEd5ESAB
	IfoBSviiDPAA2WZ7QzVMg4WTXhg9kpkD3AcpJXEGNyNBTzNB7QWTKEA8ycgD5cZB7TlMKxmMt+Vx
	PdmTDGqiqnlcFUqO9miPDXpl1uai9BiingahRnmmZzqd5TmdYKqiDAqiMOYAFwChwiZsIeoA5wmi
	Hydb/jvKcZdkaaTmktmHfUWEA9NTfrTifSTBBjnDIt4nE/qpK6kTPYnqnte3S7IVonUKp0gYmB0q
	opTXoHHaZFz6AB3XcR/Xpl4KohBIef+IAZvna69Jea7KpqxJebP4AQ/wnYX4abEaq0D3AdhIo+gp
	TFjamIrqkuY2L1agBd71GgNRFV1wfj5QPDOgQ6GJmFeKpR7wATRqeQ8Qq1KoZBVwAc7oAR2wkpcE
	AijJk4PaVOkpTJ3mAbuKkub6rwQaAebKrwoYr+4qhRuXnruUSzrprMA4mkC6mA+2qGKnKzhAQZKJ
	Uj4QNT4wn0haHtPEXjwQpS5pL9hHRAJqfQnYaeYK/qzC9LJh6K46qaXNGAEdkKq/KrBhmKUNm5c2
	CwIKq5O6hIA8y4zWF6QCKpoqy5iD1VKQaS84gAKPSW5RWm4xkIzEAzUbOz1GMC9dOy9AQJkrQzDY
	6iJwxgPd+q08pEPGs2HFE6WgWbL/yYwTy6guGVF3u4wDKrSj6YU5sENeCKA7pCvJaAPJmANQJZlZ
	S6XtxbhbiLaTmQRDQJNJwAXW6gUy4V21Iqlli59rsDI8wGUZ5qhb+7iQG7qPawNbK5kc+7hGULqn
	i7YzwLrdCjVGyn31Wbk3owXrlQW6qwWRugalFBNfsAVacJ+dm7y1oYViS63zWX5e8LzzRrk0OW9W
	LOAE1rteTrO92psEUlCf88YF1bq5tjJ+Sioom5ssyru+7Nu+7vu+8Bu/LxEQADs=
    }]
}

proc IsDouble {s} {
    return [string is double $s]
} 

#Font stuff begins here
# Default defaults
set FontInfo(family) courier
set FontInfo(size) 12
set FontInfo(weight) normal
set FontInfo(slant) roman
set FontInfo(underline) 0
set FontInfo(overstrike) 0


namespace eval fontsel {
    variable FontPropertyList [list family size weight slant underline overstrike]
    variable FontPropertyClass
    variable FSCColors

    foreach p $FontPropertyList {
	set FontPropertyClass($p) generic;
    }
    set FontPropertyClass(underline) boolean
    set FontPropertyClass(overstrike) boolean

    #We check the existence of the variable so that this
    #can safely be called AFTER non-default values are set.
    proc SetFontInfoDefaults {} {
	global FontInfo;
	foreach ft $::FontList {
	    if {![info exist FontInfo($ft,family)]} {
		set FontInfo($ft,family)	$FontInfo(family)
	    }
	    if {![info exist FontInfo($ft,size)]} {
		set FontInfo($ft,size)	$FontInfo(size)
	    }
	    if {![info exist FontInfo($ft,weight)]} {
		set FontInfo($ft,weight)	$FontInfo(weight)
	    }
	    if {![info exist FontInfo($ft,slant)]} {
		set FontInfo($ft,slant)	$FontInfo(slant)
	    }
	    if {![info exist FontInfo($ft,underline)]} {
		set FontInfo($ft,underline)	$FontInfo(underline)
	    }
	    if {![info exist FontInfo($ft,overstrike)]} {
		set FontInfo($ft,overstrike)	$FontInfo(overstrike)
	    }
	    if {![info exist FontInfo($ft,gloss)]} {
		set FontInfo($ft,gloss)	$ft;
	    }
	    if {![info exist FontInfo($ft,help)]} {
		set FontInfo($ft,help)	"?"
	    }
	}
    }

    #For a given font assign font-specific properties from generics.
    proc FontSet {which} {
	global FontInfo
	variable FontPropertyList
	foreach prop $FontPropertyList {
	    set FontInfo($which,$prop) $FontInfo($prop);
	}
    }

    #Assign the proprety values of a specified font to the generics.
    proc InverseFontSet {which} {
	global FontInfo
	variable FontPropertyList
	foreach prop $FontPropertyList {
	    set FontInfo($prop) $FontInfo($which,$prop);
	}
    }

    #Configure a specified font according to the font-specific properties.
    proc ConfigureFont {which} {
	global FontInfo
	variable FontPropertyList
	foreach prop $FontPropertyList {
	    font configure $which -$prop $FontInfo($which,$prop)
	}
    }

    #Record as default values the font-specific values of properties at the
    #time of the call. The recorded values are intended for use by
    #ResetToDefaults 
    proc RecordDefaults {} {
	global FontInfo
	global FontList;
	variable FontPropertyList

	foreach f $FontList {
	    foreach p $FontPropertyList {
		set FontInfo($f,$p,Default) $FontInfo($f,$p);
	    }
	}
    }

    #Create all of the fonts on the font list and configure them
    #according to the generic values of the properties, which are
    #also assigned at this time to the font-specific variables.
    proc CreateFonts {} {
	global FontList;

	#We create this separately because we don't want it on the FontList.
	font create FontControlPanelFont;

	foreach ft $FontList {
	    font create $ft;
	    InverseFontSet $ft;
	    ConfigureFont $ft;
	}
    }

    #Get the values from the three scales, combine them into a hex RGB spec,
    #assign its value to FontExampleColor, and configure the two examples.
    proc UpdateFontExampleColor {x} {
	variable FSCColors
	global FontExampleColorConfigureWhich

	UpdateFontExampleColorHex;
	.selectFont.curcan.att.r1c1 configure \
	    -$::FontExampleColorConfigureWhich  \#$::FontExampleColor
	.selectFont.curcan.att.r2c1 configure \
	    -$::FontExampleColorConfigureWhich \#$::FontExampleColor
	set FSCColors(red,$FontExampleColorConfigureWhich)   $::FontRed;
	set FSCColors(green,$FontExampleColorConfigureWhich) $::FontGreen;
	set FSCColors(blue,$FontExampleColorConfigureWhich)  $::FontBlue;
    }

    proc UpdateFontExampleColorHex {} {
	set ::FontExampleColor [format "%02X%02X%02X" $::FontRed $::FontGreen $::FontBlue];
    }

    proc RestoreCSColors {} {
	variable FSCColors
	global FontExampleColorConfigureWhich
	set ::FontRed   $FSCColors(red,$FontExampleColorConfigureWhich)
	set ::FontGreen $FSCColors(green,$FontExampleColorConfigureWhich)
	set ::FontBlue  $FSCColors(blue,$FontExampleColorConfigureWhich)
	UpdateFontExampleColorHex;
    }

    proc CloneMainFontAsFontControlPanelFont {} {
	variable FontPropertyList
	global FontInfo

	foreach p $FontPropertyList {
	    font configure FontControlPanelFont -$p $FontInfo(MainFont,$p);
	}
    }
					

    #This is the main procedure of this package.
    #It creates the font control panel.
    proc CreateFontControlPanel {args} {
	global FontInfo;
	global WhichFontToSet
	global FontList;
	variable FontPropertyList
	variable FSCColors

	set General 1
	set exwid 10

	set w .selectFont
	if {[winfo exists $w]} {
	    wm deiconify $w;
	    raise $w;
	    return ;
	}
	toplevel $w
	wm title $w [_ "Font Selection"]
	BindKeys $w
	wm protocol $w WM_DELETE_WINDOW "wm withdraw $w"
	
	#The idea is that in general we want to use the main
	#font here, but we keep them separate so that we
	#can wait before switching the control panel to
	#the new main font configuration so that
	#the user isn't confronted with an unusable
	#control panel if he or she sets the mainfont to something
	#crazy.
	CloneMainFontAsFontControlPanelFont;

	if {[llength $args] > 0} {
	    set ::WhichFontToSet [lindex $args 0];
	    set General 0;
	} 
	set FontTypes [llength $FontList];
	if {$FontTypes == 1} {
	    set ::WhichFontToSet [lindex $FontList 0];
	    set General 0;
	}

	frame $w.which -relief ridge -border 3
	if {$General} {
	    set msg [_ "For what aspect of the program\ndo you wish to set the font?"]
	    balloonhelp_for $w.which $msg
	    label $w.which.title -text [_ "Use for which to set font"] \
		-anchor w -font FontControlPanelFont
	    frame $w.which.btns;
	    set k 0;
	    set PerRow 4;
	    set ypad 3
	    set xpad 10
	    foreach ft $FontList {
		set bn $w.which.btns.f$ft;
		radiobutton $bn -text [_ $FontInfo($ft,gloss)]  \
		    -variable WhichFontToSet -value $ft \
		    -command fontsel::SetFontSelectionDefaults \
		    -font FontControlPanelFont \
		    -indicatoron 0 -selectcolor $::ColorSpecs(Default,Background)
		balloonhelp_for $w.which.btns.f$ft $FontInfo($ft,help)
		set row [expr 1+ $k/$PerRow]
		set col [expr $k%$PerRow]
		if {$FontTypes >= $PerRow} {
		    grid $w.which.btns.f$ft -row $row -column $col \
			-sticky we -ipadx 3 -padx $xpad -pady $ypad
		}
		incr k
	    }
	    if {$FontTypes < $PerRow} {
		foreach ft $FontList {
		    pack $w.which.btns.f$ft -side left -expand 1 -fill x \
			-ipadx 5 -ipady 3 -padx 40 -pady 3
		}
	    }
	    frame $w.which.pad  -height 4
	    pack $w.which.title -side top -expand 1 -fill both -anchor w
	    pack $w.which.btns  -side top -expand 1 -fill both -anchor w
	    pack $w.which.pad   -side top -expand 0 -fill x    -anchor w

	}

	frame $w.mid 
	frame $w.mid.opts  -relief ridge -border 3
	frame $w.mid.families  -relief ridge -border 3
	label $w.mid.families.lab -text [_ "Family"] -relief ridge \
	    -justify center -font FontControlPanelFont
	listbox $w.mid.families.lb -height 1 -exportselection 0 \
	    -yscrollcommand "$w.mid.families.sbar set" -selectmode single \
	    -font FontControlPanelFont
	scrollbar $w.mid.families.sbar -orient vertical -command "$w.mid.families.lb yview"
	bind $w.mid.families.sbar <<B3>> \
	    "ScrollbarMoveBigIncrement $w.mid.families.sbar 0.20 %x %y"

	bind $w.mid.families.lb <<B3>> ProvideFontDescription

	pack $w.mid.families.lab  -side top -expand 0 -fill x
	pack $w.mid.families.lb   -side left -expand 1 -fill both
	pack $w.mid.families.sbar -side left -expand 1 -fill y

	label $w.mid.opts.lab -text [_ "Attributes"] -relief ridge \
	    -justify center -font FontControlPanelFont
	label $w.mid.opts.sizel -text [_ "Size:"]  -font FontControlPanelFont
	scale $w.mid.opts.size -orient h -digit 1 -from 5 -to 55 \
	    -variable FontInfo(size)  -tickinterval 0 -length 150 \
	    -font FontControlPanelFont
	bind $w.mid.opts.size <<B3>> "ScaleMoveBigIncrement $w.mid.opts.size 5 %x %y"

	label $w.mid.opts.weightl -text [::msgcat::mc "Bold:"] \
	    -font FontControlPanelFont	    
	checkbutton $w.mid.opts.weight -variable FontInfo(weight) \
	    -onvalue bold -offvalue normal  -font FontControlPanelFont

	label $w.mid.opts.slantl -text [::msgcat::mc "Italic:"] \
	    -font FontControlPanelFont
	checkbutton $w.mid.opts.slant -variable FontInfo(slant) \
	    -onvalue italic -offvalue roman -font FontControlPanelFont

	label $w.mid.opts.ulinel -text [::msgcat::mc "Underline:"] \
	    -font FontControlPanelFont
	checkbutton $w.mid.opts.uline -variable FontInfo(underline) \
	    -onvalue 1 -offvalue 0  -font FontControlPanelFont

	label $w.mid.opts.strkovl -text [::msgcat::mc "Overstrike:"] \
	    -font FontControlPanelFont
	checkbutton $w.mid.opts.strkov -variable FontInfo(overstrike) \
	    -onvalue 1 -offvalue 0  -font FontControlPanelFont

	grid $w.mid.opts.lab   -row 0 -column 0 -columnspan 2 -sticky ew
	grid $w.mid.opts.sizel -row 1 -column 0 -sticky w
	grid $w.mid.opts.size -row 1 -column 1 -sticky w
	grid $w.mid.opts.weightl -row 2 -column 0 -sticky w
	grid $w.mid.opts.weight -row 2 -column 1 -sticky w
	grid $w.mid.opts.slantl -row 3 -column 0 -sticky w
	grid $w.mid.opts.slant -row 3 -column 1 -sticky w
	grid $w.mid.opts.ulinel -row 4 -column 0 -sticky w
	grid $w.mid.opts.uline -row 4 -column 1 -sticky w
	grid $w.mid.opts.strkovl -row 5 -column 0 -sticky w
	grid $w.mid.opts.strkov -row 5 -column 1 -sticky w

	pack $w.mid.families -side left -expand 1 -fill both -padx 5 -pady 2
	pack $w.mid.opts     -side left -expand 1 -fill both -padx 5 -pady 2

	eval $w.mid.families.lb insert 0 [lsort [font families]]

	bind $w.mid.families.lb <ButtonPress-1> {fontsel::SelectFontFamily %W %y}
	bind $w.mid.families.lb <B1-Motion> {fontsel::SelectFontFamily %W %y}
	bind $w.mid.families.lb <Activate> {fontsel::SelectFontFamily %W %y}

	frame $w.cntls -relief ridge -border 3
	button $w.cntls.sav -text [_ "Apply"]  -command fontsel::FontSave \
	    -font FontControlPanelFont
	button $w.cntls.res -text [_ "Reset"] -command  fontsel::ResetToDefaults \
	    -font FontControlPanelFont
	button $w.cntls.can -text [_ "Dismiss"] -command "wm withdraw $w" \
	    -font FontControlPanelFont
	button $w.cntls.cpanel -text [_ "Here Too?"] \
	    -command fontsel::CloneMainFontAsFontControlPanelFont \
	-font FontControlPanelFont
	pack $w.cntls.cpanel -side left  -expand 1 -fill both -padx 3
	pack $w.cntls.can    -side left  -expand 1 -fill both -padx 3
	pack $w.cntls.res    -side left  -expand 1 -fill both -padx 3
	pack $w.cntls.sav    -side right -expand 1 -fill both -padx 3

	set msg [_ "Press this button to dismiss the popup."];
	balloonhelp_for $w.cntls.can $msg
	set msg [_ "Press this button to reset the font to its defaults."];
	balloonhelp_for $w.cntls.res $msg
	set msg [_ "Press this button to make the changes\nyou have made take effect."]
	balloonhelp_for $w.cntls.sav $msg
	set msg [format \
	     [_ "Press this button to set the fonts\nin this control panel to the %s font."] \
		     [_ $::FontInfo(MainFont,gloss)]]
	balloonhelp_for $w.cntls.cpanel $msg

	frame $w.curcan -relief ridge -border 1
	set ATT [frame $w.curcan.att]
	set Row 0
	foreach r {Header Current Candidate} {
	    set Column 2
	    foreach p $FontPropertyList {
		set v $w.curcan.att.r${Row}c${Column};
		label $v  -font FontControlPanelFont
		incr Column;
	    } 
	    incr Row;
	}

	font create CurrentFontExampleFont \
	    -family $FontInfo($::WhichFontToSet,family) \
	    -size $FontInfo($::WhichFontToSet,size) \
	    -weight $FontInfo($::WhichFontToSet,weight) \
	    -slant $FontInfo($::WhichFontToSet,slant) \
	    -underline $FontInfo($::WhichFontToSet,underline) \
	    -overstrike $FontInfo($::WhichFontToSet,overstrike);

	font create CandidateFontExampleFont \
	    -family $FontInfo($::WhichFontToSet,family) \
	    -size $FontInfo($::WhichFontToSet,size) \
	    -weight $FontInfo($::WhichFontToSet,weight) \
	    -slant $FontInfo($::WhichFontToSet,slant) \
	    -underline $FontInfo($::WhichFontToSet,underline) \
	    -overstrike $FontInfo($::WhichFontToSet,overstrike);

	label $w.curcan.att.r0c0 -font FontControlPanelFont
	label $w.curcan.att.r0c1 -font FontControlPanelFont
	label $w.curcan.att.r1c0  -text [_ "Current"] -font FontControlPanelFont
	entry $w.curcan.att.r1c1 -font CurrentFontExampleFont -relief flat -width $exwid
	$w.curcan.att.r1c1 insert 0 [_ "example"]
	label $w.curcan.att.r2c0  -text [_ "Candidate"] -font FontControlPanelFont
	entry $w.curcan.att.r2c1 -font CandidateFontExampleFont -relief flat  -width $exwid
	$w.curcan.att.r2c1 insert 0 [_ "example"]

	#This is for use in conjunction with my character insertion library.
	#It arranges for the various character insertion widgets to insert
	#characters into the focussed window.
	if {[llength [info commands BindInsertionTarget]]} {
	    BindInsertionTarget $w.curcan.att.r1c1;
	    BindInsertionTarget $w.curcan.att.r2c1;
	}

	set CLR [frame $w.curcan.clr]
	set ln 60;
	set wd 10
	set trc \#D4B8C1
	scale $CLR.red -orient v -digit 1 -from 255 -to 0 -tickinterval 0 \
	    -variable FontRed  -showvalue 0 -length $ln -width $wd\
	    -troughcolor $trc -activebackground \#F0AAAA \
	    -bg red -fg yellow -command fontsel::UpdateFontExampleColor
	scale $CLR.grn -orient v -digit 1 -from 255 -to 0 -tickinterval 0 \
	    -variable FontGreen  -showvalue 0 -length $ln -width $wd\
	    -troughcolor $trc -activebackground \#AAF0AA \
	    -bg green -fg yellow -command fontsel::UpdateFontExampleColor
	scale $CLR.blu -orient v -digit 1 -from 255 -to 0 -tickinterval 0 \
	    -variable FontBlue  -showvalue 0 -length $ln -width $wd\
	    -troughcolor $trc -activebackground \#AAAAF0 \
	    -bg blue -fg yellow -command fontsel::UpdateFontExampleColor
	set FSCColors(red,bg)   0x00
	set FSCColors(green,bg) 0x00
	set FSCColors(blue,bg)  0x00
	set FSCColors(red,fg)   0x00
	set FSCColors(green,fg) 0x00
	set FSCColors(blue,fg)  0x00

	bind $CLR.red <<B3>> "ScaleMoveBigIncrement $CLR.red -20 %x %y"
	bind $CLR.grn <<B3>> "ScaleMoveBigIncrement $CLR.grn -20 %x %y"
	bind $CLR.blu <<B3>> "ScaleMoveBigIncrement $CLR.blu -20 %x %y"

	set ::FontRed   255
	set ::FontGreen 255
	set ::FontBlue  255
	set FontExampleColor \#FFFFFF
	label $CLR.rdt -textvariable FontExampleColor -width 7 -relief raised
	bind $CLR.rdt <Button-1> "pack forget $CLR"
	bind $ATT <Button-1> "pack $w.curcan.clr -before $ATT -side left -expand 1 -fill both"
	set msg [_ "Left click here to remove the color selector."]
	balloonhelp_for $CLR.rdt $msg;
	set msg [_ "Use this to set the colors in the example text boxes."]
	balloonhelp_for $CLR.red $msg;
	balloonhelp_for $CLR.grn $msg;
	balloonhelp_for $CLR.blu $msg;

	frame $CLR.whi
	set ::FontExampleColorConfigureWhich bg;
	radiobutton $CLR.whi.t -variable FontExampleColorConfigureWhich \
	    -value fg -command fontsel::RestoreCSColors -text [_ "fg"] \
	    -indicatoron 0 -activebackground gray -selectcolor gray \
	    -font FontControlPanelFont
	radiobutton $CLR.whi.b -variable FontExampleColorConfigureWhich \
	    -value bg -command fontsel::RestoreCSColors -text [_ "bg"] \
	    -indicatoron 0 -activebackground gray -selectcolor gray \
	    -font FontControlPanelFont
	pack $CLR.whi.t -side left -expand 1 -fill both
	pack $CLR.whi.b -side left -expand 1 -fill both

	pack $CLR.rdt -side top -expand 1  -fill both
	pack $CLR.whi -side bottom -expand 1  -fill both
	pack $CLR.red -side left -expand 1 -fill y
	pack $CLR.grn -side left -expand 1 -fill y
	pack $CLR.blu -side left -expand 1 -fill y

	set msg [_ "Choose the color for the sample text."]
	balloonhelp_for $CLR.whi.t $msg;
	set msg [_ "Choose the background color for the sample text."]
	balloonhelp_for $CLR.whi.b $msg;

	#Now grid them all
	set xp 5
	set yp 3
	set CLimit [expr [llength $FontPropertyList] + 2];
	for {set r 0} {$r < 3} {incr r} {
	    for {set c 0} {$c < $CLimit} {incr c} {
		set v $w.curcan.att.r${r}c${c};
		grid $v -row $r -column $c -sticky w -padx $xp -pady $yp
	    } 
	}

	set xp 3
	set yp 1
	if {!$General} {
	    $w.curcan.att.r0c0 configure -text [string totitle [_ $FontInfo($::WhichFontToSet,gloss)]]
	}

	pack $w.curcan.clr -side left -expand 1 -fill both -padx 9 -pady 5
	pack $w.curcan.att -side left -expand 1 -fill both -padx 3 -pady 5

	#Put it all together
	frame $w.botsep -height 4
	pack $w.which -side top -expand 1 -fill x -padx 8 -pady 6
	pack $w.curcan -side top -expand 1 -fill x -padx 8 -pady 6
	pack $w.mid   -side top -expand 1 -fill x -padx 8 -pady 1
	pack $w.cntls -side top -expand 1 -fill x -padx 8 -pady 2
	pack $w.botsep -side top -expand 1 -fill x -padx 8 -pady 2
	if {$General} {
	    $w.which.btns.f[lindex $FontList 0] invoke;#  Default to first on list
	}
	foreach f $FontPropertyList {
	    trace add variable FontInfo($f) write fontsel::FontShow;
	}
	return $w;
    }

    #This resets the properties of the font specified by WhichFontToSet
    #to their default values, where "default" means whatever values
    #are stored in FontInfo(<font>,<property>,Default). The intention
    #is that these values will have been set by RecordDefaults at
    #a suitable point. A suitable point might be program startup or it
    #might be after init files have been read.
    #After resetting the attributes for the current font to their
    #default values, it configures the fonts for both the current and candidate
    #examples in the control panel to match.
    proc ResetToDefaults {} {
	global FontInfo;
	global WhichFontToSet
	variable FontPropertyList

	foreach prop $FontPropertyList {
	    set FontInfo($::WhichFontToSet,$prop) $FontInfo($::WhichFontToSet,$prop,Default);
	    set FontInfo($prop) $FontInfo($::WhichFontToSet,$prop,Default);
	}
	ConfigureFont $::WhichFontToSet;
	ConfigureCurrentExampleFont;
	ConfigureCandidateExampleFont;
	DescribeBothFonts;
    }

    #This is the procedure called from the control panel when the user decides
    #to apply and save the values set on the control panel. It sets the font-specific
    #attributes from the generic ones, configures the target font as well as the
    #current example font, and updates the description of the current font
    #in the control panel.
    proc FontSave {} {
	global FontInfo

	set f $::WhichFontToSet;
	FontSet $f;
	ConfigureFont $f
	ConfigureCurrentExampleFont;
	DescribeBothFonts;
    } 

    #This procedure configures the font used to display the candidate example
    #in the control panel. It is intended to be called whenever a property
    #is changed in the control panel or when the target font is changed.
    proc ConfigureCandidateExampleFont {} {
	global FontInfo
	global WhichFontToSet
	variable FontPropertyList

	foreach prop $FontPropertyList {
	    font configure CandidateFontExampleFont -$prop $FontInfo($prop)
	}
    }

    #This procedure configures the font used to display the current example
    #in the control panel. It is intended to be called when the user
    #applies new values or when the target font is changed.
    proc ConfigureCurrentExampleFont {} {
	global FontInfo
	global WhichFontToSet
	variable FontPropertyList

	foreach prop $FontPropertyList {
	    font configure CurrentFontExampleFont -$prop $FontInfo($::WhichFontToSet,$prop)
	}
    }

    #This procedure configures the candidate example font#and updates the
    #description of the candidate font in the control panel. It is intended
    #to be called whenever a proprty of the candidate font is changed.
    proc FontShow {args} {
	ConfigureCandidateExampleFont;
	DescribeBothFonts;
    }

    #This procedure generates the descriptions of the current and candidate
    #fonts that are shown in the control panel.
    proc DescribeBothFonts {} {
	global FontInfo
	global WhichFontToSet;
	variable FontPropertyList

	set f $::WhichFontToSet;
	set c 2;
	foreach prop $FontPropertyList {
	    .selectFont.curcan.att.r0c$c configure -text  [string totitle [_ $prop]] 
	    set value $FontInfo($f,$prop)
	    if {$value == 1} {set value [_ "Yes"]} else {
		if {$value == 0} {set value [_ "No"]}}
	    .selectFont.curcan.att.r1c$c configure -text $value;
	    set value $FontInfo($prop)
	    if {$value == 1} {set value [_ "Yes"]} else {
		if {$value == 0} {set value [_ "No"]}}
	    .selectFont.curcan.att.r2c$c configure -text $value; 
	    incr c;
	}
    }

#This is to be called when we change font targets.
#It resets the control panel to show the current
#configuration for the newly targeted font.
    proc SetFontSelectionDefaults {} {
	global FontInfo;
	global WhichFontToSet;
	variable FontPropertyList

	foreach prop $FontPropertyList {
	    set FontInfo($prop) $FontInfo($WhichFontToSet,$prop);
	}
	set FontChoices [.selectFont.mid.families.lb size];
	set k 1;
	while {$k <= $FontChoices} {
	    set Family [.selectFont.mid.families.lb get $k];
	    if {[string equal $Family [string tolower $FontInfo($WhichFontToSet,family)]]} {
		.selectFont.mid.families.lb selection clear 0 end;
		.selectFont.mid.families.lb see $k
		.selectFont.mid.families.lb selection set $k $k;
		.selectFont.mid.families.lb activate $k;
		set FontInfo(family) [.selectFont.mid.families.lb get $k]
		break
	    }
	    incr k;
	}
	ConfigureCandidateExampleFont
	ConfigureCurrentExampleFont;
	DescribeBothFonts;
    }

    #This is the callback that extracts a new font family
    #setting from the control panel.
    proc SelectFontFamily {w y} {
	global FontInfo

	set index [$w nearest $y]
	if {$index != ""} {
	    set FontInfo(family) [$w get $index]
	}
    }

    #This is the callback that extracts a new font size
    #from the control panel.
    proc SelectFontSize {w} {
	global WhichFontToSet
	global FontInfo

	set size [$w get]
	if {[catch {expr round($size)} size] == 0} {
	    if { ($size > 0) && ($size <= 60) } {
		set FontInfo(size) $size
		return ;
	    }
	}
	$w delete 0 end
	$w insert 0 $FontInfo($WhichFontToSet,size)
    }

    #This is presently a stub.
    #It is intended to be called on an event, probably <B3>,
    #in the font family listbox in the control panel.
    #Its purpose is to provide the user with information about
    #the particular font. 
    proc ProvideFontDescription {w y} {
	variable FontDescriptions

	set index [$w nearest $y]
	if {$index != ""} {
	    FontDescriptions([$w get $index])
	}
    }

    #Create a command for setting each combination of font and property.
    proc DefineFontSettingProcs {} {
	variable FontPropertyList
	variable FontPropertyClass
	global FontList;
	global FontProcList;

	foreach ft $FontList {
	    foreach prop $fontsel::FontPropertyList {
		if {[string equal $FontPropertyClass($prop) boolean]} {
		    set ProcName  [format "::fontsel::Set%s%sP" $ft [string totitle $prop]];
		    lappend FontProcList $ProcName;
		    set cmd [list "proc"  $ProcName  "\{v\}" \
			 "set ::FontInfo($ft,$prop) \[SlaveBoolean \$v\];\nConfigureFont $ft;"]
		} else {
		    set ProcName  [format "::fontsel::Set%s%s" $ft [string totitle $prop]];
		    lappend FontProcList $ProcName;
		    set cmd [list "proc" $ProcName "\{v\}" \
			 "set ::FontInfo($ft,$prop) \$v;\nConfigureFont $ft;"]
		}
		eval $cmd;
	    }
	}
    }

    #Create aliases in the named daughter interpreter for the font setting commands
    proc AliasFontSettings {interp} {
	variable FontPropertyList
	variable FontPropertyClass
	global FontList;
	
	foreach ft $FontList {
	    foreach prop $FontPropertyList {
		set Tprop [string totitle $prop]
		set Tprop2 $Tprop;
		if {[string equal $FontPropertyClass($prop) boolean]} {
		    set Tprop ${Tprop}P
		}
		eval [split [format "%s alias %s%s ::fontsel::Set%s%s" \
			 $interp $ft $Tprop $ft $Tprop2]]
	    }
	}
    }

    #Returns a list of init file commands representing the current font settings.
    proc SaveFontSettings {} {
	variable FontPropertyList
	variable FontPropertyClass
	global FontInfo
	global FontList;
	
	set cl [list]
	foreach ft $FontList {
	    foreach prop $FontPropertyList {
		set Tprop [string totitle $prop]
		if {[string equal $FontPropertyClass($prop) boolean]} {
		    set Tprop ${Tprop}P
		}
		lappend cl [format "%s%s %s" $ft $Tprop [list $FontInfo($ft,$prop)]]
	    }
	}
	return [lsort $cl];
    }
}


namespace import ::msgcat::mcset
mcset de "Dismiss" "Abbrechen"
mcset de "bold" "Fett"
mcset de "Bold:" "Fett:"
mcset de "italic" "Kursiv"
mcset de "Italic:" "Kursiv:"
mcset de "Yes" "Ja"
mcset de "No" "Nein"
mcset de "underline" "Unterstrichen"
mcset de "Underline:" "Unterstrichen:"
mcset de "overstrike" "Durchgestrichen"
mcset de "Overstrike:" "Durchgestrichen:"
mcset de "size" "Gr\u00F6\u00DFe"
mcset de "Size:" "Gr\u00F6\u00DFe:"
mcset de "Font Selection" "Schriftart ausw\u00E4hlen"

# End of namespace fontsel

set FontList { \
MainFont\
HistoryListFont\
SilenceListFont\
BalloonHelpFont\
MenuFont\
UserPlainTextFont\
UserTechnicalTextFont\
CharacterEntryFont\
CharacterEntryLabelFont\
PanelCharacterEntryFont\
DiacriticFont\
AccentedLetterFont}

set FontInfo(family) code2000

set FontInfo(BalloonHelpFont,family) lucida
set FontInfo(BalloonHelpFont,size) 13

set FontInfo(MainFont,family) "courier"
set FontInfo(MainFont,size) 12
set FontInfo(MainFont,weight) bold

set FontInfo(HistoryListFont,family) "courier"
set FontInfo(HistoryListFont,size) 12

set FontInfo(SilenceListFont,family) lucida
set FontInfo(SilenceListFont,size) 11
set FontInfo(SilenceListFont,weight) bold
set FontInfo(UserTechnicalTextFont,family) "doulos sil"

set FontInfo(MenuFont,family) courier
set FontInfo(MenuFont,size) 12

set FontInfo(AccentedLetterFont,family)  "code2000"

set FontInfo(CharacterEntryLabelFont,family) bible
set FontInfo(CharacterEntryLabelFont,size) 13

set FontInfo(CharacterEntryFont,size) 14
set FontInfo(CharacterEntryFont,family) "doulos sil"

set FontInfo(PanelCharacterEntryFont,size) 13
set FontInfo(PanelCharacterEntryFont,family)  "doulos sil"

set FontInfo(AccentedLetterFont,size) 14
set FontInfo(DiacriticFont,size)  [expr $FontInfo(CharacterEntryFont,size) + 40];

#We package this in a procedure because in other programs in which the
#same system is used the use may change the locale in the middle of a session,
#in which case we need to obtain new translations. For this program we could
#just set these here once-and-for-all.
proc SetFontGlossHelpTranslations {} {
    global FontInfo;
    set FontInfo(BalloonHelpFont,gloss) [_ "balloon help"]
    set FontInfo(BalloonHelpFont,help) [_ "This font is used in help balloons."]
    set FontInfo(DiacriticFont,gloss) [_ "diacritics"]
    set FontInfo(DiacriticFont,help) \
	[_ "This font is used on the labels of the\ndiacritic insertion widget."]
    set FontInfo(CharacterEntryLabelFont,gloss) [_ "character entry labels"]
    set FontInfo(CharacterEntryLabelFont,help) \
	[_ "This font is used for the row and column\nlabels in character entry widgets."]
    set FontInfo(HistoryListFont,gloss) [_ "history list"]
    set FontInfo(HistoryListFont,help) [_ "This is the font used in the write history popup."]
    set FontInfo(MainFont,gloss) [_ "general"]
    set FontInfo(MainFont,help) [_ "This is the font used for most things."]
    set FontInfo(SilenceListFont,gloss) [_ "silence list entries"]
    set FontInfo(SilenceListFont,help) [_ "This font is used for the entries in the silence list."]
    set FontInfo(UserPlainTextFont,gloss) [_ "plain user text"]
    set FontInfo(UserPlainTextFont,help) [_ "This font is used for ordinary text entered\nby the user, such as file names."]
    set FontInfo(UserTechnicalTextFont,gloss) [_ "technical user text"]
    set FontInfo(UserTechnicalTextFont,help) [_ "This font is used for text entered by the\nuser that is likely to contain unusual\ncharacters, such as multigraph definitions."]
    set FontInfo(MenuFont,gloss) [_ "menu"]
    set FontInfo(MenuFont,help) [_ "This font is used for menu labels."]
    set FontInfo(CharacterEntryFont,gloss) [_ "character entry"]
    set FontInfo(CharacterEntryFont,help) \
	[_ "This font is used on the labels of\ncharacter insertion widgets."]
    set FontInfo(PanelCharacterEntryFont,gloss) [_ "character entry panel"]
    set FontInfo(PanelCharacterEntryFont,help) \
	[_ "This font is used on the labels of\n the character insertion panel."]
    set FontInfo(AccentedLetterFont,gloss) [_ "accented letters"]
    set FontInfo(AccentedLetterFont,help) \
	[_ "This font is used on the labels of the\naccented character insertion widget."]

}
SetFontGlossHelpTranslations;
#End of font stuff

proc ConfirmationDialog {WindowName TitleText MainText LeftText RightText CancelHelp} {
    global wret;
    global MainFont;
    
    toplevel $WindowName -borderwidth 4 -relief raised -bg $::ColorSpecs(ConfirmationDialogText,Background)
    wm title $WindowName "";
    label $WindowName.title -text $TitleText -font MainFont -bg $::ColorSpecs(ConfirmationDialogText,Background) -fg \#00FFFF
    label $WindowName.txt -width 50 -height 1 -font MainFont\
	-relief flat -anchor c -text $MainText -bg $::ColorSpecs(ConfirmationDialogMain,Background) -fg \#00FFFF
    button $WindowName.right   -text $RightText\
	-bg $::ColorSpecs(ConfirmationDialogButton,Background) -font MainFont -command {set ::wret 1}
    button $WindowName.left -text $LeftText\
	-bg $::ColorSpecs(ConfirmationDialogButton,Background) -font MainFont -command {set ::wret 0}
    button $WindowName.cancel -text [_ "Cancel"]\
	-bg $::ColorSpecs(ConfirmationDialogButton,Background) -font MainFont -command {set ::wret -1}
    grid $WindowName.title     -row 0 -column 0 -sticky ew -columnspan 3
    grid $WindowName.txt       -row 1 -column 0 -sticky ew -columnspan 3
    grid $WindowName.left      -row 2 -column 0
    grid $WindowName.right     -row 2 -column 2
    grid $WindowName.cancel    -row 2 -column 1
    balloonhelpd_for $WindowName.cancel $CancelHelp;
    tkwait variable wret;
    destroy $WindowName;
    return $wret;
}

proc GetHomeDir {} {
    set cwd [pwd];
    cd;
    set hd [pwd];
    cd $cwd;
    return $hd;
}

proc GetUser {} {
    if {[info exists ::env(USER)]} {
	return $::env(USER);
    } else {
	return "";
    }
}

proc ISO8601Stamp {} {
    return [clock format [clock seconds] -format "%Y-%m-%dT%H:%M:%S%z"]
}

set DefaultBrowser firefox
#set DefaultBrowser dillo
#For this purpose dillo is in many respects arguably the best choice because
#it is very lightweight and starts up fast. However, it isn't as fully
#featured as the others, and in particular, doesn't handle the full range of
#Unicode characters. You can set a different default browser here or
#in your init file.
set BrowserList [list firefox mozilla epiphany galeon konqueror dillo netscape opera]
set BrowserPIDS [list];

proc WebManual {} {
    global ManualPath;
    global ManualURL;

    if {![file exists $ManualPath]} {
	ShowMessage [format [_ "Manual not found at location %s"] $ManualPath];
	return ;
    }
    dmsg "Looking for manual at $ManualURL"
    ShowWebPage $ManualURL;
}

proc ShowWebPage {url} {
    global BrowserPIDS;

    if { $::tcl_platform(platform) == "macintosh"} {
	lappend BrowserPIDS [exec osascript -e "\"open location $url\""]
	return 
    }
    set BrowserFound 0;
    foreach Browser $::BrowserList {
	if { [string length [auto_execok $Browser]]} {
	    set BrowserFound 1;
	    break ;
	} else {
	    ShowMessage [format \
	     [_ "The browser %s is not available on this machine or not in your path."]\
		 $Browser];
	}
    }
    if {$BrowserFound} {
	ShowMessage [format [_ "Using browser %s."] $Browser];
	lappend BrowserPIDS [exec $Browser $url &]
    } else {
	ShowMessage [_ "No browser on the browser list was located."]
    }
}

LoadMessageCatalog;


proc DefineShortcut {command keyspec} {
    #Validate command
    if {![info exists ::CommandGlosses($command)]} {
	set msg [format [_ "%s is not a command for which a shortcut can be created"] $command]
	ShowMessage $msg
	puterr $msg
	return ;
    }
    #Validate keyspec
    if {![regexp -- {(<Control-[[:alpha:]]>|<KeyPress-(Down|Up|End|Home|Prior|Next|Left|Right|Menu|Multi_key|Delete|Insert)>|<KeyPress-F[1-9]>|<KeyPress-F1[0-2]>|<Control-KeyPress-F[1-9]>|<Control-KeyPress-F1[0-2]>)+} $keyspec]} {
	set msg [format [_ "%s is not a valid key specification"] $keyspec]
	ShowMessage $msg
	puterr $msg
	return ;
    }
    #Set
    set ::KeyBindings($keyspec) $command;
}

proc DescribeKeyBindings {{bl KeyBindings}} {
    global CommandGlosses;
    upvar \#0 $bl kb;
    if {[PopupDown DescribeKeyBindings] ==1} {return}
    set KeyNames [array names kb];
    set Entries [llength $KeyNames];
    if {$Entries <= 12} {
	set Lines $Entries;
    } else {
	set Lines 12
    }
    set po [CreateTextDisplay [_ "Key Bindings"] 88 $Lines]
    set ::PopupList(DescribeKeyBindings) $po;
    BindKeys $po
    #Invert array and get maximum length of gloss while we are at it.
    set MaxGlossLength 0;
    foreach KeySeq [array names kb] {
	set Gloss $CommandGlosses($kb($KeySeq));
	set GlossLength [string length $Gloss];
	if {$MaxGlossLength < $GlossLength} {set MaxGlossLength $GlossLength}
	set GlossToKeySeq($Gloss) $KeySeq;
    }
    #Now generate entries in alphabetical order of command glosses
    foreach Gloss [lsort [array names GlossToKeySeq]] {
	AppendToTextDisplay $po \
	    [format "%-*s\t%s\n" $MaxGlossLength $Gloss $GlossToKeySeq($Gloss)];
    }
}

proc PopupShortcutCommands {} {
    global PopupList;
    if {[PopupDown PopupShortcutCommands] ==1} {return}
    set CommandNames [array names ::CommandGlosses]
    set maxglosslen 0;
    set maxtotallen 0;
    foreach c $CommandNames {
	set GlossLength [string length $::CommandGlosses($c)]
	set CommandLength [string length $c]
	set TotalLength [expr $CommandLength + $GlossLength]
	if {$GlossLength > $maxglosslen} {
	    set maxglosslen $GlossLength;
	}
	if {$TotalLength > $maxtotallen} {
	    set maxtotallen $TotalLength;
	}
    }
    set ht [llength $CommandNames]
    if {$ht > 15} {set ht 15}
    set po [CreateTextDisplay [_ "Commands Available for Shortcuts"] [expr $maxtotallen + 9] $ht]
    BindKeys $po;
    set PopupList(PopupShortcutCommands) $po;
    AppendToTextDisplay $po [format "%-*s  Command\n\n" $maxglosslen "Description"];
    foreach n $CommandNames {
	lappend GlossList [list $::CommandGlosses($n) $n]
    }
    foreach pair [lsort -dictionary -index 0 $GlossList] {
	set gloss [lindex $pair 0]
	set command [lindex $pair 1]
	AppendToTextDisplay $po [format "%-*s  %s\n" $maxglosslen $gloss $command];
    }
}

array set KeyBindings {
    "<Control-a>"	ToggleAmplitudeMode
    "<Control-b>"	WindowBackwardSilence
    "<Control-h>"	ToggleBalloonHelp
    "<Control-k>"	DescribeKeyBindings
    "<Control-l>"	{RotateInfo left}
    "<Control-o>"       OverWritePreviousFile
    "<Control-p>"	PlayWindow
    "<Control-r>"	{RotateInfo right}
    "<Control-w>"       WriteWindow
    "<Control-f>"	WindowForwardSilence 
    "<KeyPress-Up>"	IncreaseVolume
    "<KeyPress-Down>"	DecreaseVolume 
};

#Any command to be made available for binding as a keyboard shortcut
#must be listed here. 
proc SetCommandGlosses {} {
    global CommandGlosses;

    set Pairs [list\
	   IncreaseVolume  "[_ "Increase playback volume"]"\
	   DecreaseVolume  "[_ "Decrease playback volume"]"\
           DescribeKeyBindings  "[_ "Describe keyboard shortcuts"]"\
	   ToggleAmplitudeMode  "[_ "Toggle amplitude mode"]"\
	   ToggleAutoPlay "[_ "Toggle Autoplay"]"\
	   ToggleBalloonHelp "[_ "Toggle balloon help"]"\
	   ToggleCloseups "[_ "Toggle the closeup windows."]"\
	   TogglePlayeBar "[_ "Toggle the buttons for audio playback."]"\
	   ToggleSegmentBar "[_ "Toggle the buttons for handling the segment list."]"\
	   ToggleSilenceBar "[_ "Toggle the buttons for motion by silence."]"\
	   ToggleDeltaBar "[_ "Toggle the buttons for motion by delta."]"\
	   ToggleWriteBar "[_ "Toggle the buttons for writing out windows."]"\
	   ToggleScrollbars "[_ "Toggle the scrollbars."]"\
	   ToggleZeroCrossingButtons "[_ "Toggle the zero crossing buttons."]"\
	   PlayFile         "[_ "Play the sound in the current file"]"\
	   PlayNeighborhood         "[_ "Play the sound in the neighborhood of the window."]"\
	   PlayWavebar         "[_ "Play the sound in the wavebar."]"\
	   PlayWindow         "[_ "Play the sound in the current window"]"\
	   StopPlay	"[_ "Stop audio playback"]"\
	   {RotateInfo left}  "[_ "Rotate the panel leftward"]"\
	   {RotateInfo right}  "[_ "Rotate the panel rightward"]"\
	   WindowForwardSilence         "[_ "Move current window to straddle next non-silent region"]"\
	   WindowBackwardSilence         "[_ "Move current window to straddle previous non-silent region"]"\
	   LeftEdgeBackwardSilence         "[_ "Move the left edge of the window to the right edge of the previous silence."]"\
	   RightEdgeBackwardSilence         "[_ "Move the right edge of the window to the right edge of the previous silence."]"\
	   LeftEdgeForewardSilence         "[_ "Move the left edge of the window to the left edge of the following silence."]"\
	   RightEdgeForewardSilence         "[_ "Move the right edge of the window to the left edge of the following silence."]"\
	   WindowForwardDelta         "[_ "Move current window forward by delta."]"\
	   WindowBackwardDelta         "[_ "Move current window backward by delta."]"\
	   LeftEdgeBackwardDelta         "[_ "Move the left edge of the window backward by delta."]"\
	   RightEdgeBackwardDelta       "[_ "Move the right edge of the window backward by delta."]"\
	   LeftEdgeForewardDelta         "[_ "Move the left edge of the window forward by delta."]"\
	   RightEdgeForewardDelta         "[_ "Move the right edge of the window forward by detla.."]"\
	   WriteWindow         "[_ "Write the sound in the current window to a file"]"\
	   OverWritePreviousFile         "[_ "Write the sound in the current window to the previously written file"]"\
	   LoadSoundFile       "[_ "Read and display a sound file."]"\
	   ExecutePause "[_ "Read and display a sound file."]"\
	   fontsel::CreateFontControlPanel  "[_ "Popup the font control panel."]"\
		   ToggleCharEntryByCode  "[_ "Toggle the popup for entering characters by their Unicode code."]"]
    array set CommandGlosses $Pairs;
}

proc BindKeys {w {bl KeyBindings}} {
    upvar \#0 $bl kb;
    foreach KeySeq [array names kb] {
	bind $w $KeySeq $kb($KeySeq);
    }
}

proc new_dialog_create {class {win "auto"}} {
    if {$win == "auto"} {
        set count 0
        set win ".ndialog[incr count]"
        while {[winfo exists $win]} {
            set win ".ndialog[incr count]"
        }
    }
    toplevel $win -class $class;
    frame $win.info
    pack $win.info -expand yes -fill both -padx 4 -pady 4
    wm title $win $class
    wm group $win .

    after idle [format {
        update idletasks
        wm minsize %s [winfo reqwidth %s] [winfo reqheight %s]
    } $win $win $win]

    return $win
}

# The following code is taken from the Efftcl library by Mark Harrison and
# Michael McLennan, copyrighted by Mark Harrison and Lucent Technologies, available
# from http://www.awprofessional.com/content/images/0201634740/sourcecode/efftcl.zip.
# As the authors explicitly give permission to "steal the code for your own applications"
# the relevant portions are included here so as not to require the user to install
# to install the library. If you install the library, remove the following and
# uncomment the line "#package require Efftcl" by deleting the crosshatch.

#  Effective Tcl/Tk Programming
#    Mark Harrison, DSC Communications Corp.
#    Michael McLennan, Bell Labs Innovations for Lucent Technologies
#    Addison-Wesley Professional Computing Series
# ======================================================================
#  Copyright (c) 1996-1997  Lucent Technologies Inc. and Mark Harrison
# ======================================================================

proc dialog_create {class {win "auto"}} {
    if {$win == "auto"} {
        set count 0
        set win ".dialog[incr count]"
        while {[winfo exists $win]} {
            set win ".dialog[incr count]"
        }
    }
    toplevel $win -class $class -background \#2200DD;

    frame $win.info
    pack $win.info -expand yes -fill both -padx 4 -pady 4
    frame $win.sep -height 2 -borderwidth 1 -relief sunken
    pack $win.sep -fill x -pady 4
    frame $win.controls
    pack $win.controls -fill x -padx 4 -pady 1

    wm title $win $class
    wm group $win .

    after idle [format {
        update idletasks
        wm minsize %s [winfo reqwidth %s] [winfo reqheight %s]
    } $win $win $win]

    return $win
}

proc dialog_info {win} {
    return "$win.info"
}

proc dialog_controls {win} {
    return "$win.controls"
}

proc dialog_wait {win varName} {
    dialog_safeguard $win

    set x [expr [winfo rootx .]+50]
    set y [expr [winfo rooty .]+50]
    wm geometry $win "+$x+$y"

    wm deiconify $win
    grab set $win

    vwait $varName

    grab release $win
    wm withdraw $win
}

bind modalDialog <ButtonPress> {
    wm deiconify %W
    raise %W
}
proc dialog_safeguard {win} {
    if {[lsearch [bindtags $win] modalDialog] < 0} {
        bindtags $win [linsert [bindtags $win] 0 modalDialog]
    }
}

#This provides an addition to the default methods of the Scrollbar
#widget. The default method, bound to <B1>, #increments or decrements
#the value by the resolution, by default 1. If you want a larger
#increment, you can use a larger resolution, but sometimes it is
#convenient to have a finer resolutio available while also being
#able to move in larger increments. A solution is to bind to
#<B3>, or some other event if you wish, a larger movement.
#This procedure moves by the specified multiplier k times
#the resolution of the Scrollbar. 

proc ScrollbarMoveBigIncrement {w f x y} {
    set part [$w identify $x $y]
    switch -exact -- $part {
	trough1 {
	    set dir -1;
	}
	arrow1 {
	    set dir -1;
	}
	trough2 {
	    set dir  1;
	}
	arrow2 {
	    set dir  1;
	}
	default {
	    return ;
	}
    }
    set CurrentFraction [lindex [$w get] 0]
    set NewFraction [expr $CurrentFraction + ($dir * $f)]
    eval [concat [$w cget -command] moveto $NewFraction]
}

proc CreateTextDisplay {title width height {bg "\#000000"} {fg "\#000000"} } {
    if {[string equal $bg $fg]} {
	set abg $::ColorSpecs(InfoPopup,Background)
	set afg $::ColorSpecs(InfoPopup,Foreground)
    } else {
	set abg $bg;
	set afg $fg;
    }
    set top [new_dialog_create Textdisplay]
    wm title $top $title
    set info [dialog_info $top]
    set sb [scrollbar $info.sbar -command "$info.text yview" ]
    lappend ::ScrollbarList  $sb;
    set ::PackCommand($sb) [list pack $info.sbar -side right -fill y]
    pack $info.sbar -side right -fill y
    bind $info.sbar <<B3>> "ScrollbarMoveBigIncrement $info.sbar 0.10 %x %y"
    text $info.text -height $height -width $width -font MainFont -wrap word \
	-yscrollcommand "$info.sbar set"  -exportselection 1 \
	-background $abg -foreground $afg
    pack $info.text -side left -expand yes -fill both
    $info.text configure -state disabled
    return $top
}

proc AppendToTextDisplay {top mesg {col 0}} {
    set info [dialog_info $top]
    $info.text configure -state normal
    if {$col > 0} {
	$info.text configure -tabs [list $col]
    }
    $info.text insert end $mesg
    $info.text configure -state disabled
}

set linkNum 0;
proc AppendLinkToTextDisplay {top mesg LinkCode} {
    global linkNum
    set info [dialog_info $top]
    $info.text configure -state normal
    set tag "link[incr linkNum]"
    bind $info.text <ButtonPress> break
    $info.text insert end $mesg [list body $tag]
    $info.text tag configure $tag -foreground red -underline 1
    $info.text tag bind $tag <Enter> \
        "$info.text tag configure $tag -foreground blue"
    $info.text tag bind $tag <Leave> \
        "$info.text tag configure $tag -foreground red"
    $info.text tag bind $tag <ButtonPress> \
        "$LinkCode"
    $info.text configure -state disabled
}

#Set up balloon help

proc SetupBalloonHelp {} {
    global bhInfo

    option add *Balloonhelp*background white widgetDefault
    option add *Balloonhelp*foreground black widgetDefault
    option add *Balloonhelpinfo.wrapLength 3i  widgetDefault
    option add *Balloonhelp.info.justify left widgetDefault
    toplevel .balloonhelp -class Balloonhelp -background black -borderwidth 1 -relief flat
    label .balloonhelp.info -font BalloonHelpFont;
    pack .balloonhelp.info -side left -fill y
    wm overrideredirect .balloonhelp 1
    wm withdraw .balloonhelp
    set bhInfo(active) 1
    array set OverlapP {}
}

proc balloonhelp_control {state} {
     global bhInfo
     if {$state} {
          set bhInfo(active) 1
     } else {
	balloonhelp_cancel
	set bhInfo(active) 0
     }
}

proc balloonhelp_for {win mesg} {
    global bhInfo
    set bhInfo($win) $mesg
    set ::bhOverlapP($win) 1; 
    bind $win <Enter> {+balloonhelp_pending %W}
    bind $win <Leave> {+balloonhelp_cancel}
}

proc balloonhelpd_for {win mesg} {
    global bhInfo
    set ::bhOverlapP($win,d) 0;
    set bhInfo($win,d) $mesg
    bind $win <Enter> {+balloonhelp_show %W 1}
    bind $win <Leave> {+wm withdraw .balloonhelp}
}

proc balloonhelp_pending {win} {
     global bhInfo
     balloonhelp_cancel
    if {[info exist bhInfo($win,d)]} {
	set PendTime 2000;
    } else {
	set PendTime 1000;
    }
    set bhInfo(pending) [after $PendTime [list balloonhelp_show $win 0]]
}

proc balloonhelp_cancel {} {
    global bhInfo
    if { [info exists bhInfo(pending)]} {
	after cancel $bhInfo(pending)
	unset bhInfo(pending)
    }
    wm withdraw .balloonhelp
}

proc balloonhelp_show {win d} {
    global bhInfo;
    global bhOverlapP;
    if {$d} {
	set Overlap -10;
	set Text $bhInfo($win,d);
    } else { 
	set Overlap 25;
	set Text $bhInfo($win);
    }

    if {[winfo exists $win]} {
	if {$bhInfo(active)} {
	    .balloonhelp.info configure -text $Text;
	    #Set abcissa
	    set MaxStringWidth 0;
	    if {$d} {
		set Text $bhInfo($win,d)
	    } else {
		set Text $bhInfo($win)
	    }
	    foreach line [split $Text "\n"] {
		set StringWidth [font measure BalloonHelpFont -displayof .balloonhelp.info $line]
		if {$StringWidth > $MaxStringWidth} {
		    set MaxStringWidth $StringWidth;
		}
	    }
	    set ScreenWidth [winfo screenwidth $win]
	    set Width [winfo width $win];
	    set LeftEdge  [winfo rootx $win];
	    set RightEdge [expr $LeftEdge + $Width];
	    if {$ScreenWidth - $RightEdge < $MaxStringWidth} { 
		if {$LeftEdge > $MaxStringWidth} {
		    set x [expr $LeftEdge - $MaxStringWidth + $Overlap];
		} else {
		    if {$ScreenWidth - $MaxStringWidth > 0} {
			set x [expr $RightEdge - $MaxStringWidth];
		    } else {
			set x [expr $ScreenWidth - $MaxStringWidth];
		    }
		}
	    } else {
		set x [expr $RightEdge - $Overlap];
	    }
	    #Set ordinate
	    set Height [winfo height $win];
	    set TopEdge [winfo rooty $win];
#	    set y [expr $TopEdge + ($Height/2)];
	    set y [expr $TopEdge + int(($Height/1.25))];
	    wm geometry .balloonhelp +$x+$y
	    wm deiconify .balloonhelp
	    raise .balloonhelp
	}
    }
    if {[info exist bhInfo(pending)]} {
	unset bhInfo(pending)
    }
}

proc ControlBalloonHelp {} {
    if {$::BalloonHelpToggle} {
	balloonhelp_control 1
#	ShowMessage [_ "Balloon Help Enabled"];
    } else {
	balloonhelp_control 0
#	ShowMessage [_ "Irritating Balloon Help Disabled"];
    }
}

#Character entry code begins here
#Set this to the path to character entry menu
set CEM .menubar.charentry
#Set the default insertion target here.
set InsertionTarget .info.notes.txt
#Anywhere that you want to insert characters, set up a binding like this:
#bind WIDGETPATHNAME <FocusIn> {SetInsertionTargets WIDGETPATHNAME}

proc BindInsertionTarget {v} {
    bind $v <FocusIn> "+SetInsertionTargets $v"
}


proc SetInsertionTargets {tgt} {
    set ::InsertionTarget $tgt;
    set ::CharByCodeInsertionTarget $tgt;
}

proc SetCharacterEntryOptions {} {
    global ColorSpecs

    option add *ipaec.Button.font CharacterEntryFont 100
    option add *ipaec.Label.background  $ColorSpecs(CharacterEntry,Background)
    option add *ipaec.Button.background $ColorSpecs(CharacterEntry,Background)
    option add *ipaec.Button.foreground $ColorSpecs(CharacterEntry,Foreground)
    option add *ipaec.Label.relief raised

    option add *ipaev.Button.font CharacterEntryFont 100
    option add *ipaev.Label.background  $ColorSpecs(CharacterEntry,Background)
    option add *ipaev.Button.background $ColorSpecs(CharacterEntry,Background)
    option add *ipaev.Button.foreground $ColorSpecs(CharacterEntry,Foreground)
    option add *ipaev.Label.relief raised

    option add *ipaea.Button.font AccentedLetterFont 100
    option add *ipaea.Label.background  "\#E0E0E0"
    option add *ipaea.Button.background "\#FFFFFF"
    option add *ipaea.Button.foreground "\#000000"
    option add *ipaea.Label.relief raised

    option add *ipaed.Button.font DiacriticFont 100
    option add *ipaed.Button.background "\#E0E0FF"
    option add *ipaed.Label.background "\#E0E0E0"
    option add *ipaed.Button.foreground "\#000000"
    option add *ipaed.Label.relief raised

    option add *ipae*.*Label.font CharacterEntryLabelFont 100
    option add *ipaec.*Button.font CharacterEntryFont 100
}

set CustomCEMEntries 0;
namespace eval ipaentry {
    variable IPAECColumnLabelList [list];
    variable IPAECRowLabelList [list];
    variable IPAEVColumnLabelList [list];
    variable IPAEVRowLabelList [list];
    variable DisplayConsonantChartColumnLabelsP 1
    variable DisplayConsonantChartRowLabelsP 1
    variable DisplayVowelChartColumnLabelsP 1
    variable DisplayVowelChartRowLabelsP 1
    namespace export SetDisplayConsonantChartColumnLabelsP
    namespace export SetDisplayConsonantChartRowLabelsP
    namespace export SetDisplayVowelChartColumnLabelsP
    namespace export SetDisplayVowelChartRowLabelsP

    set row 0;
    variable poa $row;
    incr row;
    variable vlstop $row;
    incr row;
    variable vdstop $row;
    incr row;
    variable vdimplosive $row;
    incr row;
    variable click $row;
    incr row;
    variable nasal  $row;
    incr row;
    variable trill $row;
    incr row;
    variable tap $row;
    incr row;
    variable vlfric $row;
    incr row;
    variable vdfric $row;
    incr row;
    variable vlaffric $row;
    incr row;
    variable vdaffric $row;
    incr row;
    variable approx $row;
    incr row; 
    variable latapprox $row;
    variable lastrow $row;

    set col 0;
    variable manner $col; 
    incr col;
    variable labial $col; 
    incr col;
    variable labiodental $col; 
    incr col;
    variable dental $col; 
    incr col;
    variable alveolar $col;
    incr col;
    variable postalveolar $col; 
    incr col;
    variable retroflex $col; 
    incr col;
    variable palatal $col; 
    incr col;
    variable velar $col; 
    incr col;
    variable uvular $col; 
    incr col;
    variable pharyngeal $col; 
    incr col;
    variable epiglottal $col; 
    incr col;
    variable glottal $col;
    variable lastcolumn $col;

    proc cfesh {} {
	variable vlfric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vlfric $postalveolar] configure -text "\u0161"];
    }
    proc cresh {} {
	variable vlfric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vlfric $postalveolar] configure -text "\u0283"];
    }

    proc cfeshr {} {
	variable vlfric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlfric $retroflex] configure -text "\u1E63"];
    }
    proc creshr {} {
	variable vlfric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlfric $retroflex] configure -text "\u0282"];
    }

    proc cryod {} {
	variable approx
	variable palatal
	eval [list [format ".ipaec.r%dc%d" $approx $palatal] configure -text "j"];
    }

    proc cfyod {} {
	variable approx
	variable palatal
	eval [list [format ".ipaec.r%dc%d" $approx $palatal] configure -text "y"];
    }

    proc crny {} {
	variable nasal
	variable palatal
	eval [list [format ".ipaec.r%dc%d" $nasal $palatal] configure -text "\u0272"];
    }
    proc cfny {} {
	variable nasal
	variable palatal
	eval [list [format ".ipaec.r%dc%d" $nasal $palatal] configure -text "\u00F1"];
    }

    proc crch {} {
	variable vlaffric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vlaffric $postalveolar] configure -text "t\u0283"];
    }
    proc cfch {} {
	variable vlaffric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vlaffric $postalveolar] configure -text "\u010D"];
    }

    proc crchr {} {
	variable vlaffric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlaffric $retroflex] configure -text "\u0288\u0282"];
    }

    proc cfchr {} {
	variable vlaffric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlaffric $retroflex] configure -text "\u1E6D\u1E63"];
    }


    proc crdj {} {
	eval [list [format ".ipaec.r%dc%d" $ipaentry::vdaffric $ipaentry::postalveolar] configure -text "d\u0292"];
    }

    proc cfdj {} {
	eval [list [format ".ipaec.r%dc%d" $ipaentry::vdaffric $ipaentry::postalveolar] configure -text "\u01C6"];
    }

    proc crdjr {} {
	eval [list [format ".ipaec.r%dc%d" $ipaentry::vdaffric $ipaentry::retroflex] configure -text "\u0256\u0290"];
    }

    proc cfdjr {} {
	eval [list [format ".ipaec.r%dc%d" $ipaentry::vdaffric $ipaentry::retroflex] configure -text "\u1E0D\u1E93"];
    }

    proc crzh {} {
	variable vdfric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vdfric $postalveolar] configure -text "\u0292"];
    }
    proc cfzh {} {
	variable vdfric
	variable postalveolar
	eval [list [format ".ipaec.r%dc%d" $vdfric $postalveolar] configure -text "\u017E"];
    }

    proc crtr {} {
	variable vlstop
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlstop $retroflex] configure -text "\u0288"];
    }
    proc cftr {} {
	variable vlstop
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vlstop $retroflex] configure -text "\u1E6D"];
    }

    proc crdr {} {
	variable vdstop
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vdstop $retroflex] configure -text "\u0256"];
    }
    proc cfdr {} {
	variable vdstop
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vdstop $retroflex] configure -text "\u1E0D"];
    }


    proc crnr {} {
	variable nasal
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $nasal $retroflex] configure -text "\u0273"];
    }
    proc cfnr {} {
	variable nasal
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $nasal $retroflex] configure -text "\u1E47"];
    }


    proc crzhr {} {
	variable vdfric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vdfric $retroflex] configure -text "\u0290"];
    }
    proc cfzhr {} {
	variable vdfric
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $vdfric $retroflex] configure -text "\u1E93"];
    }

    proc crflapr {} {
	variable tap;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $tap $retroflex] configure -text "\u027D"];
    }
    proc cfflapr {} {
	variable tap;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $tap $retroflex] configure -text "\u1E5B"];
    }

    proc crlr {} {
	variable latapprox;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $latapprox $retroflex] configure -text "\u026D"];
    }
    proc cflr {} {
	variable latapprox;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $latapprox $retroflex] configure -text "\u1E37"];
    }

    proc crrr {} {
	variable approx;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $approx $retroflex] configure -text "\u027B"];
    }
    proc cfrr {} {
	variable approx;
	variable retroflex
	eval [list [format ".ipaec.r%dc%d" $approx $retroflex] configure -text "\u1E5B"];
    }

    proc bhcham {w} {
	balloonhelp_for $w "The standard IPA character is shown by default. When the mouse\npointer is over the button, the \"North American\" variant is shown.\nRight click to insert the variant."
    }

    proc bhsp {w} {
	balloonhelp_for $w "The characters below and to the right are characters\nthat do not fit neatly into the chart."
    }

    proc UnpackConsonantColumnLabels {} {
	variable IPAECColumnLabelList;
	foreach l $IPAECColumnLabelList {
	    grid forget $l;
	}
    }

    proc UnpackConsonantRowLabels {} {
	variable IPAECRowLabelList;
	foreach l $IPAECRowLabelList {
	    grid forget $l;
	}
    }

    proc UnpackVowelColumnLabels {} {
	variable IPAEVColumnLabelList;
	foreach l $IPAEVColumnLabelList {
	    grid forget $l;
	}
    }

    proc UnpackVowelRowLabels {} {
	variable IPAEVRowLabelList;
	foreach l $IPAEVRowLabelList {
	    grid forget $l;
	}
    }

    proc SetDisplayConsonantChartColumnLabelsP {args} {
	variable DisplayConsonantChartColumnLabelsP
	if {[llength $args]} {
	    set DisplayConsonantChartColumnLabelsP [Boolean [lindex $args 0]];
	} else {
	    set DisplayConsonantChartColumnLabelsP;
	}
    }

    proc SetDisplayConsonantChartRowLabelsP {args} {
	variable DisplayConsonantChartRowLabelsP
	if {[llength $args]} {
	    set DisplayConsonantChartRowLabelsP [Boolean [lindex $args 0]] 
	} else {
	    set DisplayConsonantChartRowLabelsP;
	}
    }

    proc SetDisplayVowelChartColumnLabelsP {args} {
	variable DisplayVowelChartColumnLabelsP
	if {[llength $args]} {
	    set DisplayVowelChartColumnLabelsP [Boolean [lindex $args 0]];
	} else {
	    set DisplayVowelChartColumnLabelsP;
	}
    }

    proc SetDisplayVowelChartRowLabelsP {args} {
	variable DisplayVowelChartRowLabelsP
	if {[llength $args]} {
	    set DisplayVowelChartRowLabelsP [Boolean [lindex $args 0]];
	} else {
	    set DisplayVowelChartRowLabelsP;
	}
    }

    proc PopupIPAEntryC {} {
	variable poa
	variable vlstop 
	variable vdstop
	variable vdimplosive 
	variable click 
	variable nasal  
	variable trill 
	variable tap 
	variable vlfric 
	variable vdfric 
	variable vlaffric 
	variable vdaffric 
	variable approx 
	variable latapprox
	variable lastrow

	variable manner 
	variable labial 
	variable labiodental 
	variable dental 
	variable alveolar 
	variable postalveolar 
	variable retroflex 
	variable palatal 
	variable velar 
	variable uvular 
	variable pharyngeal 
	variable epiglottal 
	variable glottal
	variable lastcolumn

	variable IPAECColumnLabelList;
	variable IPAECRowLabelList;
	variable DisplayConsonantChartColumnLabelsP
	variable DisplayConsonantChartRowLabelsP

	set IPAECColumnLabelList [list];
	set IPAECRowLabelList [list];
	
	set xp 2;
	set yp 3;
	set spcolor 	\#c46276;
	toplevel .ipaec -borderwidth 3 -class CharEntry
	wm title .ipaec [_ "Consonant Symbols"]
	BindKeys .ipaec;
	set DownMsg [_ "Display IPA Consonant Chart"];
	set UpMsg   [_ "Remove IPA Consonant Chart"];
	bind .ipaec <Destroy> \
	    "set ::IPACIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPACIndex -label \"$DownMsg\""
	bind .ipaec <Unmap> \
	    "set ::IPACIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPACIndex -label \"$DownMsg\""
	bind .ipaec <Map> \
	    "set ::IPACIsDisplayedP 1;$::m.charentry entryconfigure $::ToggleIPACIndex -label \"$UpMsg\""
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $poa] \
	  -text [_ "IPA\nConsonants"]  -padx 5 -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $labial] \
	    -text [_ "labial"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $labiodental] \
	    -text [_ "labio\ndental"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $dental] \
	    -text [_ "dental"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $alveolar] \
	    -text [_ "alveolar"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $postalveolar] \
	    -text [_ "post\nalveolar"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $retroflex] \
	    -text [_ "retro\nflex"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $palatal] \
	    -text [_ "palatal"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $velar] \
	    -text [_ "velar"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $uvular] \
	    -text [_ "uvular"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $pharyngeal] \
	    -text [_ "pharyn\ngeal"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $epiglottal] \
	    -text [_ "epi\nglottal"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAECColumnLabelList [label [format ".ipaec.r%dc%d" $manner $glottal] \
	    -text [_ "glottal"]   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]

	#Voiceless oral stops
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vlstop $poa] \
	       -text [_ "voiceless stops"] -anchor w  -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list p]}
	set bn [format ".ipaec.r%dc%d"  $vlstop $labial]
	button $bn  -text "p" -padx $xp -pady $yp -command  $cmd \
	    -fg $::ColorSpecs(UserTextEntry,Foreground); #debug
	balloonhelpd_for $bn [_ "voiceless labial stop"]

	label [format ".ipaec.r%dc%d" $vlstop $labiodental] \
	    -text " " -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list t\u032A]}
	set bn [format ".ipaec.r%dc%d"  $vlstop $dental]
	button $bn  -text "t\u032A"   -padx $xp -pady $yp -command  $cmd
	balloonhelpd_for $bn [_ "voiceless dental stop"]

	set cmd {$::InsertionTarget insert insert [list t]}
	set bn [format ".ipaec.r%dc%d"  $vlstop $alveolar]
	button $bn -text "t"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless alveolar stop"]

	label [format ".ipaec.r%dc%d"  $vlstop $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0288]}
	set bn [format ".ipaec.r%dc%d"  $vlstop $retroflex]
	button $bn  -text \u0288   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E6D]}
	bind $bn <Enter> {ipaentry::cftr}
	bind $bn <Leave> {ipaentry::crtr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiceless retroflex stop"]

	set cmd {$::InsertionTarget insert insert [list c]}
	set bn [format ".ipaec.r%dc%d"  $vlstop $palatal]
	button $bn -text "c"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless palatal stop"]

	set cmd {$::InsertionTarget insert insert [list k]}
	set bn [format ".ipaec.r%dc%d" $vlstop $velar]
	button $bn -text "k" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless velar stop"]

	set cmd {$::InsertionTarget insert insert [list q]}
	set bn [format ".ipaec.r%dc%d" $vlstop $uvular]
	button $bn  -text "q"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless uvular stop"]

	label [format ".ipaec.r%dc%d" $vlstop $pharyngeal] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $vlstop $epiglottal] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0294]}
	set bn [format ".ipaec.r%dc%d" $vlstop $glottal]
	button $bn -text \u0294   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless glottal stop"]

	#Voiced oral stops
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vdstop $poa] \
	       -text [_ "voiced stops"] -anchor w   -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list b]}
	set bn [format ".ipaec.r%dc%d" $vdstop $labial]
	button $bn -text "b"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced bilabial stop"]

	label [format ".ipaec.r%dc%d" $vdstop $labiodental] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list d\u032A]}
	set bn [format ".ipaec.r%dc%d" $vdstop $dental]
	button $bn -text "d\u032A"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced dental stop"]

	set cmd {$::InsertionTarget insert insert [list d]}
	set bn [format ".ipaec.r%dc%d" $vdstop $alveolar]
	button  $bn -text "d"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced alveolar stop"]

	label [format ".ipaec.r%dc%d"  $vdstop $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0256]}
	set bn [format ".ipaec.r%dc%d"  $vdstop $retroflex]
	button $bn  -text \u0256   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E0D]}
	bind $bn <Enter> {ipaentry::cfdr}
	bind $bn <Leave> {ipaentry::crdr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiced retroflex stop"]

	set cmd {$::InsertionTarget insert insert [list \u025F]}
	set bn [format ".ipaec.r%dc%d" $vdstop $palatal]
	button $bn -text \u025F   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced palatal stop"]


	set cmd {$::InsertionTarget insert insert [list g]}
	set bn [format ".ipaec.r%dc%d" $vdstop $velar]
	button $bn -text "g"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced velar stop"]

	set cmd {$::InsertionTarget insert insert [list \u0262]}
	set bn [format ".ipaec.r%dc%d" $vdstop $uvular]
	button $bn -text \u0262  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced uvular stop"]

	label [format ".ipaec.r%dc%d" $vdstop $pharyngeal] -text " "  -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u02A1]}
	set bn [format ".ipaec.r%dc%d" $vdstop $epiglottal]
	button $bn -text \u02A1  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced epiglottal stop"]

	label [format ".ipaec.r%dc%d" $vdstop $glottal] -text " "  -padx $xp -pady $yp

	#Nasals
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $nasal $poa] \
	       -text [_ "nasals"] -anchor w -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list m]}
	set bn [format ".ipaec.r%dc%d" $nasal $labial]
	button $bn -text "m" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "bilabial nasal"]

	set cmd {$::InsertionTarget insert insert [list \u0271]}
	set bn [format ".ipaec.r%dc%d" $nasal $labiodental]
	button $bn -text \u0271   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "labiodental nasal"]

	set cmd {$::InsertionTarget insert insert [list n\u032A]}
	set bn [format ".ipaec.r%dc%d" $nasal $dental]
	button $bn -text n\u032A   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "dental nasal"]

	set cmd {$::InsertionTarget insert insert [list n]}
	set bn [format ".ipaec.r%dc%d" $nasal $alveolar]
	button $bn -text "n"      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "alveolar nasal"]

	label [format ".ipaec.r%dc%d"  $nasal $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0273]}
	set bn [format ".ipaec.r%dc%d"  $nasal $retroflex]
	button $bn  -text \u0273   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E47]}
	bind $bn <Enter> {ipaentry::cfnr}
	bind $bn <Leave> {ipaentry::crnr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "retroflex nasal"]

	set cmd {$::InsertionTarget insert insert [list \u0272]}
	set bn [format ".ipaec.r%dc%d" $nasal $palatal]
	button $bn  -text \u0272    -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u00F1]}
	bind $bn <Enter> {ipaentry::cfny}
	bind $bn <Leave> {ipaentry::crny}
	bhcham $bn;
	balloonhelpd_for $bn [_ "palatal nasal"]

	set cmd {$::InsertionTarget insert insert [list \u014B]}
	set bn [format ".ipaec.r%dc%d" $nasal $velar]
	button $bn -text \u014B    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "velar nasal"]

	set cmd {$::InsertionTarget insert insert [list \u0274]}
	set bn [format ".ipaec.r%dc%d" $nasal $uvular]
	button $bn -text \u0274    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "uvular nasal"]

	label [format ".ipaec.r%dc%d" $nasal $pharyngeal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $nasal $epiglottal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $nasal $glottal] -text " "    -padx $xp -pady $yp

	#Voiceless fricatives
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vlfric $poa] \
	       -text [_ "voiceless fricatives"] -anchor w  -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list \u03C6]}
	set bn [format ".ipaec.r%dc%d" $vlfric $labial]
	button $bn -text \u03C6  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless bilabial fricative"]

	set cmd {$::InsertionTarget insert insert [list f]}
	set bn [format ".ipaec.r%dc%d" $vlfric $labiodental]
	button $bn  -text "f"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless labiodental fricative"]

	set cmd {$::InsertionTarget insert insert [list \u03B8]}
	set bn [format ".ipaec.r%dc%d" $vlfric $dental]
	button $bn -text \u03B8   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless dental fricative"]

	set cmd {$::InsertionTarget insert insert [list "s"]}
	set bn [format ".ipaec.r%dc%d" $vlfric $alveolar]
	button $bn -text "s"  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless alveolar fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0283]}
	set bn [format ".ipaec.r%dc%d" $vlfric $postalveolar];
	button $bn -text \u0283   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u0161]}
	bind $bn <Enter> {ipaentry::cfesh}
	bind $bn <Leave> {ipaentry::cresh}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiceless postalveolar fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0282]}
	set bn [format ".ipaec.r%dc%d" $vlfric $retroflex];
	button $bn -text \u0282   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E63]}
	bind $bn <Enter> {ipaentry::cfeshr}
	bind $bn <Leave> {ipaentry::creshr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiceless retroflex fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0255]}
	set bn [format ".ipaec.r%dc%d" $vlfric $palatal]
	button $bn -text \u0255  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless palatal fricative"]

	set cmd {$::InsertionTarget insert insert [list "x"]}
	set bn [format ".ipaec.r%dc%d" $vlfric $velar]
	button $bn -text "x" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless velar fricative"]

	set cmd {$::InsertionTarget insert insert [list "\u03C7"]}
	set bn [format ".ipaec.r%dc%d" $vlfric $uvular]
	button $bn -text "\u03C7"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless uvular fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0127]}
	set bn [format ".ipaec.r%dc%d" $vlfric $pharyngeal]
	button $bn -text \u0127 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless pharyngeal fricative"]

	set cmd {$::InsertionTarget insert insert [list \u029C]}
	set bn [format ".ipaec.r%dc%d" $vlfric $epiglottal]
	button $bn -text \u029C   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless epiglottal fricative"]

	set cmd {$::InsertionTarget insert insert [list "h"]}
	set bn [format ".ipaec.r%dc%d" $vlfric $glottal]
	button $bn -text "h" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless glottal fricative"]

	#Voiced fricatives
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vdfric $poa] \
	       -text [_ "voiced fricatives"] -anchor w \
	       -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list \u03B2]}
	set bn [format ".ipaec.r%dc%d" $vdfric $labial]
	button $bn -text \u03B2  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced bilabial fricative"]

	set cmd {$::InsertionTarget insert insert [list v]}
	set bn [format ".ipaec.r%dc%d" $vdfric $labiodental]
	button $bn -text "v" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced labiodental fricative"]

	set cmd {$::InsertionTarget insert insert [list "\u00F0"]}
	set bn [format ".ipaec.r%dc%d" $vdfric $dental]
	button $bn -text "\u00F0"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced dental fricative"]

	set cmd {$::InsertionTarget insert insert [list "z"]}
	set bn [format ".ipaec.r%dc%d" $vdfric $alveolar]
	button $bn -text "z"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced alveolar fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0292]}
	set bn [format ".ipaec.r%dc%d" $vdfric $postalveolar]
	button $bn -text \u0292  -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u017E]}
	bind $bn <Enter> {ipaentry::cfzh}
	bind $bn <Leave> {ipaentry::crzh}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiced postalveolar fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0290]}
	set bn [format ".ipaec.r%dc%d" $vdfric $retroflex]
	button $bn -text \u0290   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E93]}
	bind $bn <Enter> {ipaentry::cfzhr}
	bind $bn <Leave> {ipaentry::crzhr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiced retroflex fricative"]

	set cmd {$::InsertionTarget insert insert [list \u029D]}
	set bn [format ".ipaec.r%dc%d" $vdfric $palatal]
	button $bn -text  \u029D  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced palatal fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0263]}
	set bn [format ".ipaec.r%dc%d" $vdfric $velar]
	button $bn -text \u0263  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced velar fricative"]

	set cmd {$::InsertionTarget insert insert [list "\u0281"]}
	set bn [format ".ipaec.r%dc%d" $vdfric $uvular]
	button $bn -text "\u0281" -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced uvular fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0295]}
	set bn [format ".ipaec.r%dc%d" $vdfric $pharyngeal]
	button $bn -text \u0295 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced pharyngeal fricative"]

	set cmd {$::InsertionTarget insert insert [list \u02A2]}
	set bn [format ".ipaec.r%dc%d" $vdfric $epiglottal] 
	button $bn -text \u02A2    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced epiglottal fricative"]

	set cmd {$::InsertionTarget insert insert [list \u0266]}
	set bn [format ".ipaec.r%dc%d" $vdfric $glottal]
	button $bn -text \u0266    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced glottal fricative"]

	#trills
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $trill $poa] \
	       -text [_ "trills"] -anchor w   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list \u0299]}
	set bn [format ".ipaec.r%dc%d" $trill $labial]
	button  $bn -text \u0299      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "bilabial trill"]

	label [format ".ipaec.r%dc%d" $trill $labiodental] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $trill $dental] -text " "   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list r]}
	set bn [format ".ipaec.r%dc%d" $trill $alveolar]
	button $bn -text "r"      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "alveolar trill"]

	label [format ".ipaec.r%dc%d"  $trill $postalveolar] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d"  $trill $retroflex] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $trill $palatal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $trill $velar] -text " "    -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0280]}
	set bn [format ".ipaec.r%dc%d" $trill $uvular]
	button $bn -text \u0280    -padx $xp -pady $yp
	balloonhelpd_for $bn [_ "uvular trill"]

	label [format ".ipaec.r%dc%d" $trill $pharyngeal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $trill $epiglottal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $trill $glottal] -text " "    -padx $xp -pady $yp

	#taps and flaps
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $tap $poa] \
	       -text [_ "taps/flaps"] -anchor w   -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	label [format ".ipaec.r%dc%d" $tap $labial] -text " "      -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $labiodental] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $dental] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u027E]}
	set bn [format ".ipaec.r%dc%d" $tap $alveolar]
	button $bn -text \u027E -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "uvular trill"]

	label [format ".ipaec.r%dc%d"  $tap $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u027D]}
	set bn [format ".ipaec.r%dc%d"  $tap $retroflex];
	button $bn -text \u027D   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E5B]}
	bind $bn <Enter> {ipaentry::cfflapr}
	bind $bn <Leave> {ipaentry::crflapr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "retroflex tap"]

	label [format ".ipaec.r%dc%d" $tap $palatal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $velar] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $uvular] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $pharyngeal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $epiglottal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $tap $glottal] -text " "    -padx $xp -pady $yp

	#approximants
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $approx $poa] \
	       -text [_ "approximants"] -anchor w \
	       -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	label [format ".ipaec.r%dc%d" $approx $labial] -text " "      -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u028B]}
	set bn [format ".ipaec.r%dc%d" $approx $labiodental]
	button $bn -text \u028B   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "labiodental approximant"]

	label [format ".ipaec.r%dc%d" $approx $dental] -text " "   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u0279]}
	set bn [format ".ipaec.r%dc%d" $approx $alveolar]
	button $bn -text  \u0279 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "alveolar approximant"]

	label [format ".ipaec.r%dc%d"  $approx $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u027B]}
	set bn [format ".ipaec.r%dc%d"  $approx $retroflex]
	button $bn -text \u027B   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E5B]}
	bind $bn <Enter> {ipaentry::cfrr}
	bind $bn <Leave> {ipaentry::crrr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "retroflex approximant"]

	set cmd {$::InsertionTarget insert insert [list "j"]}
	set bn [format ".ipaec.r%dc%d" $approx $palatal]
	button $bn -text "j"    -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list "y"]}
	bind $bn <Enter> {ipaentry::cfyod}
	bind $bn <Leave> {ipaentry::cryod}
	bhcham $bn;
	balloonhelpd_for $bn [_ "palatal approximant"]

	set cmd {$::InsertionTarget insert insert [list \u0270]}
	set bn [format ".ipaec.r%dc%d" $approx $velar]
	button $bn  -text \u0270    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "velar approximant"]

	label [format ".ipaec.r%dc%d" $approx $uvular] -text " "  \
	    -padx $xp -pady $yp -bg $spcolor
	label [format ".ipaec.r%dc%d" $approx $pharyngeal] -text " "  \
	    -padx $xp -pady $yp -bg $spcolor

	#label [format ".ipaec.r%dc%d" $approx $epiglottal] -text " "  \
	    -padx $xp -pady $yp -bg $spcolor
	#label [format ".ipaec.r%dc%d" $approx $glottal] -text " "   \
	    -padx $xp -pady $yp -bg $spcolor

	#lateral approximants
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $latapprox $poa] \
	       -text [_ "lateral approximants"] -anchor w \
	       -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	label [format ".ipaec.r%dc%d" $latapprox $labial] -text " "      -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $latapprox $labiodental] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $latapprox $dental] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list "l"]}
	set bn [format ".ipaec.r%dc%d" $latapprox $alveolar]
	button $bn -text "l"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "alveolar lateral approximant"]

	label [format ".ipaec.r%dc%d"  $latapprox $postalveolar] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u026D]}
	set bn [format ".ipaec.r%dc%d"  $latapprox $retroflex]
	button $bn  -text \u026D   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E37]}
	bind $bn <Enter> {ipaentry::cflr}
	bind $bn <Leave> {ipaentry::crlr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "retroflex lateral approximant"]

	set cmd {$::InsertionTarget insert insert [list \u028E]}
	set bn [format ".ipaec.r%dc%d" $latapprox $palatal]
	button $bn -text \u028E    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "palatal lateral approximant"]

	set cmd {$::InsertionTarget insert insert [list \u029F]}
	set bn [format ".ipaec.r%dc%d" $latapprox $velar]
	button $bn -text \u029F    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "velar lateral approximant"]

	label [format ".ipaec.r%dc%d" $latapprox $uvular] -text " "  \
	    -padx $xp -pady $yp -bg $spcolor
	#label [format ".ipaec.r%dc%d" $latapprox $pharyngeal] -text " "  \
	    -padx $xp -pady $yp -bg $spcolor
	#label [format ".ipaec.r%dc%d" $latapprox $epiglottal] -text " "  \
	    -padx $xp -pady $yp
	#label [format ".ipaec.r%dc%d" $latapprox $glottal] -text " "  \
	    -padx $xp -pady $yp

	#voiced implosives
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vdimplosive $poa] \
	       -text [_ "voiced implosives"] -anchor w \
	       -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list \u0253]}
	set bn [format ".ipaec.r%dc%d" $vdimplosive $labial]
	button $bn -text \u0253 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced bilabial implosive"]

	label [format ".ipaec.r%dc%d" $vdimplosive $labiodental] -text " " \
	    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $vdimplosive $dental] -text " "  \
	    -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u0257]}
	set bn [format ".ipaec.r%dc%d" $vdimplosive $alveolar]
	button $bn -text \u0257   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced alveolar implosive"]

	label [format ".ipaec.r%dc%d"  $vdimplosive $postalveolar] -text " " \
	    -padx $xp -pady $yp

	#Not officially recognized by IPA yet.
	set cmd {$::InsertionTarget insert insert [list \u1D91]}
	set bn [format ".ipaec.r%dc%d"  $vdimplosive $retroflex]
	button $bn -text \u1D91  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced retroflex implosive"]

	set cmd {$::InsertionTarget insert insert [list \u0284]}
	set bn [format ".ipaec.r%dc%d" $vdimplosive $palatal]
	button $bn -text \u0284  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced palatal implosive"]

	set cmd {$::InsertionTarget insert insert [list \u0260]}
	set bn [format ".ipaec.r%dc%d" $vdimplosive $velar]
	button $bn -text \u0260 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced velar implosive"]

	set cmd {$::InsertionTarget insert insert [list \u029B]}
	set bn [format ".ipaec.r%dc%d" $vdimplosive $uvular]
	button $bn -text \u029B    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced uvular implosive"]

	label [format ".ipaec.r%dc%d" $vdimplosive $pharyngeal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $vdimplosive $epiglottal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $vdimplosive $glottal] -text " "    -padx $xp -pady $yp

	#clicks
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $click $poa] \
	       -text [_ "clicks"] -anchor w  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list \u0298]}
	set bn [format ".ipaec.r%dc%d" $click $labial]
	button $bn -text \u0298      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "labial click"]

	label [format ".ipaec.r%dc%d" $click $labiodental] -text " "   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list \u01C0]}
	set bn [format ".ipaec.r%dc%d" $click $dental]
	button $bn -text \u01C0   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "dental click"]

	set cmd {$::InsertionTarget insert insert [list \u01C2]}
	set bn [format ".ipaec.r%dc%d" $click $alveolar]
	button $bn -text \u01C2   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "alveolar click"]

	set cmd {$::InsertionTarget insert insert [list \u01C3]}
	set bn [format ".ipaec.r%dc%d"  $click $postalveolar]
	button $bn -text \u01C3 \
	    -padx $xp -pady $yp  -command $cmd
	balloonhelpd_for $bn [_ "postalveolar click"]

	label [format ".ipaec.r%dc%d"  $click $retroflex] -text " "   -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $click $palatal] -text " "  -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $click $velar] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $click $uvular] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $click $pharyngeal] -text " "    -padx $xp -pady $yp
	label [format ".ipaec.r%dc%d" $click $epiglottal] -text " "    -padx $xp -pady $yp
	set cmd {BackDelete $::InsertionTarget}
	set bn [format ".ipaec.r%dc%d" $click $glottal];
	button $bn -text [_ "Delete"]  -padx $xp -pady $yp -command $cmd -background "\#E0D0FF";
	set DeleteButton $bn;


	#Voiceless affricates
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vlaffric $poa] \
	       -text [_ "voiceless affricates"] -anchor w -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list p\u03C6]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $labial]
	button $bn -text "p\u03C6"      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless bilabial affricate"]

	label [format ".ipaec.r%dc%d" $vlaffric $labiodental] -text "" -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list t\u03B8]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $dental]
	button $bn -text "t\u03B8"   -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless dental affricate"]

	set cmd {$::InsertionTarget insert insert [list "ts"]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $alveolar]
	button $bn -text "ts"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless alveolar affricate"]

	set cmd {$::InsertionTarget insert insert [list t\u0283]}
	set bn [format ".ipaec.r%dc%d"  $vlaffric $postalveolar]
	button $bn -text "t\u0283"   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u010D]}
	bind $bn <Enter> {ipaentry::cfch}
	bind $bn <Leave> {ipaentry::crch}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiceless postalveolar affricate"]

	set cmd {$::InsertionTarget insert insert [list \u0288\u0282]}
	set bn [format ".ipaec.r%dc%d"  $vlaffric $retroflex]
	button $bn -text \u0288\u0282   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E6D\u1E63]}
	bind $bn <Enter> {ipaentry::cfchr}
	bind $bn <Leave> {ipaentry::crchr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiceless retroflex affricate"]

	set cmd {$::InsertionTarget insert insert [list t\u0255]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $palatal]
	button $bn -text t\u0255 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless palatal affricate"]

	set cmd {$::InsertionTarget insert insert [list "kx"]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $velar]
	button $bn -text "kx"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless velar affricate"]

	set cmd {$::InsertionTarget insert insert [list "q\u03C7"]}
	set bn [format ".ipaec.r%dc%d" $vlaffric $uvular]
	button $bn -text "q\u03C7"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiceless uvular affricate"]

	label [format ".ipaec.r%dc%d" $vlaffric $pharyngeal] -text "" \
	    -padx $xp -pady $yp -bg $spcolor
	label [format ".ipaec.r%dc%d" $vlaffric $epiglottal] -text "" \
	    -padx $xp -pady $yp -bg $spcolor
	label [format ".ipaec.r%dc%d" $vlaffric $glottal] -text "" \
	    -padx $xp -pady $yp -bg $spcolor

	#Voiced affricate
	lappend IPAECRowLabelList [label [format ".ipaec.r%dc%d" $vdaffric $poa] \
	       -text [_ "voiced affricates"] -anchor w -padx $xp -pady $yp \
	       -bg $::ColorSpecs(IPAHeadings,Background)]

	set cmd {$::InsertionTarget insert insert [list b\u03B2]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $labial]
	button $bn -text b\u03B2      -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced bilabial affricate"]

	label [format ".ipaec.r%dc%d" $vdaffric $labiodental] -text ""   -padx $xp -pady $yp

	set cmd {$::InsertionTarget insert insert [list "d\u00F0"]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $dental]
	button $bn -text "d\u00F0"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced dental affricate"]

	set cmd {$::InsertionTarget insert insert [list "dz"]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $alveolar]
	button  $bn -text "dz"  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced alveolar affricate"]

	set cmd {$::InsertionTarget insert insert [list d\u0292]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $postalveolar]
	button $bn -text d\u0292  -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u01C6]}
	bind $bn <Enter> {ipaentry::cfdj}
	bind $bn <Leave> {ipaentry::crdj}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiced postalveolar affricate"]

	set cmd {$::InsertionTarget insert insert [list \u0256\u0290]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $retroflex]
	button $bn -text \u0256\u0290   -padx $xp -pady $yp -command $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u1E0D\u1E93]}
	bind $bn <Enter> {ipaentry::cfdjr}
	bind $bn <Leave> {ipaentry::crdjr}
	bhcham $bn;
	balloonhelpd_for $bn [_ "voiced retroflex affricate"]

	set cmd {$::InsertionTarget insert insert [list d\u029D]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $palatal]
	button $bn -text  d\u029D  -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced palatal affricate"]

	set cmd {$::InsertionTarget insert insert [list g\u0263]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $velar]
	button $bn -text g\u0263    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced velar affricate"]

	set cmd {$::InsertionTarget insert insert [list "\u0262\u0281"]}
	set bn [format ".ipaec.r%dc%d" $vdaffric $uvular]
	button $bn -text "\u0262\u0281"    -padx $xp -pady $yp -command $cmd
	balloonhelpd_for $bn [_ "voiced uvular affricate"]

	label [format ".ipaec.r%dc%d" $vdaffric $pharyngeal] -text "" \
	    -padx $xp -pady $yp -bg $spcolor
	#label [format ".ipaec.r%dc%d" $vdaffric $epiglottal] -text "" \
	    -padx $xp -pady $yp -bg $spcolor
	#label [format ".ipaec.r%dc%d" $vdaffric $glottal] -text ""   \
	    -padx $xp -pady $yp -bg $spcolor

	set cmd {$::InsertionTarget insert insert [list "\u028D"]}
	button .ipaec.r13c10 -text \u028D -padx $xp -pady $yp -command $cmd
	balloonhelpd_for .ipaec.r13c10  [_ "Voiceless labio-velar fricative"]
	set cmd {$::InsertionTarget insert insert [list "\u0265"]}
	button .ipaec.r11c11 -text \u0265 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for .ipaec.r11c11  [_ "Voiced labio-palatal approximant"]
	set cmd {$::InsertionTarget insert insert [list "\u0077"]}
	button .ipaec.r11c12 -text \u0077 -padx $xp -pady $yp -command $cmd
	balloonhelpd_for .ipaec.r11c12  [_ "Voiced labio-velar approximant"]
	set cmd {$::InsertionTarget insert insert [list "\u01C1"]}
	button .ipaec.r12c11 -text \u01C1 -padx $xp -pady $yp -command $cmd
	set cmd {$::InsertionTarget insert insert [list "\u02A0"]}
	button .ipaec.r12c12 -text \u02A0 -padx $xp -pady $yp -command $cmd
	set cmd {$::InsertionTarget insert insert [list "\u026C"]}
	button .ipaec.r13c11 -text \u026C -padx $xp -pady $yp -command $cmd
	set cmd {$::InsertionTarget insert insert [list "\u026E"]}
	button .ipaec.r13c12 -text \u026E -padx $xp -pady $yp -command $cmd

	for {set row 0} {$row <= $lastrow} {incr row} {
	    set line [list];
	    for {set col 0} {$col <= $lastcolumn} {incr col} {
		set cell [format ".ipaec.r%dc%d" $row $col]
		lappend line $cell
		if {[string equal [winfo class $cell] "Label"]} {
		    balloonhelp_for $cell  [_ "Left click to insert standard characters.\nRight click to insert alternative characters."]
		}
	    }
	    eval grid $line -sticky news;
	}
	balloonhelpd_for .ipaec.r12c11  [_ "Lateral click"]
	balloonhelpd_for .ipaec.r12c12  [_ "Voiceless uvular implosive"]
	balloonhelpd_for .ipaec.r13c11  [_ "Voiceless lateral fricative"]
	balloonhelpd_for .ipaec.r13c12  [_ "Voiced lateral fricative"]
	bhsp [format ".ipaec.r%dc%d" $latapprox $uvular]
	bhsp [format ".ipaec.r%dc%d" $approx $uvular]
	bhsp [format ".ipaec.r%dc%d" $approx $pharyngeal]
	bhsp [format ".ipaec.r%dc%d" $vlaffric $pharyngeal]
	bhsp [format ".ipaec.r%dc%d" $vlaffric $epiglottal]
	bhsp [format ".ipaec.r%dc%d" $vlaffric $glottal]
	bhsp [format ".ipaec.r%dc%d" $vdaffric $pharyngeal]
	balloonhelpd_for $DeleteButton [_ "No, there isn't a glottal click  called \"Delete\".\nThis is so that you can correct mistakes while using\nthe mouse, without having to go back to the keyboard."]
	after idle {
	    update idletasks
	    raise .ipaec;
	}
	if {!$DisplayConsonantChartColumnLabelsP} {UnpackConsonantColumnLabels}
	if {!$DisplayConsonantChartRowLabelsP} {UnpackConsonantRowLabels}
    }

    set row 0;
    variable frontness $row;
    incr row;
    variable close $row;
    incr row;
    variable closeclosemid $row;
    incr row;
    variable closemid $row;
    incr row;
    variable midmid $row;
    incr row;
    variable openmid $row;
    incr row;
    variable openopenmid $row;
    incr row;
    variable open $row;
    variable lastvrow $row;

    set col 0;
    variable height $col; 
    incr col;
    variable fronturd $col;
    incr col;
    variable frontrnd $col;
    incr col;
    variable centurd $col;
    incr col;
    variable centrnd $col;
    incr col;
    variable backurd $col;
    incr col;
    variable backrnd $col;
    variable lastvcolumn $col;

    proc vry {} {
	variable close
	variable frontrnd
	eval [list [format ".ipaev.r%dc%d" $close $frontrnd] configure -text "y"];
	}
    
    proc vfy {} {
	variable close
	variable frontrnd
	eval [list [format ".ipaev.r%dc%d" $close $frontrnd] configure -text "\u00FC"];
	}

    proc vrphi {} {
	variable frontrnd;
	variable closemid
	eval [list [format ".ipaev.r%dc%d" $closemid $frontrnd] configure -text "\u00F8"];
    }
    
    proc vfphi {} {
	variable frontrnd;
	variable closemid
	eval [list [format ".ipaev.r%dc%d" $closemid $frontrnd] configure -text "o\u0308"];
    }

    proc vroe {} {
	variable frontrnd;
	variable openmid
	eval [list [format ".ipaev.r%dc%d" $openmid $frontrnd] configure -text "\u0153"];
    }

    proc vfoe {} {
	variable frontrnd;
	variable openmid
	eval [list [format ".ipaev.r%dc%d" $openmid $frontrnd] configure -text "\u0254\0308"];
    }


    proc PopupIPAEntryV {} {
	variable frontness
	variable close
	variable closeclosemid
	variable closemid
	variable openmid
	variable midmid
	variable openopenmid
	variable open
	variable lastvrow

	variable height
	variable fronturd
	variable frontrnd
	variable centurd
	variable centrnd
	variable backurd
	variable backrnd
	variable lastvcolumn

	variable IPAEVColumnLabelList
	variable IPAEVRowLabelList
	variable DisplayVowelChartColumnLabelsP
	variable DisplayVowelChartRowLabelsP

	set xp 2;
	set yp 3;
	toplevel .ipaev -borderwidth 3
	wm title .ipaev [_ "Vowel Symbols"]
	BindKeys .ipaev;
	set DownMsg [_ "Display IPA Vowel Chart"];
	set UpMsg   [_ "Remove IPA Vowel Chart"];
	bind .ipaev <Destroy> \
	    "set ::IPAVIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPAVIndex -label \"$DownMsg\""
	bind .ipaev <Unmap> \
	    "set ::IPAVIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPAVIndex -label \"$DownMsg\""
	bind .ipaev <Map> \
	    "set ::IPAVIsDisplayedP 1;$::m.charentry entryconfigure $::ToggleIPAVIndex -label \"$UpMsg\""

	#Column headers
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $frontness] \
	     -text [_ "IPA\nVowels"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $fronturd] \
	     -text [_ "Front\nUnrounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $frontrnd] \
	     -text [_ "Front\nRounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $centurd] \
	     -text [_ "Central\nUnrounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $centrnd] \
	     -text [_ "Central\nRounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $backurd] \
	     -text [_ "Back\nUnrounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]
	lappend IPAEVColumnLabelList [label [format ".ipaev.r%dc%d" $height $backrnd] \
	     -text [_ "Back\nRounded"]  -padx $xp -pady $yp -bg $::ColorSpecs(IPAHeadings,Background)]


	#Close vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $close $frontness] \
	   -text [_ "Close"] -anchor w  -padx $xp -pady $yp \
  	   -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list i]}
	button [format ".ipaev.r%dc%d"  $close $fronturd] \
	     -text "i"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list y]}
	set bn  [format ".ipaev.r%dc%d"  $close $frontrnd]
	button $bn -text "y"   -padx $xp -pady $yp -command  $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u00FC]}
	bind $bn <Enter> {ipaentry::vfy}
	bind $bn <Leave> {ipaentry::vry}
	bhcham $bn;

	set cmd {$::InsertionTarget insert insert [list \u0268]}
	button [format ".ipaev.r%dc%d"  $close $centurd] \
	     -text "\u0268"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0289]}
	button [format ".ipaev.r%dc%d"  $close $centrnd] \
	     -text "\u0289"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0268]}
	button [format ".ipaev.r%dc%d"  $close $backurd] \
	     -text "\u0268"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list u]}
	button [format ".ipaev.r%dc%d"  $close $backrnd] \
	     -text "u"   -padx $xp -pady $yp -command  $cmd

	# Close close mid vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $closeclosemid $frontness] \
	     -text [_ "Close Close Mid"] -anchor w  -padx $xp -pady $yp \
	  -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list I]}
	button [format ".ipaev.r%dc%d"  $closeclosemid $fronturd] \
	     -text "I"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list Y]}
	button [format ".ipaev.r%dc%d"  $closeclosemid $frontrnd] \
	     -text "Y"   -padx $xp -pady $yp -command  $cmd
	label [format ".ipaev.r%dc%d"  $closeclosemid $centurd] \
	     -text ""   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u028A]}
	button [format ".ipaev.r%dc%d"  $closeclosemid $centrnd] \
	     -text "\u028A"   -padx $xp -pady $yp -command  $cmd
	label [format ".ipaev.r%dc%d"  $closeclosemid $backurd] \
	     -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $closeclosemid $backrnd] \
	     -text ""   -padx $xp -pady $yp

	# Close mid vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $closemid $frontness] \
	     -text [_ "Close Mid"] -anchor w  -padx $xp -pady $yp \
	  -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list e]}
	button [format ".ipaev.r%dc%d"  $closemid $fronturd] \
	     -text "e"   -padx $xp -pady $yp -command  $cmd

	set cmd {$::InsertionTarget insert insert [list \u00F8]}
	set bn [format ".ipaev.r%dc%d"  $closemid $frontrnd]
	button $bn -text "\u00F8"   -padx $xp -pady $yp -command  $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list o\u0308]}
	bind $bn <Enter> {ipaentry::vfphi}
	bind $bn <Leave> {ipaentry::vrphi}
	bhcham $bn;

	set cmd {$::InsertionTarget insert insert [list \u0258]}
	button [format ".ipaev.r%dc%d"  $closemid $centurd] \
	     -text "\u0258"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0275]}
	button [format ".ipaev.r%dc%d"  $closemid $centrnd] \
	     -text "\u0275"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0264]}
	button [format ".ipaev.r%dc%d"  $closemid $backurd] \
	     -text "\u0264"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list o]}
	button [format ".ipaev.r%dc%d"  $closemid $backrnd] \
	     -text "o"   -padx $xp -pady $yp -command  $cmd

	# Mid mid vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $midmid $frontness] \
	     -text [_ "Mid Mid"] -anchor w  -padx $xp -pady $yp \
	  -bg $::ColorSpecs(IPAHeadings,Background)]
	label [format ".ipaev.r%dc%d"  $midmid $fronturd] \
	     -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $midmid $frontrnd] \
	     -text ""   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u0259]}
	button [format ".ipaev.r%dc%d"  $midmid $centurd] \
	     -text "\u0259"   -padx $xp -pady $yp -command  $cmd
	set cmd {BackDelete $::InsertionTarget}
	set bn [format ".ipaev.r%dc%d" $midmid $centrnd];
	button $bn -text [_ "Delete"]  \
	     -padx $xp -pady $yp -command $cmd -background "\#E0D0FF";
	set DeleteButton $bn;
	label [format ".ipaev.r%dc%d"  $midmid $backurd] -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $midmid $backrnd] -text ""   -padx $xp -pady $yp

	# Open mid vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $openmid $frontness] \
	     -text [_ "Open Mid"] -anchor w  -padx $xp -pady $yp \
  	     -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list \u025B]}
	button [format ".ipaev.r%dc%d"  $openmid $fronturd] \
	     -text \u025B   -padx $xp -pady $yp -command  $cmd

	set cmd {$::InsertionTarget insert insert [list \u0153]}
	set bn [format ".ipaev.r%dc%d"  $openmid $frontrnd]
	button $bn -text "\u0153"   -padx $xp -pady $yp -command  $cmd
	bind $bn <<B3>> {$::InsertionTarget insert insert [list \u0254\u0308]}
	bind $bn <Enter> {ipaentry::vfoe}
	bind $bn <Leave> {ipaentry::vroe}
	bhcham $bn;

	set cmd {$::InsertionTarget insert insert [list \u025C]}
	button [format ".ipaev.r%dc%d"  $openmid $centurd] \
	     -text "\u025C"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u025E]}
	button [format ".ipaev.r%dc%d"  $openmid $centrnd] \
	     -text "\u025E"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u028C]}
	button [format ".ipaev.r%dc%d"  $openmid $backurd] \
	     -text "\u028C"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0254]}
	button [format ".ipaev.r%dc%d"  $openmid $backrnd] \
	     -text "\u0254"   -padx $xp -pady $yp -command  $cmd

	# Open open mid vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $openopenmid $frontness] \
	     -text [_ "Open Open Mid"] -anchor w  -padx $xp -pady $yp \
  	     -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list \u00E6]}
	button [format ".ipaev.r%dc%d"  $openopenmid $fronturd] \
	     -text \u00E6   -padx $xp -pady $yp -command  $cmd
	label [format ".ipaev.r%dc%d"  $openopenmid $frontrnd] -text ""   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u0250]}
	button [format ".ipaev.r%dc%d"  $openopenmid $centurd] \
	     -text "\u0250"   -padx $xp -pady $yp -command  $cmd
	label [format ".ipaev.r%dc%d"  $openopenmid $centrnd] \
		     -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $openopenmid $backurd] \
	     -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $openopenmid $backrnd] \
	     -text ""   -padx $xp -pady $yp

	# Open  vowels
	lappend IPAEVRowLabelList [label [format ".ipaev.r%dc%d" $open $frontness] \
	   -text [_ "Open"] -anchor w  -padx $xp -pady $yp \
	   -bg $::ColorSpecs(IPAHeadings,Background)]
	set cmd {$::InsertionTarget insert insert [list a]}
	button [format ".ipaev.r%dc%d"  $open $fronturd] \
	     -text "a"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0276]}
	button [format ".ipaev.r%dc%d"  $open $frontrnd] \
	     -text "\u0276"   -padx $xp -pady $yp -command  $cmd
	label [format ".ipaev.r%dc%d"  $open $centurd] \
	     -text ""   -padx $xp -pady $yp
	label [format ".ipaev.r%dc%d"  $open $centrnd] \
	     -text ""   -padx $xp -pady $yp
	set cmd {$::InsertionTarget insert insert [list \u0251]}
	button [format ".ipaev.r%dc%d"  $open $backurd] \
	     -text "\u0251"   -padx $xp -pady $yp -command  $cmd
	set cmd {$::InsertionTarget insert insert [list \u0252]}
	button [format ".ipaev.r%dc%d"  $open  $backrnd] \
	     -text "\u0252"   -padx $xp -pady $yp -command  $cmd

	for {set row 0} {$row <= $lastvrow} {incr row} {
	    set line [list];
	    for {set col 0} {$col <= $lastvcolumn} {incr col} {
		set cell [format ".ipaev.r%dc%d" $row $col]
		lappend line $cell
		balloonhelp_for $cell  \
		    [_ "Left click to insert standard characters.\n\
Right click to insert alternative characters."]
	    }
	    eval grid $line -sticky news;
	}
	balloonhelpd_for $DeleteButton [_ "No, there isn't a mid-mid central rounded vowel called \"Delete\".\nThis is so that you can correct mistakes while using\nthe mouse, without having to go back to the keyboard."]
	if {!$DisplayVowelChartColumnLabelsP} {UnpackVowelColumnLabels}
	if {!$DisplayVowelChartRowLabelsP} {UnpackVowelRowLabels}
    }

#Rearrange into functional groups, e.g. tone marks, vowel quality marks,
#etc. Separate IPA and non-IPA.

    proc PopupIPAEntryD {} {
	set PerRow 10;
	set BaseChar "o";
	set xp 2;
	set yp 3;
	toplevel .ipaed -borderwidth 3
	wm title .ipaed [_ "Phonetic Diacritics"]
	BindKeys .ipaed
	set DownMsg [_ "Display IPA Diacritic Chart"];
	set UpMsg   [_ "Remove IPA Diacritic Chart"];
	bind .ipaed <Destroy> \
	    "set ::IPADIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPADIndex -label \"$DownMsg\""
	bind .ipaed <Unmap> \
	    "set ::IPADIsDisplayedP 0;$::m.charentry entryconfigure $::ToggleIPADIndex -label \"$DownMsg\""
	bind .ipaed <Map> \
	    "set ::IPADIsDisplayedP 1;$::m.charentry entryconfigure $::ToggleIPADIndex -label \"$UpMsg\""
	array set Diacritics [list\
				  0  {"\u02D0" "long"}\
				  1  {"\u02D1" "half long"}\
				  2  {"\u0303" "nasalized"}\
				  3  {"\u0324" "breathy voice"}\
				  4  {"\u0325" "voiceless"}\
				  5  {"\u032C" "voiced"}\
				  6  {"\u031A" "unreleased"}\
				  7  {"\u031C" "lower/open variety of vowel"}\
				  8  {"\u031D" "raised/closed variety of vowel"}\
				  9  {"\u031E" "lower/open variety of vowel"}\
				  10  {"\u031F" "advanced/fronted"}\
				  11  {"\u0320" "retracted/backed"}\
				  12  {"\u0321" "palatalized"}\
				  13  {"\u0322" "retroflex"}\
				  14  {"\u0323" "closer variety of vowel/retroflex"}\
				  15  {"\u0329" "syllabic"}\
				  16  {"\u032A" "dental"}\
				  17  {"\u032B" "labialized"}\
				  18  {"\u0330" "creaky voice"}\
				  19  {"\u0334" "velarized/pharyngealized"}\
				  20  {"\u0346" "dentolabial"}\
				  21  {"\u0347" "alveolar"}\
				  22  {"\u0348" "strong articulation"}\
				  23  {"\u0349" "weak articulation"}\
				  24  {"\u02CA" "high tone"}\
				  25  {"\u02CB" "low tone"}\
				  26  {"\u0302" "falling tone"}\
				  27  {"\u0304" "long"}\
				  28  {"\u0306" "short"}\
				  29  {"\u0308" "non-canonical backness"}\
				  30  {"\u02CC" "secondary stress"}\
				  31  {"\u02C8" "primary stress/downstep"}\
				  32  {"\u02B8" "palatalized"}\
				  33  {"\u02DE" "rhotacized"}\
				  34  {"\u0328" "nasalized"}\
				  35  {"\u034A" "denasal"}\
				  36  {"\u034B" "nasal escape"}\
				  37  {"\u034C" "velopharyngeal friction"}\
				  38  {"\u034D" "labial spreading"}\
				  39  {"\u034E" "whistled"}
				 ];

	set DiacriticCnt [llength [array names Diacritics]];
	set Rows [expr ceil(double($DiacriticCnt)/double($PerRow))]
	set Total [expr $PerRow * $Rows]
	#Generate buttons with blank labels for empty padding slots
	for {set k 0} {$k < $Total} {incr k} {
	    set row [expr $k/$PerRow]
	    set col [expr $k%$PerRow]
	    if {[info exist Diacritics($k)]} {
		button .ipaed.r${row}c${col} -text "$BaseChar[lindex $Diacritics($k) 0]"\
		    -padx $xp -pady $yp\
		    -command "\$::InsertionTarget insert insert  [lindex $Diacritics($k) 0]"
		balloonhelpd_for .ipaed.r${row}c${col} [_ [lindex $Diacritics($k) 1]]  
	    } else {
		label .ipaed.r${row}c${col} -text "";
	    }
	    set LastRow $row;
	    set LastCol $col;
	}
	#Lay the buttons and labels out in a grid.
	for {set row 0} {$row <= $LastRow} {incr row} {
	    set line [list];
	    for {set col 0} {$col <= $LastCol} {incr col} {
		set cell [format ".ipaed.r%dc%d" $row $col]
		lappend line $cell
	    }
	    eval grid $line -sticky news;
	}
    }

#Accented letters
    proc PopupIPAEntryA {} {
	set xp 3;
	set yp 3;
	toplevel .ipaea -borderwidth 4
	wm title .ipaea [_ "Accented Letters"]
	BindKeys .ipaea
	bind .ipaea <Destroy> {set ::IPAAIsDisplayedP 0}
	set DownMsg [_ "Display Accented Letter Chart"]
	set UpMsg   [_ "Remove Accented Letter Chart"]
	set AccentedLetters [list \
				 {"\u00E0" "a with grave" "\u00C0"}\
				 {"\u00E1" "a with acute" "\u00C1"}\
				 {"\u00E2" "a with circumflex" "\u00C2"}\
				 {"\u00E3" "a with tilde" "\u00C3"}\
				 {"\u00E4" "a with diaresis" "\u00C4"}\
				 {"\u00E5" "a with ring above" "\u00C5"}\
				 {"\u0101" "a with macron" "\u0100"}\
				 {"\u0103" "a with breve" "\u0102"}\
				 {"\u0105" "a with ogonek" "\u0104"}\
				 {"\u01CE" "a with caron" "A\u030C"}\
				 {"\u2C65" "a with stroke" "\u023A"}\
				 {"\u0227" "a with dot above" "\u0226"}\
				 {"\u1EA1" "a with dot below" "\u1EA0"}\
				 {"\u0201" "a with double grave" "\u0200"}\
				 {"\u0203" "a with inverted breve" "\u0202"}\
				 {"\u01DF" "a with diaresis and macron" "\u01DE"}\
				 {"\u01E1" "a with dot above and macron" "\u01E0"}\
				 {"\u01FB" "a with ring above and acute" "\u01FA"}\
				 {"\u01E3" "ash with macron" "\u01E2"}\
				 {"\u01FD" "ash with acute" "\u01FC"}\
				 {"\u0180" "b with stroke" "\u0243"}\
				 {"\u0183" "b with topbar" "\u0182"}\
				 {"\u1E03" "b with dot above" "\u1E02"}\
				 {"\u1E05" "b with dot below" "\u1E04"}\
				 {"\u1E07" "b with line below" "\u1E06"}\
				 {"\u0188" "c with hook" "\u0187"}\
				 {"\u0107" "c with acute" "\u0106"}\
				 {"\u0109" "c with circumflex" "\u0108"}\
				 {"\u010B" "c with dot above" "\u010A"}\
				 {"\u00E7" "c with cedilla" "\u00C7"}\
				 {"\u1E09" "c with cedilla and acute" "\u1E08"}\
				 {"\u010D" "c with caron" "\u010C"}\
				 {"\u023C" "c with stroke" "\u023B"}\
				 {"\u018C" "d with topbar" "\u018B"}\
				 {"\u010F" "d with caron" "\u010E"}\
				 {"\u0111" "d with stroke" "\u0110"}\
				 {"\u0221" "d with curl" "\uFFFD"}\
				 {"\u1E0B" "d with dot above" "\u1E0A"}\
				 {"\u1E0D" "d with dot below" "\u1E0C"}\
				 {"\u1E0F" "d with line below" "\u1E0E"}\
				 {"\u00E8" "e with grave" "\u00C8"}\
				 {"\u00E9" "e with acute" "\u00C9"}\
				 {"\u00EA" "e with circumflex" "\u00CA"}\
				 {"e\u0303" "e with tilde" "E\u0303"}\
				 {"\u00EB" "e with diaresis" "\u00CB"}\
				 {"\u0113" "e with macron" "\u0112"}\
				 {"\u0115" "e with breve" "\u0114"}\
				 {"\u0117" "e with dot above" "\u0116"}\
				 {"\u1EB9" "e with dot below" "\u1EB8"}\
				 {"\u0119" "e with ogonek" "\u0118"}\
				 {"\u011B" "e with caron" "\u011A"}\
				 {"\u0247" "e with stroke" "\u0246"}\
				 {"\u0229" "e with cedilla" "\u0228"}\
				 {"\u0205" "e with double grave" "\u0204"}\
				 {"\u0207" "e with inverted breve" "\u0206"}\
				 {"\u01F5" "g with acute" "\u01F4"}\
				 {"\u011D" "g with circumflex" "\u011C"}\
				 {"\u011F" "g with breve" "\u011E"}\
				 {"\u0121" "g with dot above" "\u0000"}\
				 {"\u0123" "g with cedilla" "\u0122"}\
				 {"\u01E5" "g with stroke" "\u01E4"}\
				 {"\u01E7" "g with caron" "\u01E6"}\
				 {"\u021F" "h with caron" "\u021E"}\
				 {"\u0125" "h with circumflex" "\u0124"}\
				 {"\u0127" "h with stroke" "\u0126"}\
				 {"\u1E25" "h with dot below" "\u1E24"}\
				 {"\u00EC" "i with grave" "\u00CC"}\
				 {"\u00ED" "i with acute" "\u00CD"}\
				 {"\u00EE" "i with circumflex" "\u00CE"}\
				 {"\u00EF" "i with diaresis" "\u00CF"}\
				 {"\u0129" "i with tilde" "\u0128"}\
				 {"\u012B" "i with macron" "\u012A"}\
				 {"\u012D" "i with breve" "\u012C"}\
				 {"\u012F" "i with ogonek" "\u012E"}\
				 {"\u01D0" "i with caron" "\u01CF"}\
				 {"\u0209" "i with double grave" "\u0208"}\
				 {"\u020B" "i with inverted breve" "\u020A"}\
				 {"\u1ECB" "i with dot below" "\u1ECA"}\
				 {"\u0131" "dotless i" "\u0049"}\
				 {"\u0135" "j with circumflex" "\u0134"}\
				 {"\u01F0" "j with caron" "J\u030C"}\
				 {"\u0249" "j with stroke" "J\u0248"}\
				 {"\u01E9" "k with caron" "\u01E8"}\
				 {"\u0199" "k with hook" "\u0198"}\
				 {"\u0137" "k with cedilla " "\u0136"}\
				 {"\u1E33" "k with dot below" "\u1E32"}\
				 {"\u013A" "l with acute" "\u0139"}\
				 {"\u013C" "l with cedilla" "\u013B"}\
				 {"\u013E" "l with caron" "\u013D"}\
				 {"\u0140" "l with middle dot" "\u013F"}\
				 {"\u0142" "l with stroke" "\u0141"}\
				 {"\u019A" "l with bar" "\u023D"}\
				 {"\u0234" "l with curl" "\uFFFD"}\
				 {"\u1E37" "l with dot below" "\u1E36"}\
				 {"\u1E39" "l with dot below and macron" "\u01E38"}\
				 {"\u1E3B" "l with line below" "\u1E3A"}\
				 {"\u019B" "lambda with stroke" "\uFFFD"}\
				 {"\u1E3F" "m with acute" "\u1E3E"}\
				 {"\u1E43" "m with dot below" "\u1E42"}\
				 {"\u1E41" "m with dot above" "\u1E40"}\
				 {"\u0271" "m with hook" "\uFFFD"}\
				 {"\u0235" "n with a curl" "\uFFFD"}\
				 {"\u0146" "n with cedilla" "\u0145"}\
				 {"\u0148" "n with caron" "\u0147"}\
				 {"\u01F9" "n with grave" "\u01F8"}\
				 {"\u00F1" "n with tilde" "\u00D1"}\
				 {"\u019E" "n with long right leg" "\u0220"}\
				 {"\u0144" "n with acute" "\u0143"}\
				 {"\u1E45" "n with dot above" "\u1E44"}\
				 {"\u1E47" "n with dot below" "\u1E46"}\
				 {"\u1E49" "n with line below" "\u1E48"}\
				 {"\u00F2" "o with grave" "\u00D2"}\
				 {"\u00F3" "o with acute" "\uD3"}\
				 {"\u00F4" "o with circumflex" "\u00D4"}\
				 {"\u00F5" "o with tilde" "\u00D5"}\
				 {"\u00F6" "o with diaresis" "\u00D6"}\
				 {"\u00F8" "o with stroke" "\u00D8"}\
				 {"\u014D" "o with macron" "\u014C"}\
				 {"\u014F" "o with breve" "\u014E"}\
				 {"\u0151" "o with double acute" "\u0150"}\
				 {"\u01A1" "o with horn" "\u01A0"}\
				 {"\u01EB" "o with ogonek" "\u01EA"}\
				 {"\u01ED" "o with ogonek and macron" "\u01EC"}\
				 {"\u01D2" "o with caron" "\u01D1"}\
				 {"\u022B" "o with diaresis and macron" "\u022A"}\
				 {"\u022D" "o with tilde and macron" "\u022C"}\
				 {"\u022F" "o with dot above" "\u022E"}\
				 {"\u01FF" "o with stroke and acute" "\u01FE"}\
				 {"\u020D" "o with double grave" "\u020C"}\
				 {"\u020F" "o with inverted breve" "\u020E"}\
				 {"\u0231" "o with dot above and macron" "\u0230"}\
				 {"\u1ECD" "o with dot below" "\u1ECC"}\
				 {"\u0223" "ou" "\u0222"}\
			         {"\u01A5" "p with hook" "\u01A4"}\
				 {"\u0155" "r with acute" "\u0154"}\
				 {"\u0157" "r with cedilla" "\u0156"}\
				 {"\u0159" "r with caron" "\u0158"}\
				 {"\u024D" "r with stroke" "\u024C"}\
				 {"\u0211" "r with double grave" "\u0210"}\
				 {"\u0213" "r with inverted breve" "\u0214"}\
				 {"\u1E5B" "r with dot below" "\u1E5A"}\
				 {"\u027F" "reversed r with fishhook" "\uFFFD"}\
				 {"\u015B" "s with acute" "\u015A"}\
				 {"\u015D" "s with circumflex" "\u015C"}\
				 {"\u015F" "s with cedilla" "\u015E"}\
				 {"\u0161" "s with caron" "\u0160"}\
				 {"\u0219" "s with comma below" "\u0218"}\
				 {"\u1E63" "s with dot below" "\u1E62"}\
				 {"\u021B" "t with comma below" "\u021A"}\
				 {"\u01AB" "t with palatal hook" "\uFFFD"}\
				 {"\u01AD" "t with hook" "\u01AC"}\
				 {"\u0163" "t wwith cedilla" "\u0162"}\
				 {"\u0165" "t with caron" "\u0164"}\
				 {"\u0167" "t with stroke" "\u0166"}\
				 {"\u2C66" "t with diagonal stroke" "\u023E"}\
				 {"\u00F9" "u with grave" "\u00D9"}\
				 {"\u00FA" "u with acute" "\u00DA"}\
				 {"\u00FB" "u with circumflex" "\u00DB"}\
				 {"\u00FC" "u with diaresis" "\u00DC"}\
				 {"\u01D4" "u with caron" "\u01D3"}\
				 {"\u01D6" "u with diaresis and macron" "\u01D5"}\
				 {"\u01D8" "u with diaresis and acute" "\u01D7"}\
				 {"\u01DA" "u with diaresis and caron" "\u01D9"}\
				 {"\u01DC" "u with diaresis and grave" "\u01DB"}\
				 {"\u01B0" "u with horn" "\u01AF"}\
				 {"\u0169" "u with tilde" "\u0168"}\
				 {"\u016B" "u with macron" "\u016A"}\
				 {"\u016D" "u with breve" "\u016C"}\
				 {"\u016F" "u with ring above" "\u016E"}\
				 {"\u0171" "u with double acute" "\u0170"}\
				 {"\u0173" "u with ogonek" "\u0172"}\
				 {"\u0215" "u with double grave" "\u0214"}\
				 {"\u0217" "u with inverted breve" "\u0216"}\
				 {"\u1EE5" "u with dot below" "\u1EE4"}\
				 {"\u2C74" "v with curl" "\uFFFD"}\
				 {"\u0175" "w with circumflex" "\u0174"}\
				 {"\u01B4" "y with hook" "\u01B3"}\
				 {"\u00FD" "y with acute" "\u00DD"}\
				 {"\u00FF" "y with diaresis" "\u0278"}\
				 {"\u0233" "y with macron" "\u0232"}\
				 {"\u0177" "y with circumflex" "\u0176"}\
				 {"\u024F" "y with stroke" "\u024E"}\
				 {"\u017A" "z with acute" "\u0179"}\
				 {"\u017C" "z with dot above" "\u017B"}\
				 {"\u017E" "z with caron" "\u017D"}\
				 {"\u01B6" "z with stroke" "\u01B5"}\
				 {"\u0225" "z with hook" "\u0224"}\
				 {"\u0236" "t with curl" "\uFFFD"}\
				 {"\u01EF" "zh with caron" "\u01EE"}]

	if {$::UseNoGlyphs} {
	    lappend AccentedLetters {"\u1D8D" "x with palatal hook" "X\u0321"}\
				 {"\u1D6F" "m with middle tilde" "\uFFFD"}
	}
	
	#Sort by gloss
	set AccentedLetters [lsort -index 1 $AccentedLetters]

#Done through 0236

	set AccentedLetterCnt [llength $AccentedLetters];
	if {[info exists ::AccentedLettersPerRow]} {
	    set PerRow $::AccentedLettersPerRow
	} else {
	    set PerRow [expr int(1.2 * ceil(sqrt($AccentedLetterCnt)))]
	}
	set Rows [expr ceil(double($AccentedLetterCnt)/double($PerRow))]
	set Total [expr $PerRow * $Rows]
	#Generate buttons with blank labels for empty padding slots
	for {set k 0} {$k < $Total} {incr k} {
	    set row [expr $k/$PerRow]
	    set col [expr $k%$PerRow]
	    if {$k < $AccentedLetterCnt} {
		button .ipaea.r${row}c${col} -text "[lindex [lindex $AccentedLetters $k] 0]"\
		    -padx $xp -pady $yp\
		    -command "\$::InsertionTarget insert insert  [lindex [lindex $AccentedLetters $k] 0]"
		balloonhelpd_for .ipaea.r${row}c${col} [_ [lindex [lindex $AccentedLetters $k] 1] ]  
		set cap [lindex [lindex $AccentedLetters $k] 2]
		bind .ipaea.r${row}c${col} <<B3>> "\$::InsertionTarget insert insert $cap"
	    } else {
		label .ipaea.r${row}c${col} -text "";
	    }
	}
	set LastRow $row;
	set LastCol $col;
	set LastCell .ipaea.r${row}c${col}
	destroy $LastCell
	button $LastCell -image $::LeftArrowImage -command {BackDelete $::InsertionTarget}
	balloonhelpd_for $LastCell  [_ "Delete, so that you can correct mistakes while using\nthe mouse, without having to go back to the keyboard."]
	
	#Lay the buttons and labels out in a grid.
	for {set row 0} {$row <= $LastRow} {incr row} {
	    set line [list];
	    for {set col 0} {$col <= $LastCol} {incr col} {
		set cell [format ".ipaea.r%dc%d" $row $col]
		lappend line $cell
	    }
	    eval grid $line -sticky news;
	}
    }

}

proc BackDelete {w} {
    if {[string equal [winfo class $w] "Text"]} {
	set Insert [$w index insert]
	set FirstHalf  [$w get 1.0 $Insert-1chars]
	set SecondHalf [string trimright [$w get insert end]]
	$w delete 1.0 end;
	$w insert 1.0 $FirstHalf$SecondHalf;
    } else {
	set delind [expr [$w index insert] -1];
	$w delete $delind;
    }
}

proc PopupCharEntryByCode {} {
    toplevel .charent -borderwidth 4 -relief raised
    BindKeys .charent;
    wm title .charent "Entry By Codepoint";
    after idle {
	update idletasks
	set xmax [winfo screenwidth .charent]
	set ymax [winfo screenheight .charent]
	set x0 [expr 1 * ($xmax -[winfo reqwidth .charent])/3];
	set y0 [expr 1 * ($ymax -[winfo reqheight .charent])/3];
	wm geometry .charent "+$x0+$y0";
    }
    label .charent.title -text [_ "Insert Character by Numerical Code"]
    frame .charent.ef;
    entry .charent.ef.ent -width 8 -font MainFont -relief flat -bg \#E0EEFF;
    label .charent.ef.prefix -text "0x" -font MainFont
    pack .charent.ef.prefix -side left  -expand 1 -fill x -anchor e
    pack .charent.ef.ent    -side right -expand 1 -fill x -anchor w
    button .charent.d  -text [_ "Dismiss"] -command {destroy .charent}
    button .charent.x  -text [_ "Delete"] -command [list BackDelete $::CharByCodeInsertionTarget]
    button .charent.i  -text [_ "Insert"] -command {InsertUnicode}
    pack .charent.title -side top
    pack .charent.ef -side top
    pack .charent.d -side left -expand 1 -fill both
    pack .charent.x -side left -expand 1 -fill both
    pack .charent.i -side right -expand 1 -fill both
    focus .charent.ef.ent;
    set DownMsg [_ "Display Widget for Entering Characters by Unicode Code"];
    set UpMsg   [_ "Remove Widget for Entering Characters by Unicode Code"];
    bind .charent <Destroy> \
	"set ::CharEntryByCodeIsDisplayedP 0;$::CEM entryconfigure $::ToggleCharEntryByCodeIndex -label \"$DownMsg\""
    bind .charent <Unmap> \
	"set ::CharEntryByCodeIsDisplayedP 0;$::CEM entryconfigure $::ToggleCharEntryByCodeIndex -label \"$DownMsg\""
    bind .charent <Map> \
	"set ::CharEntryByCodeIsDisplayedP 1;$::CEM entryconfigure $::ToggleCharEntryByCodeIndex -label \"$UpMsg\""
    bind .charent.ef.ent <Destroy> {set ::InsertionTarget .info.notes.txt}
    bind .charent.ef.ent <Return> {InsertUnicode}
    bind .charent.ef.ent <Control-k> {.charent.ef.ent delete 0 end;break}


    set charentbh  [_ "Enter a character by its Unicode code, as a sequence of four hexadecimal digits.\nFor example, you may specify \'\u0298\', the International Phonetic Alphabet\nsymbol for the bilabial click, as 0298, and the Chinese character \'\u4E39\' \"egg\" as 4E39.\nDo not type the prefix 0x shown to the left of the entry box.\nIt is entered for you automatically. Return inserts the current character.\nControl-k erases the current character code."]
    balloonhelp_for .charent $charentbh
    balloonhelp_for .charent.title $charentbh
    balloonhelp_for .charent.ef.ent $charentbh
    balloonhelp_for .charent.i $charentbh
    balloonhelp_for .charent.d $charentbh
    balloonhelp_for .charent.x $charentbh
    set ::CharEntryByCodeIsDisplayedP 1;
}

#Get entry from popup, validate it, and insert it into the insertion target.
proc InsertUnicode {} {
    ClearMessageWindow;
    set str [.charent.ef.ent get];
    if {[string length $str] == 0} {
	ShowMessage [_ "The empty string is not a valid Unicode codepoint"]
	return ;
    }
    #Validate
    set BadValueP 0;
    #Make sure all digits are hex and that prefix is appropriate.
    if {[regexp {[[:xdigit:]]{4,4}} $str] == 0} {
	ShowMessage [_ "$str is not a well-formed hexadecimal Unicode value"]
	return;
    }
    set str [format "0x%s" $str]
    if {[scan $str "%x" num] < 1} {
	ShowMessage [format [_ "Ill-formed code %s"] $str]
	return;
    }

    #Reject illegal codepoints.
    if {$num  >  65535} {
	ShowMessage [_ "Tcl/Tk may not support codepoints outside the BMP (Plane 0)."]
    }
    set BadValueP 0;
    set BadRanges [list\
  	       0x0750 0x077F\
	       0x07C0 0x08FF\
	       0x1380 0x139F\
	       0x18B0 0x18FF\
	       0x1980 0x19DF\
	       0x1A00 0x1CFF\
	       0x1D80 0x1DFF\
	       0x2C00 0x2E7F\
	       0x2FE0 0x2FEF\
	       0x31C0 0x31EF\
	       0x9FB0 0x9FFF\
	       0xA4D0 0xABFF\
	       0xD7B0 0xD7FF\
	       0xD800 0xDBFF\
	       0xDC00 0xDFFF\
	       0xFE10 0xFE1F\
	       0x10140 0x102FF\
	       0x104B0 0x107FF\
	       0x10840 0x1CFFF\
	       0x1D200 0x1D2FF\
	       0x1D360 0x1D3FF\
	       0x1D800 0x1FFFF\
	       0x2A6E0 0x2F7FF\
	       0x2FAB0 0x2FFFF\
	       0xE0080 0xE00FF\
	       0xE01F0 0xEFFFF\
	       0xFFFFE 0xFFFFF];

    for {set k 0} {$k < [llength $BadRanges]} {incr k} {
	if { ($num >= [lindex $BadRanges [expr 2 * $k]]) &&\
		 ($num <= [lindex $BadRanges [expr (2 * $k) + 1]])} { 
	    set BadValueP 1;
	    break; 
	}
    }
    if {$BadValueP} {
	ShowMessage [format [_ "%s is not a valid Unicode codepoint"] $str]
	return;
    }
    if {$num >= 1114110} {
	ShowMessage [_ "Warning: codepoints above 0x10FFFD have not been assigned as of version 5.1."]
    }

    #Insert
    $::CharByCodeInsertionTarget insert insert [format "%c" $num]
}


proc IndicateIPACUp {} {
	$::CEM entryconfigure $::ToggleIPACIndex \
	    -label [_ "Remove IPA Consonant Chart"];
	set ::IPACIsDisplayedP 1;
}

proc IndicateIPACDown {} {
	$::CEM entryconfigure $::ToggleIPACIndex \
	    -label [_ "Display IPA Consonant Chart"];
	set ::IPACIsDisplayedP 0;
}

proc ToggleIPAC {} {
    global IPACIsDisplayedP;
    global m;

    if { $IPACIsDisplayedP == 0} {
	if {[winfo exists .ipaec]} {
	    wm deiconify .ipaec;
	} else { 
	    ipaentry::PopupIPAEntryC;
	}
	IndicateIPACUp;
    } else {
	wm iconify .ipaec;
	IndicateIPACDown;
    }
}

proc IndicateIPAVUp {} {
	$::CEM entryconfigure $::ToggleIPAVIndex \
	    -label [_ "Remove IPA Vowel Chart"];
	set ::IPAVIsDisplayedP 1;
}

proc IndicateIPAVDown {} {
	$::CEM entryconfigure $::ToggleIPAVIndex \
	    -label [_ "Display IPA Vowel Chart"];
	set ::IPAVIsDisplayedP 0;
}

proc ToggleIPAV {} {
    global IPAVIsDisplayedP;
    global m;

    if { $IPAVIsDisplayedP == 0} {
	if {[winfo exists .ipaev]} {
	    wm deiconify .ipaev;
	} else { 
	    ipaentry::PopupIPAEntryV;
	}
	$::CEM entryconfigure $::ToggleIPAVIndex -label [_ "Remove IPA Vowel Chart"];
	set IPAVIsDisplayedP 1;
    } else {
	wm iconify .ipaev;
	$::CEM entryconfigure $::ToggleIPAVIndex -label [_ "Display IPA Vowel Chart"];
	set IPAVIsDisplayedP 0;
    }
}

proc IndicateIPADUp {} {
	$::CEM entryconfigure $::ToggleIPADIndex \
	    -label [_ "Remove IPA Diacritic Chart"];
	set ::IPADIsDisplayedP 1;
}

proc IndicateIPADDown {} {
	$::CEM entryconfigure $::ToggleIPADIndex \
	    -label [_ "Display IPA Diacritic Chart"];
	set ::IPADIsDisplayedP 0;
}

proc ToggleIPAD {} {
    global IPADIsDisplayedP;
    global m;

    if { $IPADIsDisplayedP == 0} {
	if {[winfo exists .ipaed]} {
	    wm deiconify .ipaed;
	} else { 
	    ipaentry::PopupIPAEntryD;
	}
	IndicateIPADUp
    } else {
	wm iconify .ipaed;
	IndicateIPADDown;
    }
}

proc IndicateIPAAUp {} {
	$::CEM entryconfigure $::ToggleIPAAIndex \
	    -label [_ "Remove Accented Letter Chart"];
	set ::IPAAIsDisplayedP 1;
}

proc IndicateIPAADown {} {
	$::CEM entryconfigure $::ToggleIPAAIndex \
	    -label [_ "Display Accented Letter Chart"];
	set ::IPAAIsDisplayedP 0;
}

proc ToggleIPAA {} {
    global m;

    if { $::IPAAIsDisplayedP == 0} {
	if {[winfo exists .ipaea]} {
	    wm deiconify .ipaea;
	} else { 
	    ipaentry::PopupIPAEntryA;
	}
	IndicateIPAAUp;
    } else {
	wm iconify .ipaea;
	IndicateIPAADown;
    }
}

proc SetAccentedLetterColumns {s} {
    if {$s > 1} {
	set ::AccentedLettersPerRow $s;
    }
}

####################################################

#File     -> LineList	LoadCustomCharacterChart
#LineList -> CDEF	DefineCustomCharacterChart
#CDEF     -> Popup      PopupSpecialPalette
#CDEF     -> Panel	CreateCustomChartPanel

proc ReadCustomCharacterChartPopup {args} {
    if {[llength $args]} {
	set dl [LoadCustomCharacterChart [lindex $args 0]]
    } else {
	set dl [LoadCustomCharacterChart];
    }
    PopupSpecialPalette [DefineCustomCharacterChart $dl]
}

proc ReadCustomCharacterChartPanel {args} {
    if {[llength $args]} {
	set dl [LoadCustomCharacterChart [lindex $args 0]]
    } else {
	set dl [LoadCustomCharacterChart];
    }
    CreateCustomChartPanel [DefineCustomCharacterChart $dl]
}

proc DefineCustomCharacterChartPopup {ll} {
    PopupSpecialPalette [DefineCustomCharacterChart $ll];
}

proc DefineCustomCharacterChartPanel {ll} {
    CreateCustomChartPanel [DefineCustomCharacterChart $ll];
}

#PopupSpecialPalette and CreateCustomChartPanel share most of their
#code. It should be possible to unify them. Maybe call a single
#routine with a flag indicating whether for the panel or popup.

#Returns a linelist.
proc LoadCustomCharacterChart {args} {
    if {[llength $args]} {
	set fn [lindex $args 0]
    } else {
	set fn [tk_getOpenFile -title [_ "Load Custom Character Chart"]];
	if {[string equal $fn ""]} {
	    ShowMessage [_ "File selection cancelled."];
	    return ;
	}
    }
    if { [catch {open $fn "r"} fhd ] != 0} {
	ShowMessage [format [_ "Unable to open character chart definition file %s."] $fn];
	return ;
    }
    set LineCnt 0
    while { [gets $fhd line] > 0} {
	lappend Lines $line;
	incr LineCnt
    }
    close $fhd;
    if {$LineCnt < 1} {
	ShowMessage [_ "File %s is empty" $fn]
	return "";
    }
    ShowMessage [format [_ "Loaded custom character chart definition from %s."] $fn]
    return $Lines;
}


#This procedure takes a list of lines defining a custom
#character entry chart, which may have been read from a
#standalone file or may be an instant list in an
#init file, and generates an internal character chart
#definition, which it stores. It does not actualy
#create a display
proc DefineCustomCharacterChart {LineList {fn NONE}} {
    #The first line is special. It contains meta-information:
    #the title, the desired number of buttons per row,
    #and the proposed font family and size. Only the
    #title is obligatory.
    set line [lindex $LineList 0]
    set flds [split $line "|"]
    set FieldCnt [llength $flds];
    set Title [lindex $flds 0];
    #The remaining lines contain pairs of code sequences and glosses.
    set cd [list];
    set LineList [lrange $LineList 1 end]
    foreach line $LineList {
	set f [split $line "|"];
	set gloss [lindex $f 1];
	set c [string trim [lindex $f 0] \"];
	set cf [split $c];
	set str "\{\"";
	foreach n $cf {
	    append str [format "%s" $n]
	}
	append str "\""
	append str [format " \"%s\"\}" $gloss]
	lappend cd $str;
    }
    set info [list [join $cd]]
    if {$FieldCnt > 1} {
	lappend info [lindex $flds 1];	# Columns
    }
    if {$FieldCnt > 2} {
	lappend info [lindex $flds 2];	# Font family
    }
    if {$FieldCnt > 3} {
	lappend info [lindex $flds 3];	# Font size
    }
    if {![string equal $fn NONE]} {	# File name
	lappend info $fn;
    }
    set ::SpecialCharacterPalette($Title) $info;
    $::CEM add command -label $Title -command "PopupSpecialPalette $Title";
    incr ::CustomCEMEntries;
    return $Title;
}


if {$::IwidgetsAvailableP} {
    #Creates a popup chart from a stored definition.
    set SccCnt 0;
    proc PopupSpecialPalette {Title} {
	set name [format ".scc%d" $::SccCnt] 
	if {[info exists ::SpecialCharacterPalette($Title,WidgetName)]} {
	    set w $::SpecialCharacterPalette($Title,WidgetName);
	    if {[winfo exists $w]} {
		wm deiconify $w;
		raise $w;
		return ;
	    }
	}
	set cdefs [lindex $::SpecialCharacterPalette($Title) 0];
	set Items [llength $::SpecialCharacterPalette($Title)];
	if {$Items > 1} {
	    set PerRow [lindex $::SpecialCharacterPalette($Title) 1];
	} else {
	    set PerRow 5;
	}
	if {$Items > 2} {
	    set FontFamily [lindex $::SpecialCharacterPalette($Title) 2];
	}
	if {$Items > 3} {
	    set FontSize [lindex $::SpecialCharacterPalette($Title) 3];
	}
	incr ::SccCnt;
	set xp 3;
	set yp 3;
	toplevel $name -borderwidth 4
	set ::SpecialCharacterPalette($Title,WidgetName) $name; 
	wm title $name $Title
	iwidgets::scrolledframe $name.sf -vscrollmode dynamic -hscrollmode dynamic \
	    -height 180 -width 250
	set tf [$name.sf childsite]
	pack $name.sf -expand 1 -fill both
	BindKeys $name
	bind [$name.sf component vertsb] <<B3>> \
	    "ScrollbarMoveBigIncrement [$name.sf component vertsb] 0.20 %x %y"
	set CdefCnt [llength $cdefs];
	set Rows [expr int(ceil(double($CdefCnt)/double($PerRow)))]
	set Total [expr $PerRow * $Rows]
	if {$CdefCnt == $Total} {
	    incr Rows;
	    set Total [expr $PerRow * $Rows]
	}
	for {set k 0} {$k < $Total} {incr k} {
	    set row [expr $k/$PerRow]
	    set col [expr $k%$PerRow]
	    if {$k < $CdefCnt} {
		set entry [lindex $cdefs $k];
		set cs [lindex $entry 0];
		set gloss [lindex $entry 1];
		button $tf.r${row}c${col} -text $cs\
		    -padx $xp -pady $yp\
		    -command "\$::InsertionTarget insert insert $cs"
		balloonhelpd_for $tf.r${row}c${col} $gloss;
	    } else {
		set ln $tf.r${row}c${col};
		#Generate buttons with blank labels for empty padding slots
		label $ln  -text "";
		balloonhelp_for $ln [_ "This space for rent."]
	    }
	}
	set LastRow $row;
	set LastCol $col;
	set LastCell $tf.r${row}c${col}
	destroy $LastCell
	button $LastCell -image $::LeftArrowImage -command {BackDelete $::InsertionTarget}
	balloonhelpd_for $LastCell  [_ "Delete, so that you can correct mistakes while using\nthe mouse, without having to go back to the keyboard."]
	
	#Lay the buttons and labels out in a grid.
	for {set row 0} {$row <= $LastRow} {incr row} {
	    set line [list];
	    for {set col 0} {$col <= $LastCol} {incr col} {
		set cell [format "%s.r%dc%d" $tf $row $col]
		lappend line $cell
	    }
	    eval grid $line -sticky news;
	}
	return $name;
    }
} else {
    proc PopupSpecialPalette {Title} {
	ShowMessage [_ "Custom character charts are not available due to the absence of the Iwidgets library."]
    }
}

#Creates a panel chart given stored information.
proc CreateCustomChartPanel {Title} {
    #Organize information
    set def $::SpecialCharacterPalette($Title);
    set cdefs [lindex $def 0];
    set Items [llength $def];
    if {$Items > 1} {
	set PerRow [lindex $::SpecialCharacterPalette($Title) 1];
    } else {
	set PerRow 5;
    }
    if {$Items > 2} {
	set FontFamily [lindex $::SpecialCharacterPalette($Title) 2];
	set ::FontInfo(PanelCharacterEntryFont,family) $FontFamily;
	font configure PanelCharacterEntryFont -family $FontFamily;
    }
    if {$Items > 3} {
	set FontSize [lindex $::SpecialCharacterPalette($Title) 3];
	set ::FontInfo(PanelCharacterEntryFont,size) $FontSize;
	font configure PanelCharacterEntryFont -size $FontSize;
    }
    #Create the gui
    set xp 3;
    set yp 3;
    set name .info.charentry;
    destroy $name;
    frame $name
    iwidgets::scrolledframe $name.sf -vscrollmode dynamic -hscrollmode dynamic \
	-height 180 -width 250
    bind [$name.sf component vertsb] <<B3>> \
	"ScrollbarMoveBigIncrement [$name.sf component vertsb] 0.20 %x %y"
    set tf [$name.sf childsite]
    pack $name.sf -expand 1 -fill both
    label $name.title -text $Title -anchor n \
	-fg $::ColorSpecs(PanelCharacterChartTitle,Foreground) \
	-bg $::ColorSpecs(PanelCharacterChartTitle,Background)
    set CdefCnt [llength $cdefs];
    set Rows [expr int(ceil(double($CdefCnt)/double($PerRow)))]
    set Total [expr $PerRow * $Rows]
    if {$CdefCnt == $Total} {
	#We need a slot for the delete button
	incr Rows;
	set Total [expr $PerRow * $Rows]
    }
    for {set k 0} {$k < $Total} {incr k} {
	set row [expr $k/$PerRow]
	set col [expr $k%$PerRow]
	if {$k < $CdefCnt} {
	    button $tf.r${row}c${col} -text "[lindex [lindex $cdefs $k] 0]"\
		-padx $xp -pady $yp\
		-font PanelCharacterEntryFont\
		-command "\$::InsertionTarget insert insert  [lindex [lindex $cdefs $k] 0]" \
		-bg $::ColorSpecs(PanelCharacterChartButton,Background) \
		-fg $::ColorSpecs(PanelCharacterChartButton,Foreground)

	    balloonhelpd_for $tf.r${row}c${col} [_ [lindex [lindex $cdefs $k] 1] ]  
	} else {
	    #Generate buttons with blank labels for empty padding slots
	    set ln $tf.r${row}c${col};
	    label $ln  -text "" -bg $::ColorSpecs(PanelCharacterChartEmpty,Background);
	    balloonhelp_for $ln [_ "This space for rent."]
	}
    }
    set LastRow $row;
    set LastCol $col;
    set LastCell $tf.r${row}c${col}
    destroy $LastCell
    button $LastCell -image $::LeftArrowImage  -command {BackDelete $::InsertionTarget}
    balloonhelpd_for $LastCell  \
	[_ "Delete, so that you can correct mistakes while using
the mouse, without having to go back to the keyboard."]
    
    #Lay the buttons and labels out in a grid.
    for {set row 0} {$row <= $LastRow} {incr row} {
	set line [list];
	for {set col 0} {$col <= $LastCol} {incr col} {
	    set cell [format "%s.r%dc%d" $tf $row $col]
	    lappend line $cell
	}
	eval grid $line -sticky news;
    }
    pack $name.title -side top -expand 1 -fill none
    #Insert into frame list
    
    if {[lsearch -exact $::InfoFrameList $name] < 0} {
	lappend ::InfoFrameList $name;# Not already in list
    }
    RotateInfo left;
    RotateInfo right;
    #Enable menu item
    .menubar.configure.panel entryconfigure $::CharacterEntryIndex -state normal
    set ::PanelToggleL 1
}

proc CommandLineOptions {} {
    if {[PopupDown CommandLineOptions] ==1} {return}
    set po [CreateTextDisplay [_ "Command Line Options"] 60 13];
    BindKeys $po;
    set ::PopupList(CommandLineOptions) $po;
    AppendToTextDisplay $po [_ "Usage: sndbite \[options\] (<sound file>)\n\n"];
    AppendToTextDisplay $po [_ "  -b              run in batch mode\n"];
    AppendToTextDisplay $po [_ "  -d              set the debug flag\n"];
    AppendToTextDisplay $po [_ "  -f <file name>  execute commands from <file name>\n"];
    AppendToTextDisplay $po [_ "  -h              provide help\n"];
    AppendToTextDisplay $po [_ "  -i              do not read the init file\n"];
    AppendToTextDisplay $po [_ "  -v              identify version"];
}


proc About {} {
    global Version;
    if {[PopupDown About] ==1} {return}
    set po [CreateTextDisplay [_ "About"] 56 8];
    BindKeys $po;
    set ::PopupList(About) $po
    AppendToTextDisplay $po [format [_ "This is SndBite version %s, Copyright 2005-2008 William J. Poser.\n"] $Version];
    AppendToTextDisplay $po [_ "\n"];
    AppendToTextDisplay $po [_ "SndBite is a specialized audio editor designed for breaking large recordings into smaller components with great efficiency.  Its principal intended application is in linguistic research where it is often desirable to put each word or sentence into a separate file before further processing.\n"];
    AppendToTextDisplay $po [_ "\n"];
    AppendToTextDisplay $po [_ " You can obtain the latest version of SndBite from: "];
    AppendLinkToTextDisplay $po "http://www.billposer.org/Software/SndBite.html.\n" {ShowWebPage http://www.billposer.org/Software/SndBite.html};
    AppendToTextDisplay $po [_ "\n"];
    AppendToTextDisplay $po [_ "SndBite is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License. A copy of this license is included. Select the License button on the Help menu to display it."];
}


proc BugReports {} {
    global Version;
    global PackageVersion;
    global PauseVersion;
    global tcl_platform;

    if {[PopupDown BugReports] ==1} {return}
    set po [CreateTextDisplay [_ "Bug Reports"] 50 21];
    BindKeys $po;
    set ::PopupList(BugReports) $po
    AppendToTextDisplay $po [_ "Report bugs to: billposer@alum.mit.edu.\n"];
    AppendToTextDisplay $po [_ "Please include the following information:\n\n"];
    AppendToTextDisplay $po [_ "\tWhat version of the program are you using?\n"];
    AppendToTextDisplay $po [format [_ "\t\t(This is version %s.)\n\n"] $Version];
    if {$::PauseAvailableP} {
	AppendToTextDisplay $po [_ "\tWhat version of pause are you using?\n"];
	AppendToTextDisplay $po [format [_ "\t\t(Version located: %s.)\n\n"] $PauseVersion];
    } else {
	AppendToTextDisplay $po "\t";
	AppendLinkToTextDisplay $po "Pause" {ShowWebPage http://www.billposer.org/Software/pause.html};
	AppendToTextDisplay $po [_ " seems to be unavailable.\n\t\tCould that be the problem?\n\n"];
    }
    AppendToTextDisplay $po [_ "\tWhat operating system are you running?.\n"];
    set OS $tcl_platform(os);
    if {$OS == "Linux"} {set OS "GNU/Linux"};
    AppendToTextDisplay $po [format [_ "\t\t(This is %s  %s.)\n\n"] $OS  $tcl_platform(osVersion)];
    AppendToTextDisplay $po [_ "\tWhat window system are you using?.\n"];
    AppendToTextDisplay $po [format [_ "\t\t(This is %s.)\n\n"] $::Pars(WindowSystem)]
    AppendToTextDisplay $po [_ "\tWhat version of tcl/tk are you using?.\n"];
    AppendToTextDisplay $po [format [_ "\t\t(This is version %s.)\n\n"] [info patchlevel]];
    AppendToTextDisplay $po [_ "Bug reports may be sent in any language that I can read without too much trouble or am trying to learn or improve. These include:\n\n"];
    AppendLinkToTextDisplay $po [_ "\tCatalan"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=cat};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tDakelh (Carrier)"] {ShowWebPage http://ydli.org}
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tDutch"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=nld};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tEnglish"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=eng};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tEsperanto"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=epo};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tFrench"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=fra};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tGerman"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=deu};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tItalian"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=ita};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tJapanese"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=jpn};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tKorean"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=kor};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tKazakh"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=kaz};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tLatin"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=lat};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tPortuguese"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=por};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tSpanish"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=spa};
    AppendToTextDisplay $po "\n";
    AppendLinkToTextDisplay $po [_ "\tTurkish"] {ShowWebPage http://www.ethnologue.com/show_language.asp?code=tur};
    AppendToTextDisplay $po "\n";
    AppendToTextDisplay $po "Please note that in many cases although I can understand the language my ability to respond in it may be limited.\n";
    AppendToTextDisplay $po "\n";
}

proc ShowGPL {} {
    if {[PopupDown ShowGPL] ==1} {return}
    set po [CreateTextDisplay [_ "License"] 70 24]
    set ::PopupList(ShowGPL) $po;
    BindKeys $po;
    AppendToTextDisplay $po [format "%s%s" [format "%s\n\t%s\n" [_ "For this license in your language see:"] [_ "http://www.gnu.org/copyleft/gpl.html"]]  "\
\

		GNU GENERAL PUBLIC LICENSE\

   Version 3, 29 June 2007\


 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.
\

Preamble
\

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.
\

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.
\

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
							them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
\

To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
\

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.
\

Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
\

For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
\

Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
\

Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
\

The precise terms and conditions for copying, distribution and
modification follow.
\

TERMS AND CONDITIONS
\

0. Definitions.
\

\"This License\" refers to version 3 of the GNU General Public License.
\

\"Copyright\" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
\

\"The Program\" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as \"you\".  \"Licensees\" and
\"recipients\" may be individuals or organizations.
\

To \"modify\" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a \"modified version\" of the
earlier work or a work \"based on\" the earlier work.
\

A \"covered work\" means either the unmodified Program or a work based
on the Program.
\

To \"propagate\" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
\

To \"convey\" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
\

An interactive user interface displays \"Appropriate Legal Notices\"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
						       extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
\

1. Source Code.
\

The \"source code\" for a work means the preferred form of the work
for making modifications to it.  \"Object code\" means any non-source
form of a work.
\

A \"Standard Interface\" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
\

The \"System Libraries\" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
\"Major Component\", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
\

The \"Corresponding Source\" for a work in object code form means all
the source code needed to generate, install, and (for an executable
						  work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
\

The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
\

The Corresponding Source for a work in source code form is that
same work.
\

2. Basic Permissions.
\

All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
\

You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
\

Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.
\

3. Protecting Users' Legal Rights From Anti-Circumvention Law.
\

No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
\

When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
\

4. Conveying Verbatim Copies.
\

You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
\

You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
\

5. Conveying Modified Source Versions.
\

You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
\

a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
\

b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7.  This requirement modifies the requirement in section 4 to
\"keep intact all notices\".
\

c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy.  This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged.  This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
\

d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
\

A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
\"aggregate\" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
\

6. Conveying Non-Source Forms.
\

You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
\

a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
\

b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
\

c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source.  This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
\

d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge.  You need not require recipients to copy the
Corresponding Source along with the object code.  If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source.  Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
\

e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
\

A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
\

A \"User Product\" is either (1) a \"consumer product\", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, \"normally used\" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
\

\"Installation Information\" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
\

If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
					  been installed in ROM).
\

The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
\

Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
	    source code form), and must require no special password or key for
unpacking, reading or copying.
\

7. Additional Terms.
\

\"Additional permissions\" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
\

When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
      removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
\

Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
				that material) supplement the terms of this License with terms:
\

a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
\

b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
\

c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
\

d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
\

e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
\

f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
					     it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
\

All other non-permissive additional terms are considered \"further
restrictions\" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
\

If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
\

Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
\

8. Termination.
\

You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
	      paragraph of section 11).
\

However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
\

Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
\

Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
\

9. Acceptance Not Required for Having Copies.
\

You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
\

10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.
\

An \"entity transaction\" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
\

You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
\

11. Patents.
\

A \"contributor\" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's \"contributor version\".
\

A contributor's \"essential patent claims\" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, \"control\" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
\

Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
\

In the following three paragraphs, a \"patent license\" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
 sue for patent infringement).  To \"grant\" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
\

If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  \"Knowingly relying\" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
\

If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
\

A patent license is \"discriminatory\" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
\

Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
\

12. No Surrender of Others' Freedom.
\

If conditions are imposed on you (whether by court order, agreement or
				  otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
\

13. Use with the GNU Affero General Public License.
\

Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
\

14. Revised Versions of this License.
\

The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
\

Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License \"or any later version\" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
\

If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
\

Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
\

15. Disclaimer of Warranty.
\

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
\

16. Limitation of Liability.
\

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
				     DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
				     PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
\

17. Interpretation of Sections 15 and 16.
\

If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
"]
}

# tk_exec is like exec but allows updates while the child process is running.
proc tk_exec_fileevent {id} {
    global tk_exec_data
    global tk_exec_cond
    global tk_exec_pipe

    if {[eof $tk_exec_pipe($id)]} {
	fileevent $tk_exec_pipe($id) readable ""
	set tk_exec_cond($id) 1
	return
    }
    append tk_exec_data($id) [read $tk_exec_pipe($id) 1024]
  }

  proc tk_exec {args} {
    global tk_exec_id
    global tk_exec_data
    global tk_exec_cond
    global tk_exec_pipe

    if {![info exists tk_exec_id]} {
	set tk_exec_id 0
    } else {
	incr tk_exec_id
    }
    set keepnewline 0

    for {set i 0} {$i < [llength $args]} {incr i} {
	set arg [lindex $args $i]
	switch -glob -- $arg {
	    -keepnewline {
		set keepnewline 1
	    }
	    -- {
		incr i
		break
	    }
	    -* {
		error "unknown option: $arg"
	    }
            ?* {
		break
	    }
	}
    }

    if {$i > 0} {
	set args [lrange $args $i end]
    }

    set pipe [open "|$args" r]
    set tk_exec_pipe($tk_exec_id) $pipe
    set tk_exec_data($tk_exec_id) ""
    set tk_exec_cond($tk_exec_id) 0

    fconfigure $pipe -blocking 0
    fileevent $pipe readable "tk_exec_fileevent $tk_exec_id"

    vwait tk_exec_cond($tk_exec_id)

    if {$keepnewline} {
	set data $tk_exec_data($tk_exec_id)
    } else {
	set data [string trimright $tk_exec_data($tk_exec_id) \n]
    }

    unset tk_exec_pipe($tk_exec_id)
    unset tk_exec_data($tk_exec_id)
    unset tk_exec_cond($tk_exec_id)

    if {[catch {close $pipe} err]} {
	error "pipe error: $err"
    }
    return $data
  }



proc IndicateCharEntryByCodeUp {} {
	$::CEM entryconfigure $::ToggleCharEntryByCodeIndex \
	    -label [_ "Remove Widget for Entering Characters by Unicode Code"];
	set ::CharEntryByCodeIsDisplayedP 1;
}

proc IndicateCharEntryByCodeDown {} {
	$::CEM entryconfigure $::ToggleCharEntryByCodeIndex \
	    -label [_ "Display Widget for Entering Characters by Unicode Code"];
	set ::CharEntryByCodeIsDisplayedP 0;
}

proc ToggleCharEntryByCode {} {
    global CharEntryByCodeIsDisplayedP;
    global m;

    if { $CharEntryByCodeIsDisplayedP == 0} {
	if {[winfo exists .charent]} {
	    wm deiconify .charent;
	    raise .charent;
	} else { 
	    PopupCharEntryByCode;
	}
	IndicateCharEntryByCodeUp;
    } else {
	wm iconify .charent;
	IndicateCharEntryByCodeDown;
    }
}


namespace import ipaentry::SetDisplayConsonantChartColumnLabelsP
namespace import ipaentry::SetDisplayConsonantChartRowLabelsP
namespace import ipaentry::SetDisplayVowelChartColumnLabelsP
namespace import ipaentry::SetDisplayVowelChartRowLabelsP

namespace eval synchpulse {
    #Detection of synchronization pulse:
    variable ExpectedPeakBinList
    variable MaximumExtentToSearch 1.0; #seconds 
    variable SynchPulseDuration 0.12; #seconds
    variable WindowLength 512; #samples
    variable FramesPerSecond 100

    proc SynchPulseFramesToSeconds {f} {
	variable FramesPerSecond
	return [expr {double($f) / $FramesPerSecond}]
    }

    proc SynchPulseSecondsToFrames {s} {
	variable FramesPerSecond
	return [expr {int($FramesPerSecond * $s)}]
    }

    #Compute the FFT bin containing a given frequency
    proc FrequencyToBin {f} {
	variable WindowLength
	return [expr int(ceil(double($f)/double($::SamplingRate / $WindowLength)))]
    }

    #Return 1 if the arguments are close enough.
    proc CompareBinLists {AList BList} {
	foreach a $AList b $BList {
	    if {abs($a - $b) > 1} {return 0}
	}
	return 1
    }

    proc EvaluateFrame {FrameNumber sn} {
	variable ExpectedPeakBinList
	variable WindowLength
	set StartSample [expr int([SynchPulseFramesToSeconds $FrameNumber] * $::SamplingRate)]
	set Spectrum [$sn powerSpectrum -windowtype Hamming \
			  -start $StartSample -windowlength $WindowLength]
	#Create a list of pairs of FFT values and bin numbers
	set cnt 0
	foreach b $Spectrum {
	    lappend SpectrumList [list $b $cnt]
	    incr cnt
	}
	set RankedSpectrumList [lsort -index 0 -real -decreasing $SpectrumList]
	set ActualPeakBinList [list]
	lappend ActualPeakBinList [lindex [lindex $RankedSpectrumList 0] 1]
	lappend ActualPeakBinList [lindex [lindex $RankedSpectrumList 1] 1]
	lappend ActualPeakBinList [lindex [lindex $RankedSpectrumList 2] 1]
	set ActualPeakBinList [lsort -integer $ActualPeakBinList]
	if {[CompareBinLists $ActualPeakBinList $ExpectedPeakBinList]} {return 1}
	return 0
    }
    
    #Argument is name of sound
    proc LocateSynchPulse {sn} {
	variable ExpectedPeakBinList
	variable MaximumExtentToSearch
	variable SynchPulseDuration
	variable WindowLength

	set SynchPulseLocationSeconds 0.0;
	set FramesPerSecond [expr double($::SamplingRate) / double($WindowLength)]
	set FramesExpectedInSynchPulse [expr int($SynchPulseDuration * $FramesPerSecond)]

	#Compute bins in which spectral peaks should appear
	lappend ExpectedPeakBinList [FrequencyToBin 1100]
	lappend ExpectedPeakBinList [FrequencyToBin 3000]
	lappend ExpectedPeakBinList [FrequencyToBin 4200]
	set ExpectedPeakBinList [lsort -integer $ExpectedPeakBinList]

	if {$MaximumExtentToSearch} {
	    set SearchRegionSeconds [min $MaximumExtentToSearch $::SoundSeconds]
	} else {
	    set SearchRegionSeconds $:SoundSeconds
	}
	set SearchRegionFrames [SynchPulseSecondsToFrames $SearchRegionSeconds]
	set PulseDurationFrames 0
	for {set f 0} {$f < $SearchRegionFrames} {incr f} {
	    set res [EvaluateFrame $f $sn]
	    if {$res} {
		incr PulseDurationFrames
	    } else {
		if {$PulseDurationFrames > 0} {
		    #Detected endpoint of pulse
		    if {$PulseDurationFrames < $FramesExpectedInSynchPulse} {
			set PulseDurationFrames 0
			continue
		    } else {
			set SynchPulseLocationSeconds [SynchPulseFramesToSeconds $f]
			break
		    }
		}
	    }
	}
	return $SynchPulseLocationSeconds
    }
}


namespace eval silence {

    #Each master entry is itself a 3 element list, consisting of a beginning, an end,
    #and a duration, all in samples. Entries on the active list have a
    #fourth element, which is the index of the corresponding entry on the master list.
    variable MasterSilenceList [list];
    variable ActiveSilenceList [list];
    variable SilenceThresholdSeconds 0.500;
    variable LeftSavedSilenceIndex -1;
    variable RightSavedSilenceIndex -1;
    variable SavedPriority Left;
    variable LinearPowerList;

    proc FilterSilenceList {n e o} {
	variable SilenceThresholdSeconds;
	set ThresholdSamples [expr int($SilenceThresholdSeconds * $::SamplingRate)]
	set silence::ActiveSilenceList [list];
	set ActiveCnt 0;
	set MasterCnt 0;
	foreach s $silence::MasterSilenceList {
	    if {[lindex $s 2] > $ThresholdSamples} {
		lappend s $MasterCnt;
		lappend silence::ActiveSilenceList $s;
		incr ActiveCnt;
	    }
	    incr MasterCnt;
	}
	set ::ActiveSilenceCntTxt [format "%3d" $ActiveCnt]
	UpdateSilenceDisplay x y z; #Dummies needed because this is also called from traces
    }

    trace add variable SilenceThresholdSeconds write silence::FilterSilenceList;

    proc ClearSilenceList {} {
	variable MasterSilenceList;
	variable ActiveSilenceList;

	set MasterSilenceList [list];
	set ActiveSilenceList [list];
	set ::MasterSilenceCntTxt "0";
	set ::ActiveSilenceCntTxt "0";
	ClearSilenceDisplay;
    }

    proc SaveDisplayedSilenceList {} {
	variable SilenceThresholdSeconds
	set Text [string trim [$::SILI.lsf.txt get 1.0 end] "\n"]
	if {[string length $Text] == 0} {
	    ShowMessage [_ "There is nothing to save."]
	    return
	}
	set FileName [tk_getSaveFile -defaultextension .txt -title [_ "Specify a File Name"]];
	if {$FileName == ""} {
	    ShowMessage [format [_ "File selection cancelled."]];
	    return ;
	}
	if {[file exists $FileName]} {
	    set resp [ConfirmationDialog .sdt \
			  [format [_ "A File Named %s Already Exists"] $FileName]\
			  [_ "Overwrite the Existing File?"] [_ "No. Let me Choose Another Name"] \
			  [_ "Yes, Overwrite It."]\
			  [_ "Click here if you don't really want to write the region to a file after all."]]
	    switch -exact -- $resp {
		-1 { return }
		0 {
		    set FileName [tk_getSaveFile -defaultextension .txt -title \
				      [_ "Specify a File Name"]];
		    if {$FileName == ""} {
			ShowMessage [_ "File selection cancelled."];
			return ;
		    }
		}
		1 {}
	    }
	}
	if {[catch {open $FileName "w"} SaveHandle ] != 0} {
	    ShowMessage [format [_ "Unable to open file %s."] $FileName];
	    return ;
	} 
	if {$::SilencesInSecondsP} {
	    set Units "seconds"
	} else {
	    set Units "samples"
	}
	set Header [format [_ "\#%s silences in units of %s from file\n\#%s\n\#saved by user %s on %s" ] \
			$::WhichList $Units $::SoundFileName [GetUser] [ISO8601Stamp]]
	if {!$::SilencesInSecondsP} {
	    append Header [format [_ "\n\#Sampling rate: %d"] $::SamplingRate]
	}
	if {[string equal $::WhichList "Active"]} {
	    if {$::SilencesInSecondsP} {
		append Header [format [_ "\n\#Duration threshold: %4.1f"] $SilenceThresholdSeconds]
	    } else {
		set SilenceThresholdSamples [expr int($SilenceThresholdSeconds * $::SamplingRate)]
		append Header [format [_ "\n\#Duration threshold: %d"] $SilenceThresholdSamples]
	    }
	}
	puts $SaveHandle $Header
	puts $SaveHandle $Text
	close $SaveHandle
	ShowMessage [format [_ "Silence list written to file %s"] $FileName]
}


    proc LoadSilenceList {args} {
	variable MasterSilenceList;

	if {[llength $args] > 0} {
	    set FileName [lindex $args 0];
	} else {
	    set FileName [tk_getOpenFile -title [_ "Specify Silence File"]]
	}
	if {$FileName == ""} {
	    ShowMessage [_ "No file name specified."]
	    return ;
	}
	if {[catch {open $FileName "r"} fh] != 0} {
	    ShowMessage [format [_ "LoadSilenceList: Unable to open file %s."] $FileName];
	    return ;
	}
	set MasterSilenceList [list];
	set LineNum 0;
	set EntryNum 0;
	while {![eof $fh]} {
	    gets $fh line;
	    incr LineNum;
	    set line [string trim $line];
	    if {[string length $line] < 1} { continue }
	    incr EntryNum;
	    set entry [split $line];

	    if {[llength $entry] < 2} {
		ShowMessage [format [_ "Ill-formed silence entry at line %d of file %s"] \
				 $LineNum $FileName]
		set MasterSilenceList [list]
		return ;
	    } else {
		if {$EntryNum == 1} {
		    if {[string first "." [lindex $entry 0]] >= 0} {
			set UnitSecondsP 1;
		    } else {
			set UnitSecondsP 0;
		    }
		}
		set begin [lindex $entry 0]
		set end   [lindex $entry 1]
		if {$UnitSecondsP} {
		    set dur [expr $end - $begin]
		} else {
		    set dur [expr $end - $begin +1]
		}
		if {$dur < 0} {
		    ShowMessage \
			[format [_ "Silence entry of negative duration at line %d of file %s"] \
			     $LineNum $FileName]
		    set MasterSilenceList [list];
		    return ;
		}
		if {$UnitSecondsP} {
		    unset entry;
		    lappend entry [SecondsToSamples $begin]
		    lappend entry [SecondsToSamples $end]
		    lappend entry [SecondsToSamples $dur]
		} else {
		    lappend entry $dur
		}
		lappend MasterSilenceList $entry
	    }
	}
	set ::MasterSilenceCntTxt [format [_ "%3d"] $EntryNum]
	FilterSilenceList a b c;
	set ::SilenceFileNameTxt [format [_ "%s"] [file tail $FileName]]
	if {$EntryNum < 1} {
	    ShowMessage [format [_ "File %s contains no silences.\n"] $FileName];
	} else {
	    ShowMessage [format [_ "%d silences read from file %s"] \
			     $EntryNum $FileName]
	}
    }

    #Return linear power value of frame containing sample
    proc GetAmplitude {Sample} {
	variable LinearPowerList	
	set SamplesPerFrame [expr int($::PauseParameters(FrameSize) * $::SamplingRate)]
	set FrameNumber [expr int(floor( double($Sample)/double($SamplesPerFrame)))]
	if {$FrameNumber < [llength $LinearPowerList]} {
	    return [lindex $LinearPowerList $FrameNumber]
	} else {
	    return 0.0
	}
    }

    proc ComputeSilencesInternally {s} {
	variable MasterSilenceList;
	variable LinearPowerList;
	set SamplesPerFrame [expr int($::PauseParameters(FrameSize) * $::SamplingRate)]
	set SamplesPerHalfFrame [expr $SamplesPerFrame/2]
	set WindowLength $SamplesPerFrame
	set MinimumDurationSamples [expr int($::PauseParameters(MinimumDuration)/1000.0 * \
						 $::SamplingRate)]
	set Threshold $::PauseParameters(Threshold)
	set CurrentSampleIndex 1
	set PreviousFrame 0
	set Begin 0
	set EntryNum 0;
	set MasterSilenceList [list];

	set PowerList [$s power \
		       -start $SamplesPerHalfFrame \
		       -end [expr $::SoundLastSample - $SamplesPerHalfFrame] \
		       -framelength $::PauseParameters(FrameSize)\
		       -windowlength $WindowLength\
		       -windowtype hamming]

	#Convert from decibels to linear power units
	foreach f $PowerList {
	    lappend LinearPowerList [expr pow(10.0,(double($f)/20.0))]
	}
	set Frames [llength $LinearPowerList]
	for {set f 0} {$f < $Frames} {incr f} {
	    set amp [lindex $LinearPowerList $f]
	    if {$amp > $Threshold} {
		set CurrentFrame 1
	    } else {
		set CurrentFrame 0
	    }
	    if {$CurrentFrame != $PreviousFrame} {
		if {$CurrentFrame == 0} {
		    set Begin [expr $f * $SamplesPerFrame]
		} else {
		    set End [expr $f * $SamplesPerFrame]
		    set DurationSamples [expr $End - $Begin + 1]
		    if {$DurationSamples > $MinimumDurationSamples} {
			set entry [list]
			lappend entry $Begin
			lappend entry $End
			lappend entry $DurationSamples
			lappend MasterSilenceList $entry
			incr EntryNum
		    }
		}
	    }
	    set PreviousFrame $CurrentFrame
	}
	set ::MasterSilenceCntTxt [format "%3d" $EntryNum]
	FilterSilenceList a b c;
	set ::SilenceFileNameTxt "Internally Computed"
    }

    trace add variable WhichList write silence::UpdateSilenceDisplay
    trace add variable ::SilencesInSecondsP write silence::UpdateSilenceDisplay

    proc FillSilenceDisplay {} {
	if {$::BatchModeP} {return}
	$::SILI.lsf.txt configure -state normal
	set num 0
	if {[string equal $::WhichList "Active"]} {
	    foreach i $silence::ActiveSilenceList {
		incr num;
		$::SILI.lsf.txt insert end [FormatSilenceTxt $i $num]
	    }
	} else {
	    foreach i $silence::MasterSilenceList {
		incr num
		$::SILI.lsf.txt insert end [FormatSilenceTxt $i $num]
	    }
	}
	$::SILI.lsf.txt configure -state disabled
    }

    proc FormatSilenceTxt {entry num} {
	set BeginSamples    [lindex $entry 0]
	set EndSamples      [lindex $entry 1]
	set DurationSamples [lindex $entry 2]
	if {$::SilencesInSecondsP} {
	    set BeginSeconds    [expr double($BeginSamples) / double($::SamplingRate)]
	    set EndSeconds      [expr double($EndSamples) / double($::SamplingRate)]
	    set DurationSeconds [expr double($DurationSamples) / double($::SamplingRate)]
	    return [format "%3d  %s  %s %6.2f\n"  $num [SecondsToMSF $BeginSeconds] \
			[SecondsToMSF $EndSeconds] $DurationSeconds]
	} else {
	    return [format "%3u %8u %8u  %7u\n"  $num $BeginSamples $EndSamples $DurationSamples]
	}
    }

    proc ClearSilenceDisplay {} {
	if {$::BatchModeP} {return}
	$::SILI.lsf.txt configure -state normal
	$::SILI.lsf.txt delete 1.0 end
	$::SILI.lsf.txt configure -state disabled
    }
    
    proc UnpackSilenceListButtons {} {
	pack forget $::SILI.cntls.rb1
	pack forget $::SILI.cntls.rb2
	pack forget $::SILI.cntls.rb3
	pack forget $::SILI.cntls.rb4
    }

    proc PackSilenceListButtons {l} {
	foreach k $l {
	    pack $::SILI.cntls.rb$k -side left -expand 1 -fill both
	}
    }

    proc UpdateSilenceDisplay {n e o} {
	if {$::BatchModeP} {return}
	if {[winfo exists $::SILI.lsf.txt]} {
	    $::SILI.title configure -text [format "%s Silence List" $::WhichList]
	    UnpackSilenceListButtons;
	    if {[string equal $::WhichList Active]} {
		set ButtonList [list 1 3 4];
	    } else {
		set ButtonList [list 2 3 4];
	    }
	    PackSilenceListButtons $ButtonList;
	    ClearSilenceDisplay;
	    silence::FillSilenceDisplay;
	    if {![string equal $n x]} {
		ScrollSilenceDisplay [expr $silence::LeftSavedSilenceIndex - 1]\
		    [expr $silence::RightSavedSilenceIndex - 1] $silence::SavedPriority;
	    }
	}
    }

    proc ScrollSilenceDisplay {LeftIndex RightIndex Priority} {
	if {$::BatchModeP} {return}
	incr LeftIndex;
	incr RightIndex;
	#We save the indices into the Active list.
	set silence::LeftSavedSilenceIndex $LeftIndex;
	set silence::RightSavedSilenceIndex $RightIndex;
	set silence::SavedPriority $Priority;
	#Both indices valid
	if { ($LeftIndex > 0) && ($RightIndex > 0)} {
	    if {[string equal $::WhichList "Active"]} {
		set LeftDesiredLine $LeftIndex
		set RightDesiredLine $RightIndex
	    } else {
		set LeftDesiredLine \
		    [expr 1 + [lindex [lindex $silence::ActiveSilenceList [expr $LeftIndex -1]] 3]];
		set RightDesiredLine \
		    [expr 1 + [lindex [lindex $silence::ActiveSilenceList [expr $RightIndex -1]] 3]];
	    }
	    silence::TagSilenceLeft $LeftDesiredLine;
	    silence::TagSilenceRight $RightDesiredLine;
	    if {$RightDesiredLine - $LeftDesiredLine < $::SilenceListHeight} {
		$::SILI.lsf.txt yview [expr $LeftDesiredLine - 1];
	    } elseif {[string equal $Priority "Left"]} {
		$::SILI.lsf.txt yview [expr $LeftDesiredLine - 1];
	    } else {
		$::SILI.lsf.txt yview [expr $RightDesiredLine  - $::SilenceListHeight];
	    }
	    return;
	}
	#Only right index valid
	if {$RightIndex > 0} {
	    if {[string equal $::WhichList "Active"]} {
		set RightDesiredLine $RightIndex
	    } else {
		set RightDesiredLine [lindex [lindex $silence::ActiveSilenceList $RightIndex] 3];
	    }
	    silence::TagSilenceRight $RightDesiredLine;
	    silence::UntagSilenceLeft;
	    set silence::RightSavedSilenceIndex $RightDesiredLine;
	    $::SILI.lsf.txt yview [expr $RightDesiredLine - 2];
	    return ;
	}
	#Only left index valid
	if {$LeftIndex > 0} {
	    if {[string equal $::WhichList "Active"]} {
		set LeftDesiredLine $LeftIndex
	    } else {
		set LeftDesiredLine [lindex [lindex $silence::ActiveSilenceList $LeftIndex] 3];
	    }
	    silence::TagSilenceLeft $LeftDesiredLine;
	    silence::UntagSilenceRight;
	    set silence::LeftSavedSilenceIndex $LeftDesiredLine;
	    $::SILI.lsf.txt yview [expr $LeftDesiredLine - 2];
	    return ;
	}
	#Neither index valid
	set silence::LeftSavedSilenceIndex  -1;
	set silence::RightSavedSilenceIndex -1;
	silence::UntagSilenceLeft;
	silence::UntagSilenceRight;
    }

    proc TagSilenceLeft {Line} {
	$::SILI.lsf.txt tag delete lhl
	$::SILI.lsf.txt tag configure lhl -background $::ColorSpecs(LeftSilenceHighlight,Foreground);
	$::SILI.lsf.txt tag add lhl $Line.0 $Line.end
    }

    proc TagSilenceRight {Line} {
	$::SILI.lsf.txt tag delete rhl
	$::SILI.lsf.txt tag configure rhl -background $::ColorSpecs(RightSilenceHighlight,Foreground);
	$::SILI.lsf.txt tag add rhl $Line.0 $Line.end
    }

    proc UntagSilenceLeft {} {
	$::SILI.lsf.txt tag delete lhl
    }

    proc UntagSilenceRight {} {
	$::SILI.lsf.txt tag delete rhl
    }

    proc SetSilenceThreshold {args} {
	variable SilenceThresholdSeconds;
	if {[llength $args]} {
	    return $SilenceThresholdSeconds;
	}
	set cand  [.info.silence.threshold get]
	if {[string length $cand] > 0} {
	    if {$cand > 0.0} {
		set SilenceThresholdSeconds $cand;
	    }
	}
    }
}

proc OverWritePreviousFile {} {
    if {$::OutFileIndex > 1} {
	incr ::OutFileIndex -1; 
	.info.sfname.next delete 0 end
	set FileName $::LastSegmentFileWritten;
	.info.sfname.next insert insert $FileName
	WriteWindow -1;
    } else {
	ShowMessage [_ "There is no previous file to over-write"]
    }
}

#If no argument, toggle amplitude mode
#If an argument is supplied, change to that value
proc ToggleAmplitudeMode {args} {
    if {[llength $args]} {
	set AmplitudeModeP [expr ![lindex $args 0]]
    } else {
	set AmplitudeModeP $::AmplitudeModeP
    }
    if {$AmplitudeModeP} {
	set ::AmplitudeModeP 0
	if {$::InteractiveP} {
	    ShowMessage [_ "No longer in amplitude mode."]
	}
    } else {
	set ::AmplitudeModeP 1
	if {$::InteractiveP} {
	    ShowMessage [_ "Now in amplitude mode."]
	}
    }
}


proc ShowAmplitudeAtPointer {w x} {
    set Sample [PixelToSample $w $x]
    set Amplitude [silence::GetAmplitude $Sample]
    set Time [SamplesToSeconds $Sample]
    ShowMessage [format [_ "Amplitude at %5.2f = %3.0f"] $Time $Amplitude]
}

proc ConstructHistoryPopup {} {
    toplevel .hl
    label .hl.hdr -text "Region    Duration  File"
    listbox .hl.hlist -height 6 -width 0 -font RegexpFont \
	-fg $::ColorSpecs(HistoryList,Foreground) \
	-bg $::ColorSpecs(HistoryList,Background) \
	-yscrollcommand {.hl.sbar set} \
	-font HistoryListFont
    scrollbar .hl.sbar -command {.hl.hlist yview} \
	-trough $::ColorSpecs(HistoryList,Background);
    bind .hl.sbar <<B3>> "ScrollbarMoveBigIncrement .hl.sbar 0.20 %x %y"
    pack .hl.hdr -side top -expand 1 -fill both
    pack .hl.sbar -side right -anchor w -expand 0 -fill y
    pack .hl.hlist -side right -anchor w -expand 1 -fill both
    wm title .hl [_ "Write History"]
    wm protocol .hl WM_DELETE_WINDOW "wm withdraw .hl"
    wm withdraw .hl
}

proc AppendToHistoryList {s} {
    set Number [format "%3d" [expr {$::WriteCnt + 1}]]
    set txt [format "%s %s" $Number $s]
    .hl.hlist insert end $txt
    if {$::WriteCnt % 2} {
	.hl.hlist itemconfigure $::WriteCnt -background $::ColorSpecs(HistoryList,AltBackground)
	.hl.hlist itemconfigure $::WriteCnt -foreground $::ColorSpecs(HistoryList,AltForeground)
    } 
    incr ::WriteCnt
}

proc ToggleHistoryPopup {e o n} {
    if {$::DisplayHistoryPopupP} {
	wm deiconify .hl
    } else {
	wm withdraw  .hl
    }
}

proc SaveSegmentList {args} {
    if {[llength $args] > 0} {
	set FileName [lindex $args 0]
    } else {
	set FileName [tk_getSaveFile \
			  -initialfile [_ "SegmentList"] \
			  -title [_ "Specify Segment File"]]
	if {$FileName == ""} {
	    ShowMessage [_ "No file name specified."]
	    return 
	}
    }
    set FileName [MinimizeFileName $FileName]
    if {[catch {open $FileName "w"} fh] != 0} {
	ShowMessage [format [_ "SaveSegmentList: Unable to open file %s."] $FileName]
	return 
    }
    puts $fh [format [_ "\#Segments in file %s\n\#written by %s at %s in %s"]  \
		  $::SoundFileName [GetUser] [clock format [clock seconds]] [pwd]]
    foreach s $::SegmentList {
	set lb [lindex $s 0]
	set rb [lindex $s 1]
	set fn [lindex $s 2]
	puts $fh [format "AppendToSegmentList \{%s %s %s\}" $lb $rb $fn]
    }
    close $fh
    ShowMessage [format [_ "Segment list saved to file %s"] $FileName]
}

#Argument is a list consisting of the left and right bounds, in seconds, followed by the
#file name.
proc AppendToSegmentList {sg} {
    lappend ::SegmentList $sg
}

proc OverWriteSegmentList {sg} {
    set ::SegmentList [lreplace ::SegmentList end end $sg]
}

proc ClearSegmentList {} {
    set ::SegmentList [list]
}

proc ScrollSegmentDisplay {} {
    if {$::BatchModeP} {return}
    UntagSegment
    TagSegment [expr $::CurrentSegmentIndex + 1]
    if {$::CurrentSegmentIndex >= 0} {
	$::SEGLI.lsf.txt yview $::CurrentSegmentIndex
    }
}

proc TagSegment {Line} {
    $::SEGLI.lsf.txt tag delete lhl
    $::SEGLI.lsf.txt tag configure lhl -background $::ColorSpecs(SegmentHighlight,Foreground);
    $::SEGLI.lsf.txt tag add lhl $Line.0 $Line.end
}

proc UntagSegment {} {
    $::SEGLI.lsf.txt tag delete lhl
}

proc WriteSegments {} {
    foreach sg $::SegmentList {
	set LWriteBound [SecondsToSamples [lindex $sg 0]]
	set RWriteBound [SecondsToSamples [lindex $sg 1]]
	set FileName [lindex $sg 2]
	snd write $FileName -start $LWriteBound -end $RWriteBound;
    } 
    ShowMessage [_ "Wrote segments"]
}

#Remove the current segment from the list
proc DeleteCurrentSegment {} {
    set Segments [llength $::SegmentList]
    if {!(($::CurrentSegmentIndex < $Segments) && ($::CurrentSegmentIndex >= 0))} {return}
    set ::SegmentList [lreplace $::SegmentList $::CurrentSegmentIndex $::CurrentSegmentIndex]
    UpdateSegmentDisplay x y z
}

#Replace the current entry in the segment list with the current segment
#The filename is unchanged - just the boundaries are changed.
proc ReplaceCurrentSegment {} {
    set Segments [llength $::SegmentList]
    if {!(($::CurrentSegmentIndex < $Segments) && ($::CurrentSegmentIndex >= 0))} {return}
    set FileName [lindex [lindex $::SegmentList $::CurrentSegmentIndex] 2]
    set LBText [format "%.4f" [SamplesToSeconds $::WindowLeftEdge]]
    set RBText [format "%.4f" [SamplesToSeconds $::WindowRightEdge]]
    set ::SegmentList [lreplace $::SegmentList $::CurrentSegmentIndex $::CurrentSegmentIndex \
			   [list $LBText $RBText $FileName]]
    UpdateSegmentDisplay x y z
}

proc GotoNextSegment {dir} {
    incr ::CurrentSegmentIndex $dir
    set Segments [llength $::SegmentList]
    if {!(($::CurrentSegmentIndex < $Segments) && ($::CurrentSegmentIndex >= 0))} {return}
    set SegmentInfo [lindex $::SegmentList $::CurrentSegmentIndex]
    set lb [lindex $SegmentInfo 0]
    set rb [lindex $SegmentInfo 1]
    set OldWLE $::WindowLeftEdge;
    set OldWRE $::WindowRightEdge;
    set ::WindowLeftEdge [SecondsToSamples $lb]
    set ::WindowRightEdge [SecondsToSamples $rb]
    CheckWindowBounds;
    if {!$::BatchModeP} {
	ShowWavebar;
	if { ($::WindowLeftEdge <= $::NeighborhoodLeftEdge) || \
		 ($::WindowRightEdge >= $::NeighborhoodRightEdge)} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateLeftCut;
	UpdateRightCut;
	set Delta [expr $::SamplingRate * 0.001]
	if { abs($::WindowLeftEdge - $OldWLE) > $Delta} {
	    silence::UntagSilenceLeft;
	}
	if { abs($::WindowRightEdge - $OldWRE) > $Delta} {
	    silence::UntagSilenceRight;
	}
    }
    ScrollSegmentDisplay
    AnnounceWindowBounds;
    #AutoPlayWindow
}

#This is for exposure in scripts.
proc WriteWindowNoCheck {} {
    WriteWindow 0;
}

proc WriteWindow {Code} {
    set CheckP 0
    set OverWriteP 0
    if {$Code == 1} {
	set CheckP 1
    } elseif {$Code == -1} {
	set OverWriteP 1
    }
    if {$::BatchModeP} {
	set FileName [ConstructOutFileName]
    } else {
	set FileName [.info.sfname.next get]
    }
    set FileName [MinimizeFileName $FileName]
    if {$CheckP && !$::DeferWritesP} {
	if {[file exists $FileName]} {
	    #Disable write button
	    .cntls.b1 configure -state disabled
	    set resp [ConfirmationDialog .sdt \
		  [format [_ "A File Named %s Already Exists"] $FileName]\
		  [_ "Overwrite the Existing File?"] [_ "No. Let me Choose Another Name"] \
			  [_ "Yes, Overwrite It."]\
		  [_ "Click here if you don't really want to write the window to a file after all."]]
	    #Re-enable write button now that we've got a response
	    .cntls.b1 configure -state normal
	    switch -exact -- $resp {
		-1 { return }
		0 {
		    set FileName [tk_getSaveFile -defaultextension .wav -title \
				      [_ "Specify a File Name"]];
		    if {$FileName == ""} {
			ShowMessage [_ "File selection cancelled."];
			return ;
		    }
		    set FileName [MinimizeFileName $FileName]
		}
		1 {}
	    }
	}
    }
    set LWriteBound [expr $::WindowLeftEdge  - [SecondsToSamples $::WriteMargin]];
    set RWriteBound [expr $::WindowRightEdge + [SecondsToSamples $::WriteMargin]];
    if {$LWriteBound < 0} {
	set LWriteBound 0;
    }
    if {$RWriteBound > $::SoundLastSample} {
	set RWriteBound $::SoundLastSample;
    }
    if {!$::DeferWritesP} {
	snd write $FileName -start $LWriteBound -end $RWriteBound;
    }
    set LBSeconds [SamplesToSeconds $LWriteBound]
    set RBSeconds [SamplesToSeconds $RWriteBound]
    if {$::UseSecondsP($::C)} {
	set Region [format "\[%4.3f,%4.3f\]" $LBSeconds $RBSeconds]
	set Duration [format "%5.3f" [SamplesToSeconds [expr $RWriteBound - $LWriteBound]]]
    } else {
	set Region [format "\[%0*d,%0*d\]" $::SampleStrLen $LWriteBound\
			       $::SampleStrLen $RWriteBound];
	set Duration [expr $RWriteBound - $LWriteBound]
    }
    if {$OverWriteP} {
	set msg [format [_ "File %s overwritten with region %s duration %s."] \
		     $FileName $Region $Duration];
    } else {
	set msg [format [_ "Region %s duration %s written to file %s"] \
		     $Region $Duration $FileName];
    }
    ShowMessage $msg;
    WriteJournal $msg;
    AppendToHistoryList [format [_ "%15s  %5s   %s"] $Region $Duration $FileName]
    set LBText [format "%.4f" $LBSeconds]
    set RBText [format "%.4f" $RBSeconds]
    if {$OverWriteP} {
	OverWriteSegmentList [list $LBText $RBText $FileName]
    } else {
	AppendToSegmentList [list $LBText $RBText $FileName]
    }
    UpdateSegmentDisplay x y z
    set ::LastWriteInfo [format "\[%0*d,%0*d\] %s" $::SampleStrLen \
		     $LWriteBound $::SampleStrLen $RWriteBound $FileName]
    if {!$::BatchModeP} {
	.info.sfname.last configure -anchor w
    }
    set ::LastSegmentFileWritten [file tail $FileName]
    #Don't increment the index if we're writing to a file named by the user.
    if {[string equal $FileName [ConstructOutFileName]]} {
	incr ::OutFileIndex;
    }
    UpdateNextOutFileName x y z
    if {$::AutoPlayWritesP} {
	PlayNamedFile $FileName;
    }
}

proc SaveRegionToFile {args} {
    set start $::WindowLeftEdge;
    set end   $::WindowRightEdge;
    if {[llength $args] > 0} {
	set FileName [lindex $args 0];
	if {[llength $args] > 1} {
	    set start [lindex $args 1];
	    set end   [lindex $args 2];
	}
    } else {
	set FileName [tk_getSaveFile -defaultextension .wav -title [_ "Specify a File Name"]];
	if {$FileName == ""} {
	    ShowMessage [format [_ "File selection cancelled."]];
	    return ;
	}
    }
    if {[file exists $FileName]} {
	set resp [ConfirmationDialog .sdt \
		      [format [_ "A File Named %s Already Exists"] $FileName]\
		      [_ "Overwrite the Existing File?"] [_ "No. Let me Choose Another Name"] [_ "Yes, Overwrite It."]\
		      [_ "Click here if you don't really want to write the region to a file after all."]]
	switch -exact -- $resp {
	    -1 { return }
	    0 {
		set FileName [tk_getSaveFile -defaultextension .wav -title [_ "Specify a File Name"]];
		if {$FileName == ""} {
		    ShowMessage [_ "File selection cancelled."];
		    return ;
		}
	    }
	    1 {}
	}
    }
    if {[catch {open $FileName "w"} SaveHandle ] != 0} {
	ShowMessage [format [_ "Unable to open file %s."] $FileName];
	return ;
    } else {close $SaveHandle};

    snd write $FileName -start $start -end $end;
    if {$::AutoPlayWritesP} {
	PlayNamedFile $FileName;
    }
    ShowMessage [format [_ "Region \[%0*d,%0*d\] written to file %s"] $::SampleStrLen \
		     $start $::SampleStrLen $end $FileName];
    set ::LastWriteInfo [format "\[%0*d,%0*d\] %s" $::SampleStrLen \
		     $start $::SampleStrLen $end $FileName]
}

proc WriteRegionToFile {Start End FileName} {
    if {$Start < 0} {
	ShowMessage [format [_ "%s precedes the beginning of the file."] $Start];
	return
    }
    if {$End > $::SoundLastSample} {
	ShowMessage [format [_ "%s follows the end of the file."] $End];
	return
    }
    if {[catch {open $FileName "w"} SaveHandle ] != 0} {
	ShowMessage [format [_ "Unable to open file %s."] $FileName];
	return ;
    } else {close $SaveHandle};
    snd write $FileName -start $Start -end $End;
    ShowMessage [format [_ "Region \[%0*d,%0*d\] written to file %s"] $::SampleStrLen \
		     $Start $::SampleStrLen $End $FileName];
    AppendToHistoryList [format [_ "%15s  %5s   %s"] $Region $Duration $FileName]
}


proc SamplesToSeconds {s} {
    return [expr double($s)/double($::SamplingRate)]
}

proc SecondsToSamples {s} {
    return [expr int($s * double($::SamplingRate))]
}

proc PixelToSample {w x} { 
    set ThisWindowLeftEdgePixels [expr int([lindex [$w xview] 0] * $::WaveformInfo($w,PixelsInWaveform))]
    set XInPixels [expr $x + $ThisWindowLeftEdgePixels];
    set XInSamplesReFirstSample [expr int(double($XInPixels) / $::WaveformInfo($w,PixelsPerSample))] 
    set XInSamplesAbsolute [expr $XInSamplesReFirstSample + $::WaveformInfo($w,FirstSample)]
    return $XInSamplesAbsolute;
}

proc SetCoords {w x y} {
    #set Y [expr $::WaveformInfo($w,ZeroHeight) - $y]; 
    set XSamples [PixelToSample $w $x]
    if {$::UseSecondsP($w)} {
	set XSeconds [expr double($XSamples)/double($::SamplingRate)]
	set msg [format "%6.3f" $XSeconds]
    } else {
	set msg [format "%9d" $XSamples]
    }
    if {$::AmplitudeModeP} {
	set msg [format "%s  %3.0f" $msg [silence::GetAmplitude [PixelToSample $w $x]]]
    }
    set ::InfoBar($w) $msg
}

proc ToggleUseSeconds {wi} {
    set w [string range $wi 0 "end-5 "]
    if {$::UseSecondsP($w)} {
	set ::UseSecondsP($w) 0;
    } else {
	set ::UseSecondsP($w) 1;
    }
    if {[string equal $w $::C]} {
	UpdateWindowBoundsBar;
    }
}

proc RedrawEverything {} {
    ShowWavebar;
    SetNeighborhood;
    UpdateRightCut;
    UpdateLeftCut;
    AnnounceWindowBounds;
}

proc SetLeftEdgeOverview {x} {
    set ::WindowLeftEdge [PixelToSample .ov $x]
    if {$::SetLeftEdgeOverviewImmediateP} {
	if {![CheckWindowBounds]} {
	    UpdateLeftEdge;
	} else {
	    RedrawEverything;
	}
    }
    silence::UntagSilenceLeft;
}

proc SetRightEdgeOverview {x} {
    set ::WindowRightEdge [PixelToSample .ov $x]
    if {![CheckWindowBounds]} {
	UpdateRightEdge;
    } else {
	RedrawEverything;
    }
    silence::UntagSilenceRight;
}

proc SetLeftEdgeCloseup {x} {
    set ::WindowLeftEdge [PixelToSample $::CLUPL $x]
    $::CLUPL delete $::LeftCutMark;
    set ::LeftCutMark [DrawLeftCutMark];
    AnnounceWindowBounds;
}

proc SetRightEdgeCloseup {x} {
    set ::WindowRightEdge [PixelToSample $::CLUPR $x]
    $::CLUPR delete $::RightCutMark;
    set ::RightCutMark [DrawRightCutMark];
    AnnounceWindowBounds;
}

proc SetLeftEdgeNeighborhood {x} {
    set ::WindowLeftEdge [PixelToSample .c $x]
    if {![CheckWindowBounds]} {
	ShowNeighborhood;
	UpdateLeftCut;
	AnnounceWindowBounds;
    } else {
	RedrawEverything;
    }
    silence::UntagSilenceLeft;
}

proc SetRightEdgeNeighborhood {x} {
    set ::WindowRightEdge [PixelToSample .c $x]
    RedrawEverything
    silence::UntagSilenceRight
}

proc PlayWindow {} {
    if {$::SoundSamples < 1} {
	ShowMessage [_ "There is no sound to play"]
	return ;
    }
    if {$::AutoScaleSoundP} {
	set WindowMax [snd max -start $::WindowLeftEdge -end $::WindowRightEdge]
	set WindowMin [snd min -start $::WindowLeftEdge -end $::WindowRightEdge]
	set WindowRange [expr $WindowMax - $WindowMin]
	set DoubleWindowRange [expr double($WindowRange)];
	if {$DoubleWindowRange > 0.0} {
	    set ScaleFactor [expr double($::SoundRange)/$DoubleWindowRange]
	    audio scaling $ScaleFactor
	}
    }
    snd play -start $::WindowLeftEdge -end $::WindowRightEdge -command StopPlayMarkerWindow
    set ::PlayCommand window
    PutPlayMarkerWindow 1;
}

proc PlayNeighborhood {} {
    if {$::SoundSamples < 1} {
	ShowMessage [_ "There is no sound to play"]
	return ;
    }
    snd play -start $::NeighborhoodLeftEdge -end $::NeighborhoodRightEdge \
	-command StopPlayMarkerNeighborhood
    set ::PlayCommand neighborhood
    PutPlayMarkerNeighborhood 1
}

proc PlayWavebar {} {
    if {$::SoundSamples < 1} {
	ShowMessage [_ "There is no sound to play"]
	return ;
    }
    set fl [.ov xview]
    set FirstPixelVisible   [expr [lindex $fl  0] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set LastPixelVisible    [expr [lindex $fl  1] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set FirstSampleVisible  [expr int(double($FirstPixelVisible) / $::WaveformInfo(.ov,PixelsPerSample))]
    set LastSampleVisible   [expr int(double($LastPixelVisible)  / $::WaveformInfo(.ov,PixelsPerSample))]
    snd play -start $FirstSampleVisible -end $LastSampleVisible -command StopPlayMarkerWavebar
    set ::PlayCommand wavebar
    PutPlayMarkerWavebar 1;
    #Note that we omit adding $::WaveformInfo(.ov,FirstSample) to the expressions
    #for first and last sample as in PixelToSample because we know that in the
    #wavebar window this value is always 0.
}

proc PlayFile {} {
    if {$::SoundSamples < 1} {
	ShowMessage [_ "There is no sound to play"]
	return ;
    }
    snd play -command StopPlayMarker
}

proc PlayNamedFile {fn} {
    sound wvsnd -file $fn;
    wvsnd play;
    wvsnd destroy;
}

proc StopPlay {} {
    snd stop;
    switch -exact -- $::PlayCommand {
	window {PutPlayMarkerWindow 0}
	neighborhood {PutPlayMarkerNeighborhood 0}
	wavebar {PutPlayMarkerWavebar 0}
    }
}
proc AutoPlayWindow {} {
    if {$::AutoPlayP && $::InteractiveP} {PlayWindow}
}

proc StopPlayMarkerWindow {} {
    PutPlayMarkerWindow 0
    after 50
    after cancel PutPlayMarkerWindow 1
    after cancel PutPlayMarkerWindow 0
}

proc StopPlayMarkerNeighborhood {} {
    PutPlayMarkerNeighborhood 0
    after 50
    after cancel PutPlayMarkerNeighborhood 1
    after cancel PutPlayMarkerNeighborhood 0
}

proc StopPlayMarkerWavebar {} {
    PutPlayMarkerWavebar 0
    after 50
    after cancel PutPlayMarkerWavebar 1
    after cancel PutPlayMarkerWavebar 0
}

proc PutPlayMarkerWindow {ContinueP} {
    if {$::BatchModeP} {return}
    set PlayTimeElapsedSeconds [audio elapsed];
    set fl [.ov xview]
    set FirstPixelVisible   [expr [lindex $fl  0] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set FirstSampleVisible  [expr int(double($FirstPixelVisible) / $::WaveformInfo(.ov,PixelsPerSample))]
    set SpWindowOffsetSamples [expr $::WindowLeftEdge - $FirstSampleVisible]
    set SpWindowOffsetPixels  [expr $SpWindowOffsetSamples * $::WaveformInfo(.ov,PixelsPerSample)]
    set FirstPixelInSpWindow [expr $FirstPixelVisible + $SpWindowOffsetPixels]
    set SamplesInSpWindow [expr $::WindowRightEdge - $::WindowLeftEdge + 1]
    set SamplesPlayed [expr $PlayTimeElapsedSeconds * $::SamplingRate];
    set PixelsPlayed [expr $SamplesPlayed * $::WaveformInfo(.ov,PixelsPerSample)]
    set x [expr $PixelsPlayed + $FirstPixelInSpWindow]
    set y [expr $::WavebarHeight]
    .ov coords pm [expr $x-5] $y $x [expr $y-10] [expr $x+5] $y
    if {$ContinueP} {
	after 50 PutPlayMarkerWindow 1
    }
}

proc PutPlayMarkerNeighborhood {ContinueP} {
    set PlayTimeElapsedSeconds [audio elapsed];
    set fl [.ov xview]
    set FirstPixelVisible   [expr [lindex $fl  0] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set LastPixelVisible    [expr [lindex $fl  1] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set FirstSampleVisible  [expr int(double($FirstPixelVisible) / $::WaveformInfo(.ov,PixelsPerSample))]
    set NeighborhoodOffsetSamples [expr $::NeighborhoodLeftEdge - $FirstSampleVisible]
    set NeighborhoodOffsetPixels  [expr $NeighborhoodOffsetSamples * $::WaveformInfo(.ov,PixelsPerSample)]
    set FirstPixelInNeighborhood [expr $FirstPixelVisible + $NeighborhoodOffsetPixels]
    set SamplesInNeighborhood [expr $::NeighborhoodRightEdge - $::NeighborhoodLeftEdge + 1]
    set SamplesPlayed [expr $PlayTimeElapsedSeconds * $::SamplingRate];
    set PixelsPlayed [expr $SamplesPlayed * $::WaveformInfo(.ov,PixelsPerSample)]
    set x [expr $PixelsPlayed + $FirstPixelInNeighborhood]
    if {$x > $LastPixelVisible} {
	return;
    }
    set y [expr $::WavebarHeight]
    .ov coords pm [expr $x-5] $y $x [expr $y-10] [expr $x+5] $y
    if {$ContinueP} {
	after 50 PutPlayMarkerNeighborhood 1
    }
}

proc PutPlayMarkerWavebar {ContinueP} {
    set PlayTimeElapsedSeconds [audio elapsed];
    set fl [.ov xview]
    set FirstPixelVisible   [expr [lindex $fl  0] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set SamplesPlayed [expr $PlayTimeElapsedSeconds * $::SamplingRate];
    set PixelsPlayed [expr $SamplesPlayed * $::WaveformInfo(.ov,PixelsPerSample)]
    set x [expr $PixelsPlayed + $FirstPixelVisible]
    set y [expr $::WavebarHeight]
    .ov coords pm [expr $x-5] $y $x [expr $y-10] [expr $x+5] $y
    if {$ContinueP} {
	after 50 PutPlayMarkerWavebar 1
    }
}

proc ShowCloseup {canvas Snd center} {
    if {$center > $::SoundSamples} return ;
    if {$::SoundSamples == 0} return ;
    set XOffset 0;
    set YOffset 0;
    set PixelsPerSample $::WaveformInfo(Closeup,PixelsPerSample)
    set ::WaveformInfo($canvas,ZeroHeight) [expr ($::CloseupHeight - $YOffset)/2]
    set SamplingRate [lindex [$Snd info] 1];
    set FirstSample [expr $center - int($::CutMargin/double($PixelsPerSample))];
    set LastSample  [expr $center + int($::CutMargin/double($PixelsPerSample))];
    set RequestedFirstSample $FirstSample
    set RequestedLastSample  $LastSample

    if {$FirstSample < 0} {
	set XOffset [expr $XOffset - $FirstSample]
	set FirstSample 0;
    }
    if {$LastSample > $::SoundLastSample} {
	set LastSample $::SoundLastSample;
    }

    set ::WaveformInfo($canvas,FirstSample) $FirstSample;
    set ::WaveformInfo($canvas,zxlist) [GetZeroCrossings $Snd $FirstSample $LastSample];
    set width [expr ($RequestedLastSample - $RequestedFirstSample + 1) * $PixelsPerSample]
    set ::WaveformInfo($canvas,PixelsInWaveform) $width

    if {!$::BatchModeP} {
	set wf [$canvas create waveform $XOffset $YOffset  -sound $Snd  -frame 0 \
		-height $::CloseupHeight -fill $::ColorSpecs(CloseupWaveform,Foreground) \
		     -pixelspersecond [expr $SamplingRate * $PixelsPerSample] \
		     -start $FirstSample -end $LastSample]
    } else {
	set wf 0;			# This is a meaningless value in batch mode
					# but won't ever be used.	
    }
    return $wf;
}

proc ZeroCrossingNextLeft {{RefPt -1}} {
    set new -1;
    set zxl $::WaveformInfo($::CLUPL,zxlist);
    if {$RefPt < 0} {
	set rpt $::WindowLeftEdge;
    } else {
	set rpt $RefPt;
    }
    set pts [llength $zxl];
    for {set i 0} {$i < $pts} {incr i} {
	set zxp [lindex $zxl $i];
	if {$zxp > $rpt} {
	    set new $zxp;
	    break ;
	}
    }
    if {$RefPt > -1} {
	return $new
    }
    if {$new >= 0} {
	set ::WindowLeftEdge $new;
	$::CLUPL delete $::LeftCutMark;
	set ::LeftCutMark [DrawLeftCutMark];
	UpdateWindowBoundsBar;
	if {$::UseSecondsP($::CLUPL)} {
	    set msg [format [_ "Left edge moved to zero-crossing at %7.5f"] \
			 [SamplesToSeconds $new]];
	} else {
	    set msg [format [_ "Left edge moved to zero-crossing at %d."] $new];
	}
	ShowMessage $msg;
    } else {
	ShowMessage [_ "There is no zero crossing within range to the right."]
    }
}

proc ZeroCrossingNextRight {{RefPt -1}} {
    set new -1;
    set zxl $::WaveformInfo($::CLUPR,zxlist);
    if {$RefPt < 0} {
	set rpt $::WindowRightEdge;
    } else {
	set rpt $RefPt;
    }
    set pts [llength $zxl];
    for {set i 0} {$i < $pts} {incr i} {
	set zxp [lindex $zxl $i];
	if {$zxp > $rpt} {
	    set new $zxp;
	    break ;
	}
    }
    if {$RefPt > -1} {
	return $new
    }
    if {$new >= 0} {
	set ::WindowRightEdge $new;
	if {!$::BatchModeP} {
	    $::CLUPR delete $::RightCutMark;
	    set ::RightCutMark [DrawRightCutMark];
	    UpdateWindowBoundsBar;
	}
	if {$::UseSecondsP($::CLUPR)} {
	    set msg [format [_ "Right edge moved to zero-crossing at %7.5f"] \
			 [SamplesToSeconds $new]];
	} else {
	    set msg [format [_ "Right edge moved to zero-crossing at %d."] $new];
	}
	ShowMessage $msg
    } else {
	ShowMessage [_ "There is no zero crossing within range to the right."]
    }
}

proc ZeroCrossingPrevRight {{RefPt -1}} {
    set new -1;
    set zxl $::WaveformInfo($::CLUPR,zxlist);
    if {$RefPt < 0} {
	set rpt $::WindowRightEdge;
    } else {
	set rpt $RefPt;
    }
    set pts [llength $zxl];
    for {set i [expr $pts -1]} {$i >= 0} {incr i -1} {
	set zxp [lindex $zxl $i];
	if {$zxp < $rpt} {
	    set new $zxp;
	    break ;
	}
    }
    if {$RefPt > -1} {
	return $new
    }
    if {$new >= 0} {
	set ::WindowRightEdge $new;
	$::CLUPR delete $::RightCutMark;
	set ::RightCutMark [DrawRightCutMark];
	UpdateWindowBoundsBar;
	if {$::UseSecondsP($::CLUPR)} {
	    set msg [format [_ "Right edge moved to zero-crossing at %7.5f"] \
			 [SamplesToSeconds $new]];
	} else {
	    set msg [format [_ "Right edge moved to zero-crossing at %d."] $new];
	}
	ShowMessage $msg
    } else {
	ShowMessage [_ "There is no zero crossing within range to the left."]
    }
}

proc ZeroCrossingPrevLeft {{RefPt -1}} {
    set new -1;
    set zxl $::WaveformInfo($::CLUPL,zxlist);
    if {$RefPt < 0} {
	set rpt $::WindowLeftEdge;
    } else {
	set rpt $RefPt;
    }
    set pts [llength $zxl];
    for {set i [expr $pts -1]} {$i >= 0} {incr i -1} {
	set zxp [lindex $zxl $i];
	if {$zxp < $rpt} {
	    set new $zxp;
	    break ;
	}
    }
    if {$RefPt > -1} {
	return $new
    }
    if {$new >= 0} {
	set ::WindowLeftEdge $new;
	if {!$::BatchModeP} {
	    $::CLUPL delete $::LeftCutMark;
	    set ::LeftCutMark [DrawLeftCutMark];
	    UpdateWindowBoundsBar;
	}
	if {$::UseSecondsP($::CLUPL)} {
	    set msg [format [_ "Left edge moved to zero-crossing at %7.5f"] \
			 [SamplesToSeconds $new]];
	} else {
	    set msg [format [_ "Left edge moved to zero-crossing at %d."] \
			 $new];
	}
	ShowMessage $msg;
    } else {
	ShowMessage [_ "There is no zero crossing within range to the left."]
    }
}

#Return a list of indices of samples immediately before which a
#zero-crossing occurs.
#Arguments: sound name, index of first sample, index of last sample
proc GetZeroCrossings {s f l} {
    if {$f == 0} {incr f}
    set zx [list];
    for {set k $f} {$k <= $l} {incr k} {
	set vf [$s sample [expr $k - 1] ]
	set vn [$s sample $k]
	if {($vf < 0 && $vn > 0) || ($vf > 0 && $vn < 0)} {
	    lappend zx $k;
	}
    }
    return $zx;
}


proc CreateWavebarCoordsWindow {} {
    set ScrollEdge [expr [lindex [.ov xview] 0] * $::WaveformInfo(.ov,PixelsInWaveform)]
    set ::WavebarCoordsID [.ov create window  $ScrollEdge 0 -window .ov.info -anchor nw]
}

proc ShowWavebar {args} {
    set XOffset 0;
    set YOffset 0;

    if {$::SoundSamples < 1} {
	return ;
    }
    set TotalSamples $::SoundSamples;

    set Start 0;
    set End [expr $TotalSamples - 1];

    set SamplesInWindow [expr $::WindowRightEdge - $::WindowLeftEdge + 1]
    set SamplesInPrefix [expr $::WindowLeftEdge - $Start + 1];
    set SamplesInSuffix [expr $TotalSamples - $::WindowRightEdge + 1];

    set PreWStart $Start;
    set PreWEnd   [expr $::WindowLeftEdge - 1];
    set PostWStart [expr $::WindowRightEdge + 1];
    set PostWEnd  $End;

    set PixelsPerSample [expr {double($::WavebarPixelsPerSecond) / double($::SamplingRate)}]
    set PixelsInPrefix  [expr int(double($SamplesInPrefix) * $PixelsPerSample)]
    set PixelsInWindow  [expr int(double($SamplesInWindow) * $PixelsPerSample)]
    set PixelsInSuffix  [expr int(double($SamplesInSuffix) * $PixelsPerSample)]

    set ::WaveformInfo(.ov,PixelsPerSample) $PixelsPerSample;
    set PixelsInWaveform [expr $PixelsInPrefix + $PixelsInWindow + $PixelsInSuffix]
    set ::WaveformInfo(.ov,PixelsInWaveform) $PixelsInWaveform;

    if {$PixelsInWaveform < [winfo width .ov]} {
	if {[winfo ismapped .ovsb]} {
	    pack forget .ovsb;
	}
    } else {
	if {![winfo ismapped .ovsb]} {
	    pack .ovsb -before .ovccsep -expand 1 -fill x;
	}
    }

    set PreX $XOffset
    set WinX  [expr $PreX  + $PixelsInPrefix]
    set PostX [expr $WinX + $PixelsInWindow]

    .ov delete all;
    set ::WaveformInfo(.ov,FirstSample) $PreWStart;
    set ::WaveformInfo(.ov,ZeroHeight) [expr ($::WavebarHeight - $YOffset)/2]

    .ov create waveform $PreX 0 -sound snd -frame 0 \
	   -height $::WavebarHeight -zerolevel 1\
	-start $PreWStart -end $PreWEnd -width $PixelsInPrefix \
	-fill $::ColorSpecs(WavebarWaveform,Foreground)

    .ov create waveform $WinX 0 -sound snd -frame 0 \
	   -height $::WavebarHeight 	-fill $::ColorSpecs(WavebarWindowWaveform,Foreground) -zerolevel 1\
	-start $::WindowLeftEdge -end $::WindowRightEdge -width $PixelsInWindow;

    .ov create waveform $PostX 0 -sound snd -frame 0 \
	   -height $::WavebarHeight  -zerolevel 1\
	-start $PostWStart -end $PostWEnd -width $PixelsInSuffix \
	-fill $::ColorSpecs(WavebarWaveform,Foreground)

    CreateWavebarCoordsWindow;
    .ov create poly -1 -1 -1 -1 -1 -1 -fill $::ColorSpecs(WavebarPlayMarker,Foreground) -tags pm
    .ov configure -scrollregion [.ov bbox all]
}

proc ComputeCloseupRegion {center w} {
    set PixelsPerSample $::WaveformInfo(Closeup,PixelsPerSample)
    set FirstSample [expr $center - int($::CutMargin/double($PixelsPerSample))];
    set LastSample  [expr $center + int($::CutMargin/double($PixelsPerSample))];
    set RequestedFirstSample $FirstSample
    set RequestedLastSample  $LastSample
    set WidthSamples [expr $LastSample - $FirstSample +1]    

    if {$::UseSecondsP($w) } {
	set ::WaveformInfo($w,CloseupRegionWidth) \
	    [format "%6.1f ms" [expr 1000.0 *double($WidthSamples) / $::SamplingRate]]
    } else {
	set ::WaveformInfo($w,CloseupRegionWidth) [format "%6d" $WidthSamples]
    }
    if {$FirstSample < 0} {
	set FirstSample 0;
    }
    if {$LastSample > $::SoundLastSample} {
	set LastSample $::SoundLastSample;
    }
    return [list $FirstSample $LastSample]
}

#Compute the bounds of the neighborhood. This is a separate subroutine from ShowNeighborhood
#because we don't want to change the overall region displayed in the neighborhood window
#on every change in window bounds, whereas we do need to update the display of the window
#boundaries every time they change (other than changes in the closeup windows).
#We also have to save the NeighborhoodXOffset.
proc SetNeighborhood {args} {
#    dmsg "SetNeighborhood called"
#    dmsg "WLE = $::WindowLeftEdge WRE = $::WindowRightEdge"
#    dmsg "NLE = $::NeighborhoodLeftEdge NRE = $::NeighborhoodRightEdge"
    set XOffset 0;
    set SamplesInWindow [expr $::WindowRightEdge - $::WindowLeftEdge + 1];
    set SamplesInNeighborhood [expr int($::NeighborhoodWindowRatio * $SamplesInWindow)]
    set SamplesInPrefix [expr ($SamplesInNeighborhood - $SamplesInWindow)/2]
    set SamplesInSuffix [expr $SamplesInNeighborhood - $SamplesInWindow - $SamplesInPrefix];
    set FirstSampleInNeighborhood [expr $::WindowLeftEdge - $SamplesInPrefix]
    set LastSampleInNeighborhood   [expr $::WindowRightEdge + $SamplesInSuffix]

    if {$FirstSampleInNeighborhood < 0} {
	set FirstSampleInNeighborhood 0;
	set XOffset [expr 0 - $FirstSampleInNeighborhood]
    }
    if {$LastSampleInNeighborhood > $::SoundLastSample} {
	set LastSampleInNeighborhood $::SoundLastSample;
    }
    set ::NeighborhoodLeftEdge  $FirstSampleInNeighborhood;
    set ::NeighborhoodRightEdge $LastSampleInNeighborhood;
    set ::NeighborhoodXOffset $XOffset;

    set PixelsPerSample [expr double(($::MainWindowWidth - $XOffset)) / \
		    double($SamplesInNeighborhood)]
    set ::WaveformInfo(.c,PixelsPerSample) $PixelsPerSample;
    ShowNeighborhood
}


proc ShowNeighborhood  {args} {
    set YOffset 0;
#    set ::WaveformInfo(.c,PixelsPerSample) [expr {$::ExpansionFactor * double($::MainWindowWidth) / double($::SamplingRate)}]
    set SamplesInWindow [expr $::WindowRightEdge - $::WindowLeftEdge + 1];
    set SamplesInNeighborhood [expr $::NeighborhoodRightEdge - $::NeighborhoodLeftEdge + 1]

    set lcl [ComputeCloseupRegion $::WindowLeftEdge $::CLUPL]
    set LeftCutLeftEdge  [expr [lindex $lcl 0] - $::NeighborhoodLeftEdge]
    set LeftCutLeftEdgePix  [expr $::NeighborhoodXOffset + \
				 int($LeftCutLeftEdge * $::WaveformInfo(.c,PixelsPerSample))]
    set LeftCutRightEdge [expr [lindex $lcl 1] - $::NeighborhoodLeftEdge]
    set LeftCutRightEdgePix [expr $::NeighborhoodXOffset + \
		      int($LeftCutRightEdge * $::WaveformInfo(.c,PixelsPerSample))]
    set rcl [ComputeCloseupRegion $::WindowRightEdge $::CLUPR]
    set RightCutLeftEdge [expr [lindex $rcl 0] - $::NeighborhoodLeftEdge]
    set RightCutLeftEdgePix  [expr $::NeighborhoodXOffset + \
		       int($RightCutLeftEdge * $::WaveformInfo(.c,PixelsPerSample))]
    set RightCutRightEdge [expr [lindex $rcl 1] - $::NeighborhoodLeftEdge]
    set RightCutRightEdgePix [expr $::NeighborhoodXOffset + \
		       int($RightCutRightEdge * $::WaveformInfo(.c,PixelsPerSample))]

    set SamplesInPrefix [expr $::WindowLeftEdge - $::NeighborhoodLeftEdge + 1]
    set SamplesInSuffix [expr $::NeighborhoodRightEdge - $::WindowRightEdge + 1]

    set PixelsInPrefix  [expr int($SamplesInPrefix * $::WaveformInfo(.c,PixelsPerSample))]
    set PixelsInWindow  [expr int($SamplesInWindow * $::WaveformInfo(.c,PixelsPerSample))]
    set PixelsInSuffix  [expr int($SamplesInSuffix * $::WaveformInfo(.c,PixelsPerSample))]

    set PreWEnd   [expr $::WindowLeftEdge - 1];
    set PostWStart [expr $::WindowRightEdge + 1];

    set PreX $::NeighborhoodXOffset
    set WinX  [expr $PreX  + $PixelsInPrefix]
    set PostX [expr $WinX + $PixelsInWindow]

    if {!$::BatchModeP} {
	.c delete all
	set ::WaveformInfo(.c,FirstSample) $::NeighborhoodLeftEdge

	.c create waveform $PreX 0 -sound snd -frame 0 -height $::MainWindowHeight \
	    -fill $::ColorSpecs(NeighborhoodWaveform,Foreground) -zerolevel 1\
	    -start $::NeighborhoodLeftEdge -end $PreWEnd -width $PixelsInPrefix;

	.c create waveform $WinX 0 -sound snd -frame 0 -height $::MainWindowHeight \
	    -fill $::ColorSpecs(NeighborhoodWindowWaveform,Foreground) -zerolevel 1\
	    -start $::WindowLeftEdge -end $::WindowRightEdge -width $PixelsInWindow;

	.c create waveform $PostX 0 -sound snd -frame 0 -height $::MainWindowHeight \
	    -fill $::ColorSpecs(NeighborhoodWaveform,Foreground) -zerolevel 1\
	    -start $PostWStart -end $::NeighborhoodRightEdge -width $PixelsInSuffix;

	if {$::DrawCutMarksP} {  
	    .c create line $LeftCutLeftEdgePix 0 $LeftCutLeftEdgePix $::MainWindowHeight \
		-fill $::ColorSpecs(CloseupRegionMarker,Foreground) -width 1
	    .c create line $LeftCutRightEdgePix 0 $LeftCutRightEdgePix $::MainWindowHeight \
		-fill $::ColorSpecs(CloseupRegionMarker,Foreground) -width 1
	    .c create line $RightCutLeftEdgePix 0 $RightCutLeftEdgePix $::MainWindowHeight \
		-fill $::ColorSpecs(CloseupRegionMarker,Foreground) -width 1
	    .c create line $RightCutRightEdgePix 0 $RightCutRightEdgePix $::MainWindowHeight \
		-fill $::ColorSpecs(CloseupRegionMarker,Foreground) -width 1
	}

	set ::WaveformInfo(.c,ZeroHeight) [expr ($::MainWindowHeight - $YOffset)/2]
	set ::WaveformInfo(.c,PixelsInWaveform) $::MainWindowWidth
	#    .c create window $::MainWindowWidth 2 -window .c.info -anchor ne
	.c create window 0 2 -window .c.info -anchor nw

	set EWXOffset [expr $::MainWindowWidth / 16]
	.c create window $EWXOffset $::MainWindowHeight \
	    -window .c.wldg  -anchor sw
	.c create window [expr $::MainWindowWidth /2]  $::MainWindowHeight \
	    -window .c.wdur  -anchor se
	.c create window [expr $::MainWindowWidth - $EWXOffset] $::MainWindowHeight \
	    -window .c.wrdg -anchor s
    }
}


proc UpdateLeftCut {} {
    if {!$::BatchModeP} {
	$::CLUPL delete $::WaveformInfo($::CLUPL,wf);
    }
    set ::WaveformInfo($::CLUPL,wf) \
	[ShowCloseup $::CLUPL snd $::WindowLeftEdge]
    if {!$::BatchModeP} {
	$::CLUPL delete $::LeftCutMark;
	set ::LeftCutMark [DrawLeftCutMark];
    }
}

proc UpdateRightCut {} {
    if {!$::BatchModeP} {
	$::CLUPR delete $::WaveformInfo($::CLUPR,wf);
    }
    set ::WaveformInfo($::CLUPR,wf) \
	[ShowCloseup $::CLUPR snd $::WindowRightEdge]
    if {!$::BatchModeP} {
	$::CLUPR delete $::RightCutMark;
	set ::RightCutMark [DrawRightCutMark];
    }
}

proc DrawLeftCutMark {} {
    set x [expr ($::WindowLeftEdge - $::WaveformInfo($::CLUPL,FirstSample)) * \
	       $::WaveformInfo(Closeup,PixelsPerSample)];
    set top 0;
    set bot [$::CLUPL cget -height];
    return [$::CLUPL create line $x $bot $x $top -fill $::ColorSpecs(CutMark,Foreground)]
}

proc DrawRightCutMark {} {
    set x [expr ($::WindowRightEdge - $::WaveformInfo($::CLUPR,FirstSample)) * \
	       $::WaveformInfo(Closeup,PixelsPerSample)];
    set top 0;
    set bot [$::CLUPR cget -height];
    return [$::CLUPR create line $x $bot $x $top -fill $::ColorSpecs(CutMark,Foreground)];
}

#The value returned is a flag indicating whether or not
#the call changed anything.
proc CheckWindowBounds {} {
    set Flag 0;

    if {$::WindowLeftEdge > $::WindowRightEdge} {
	set tmp $::WindowRightEdge;
	set ::WindowRightEdge $::WindowLeftEdge;
	set ::WindowLeftEdge $tmp;
	set Flag 1;
    } else {
	if {$::WindowLeftEdge == $::WindowRightEdge} {
	    ShowMessage [_ "A window of length 0 is not a good idea. Resetting to default."]
	    SetDefaultWindow;
	    set Flag 1;
	}
    }
    if {$::WindowLeftEdge < 0} {
	ShowMessage [_ "The window's left edge cannot be set before the beginning of the file."]
	SetDefaultWindow;
	set Flag 1;
    }
    if {$::WindowRightEdge > $::SoundLastSample} {
	ShowMessage [_ "The window's right edge cannot be set after the end of the file."]
	SetDefaultWindow;
	set Flag 1;
    }
    return $Flag;
}

proc AnnounceWindowBounds {} {
    set LeftSeconds  [expr double($::WindowLeftEdge)/double($::SamplingRate)];
    set RightSeconds [expr double($::WindowRightEdge)/double($::SamplingRate)];
    ShowMessage [format [_ "Window now: \[%5.3f - %5.3f\]"] $LeftSeconds $RightSeconds];
    UpdateWindowBoundsBar;
    AutoPlayWindow
}

proc UpdateWindowBoundsBar {} {
    if {$::UseSecondsP($::C)} {
	set LeftSeconds  [expr double($::WindowLeftEdge)/double($::SamplingRate)];
	set RightSeconds [expr double($::WindowRightEdge)/double($::SamplingRate)];
	set DurationSeconds [expr $RightSeconds - $LeftSeconds];
	set ::WindowBoundsLeft \
	    [format [_ "%5.3f"] $LeftSeconds];
	set ::WindowBoundsRight \
	    [format [_ "%5.3f"] $RightSeconds]
	set ::WindowDuration \
	    [format [_ "%5.3f"] $DurationSeconds];
    } else {
	set DurationSamples [expr $::WindowRightEdge - $::WindowLeftEdge + 1];
	set ::WindowBoundsLeft \
	    [format [_ "%5d"] $::WindowLeftEdge];
	set ::WindowBoundsRight \
	    [format [_ "%5d"] $::WindowRightEdge]
	set ::WindowDuration \
	    [format [_ "%5d"] $DurationSamples];
    }
}

proc UpdateLeftEdge {} {
    ShowWavebar;
    SetNeighborhood
    UpdateLeftCut;
    AnnounceWindowBounds;
}

proc UpdateRightEdge {} {
    ShowWavebar;
    SetNeighborhood
    UpdateRightCut;
    if {!$::SetLeftEdgeOverviewImmediateP} {
	UpdateLeftCut;
    }
    AnnounceWindowBounds;
}

proc LeftEdgeForwardDelta {} {
    set ::WindowLeftEdge [expr $::WindowLeftEdge + $::DeltaSamples]
    if {![CheckWindowBounds]} {
	ShowWavebar;
	if {$::DeltaSamples > $::NeighborhoodChangeThreshold} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateLeftCut;
	AnnounceWindowBounds;
    } else {
	RedrawEverything;
	AutoPlayWindow;
    }
    silence::UntagSilenceLeft;
}

proc RightEdgeForwardDelta {} {
    set ::WindowRightEdge [expr $::WindowRightEdge + $::DeltaSamples]
    ShowWavebar;
    if {($::DeltaSamples > $::NeighborhoodChangeThreshold) || \
	     ($::WindowRightEdge >= $::NeighborhoodRightEdge)} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateRightCut;
    AnnounceWindowBounds;
    silence::UntagSilenceRight;
    #AutoPlayWindow;
}

proc WindowForwardDelta {} {
    set ::WindowLeftEdge [expr $::WindowLeftEdge + $::DeltaSamples]
    set ::WindowRightEdge [expr $::WindowRightEdge + $::DeltaSamples]
    ShowWavebar;
    if {($::DeltaSamples > $::NeighborhoodChangeThreshold) || \
	     ($::WindowRightEdge >= $::NeighborhoodRightEdge)} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateLeftCut;
    UpdateRightCut;
    silence::UntagSilenceLeft;
    silence::UntagSilenceRight;
    AnnounceWindowBounds;
    #AutoPlayWindow;
}

proc LeftEdgeBackwardDelta {} {
    set ::WindowLeftEdge [expr $::WindowLeftEdge - $::DeltaSamples]
    ShowWavebar;
    if { ($::DeltaSamples > $::NeighborhoodChangeThreshold) || \
	     ($::WindowLeftEdge <= $::NeighborhoodLeftEdge)} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateLeftCut;
    AnnounceWindowBounds;
    silence::UntagSilenceLeft;
    #AutoPlayWindow;
}

proc RightEdgeBackwardDelta {} {
    set ::WindowRightEdge [expr $::WindowRightEdge - $::DeltaSamples]
    if {![CheckWindowBounds]} {
	ShowWavebar;
	if {$::DeltaSamples > $::NeighborhoodChangeThreshold} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateRightCut;
	AnnounceWindowBounds;
    } else {
	RedrawEverything;
	AutoPlayWindow;
    }
    silence::UntagSilenceRight;
}

proc WindowBackwardDelta {} {
    set ::WindowLeftEdge [expr $::WindowLeftEdge - $::DeltaSamples]
    set ::WindowRightEdge [expr $::WindowRightEdge - $::DeltaSamples]
    ShowWavebar;
    if { ($::DeltaSamples > $::NeighborhoodChangeThreshold) || \
	     ($::WindowLeftEdge <= $::NeighborhoodLeftEdge)} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateLeftCut;
    UpdateRightCut;
    AnnounceWindowBounds;
    silence::UntagSilenceLeft;
    silence::UntagSilenceRight;
    #AutoPlayWindow;
}

#Return the index of the first silence whose right edge follows the specified sample.
#Returns -1 if the specified sample follows the last silence.
proc GetNextSilence {CurrentSample SilenceList} {
    set Result -1;
    set limit [llength $SilenceList]
    set m 0;
    while {$m < $limit} {
	if {$CurrentSample < [lindex [lindex $SilenceList $m] 1] } {
	    return $m;
	} else {
	    incr m;
	}
    }
}

#Return the index of the first silence whose left edge precedes the specified sample.
#Returns -1 if the specified sample precedes the first proc
proc GetPreviousSilence {CurrentSample SilenceList} {
    set Result -1;
    set m [expr [llength $SilenceList] -1]
    while {$m >= 0} {
	if {$CurrentSample > [lindex [lindex $SilenceList $m] 0] } {
	    return $m;
	} else {
	    incr m -1;
	}
    }
}


#If the right edge is currently in a silence, move the right edge to the next
#silence and move the left edge to the current silence.
#If the right edge is not in a silence, move the left edge to the next silence
#and the right edge to the silence following that.
proc WindowForwardSilence {} {
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1]; 
    set LeftScrollSilenceNumber -1;
    set RightScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetNextSilence $::WindowRightEdge $sl];
    if {$Result < 0} {
	set wle [expr [lindex [lindex $sl $LastSilenceIndex] 1] + 1]
	set wre $::SoundLastSample
	set LeftScrollSilenceNumber $LastSilenceIndex;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	if {$::WindowRightEdge > $ResultLeftEdge} {
	    #wre falls within silence $Result;
	    #move left edge to current silence
	    set wle [expr $ResultRightEdge + 1]
	    set LeftScrollSilenceNumber $Result;
	    #move right edge to next silence
	    if {$Result < $LastSilenceIndex} {
		set NextIndex [expr $Result + 1]
		set NextEntry [lindex $sl $NextIndex]
		set NextLeftEdge [lindex $NextEntry 0];
		set wre [expr $NextLeftEdge - 1]
		set RightScrollSilenceNumber $NextIndex;
	    } else {
		set wre $::SoundLastSample
		ShowMessage [_ "There are no more silences to the right. Moving to end of file."]
	    }
	} else {
	    #wre lies in the non-silence preceding silence $Result.
	    #Check to see if there is a silence within the original
	    #window. If so move wle to it and wre to the silence to the right.
	    #If there is more than one silence within the window, take the
	    #rightmost one.
	    set LCR [GetPreviousSilence $::WindowRightEdge $sl]
	    set Flag 0;
	    if {$LCR >= 0} {
		set LCRRightEdge [lindex [lindex $sl $LCR] 1];
		if {$LCRRightEdge >= $::WindowLeftEdge} {
		    set Flag 1;
		}
	    }
	    if {$Flag == 1} {
		set wle [expr $LCRRightEdge + 1]
		set wre [expr $ResultLeftEdge - 1]
		set LeftScrollSilenceNumber $LCR;
		set RightScrollSilenceNumber $Result;
	    } else {
		#Move the left edge to the next silence
		#and the right edge to the silence following that.
		set wle [expr $ResultRightEdge + 1]
		set LeftScrollSilenceNumber $Result;
		set NextIndex [GetNextSilence $ResultRightEdge $sl];
		if {$NextIndex > 0} {
		    set RightScrollSilenceNumber $NextIndex;
		    set wre [expr [lindex [lindex $sl $NextIndex] 0] - 1]
		} else {
		    set wre $::SoundLastSample
		    ShowMessage \
			[_ "There are no more silences to the right. Moving to end of file."]
		    return 0;
		}
	    }
	}
    }
    set ::WindowLeftEdge $wle;
    set ::WindowRightEdge $wre;
    if {!$::BatchModeP} {
	ShowWavebar;
    }
    if {$::WindowRightEdge >= $::NeighborhoodRightEdge} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    if {!$::BatchModeP} {
	set ::SavedLeftScrollSilenceNumber $LeftScrollSilenceNumber;
	set ::SavedRightScrollSilenceNumber $RightScrollSilenceNumber;
	silence::ScrollSilenceDisplay $LeftScrollSilenceNumber $RightScrollSilenceNumber Right;
    }
    UpdateLeftCut;
    UpdateRightCut;
    AnnounceWindowBounds;
    #AutoPlayWindow;
    return 1
}

proc WindowBackwardSilence {} {
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1]; 
    set LeftScrollSilenceNumber -1;
    set RightScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetPreviousSilence $::WindowLeftEdge $sl];
    if {$Result < 0} {
	ShowMessage [_ "There are no silences to the left."]
	return ;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	if {$::WindowLeftEdge <= $ResultRightEdge} {
	    #wle falls within silence $Result
	    #move right edge to current silence
	    set wre [expr $ResultLeftEdge - 1];
	    set RightScrollSilenceNumber $Result;
	    #move left edge to silence before that
	    if {$Result > 0} {
		set PrevIndex [expr $Result - 1]
		set PrevEntry [lindex $sl $PrevIndex]
		set PrevRightEdge [lindex $PrevEntry 1];
		set wle [expr $PrevRightEdge + 1];
		set LeftScrollSilenceNumber $PrevIndex;
	    } else {
		ShowMessage [_ "There are no more silences to the left. Moving to beginning of file."]
		set wle 0;
	    }
	} else {
	    #wle lies in the non-silence following silence $Result.
	    #Check to see if there is a silence within the original
	    #window. If so move wre to it and wle to the silence to the left.
	    #If there is more than one silence within the window, take the
	    #leftmost one.
	    set LCR [GetNextSilence $::WindowLeftEdge $sl]
	    set Flag 0;
	    if {$LCR >= 0} {
		set LCRLeftEdge [lindex [lindex $sl $LCR] 0];
		if {$LCRLeftEdge <= $::WindowRightEdge} {
		    set Flag 1;
		}
	    }
	    if {$Flag == 1} {
		set wre [expr $LCRLeftEdge - 1]
		set RightScrollSilenceNumber $LCR;
		set wle [expr $ResultRightEdge + 1]
		set LeftScrollSilenceNumber $Result;
	    } else {
		#Move the right edge to the next silence
		#and the left edge to the silence preceding that.
		set wre [expr $ResultLeftEdge - 1];
		set RightScrollSilenceNumber $Result;
		set PrevIndex [GetPreviousSilence $ResultLeftEdge $sl];
		if {$PrevIndex >= 0} {
		    set wle [expr [lindex [lindex $sl $PrevIndex] 1] + 1]
		    set LeftScrollSilenceNumber $PrevIndex;

		} else {
		    ShowMessage [_ "There are no more silences to the left. Moving to beginning of file."]
		    set wle 0;
		    return ;
		}
	    }
	}
    }
    set ::WindowLeftEdge $wle;
    set ::WindowRightEdge $wre;
    ShowWavebar;
    if {$::WindowLeftEdge <= $::NeighborhoodLeftEdge} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateLeftCut;
    UpdateRightCut;
    AnnounceWindowBounds;
    #AutoPlayWindow;
    set ::SavedLeftScrollSilenceNumber $LeftScrollSilenceNumber;
    set ::SavedRightScrollSilenceNumber $RightScrollSilenceNumber;
    silence::ScrollSilenceDisplay $LeftScrollSilenceNumber $RightScrollSilenceNumber Left;
}

proc LeftEdgeBackwardSilence {} {
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1];
    set LeftScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetPreviousSilence [expr $::WindowLeftEdge - 1] $sl];
    if {$Result < 0} {
	ShowMessage [_ "There are no more silences to the left. Moving to beginning of file."]
	set wle 0;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	if {$::WindowLeftEdge <= [expr $ResultRightEdge + 1]} {
	    #wle falls within silence $Result;
	    #move left edge to next silence
	    if {$Result > 0} {
		set PrevIndex [expr $Result - 1]
		set LeftScrollSilenceNumber $PrevIndex;
		set PrevEntry [lindex $sl $PrevIndex]
		set PrevRightEdge [lindex $PrevEntry 1];
		set wle [expr $PrevRightEdge + 1];
	    } else {
		ShowMessage \
		    [_ "There are no more silences to the left. Moving to beginning of file."]
		set wle 0;
	    }
	} else {
	    #wle lies in the non-silence preceding silence $Result.
	    set wle [expr $ResultRightEdge + 1];
	    set LeftScrollSilenceNumber $Result;
	}
    }
    set ::WindowLeftEdge $wle;
    silence::ScrollSilenceDisplay $LeftScrollSilenceNumber $::SavedRightScrollSilenceNumber Left;
    set ::SavedLeftScrollSilenceNumber $LeftScrollSilenceNumber;
    ShowWavebar;
    if {$::WindowLeftEdge <= $::NeighborhoodLeftEdge} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateLeftCut;
    AnnounceWindowBounds;
    #AutoPlayWindow;
}

proc LeftEdgeForwardSilence {} {
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1]; 
    set LeftScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetNextSilence $::WindowLeftEdge $sl];
    if {$Result < 0} {
	ShowMessage [_ "There are no more silences to the right. Left edge left in place."]
	return ;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	set LeftScrollSilenceNumber $Result;
	if {$::WindowLeftEdge >= $ResultLeftEdge} {
	    #wle falls within silence $Result;
	    #move left edge to next silence
	    if {$Result < $LastSilenceIndex} {
		set NextIndex [expr $Result + 1]
		set LeftScrollSilenceNumber $NextIndex;
		set NextEntry [lindex $sl $NextIndex]
		set NextRightEdge [lindex $NextEntry 1];
		set wle $NextRightEdge;
	    } else {
		ShowMessage [_ "There are no more silences to the right."]
		return ;
	    }
	} else {
	    #wle lies in the non-silence preceding silence $Result.
	    #Move the left edge to the silence
	    #and the right edge to the silence following that.
	    set wle $ResultRightEdge;
	}
    }
    if {$wle >= $::WindowRightEdge} {
	ShowMessage [_ "The left edge of the window cannot follow the right edge."]
	return ;
    }
    set ::WindowLeftEdge $wle;
    silence::ScrollSilenceDisplay $LeftScrollSilenceNumber $::SavedRightScrollSilenceNumber Left;
    set ::SavedLeftScrollSilenceNumber $LeftScrollSilenceNumber;
    if {![CheckWindowBounds]} {
	ShowWavebar;
	if {$::WindowRightEdge >= $::NeighborhoodRightEdge} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateLeftCut;
	AnnounceWindowBounds;
    } else {
	RedrawEverything;
	AutoPlayWindow;
    }
}

proc RightEdgeForwardSilence {} {
    set RightScrollSilenceNumber -1;
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1]; 
    set ScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetNextSilence [expr $::WindowRightEdge + 1] $sl];
    if {$Result < 0} {
	ShowMessage [_ "There are no more silences to the right. Moving to end of file."]
	set wre $::SoundLastSample;
	UntagSilenceRight;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	if {$::WindowRightEdge >= [expr $ResultLeftEdge - 1]} {
	    #wre falls within silence $Result;
	    #move right edge to next silence
	    if {$Result < $LastSilenceIndex} {
		set NextIndex [expr $Result + 1]
		set NextEntry [lindex $sl $NextIndex]
		set NextLeftEdge [lindex $NextEntry 0];
		set wre [expr $NextLeftEdge - 1];
		set RightScrollSilenceNumber $NextIndex;
	    } else {
		ShowMessage [_ "There are no more silences to the right. Moving to end of file."]
		set wre $::SoundLastSample;
	    }
	} else {
	    set wre [expr $ResultLeftEdge -1];
	    set RightScrollSilenceNumber $Result;
	}
    }
    set ::WindowRightEdge $wre;
    ShowWavebar;
    if {$::WindowRightEdge >= $::NeighborhoodRightEdge} {
	SetNeighborhood;
    } else {
	ShowNeighborhood;
    }
    UpdateRightCut;
    AnnounceWindowBounds;
    #AutoPlayWindow;
    silence::ScrollSilenceDisplay $::SavedLeftScrollSilenceNumber $RightScrollSilenceNumber Right;
    set ::SavedRightScrollSilenceNumber $RightScrollSilenceNumber;
}

proc RightEdgeBackwardSilence {} {
    set sl $silence::ActiveSilenceList;
    set LastSilenceIndex [expr [llength $sl] - 1]; 
    set RightScrollSilenceNumber -1;
    if {$LastSilenceIndex < 0} {
	ShowMessage [_ "The silence list is empty."]
	return ;
    }
    set Result [GetPreviousSilence $::WindowRightEdge $sl];
    if {$Result < 0} {
	ShowMessage [_ "There are no more silences to the left. Leaving in place."]
	return ;
    } else {
	set ResultLeftEdge [lindex [lindex $sl $Result] 0]
	set ResultRightEdge [lindex [lindex $sl $Result] 1]
	set RightScrollSilenceNumber $Result;
	if { $::WindowRightEdge > $ResultRightEdge } {
	    set wre [expr $ResultLeftEdge - 1];  #wre precedes the result window.
	} else {
	    if {$Result > 0} {
		set PrevIndex [expr $Result - 1]
		set PrevEntry [lindex $sl $PrevIndex]
		set PrevLeftEdge [lindex $PrevEntry 0];
		set wre [expr $PrevLeftEdge - 1];
		set RightScrollSilenceNumber $PrevIndex;
	    } else {
		ShowMessage [_ "There are no more silences to the left. Leaving in place."]
		return ;
	    }
	}
    }
    if {$wre <= $::WindowLeftEdge} {
	ShowMessage [_ "The right edge of the window cannot precede the left edge."]
	return ;
    }
    set ::WindowRightEdge $wre;
    silence::ScrollSilenceDisplay $::SavedLeftScrollSilenceNumber $RightScrollSilenceNumber Right;
    set ::SavedRightScrollSilenceNumber $RightScrollSilenceNumber;
    if {![CheckWindowBounds]} {
	ShowWavebar;
	if {$::WindowLeftEdge <= $::NeighborhoodLeftEdge} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateRightCut;
	AnnounceWindowBounds;
    } else {
	RedrawEverything;
	AutoPlayWindow;
    }
}

proc ResetPauseParameters {} {
    set ::PauseParameters(FrameSize)        $::DefaultPauseFrameSize
    set ::PauseParameters(MinimumDuration)  $::DefaultPauseMinimumDuration
    set ::PauseParameters(Threshold)	    $::DefaultPauseThreshold
    .info.pause.main.fent delete 0 end
    .info.pause.main.fent insert end $::DefaultPauseFrameSize
    .info.pause.main.ment delete 0 end
    .info.pause.main.ment insert end $::DefaultPauseMinimumDuration
    .info.pause.main.tent delete 0 end
    .info.pause.main.tent insert end $::DefaultPauseThreshold;
}

proc GetPauseParameters {} {
    set ::PauseParameters(FrameSize)		[.info.pause.main.fent get]
    set ::PauseParameters(MinimumDuration)	[.info.pause.main.ment get]
    set ::PauseParameters(Threshold)		[.info.pause.main.tent get]
    ComputeSilences
}

proc SetPauseFrameSize {s} {
    set ::PauseParameters(FrameSize) $s;
}

proc SetPauseMinimumDuration {s} {
    set ::PauseParameters(MinimumDuration) $s;
}

proc SetPauseThreshold {s} {
    set ::PauseParameters(Threshold) $s;
}

#These next are for use in slave interpreters
proc TellSoundFileLengthSamples {} {
    return $::SoundSamples;
}

proc TellWindowLeftEdgeSamples {} {
    return $::WindowLeftEdge;
}

proc TellWindowRightEdgeSamples {} {
    return $::WindowRightEdge;
}

proc ConstructCommandLine {} {
    set cl [list $::PauseCommandName];
    lappend cl "-q";
    lappend cl "-f";
    lappend cl [string trim [format "%5.4f" $::PauseParameters(FrameSize)]];
    lappend cl "-m"
    lappend cl [string trim [format "%5.1f" $::PauseParameters(MinimumDuration)]];
    lappend cl "-t"
    lappend cl [string trim [format "%d" $::PauseParameters(Threshold)]];
    if {[string equal $::SoundFileName ""]} {
	ShowMessage [_ "No input file has been specified. You must supply one."]
	after 2000 {return "err"}
    }
    if {[file exists $::SoundFileName] == 0} {
	ShowMessage [format [_ "Input file \`%s\' does not exist."] $::SoundFileName]
	after 2000 {return "err"}
    }
    if {[file readable $::SoundFileName] == 0} {
	ShowMessage [format [_ "Input file \`%s\' is not readable."] $::SoundFileName]
	after 2000 {return "err"}
    }
    lappend cl $::SoundFileName;
    return [join $cl]; 
}

proc ExecutePause {} {
    if {!$::PauseAvailableP} {
	ShowMessage [_ "Pause is not available on this machine or not in your path."];
	return ;
    }
    ClearMessageWindow;
    set msg "";
    set cl [ConstructCommandLine]
    set cl [split $cl];
    lappend cl "2>";
    lappend cl "/dev/null";
    set cl [linsert $cl 0 exec]
    set status [catch {eval $cl} out];
    if {($status == 0) || [string equal $::errorCode NONE]} {
	silence::LoadSilenceList [format "%s.sf" [file rootname $::SoundFileName]]
    } else {
	ShowMessage [_ "Error while running pause."]
	set spec [split $::errorCode]
	switch -exact -- [lindex $spec 0] {
	    CHILDSTATUS {
		set PauseErrorCode [lindex $spec 2];
		lappend msg $PauseErrorCode
	    }
	    POSIX {
		lappend msg [lindex $spec 2]
	    }
	}
	if {[llength $msg]} {ShowMessage [join $msg]}
	return ;
    }
}

proc ShowCommandLine {} {
    set cl [ConstructCommandLine];
    if {[string equal $cl "err"] == 0} {
	ShowMessage [join $cl];
    }
}

proc DelimitNumber {number {delim ","} {GroupSize 3}} {
     # First, extract right hand part of number, up to and including decimal point
     set point [string last "." $number];
     if {$point >= 0} {
         set PostDecimal [string range $number [expr $point + 1] end];
         set PostDecimalP 1;
     } else {
         set point [expr [string length $number] + 1]
         set PostDecimal "";
         set PostDecimalP 0;
     }

     # Now extract any leading spaces.
     set ind 0;
     while {[string equal [string index $number $ind] \u0020]} {
         incr ind;
     }
     set FirstNonSpace $ind;
     set LastSpace [expr $FirstNonSpace - 1];
     set LeadingSpaces [string range $number 0 $LastSpace];

     # Now extract the non-fractional part of the number, omitting leading spaces.
     set MainNumber [string range $number $FirstNonSpace [expr $point -1]];

     # Insert commas into the non-fractional part.
     set Length [string length $MainNumber];
     set Phase  [expr $Length % $GroupSize]
     set PhaseMinusOne  [expr $Phase -1];
     set DelimitedMain "";

     #First we deal with the extra stuff.
     if {$Phase > 0} {
         append DelimitedMain [string range $MainNumber 0 $PhaseMinusOne];
     }
     set FirstInGroup $Phase;
     set LastInGroup [expr $FirstInGroup + $GroupSize -1];
     while {$LastInGroup < $Length} {
         if {$FirstInGroup > 0} {
             append DelimitedMain $delim;
         }
         append DelimitedMain [string range $MainNumber $FirstInGroup $LastInGroup];
         incr FirstInGroup $GroupSize
         incr LastInGroup  $GroupSize
     }

     # Reassemble the number.
     if {$PostDecimalP} {
         return [format "%s%s.%s" $LeadingSpaces $DelimitedMain $PostDecimal];
     } else {
         return [format "%s%s" $LeadingSpaces $DelimitedMain];
     }
 }

proc LoadSoundFile {args} {
    if {[llength $args] > 0} {
	set SoundFile [lindex $args 0];
    } else {
	set SoundFile [tk_getOpenFile -title [_ "Load Sound File"]];
    }
    if {$SoundFile eq ""} {
	ShowMessage [_ "No sound file name specified."];
	return ;
    }
    set SoundFile [MinimizeFileName $SoundFile]
    catch {snd destroy}
    set ::SoundSamples 0;
    set ::SoundSamplesText "0";
    if {[catch {snack::sound snd -load $SoundFile} ] != 0} {
	ShowMessage [format [_ "Unable to open audio file %s"] $SoundFile]
	return
    }
    set ::SoundFileName $SoundFile;
    set ::SoundFileNameTxt [format "Sound File %s" [file tail $SoundFile] ]
    set ::SoundSamples [lindex [snd info] 0];
    set ::SoundSamplesText [DelimitNumber $::SoundSamples]
    set ::SoundSeconds [SamplesToSeconds $::SoundSamples]
    set ::SoundSecondsText [format "%5.3f" $::SoundSeconds]
    set ::SoundHoursMinutesSeconds [SecondsToHMS $::SoundSeconds]
    set ::SampleStrLen [string length $::SoundSamples];
    set ::SoundLastSample [expr $::SoundSamples - 1];
    set ::SamplingRate [lindex [snd info] 1];
    set ::SamplingRateText [DelimitNumber $::SamplingRate]
    set ::DeltaSamples [expr int($::DeltaSeconds * $::SamplingRate)]
    set ::SoundEncoding [lindex [snd inf]o 4];
    set ::SoundFileFormat  [lindex [snd info] 6];
    set ::SoundChannels   [lindex [snd info] 5];
    set ::SoundRange [expr [snd max] - [snd min]]
    SetDefaultWindow;
    if {!$::BatchModeP} {
	silence::ClearSilenceList;
	RedrawEverything;
	BindSoundWindows;
    }
    if {$::UseSecondsP($::C)} {
	set len [format [_ "%4.3f seconds"] $::SoundSeconds]
    } else {
	set len [format [_ "%0*d samples"] $::SampleStrLen $::SoundSamples];
    }
    set msg [format [_ "Loaded sound file %s (%s)."] $SoundFile $len];
    WriteJournal $msg;
    if {$::AutoComputeSilencesP} {
	set msg [format [_ "Loaded sound file %s (%s). Computing silences..."] $SoundFile $len];
    }
    ShowMessage $msg;
    update
    if {$::AutoComputeSilencesP} {
	ComputeSilences
    }
    if {$::AutoLoadOutFileNamesP} {
	LoadOutFileNameList [file rootname $SoundFile]-SegmentNames;
    }
}

proc ComputeSilences {} {
    if {$::SoundSamples == 0} {return}
    set StartTime [clock seconds]
    if {$::UsePauseP} {
	ExecutePause
    } else {
	silence::ComputeSilencesInternally snd
    }
    set ElapsedTime [expr [clock seconds] - $StartTime]
    ShowMessage [format \
	     [_ "Silence computation took %d seconds ( %.2f seconds per minute of audio)."] \
		     $ElapsedTime [expr 60 * double($ElapsedTime)/$::SoundSeconds]]
}

proc SetDefaultWindow {} {
    if {$::SoundSamples >= 10000} {
	set ::WindowLeftEdge 5000;
    } else {
	set ::WindowLeftEdge [expr $::SoundSamples /4]
    }
    set HalfSR [expr $::SamplingRate /2]
    if {$::SoundSamples >= $HalfSR} {
	set ::WindowRightEdge $HalfSR;
    } else {
	set ::WindowRightEdge [expr $::SoundSamples /2];
    }
}

#Scroll the wavebar if necessary to bring the window into view.
#The arguments are not used but required since this is called from a trace.
proc ScrollWavebar {n e o} {
    set fl [.ov xview];
    set WavebarLeftEdge  [expr [lindex $fl 0] * $::SoundSamples];
    set WavebarRightEdge [expr [lindex $fl 1] * $::SoundSamples];
    if {($::WindowLeftEdge < $WavebarLeftEdge) || ($::WindowRightEdge > $WavebarRightEdge)} {
	set WindowLength [expr $::WindowRightEdge - $::WindowLeftEdge + 1]
	set WavebarLength [expr $WavebarRightEdge - $WavebarLeftEdge + 1]
	set NewWavebarLeftEdge [expr $::WindowLeftEdge + ($WindowLength/2) - ($WavebarLength/2)]
	set NewWavebarLeftEdgeFraction [expr double($NewWavebarLeftEdge)/double($::SoundSamples)]
	.ov xview moveto $NewWavebarLeftEdgeFraction;
    }
}

proc SetNeighborhoodChangeThreshold {n e o} {
    set ::NeighborhoodChangeThreshold \
	[expr int(double($::WindowRightEdge - $::WindowLeftEdge + 1)/$::NeighborhoodChangeThresholdFraction)]
}

proc RePositionWavebarInfo {} {
    #The test is to prevent a flood of expose events from
    #causing call after call, which makes the window flicker
    #and loads the CPU.
    set WavebarLeftEdgeFraction [lindex [.ov xview] 0];
    if {[expr $WavebarLeftEdgeFraction != $::WavebarLeftEdgeFraction]} {
	.ov delete $::WavebarCoordsID
	CreateWavebarCoordsWindow;
    }
    set ::WavebarLeftEdgeFraction $WavebarLeftEdgeFraction;
}

#This procedure strips leading zeroes from a string so as
#to ensure that it will not be mis-interpreted as an octal number.
#It ensures that this does not eliminate the string
#entirely, as use of [string trimleft] alone would, when the input
#consists entirely of zeroes.
proc TrimLeadingZeroes {n} {
    if {[string length $n] == 0} { return ""}
    set trimmed [string trimleft $n 0]
    if {[string length $trimmed] == 0} {
	return "0";
    } else {
	return $trimmed;
    }
}

proc PackMain {} {
    pack $::MSG    -side top -expand 1 -fill both -padx 4 -pady 4
    pack .info     -side top -expand 1 -fill both -padx 4 -pady 4
    pack .infosep  -side top -expand 1 -fill both -padx 4 -pady 0
    pack .ov       -side top -expand 1 -fill both -padx 4 -pady 2
    pack .ovccsep  -side top -expand 1 -fill both -padx 4 -pady 0
    pack .c        -side top -expand 1 -fill both -padx 4 -pady 2
    if {$::DisplayCloseupsP} {
	PackCloseups;
    }
    pack .sepcc    -side top -expand 1 -fill x
    if {$::DisplayPlayBarP} {
	PackPlayBar;
    }
    if {$::DisplayWriteBarP} {
	PackWriteBar;
    }
    if {$::DisplayDeltaBarP} {
	PackDeltaBar;
    }
    if {$::DisplaySilenceBarP} {
	PackSilenceBar;
    }
    if {$::DisplaySegmentBarP} {
	PackSegmentBar;
    }
}

proc UnpackMain {} {
    pack forget $::MSG    
    pack forget .ov
    pack forget .ovccsep
    pack forget .info
    pack forget .infosep
    pack forget .c
    pack forget .clup   
    pack forget .sepcc  
    pack forget .play
    pack forget .cntls 
    pack forget .delmov
    pack forget .segmov
    pack forget .silmov
}

proc ToggleWriteBar {} {
    if {[winfo ismapped .cntls]} {
	set ::DisplayWriteBarP 0;
	pack forget .cntls
    } else {
	set ::DisplayWriteBarP 1;
	PackWriteBar;
    }
}

proc PackWriteBar {} {
    pack .cntls  -side top -expand 1 -fill both -padx 4
}

proc TogglePlayBar {} {
    if {[winfo ismapped .play]} {
	set ::DisplayPlayBarP 0;
	pack forget .play
    } else {
	set ::DisplayPlayBarP 1;
	PackPlayBar;
    }
}


proc PackPlayBar {} {
    pack .play  -side top -expand 1 -fill both -padx 4
}

proc ToggleAutoPlay {} {
    if {$::AutoPlayP} {
	ShowMessage [_ "Autoplay enabled."]
    } else {
	ShowMessage [_ "Autoplay disabled."]
    }
}

proc ToggleDrawCutMarks {} {
    if {$::DrawCutMarksP} {
	set ::DrawCutMarksP 0
	ShowNeighborhood;
	ShowMessage [_ "Closeup region markers removed."]
    } else {
	set ::DrawCutMarksP 1
	ShowNeighborhood;
	ShowMessage [_ "Closeup region markers restored."]
    }
}


proc ToggleCloseups {} {
    if {[winfo ismapped .clup]} {
	set ::DisplayCloseupsP 0;
	pack forget .cclupsep
	pack forget .clup;
    } else {
	set ::DisplayCloseupsP 1;
	PackCloseups;
    }
}

proc PackCloseups {} {
#    pack .cclupsep  -after .c -expand 1 -fill both -padx 4 -pady 0
#    pack .clup -after .cclupsep -expand 1 -fill both -padx 4
    pack .clup -after .c -expand 1 -fill both -padx 4
}

proc ToggleZeroCrossingButtons {} {
    if {[winfo ismapped .clup.l.cntrls.b1]} {
	set ::DisplayZeroCrossingButtonsP 0;
	UnpackZeroCrossingButtons;
    } else {
	set ::DisplayZeroCrossingButtonsP 1;
	PackZeroCrossingButtons;
    }
}

proc PackZeroCrossingButtons {} {
    pack .clup.l.cntrls -side top -expand 1 -fill both
    pack .clup.r.cntrls -side top -expand 1 -fill both
}

proc UnpackZeroCrossingButtons {} {
    pack forget .clup.l.cntrls
    pack forget .clup.r.cntrls
}

proc ToggleDeltaBar {} {
    if {[winfo ismapped .delmov]} {
	set ::DisplayDeltaBarP 0;
	pack forget .delmov;
    } else {
	set ::DisplayDeltaBarP 1;
	PackDeltaBar;
    }
}

proc PackDeltaBar {} {
    pack .delmov -side top -expand 1 -fill both -padx 4
}

proc ToggleSegmentBar {} {
    if {[winfo ismapped .segmov]} {
	set ::DisplaySegmentBarP 0;
	pack forget .segmov;
    } else {
	set ::DisplaySegmentBarP 1;
	PackSegmentBar;
    }
}

proc PackSegmentBar {} {
    pack .segmov -side top -expand 1 -fill both -padx 4
}

proc ToggleSilenceBar {} {
    if {[winfo ismapped .silmov]} {
	set ::DisplaySilenceBarP 0;
	pack forget .silmov;
    } else {
	set ::DisplaySilenceBarP 1;
	PackSilenceBar;
    }
}

proc PackSilenceBar {} {
    pack .silmov -side top -expand 1 -fill both -padx 4
}

proc ToggleDeltaEntryActive {n e o} {
    if {$::MSDelta > 0} {
	.info.wdelta.bg.ef.ent configure -state disabled
    } else {
	.info.wdelta.bg.ef.ent configure -state normal
    }
}

proc SetDeltaFromMSDelta {n e o} {
    if {$::MSDelta < 0} {
	set nv [string trim [.info.wdelta.bg.ef.ent get]]
	if { [regexp {[^0123456789]} $nv] } {
	    ShowMessage [format [_ "%s is not a valid value. It must be a positive integer."] $nv]
	    return
	}
	set msd $nv;
    } else {
	set msd $::MSDelta;
    }
    set ::DeltaSeconds [expr double($msd) / 1000.0]
    set ::DeltaSamples [expr int($::DeltaSeconds * $::SamplingRate)]
    ShowMessage [format [_ "Motion increment set to %5.4f seconds (%d samples)"] \
	     $::DeltaSeconds $::DeltaSamples];
}

proc WriteFileDialog {} {
    set w [toplevel .wfd]
    wm title $w "";

    label  $w.title -text [_ "File Name Settings"]

    #Insert entyboxes here

    frame  $w.cntls
    button $w.cntls.set -text [_ "Store New Values"] -command {SetWriteFileComponents}
    button $w.cntls.dis -text [_ "Dismiss Popup"]  -command [list destroy $w]
    pack   $w.cntls.set -side left  -expand 1 -fill both
    pack   $w.cntls.dis -side right -expand 1 -fill both

    pack   $w.title -side top -expand 1 -fill both -pady 4
    #Pack entyboxes here
    pack   $w.cntls -side top -expand 1 -fill both -pady 4

    set msg [_ "Use this dialog to set the various components of output file names."]
    balloonhelp_for $w            $msg
    balloonhelp_for $w.title      $msg
    balloonhelp_for $w.cntls      $msg
    balloonhelp_for $w.bg.ef.ent \
	[_ "Enter the desired value for the increment in milliseconds.\nIt should be a positive integer."]
    balloonhelp_for $w.cntls.set [_ "Click this button to save the new values."]
    balloonhelp_for $w.cntls.dis \
	[_ "Click this button to dismiss the dialog.\nNothing will be changed if you\nhave not pressed the \'Set\' button."]
}


proc SetDrawCutMarksP {b} {
     set ::DrawCutMarksP [Boolean $b];
}

proc SetDisplayCloseupsP {b} {
     set ::DisplayCloseupsP [Boolean $b];
}

proc SetDisplayDeltaBarP {b} {
     set ::DisplayDeltaBarP [Boolean $b];
}

proc SetDisplaySegmentBarP {b} {
     set ::DisplaySegmentBarP [Boolean $b];
}

proc SetDisplaySilenceBarP {b} {
     set ::DisplaySilenceBarP [Boolean $b];
}

proc SetDisplayWriteBarP {b} {
     set ::DisplayWriteBarP [Boolean $b];
}

proc SetAutoLoadOutFileNamesP {b} {
     set ::AutoLoadOutFileNamesP [Boolean $b];
}

proc SetAutoPlayP {b} {
     set ::AutoPlayP [Boolean $b];
}

proc SetAutoComputeSilencesP {b} {
     set ::AutoComputeSilencesP [Boolean $b];
}

proc SetBalloonHelpShowP {b} {
     set ::BalloonHelpP [Boolean $b];
}

proc SetAutoPlayWritesP {b} {
    set ::AutoPlayWritesP [Boolean $b];
}

proc SetSilencesInSecondsP {b} {
     set ::SilencesInSecondsP [Boolean $b];
}

#These four functions return -1 if there is no zero-crossing
#within the closeup region in the direction requested.
proc PreviousZeroCrossingLeft {rpt} {
    return [ZeroCrossingPrevLeft $rpt];
}

proc PreviousZeroCrossingRight {rpt} {
    return [ZeroCrossingPrevRight $rpt];
}

proc NextZeroCrossingLeft {rpt} {
    return [ZeroCrossingNextLeft $rpt];
}

proc NextZeroCrossingRight {rpt} {
    return [ZeroCrossingNextRight $rpt];
}

proc SetWriteMargin {s} {
    set n $s;
    if { [scan $n %f n] != 1} {
	putstd "$s is not a floating point number"
	return
    }
    if {$n < 0.0} {
	putstd "$s is not a positive number"
	return 
    }
    set ::WriteMargin $n;
}

proc SetUseScrollbarsP {b} {
     set ::UseScrollbarsP [Boolean $b];
}

proc SetSetLeftEdgeWavebarImmediateP {b} {
    set ::SetLeftEdgeOverviewImmediateP [Boolean $b];
}


proc SetSilenceThreshold {s} {
    set silence::SilenceThresholdSeconds $s;
}

proc SetDelta {s} {
    set ::DeltaSeconds $s;
}

proc SetDefaultBrowser {s} {
    set ::DefaultBrowser $s;
}

proc SetCloseupResolution {s} {
    set ::CloseupSamplesPerPixel $s
}

proc SetNeighborhoodWindowRatio {s} {
    set ::NeighborhoodWindowRatio $s;
}

proc SetWavebarPixelsPerSecond {s} {
    set ::WavebarPixelsPerSecond $s;
}

proc SetPanelsToShowAtOnce {s} {
    if {($s < 2) || ($s > 5)} {  
	WriteJournal [format [_ "%s is not an appropriate number of panels to show at once."] $s]
	return ;
    }
    set ::PanelsToShow $s;
}

proc SetAutoScaleSoundP {s} {
    set ::AutoScaleSoundPDefault $s;
}

proc SetJournalHomeP {s} {
    set ::JournalHomeP $s;
}

proc UpdateOutFileIndex {n e o} {
    .info.sfname.index delete 0 end
    .info.sfname.index insert end [format "%03d" $::OutFileIndex]
}

proc UpdateNextOutFileName {n e o} {
    if {$::BatchModeP} {return}
    .info.sfname.next delete 0 end
    .info.sfname.next insert end [ConstructOutFileName];
}

#For scripts
proc NextOutputFile {} {
    set name [ConstructOutFileName];
    incr ::OutFileIndex;
    return $name;
}

proc ConstructOutFileName {} {
    if {$::UseOutFileNameListP} {
	if {$::OutFileIndex <= [llength $::OutFileNameList]} {
	    return [lindex $::OutFileNameList [expr $::OutFileIndex - 1]]$::OutFileExtension;
	} else {
	    ShowMessage [_ ""];
	}
    }
    return [format "%s%03d%s%s" $::OutFilePrefix $::OutFileIndex \
		$::OutFileSuffix $::OutFileExtension];
}

proc SetOutFilePrefixFromEntry {} {
    set ::OutFilePrefix [.info.sfname.prefix get]
}

proc SetOutFileIndexFromEntry {} {
    set num [string trimleft [.info.sfname.index get] 0]
    if {[string length $num] < 1} {
	set num 0
    }
    set ::OutFileIndex $num
}

proc SetOutFileSuffixFromEntry {} {
    set ::OutFileSuffix [.info.sfname.suffix get]
}

proc SetOutFileExtensionFromEntry {} {
    set ::OutFileExtension [.info.sfname.ext get]
}

proc SetOutFilePrefix {s} {
    set ::OutFilePrefix $s;
}

proc SetOutFileIndex {s} {
    set ::OutFileIndex $s;
}

proc SetOutFileSuffix {s} {
    set ::OutFileSuffix $s;
}

proc SetOutFileExtension {s} {
    set ::OutFileExtension $s;
}

proc SetUseOutFileNameListP {b} {
    set ::UseOutFileNameListP $b;
}

proc SetCloseupHeight {s} {
    set ::CloseupHeight $s;
}

proc SetNeighborhoodHeight {s} {
    set ::MainWindowHeight $s;
}

proc SetWavebarHeight {s} {
    set ::WavebarHeight $s;
}

proc UserWindowBounds {l r} {
    if {$::WindowSetSecondsP} {
	UserSetWindow [SamplesToSeconds $l] [SamplesToSeconds $r];
    } else {
	UserSetWindow $l $r
    }
}

proc SetUsePauseP {b} {
    set ::UsePauseP [Boolean $b]
}

proc ToggleScrollbars {} {
    if {$::UseScrollbarsP} {
	set ::UseScrollbarsP 0;
	UnpackScrollbars;
    } else {
	set ::UseScrollbarsP 1;
	PackScrollbars;
    }
}

proc UnpackScrollbars {} {
    foreach w $::ScrollbarList {
	pack forget $w;
    }
}

proc PackScrollbars {} {
    foreach w $::ScrollbarList {
	if {[winfo exists $w]} {
	    eval $::PackCommand($w);
	} else {
	    unset ::PackCommand`($w);
	}
    }
}


set RotateInfoStart 0;

if {$::SegmenterP} {
    set InfoFrameList [list \
			   .info.notes \
			   .info.segli \
			   .info.nbrhd \
			   .info.closeup\
			   .info.wavebar \
			   .info.sfile \
			   .info.wdelta \
			   .info.setwin \
			   .info.pause \
			   .info.silence \
			   .info.sili \
			   .info.prli \
			   .info.sfname];
} else {
    set InfoFrameList [list \
			   .info.notes \
			   .info.nbrhd \
			   .info.closeup\
			   .info.wavebar \
			   .info.sfile \
			   .info.wdelta \
			   .info.setwin \
			   .info.pause \
			   .info.silence \
			   .info.sili \
			   .info.sfname];
}

proc RotateInfo {direction} {
    set Total [llength $::InfoFrameList];
    if {[string equal $direction left]} {
	set IndexIncrement -1;
    } else {
	set IndexIncrement 1;
    }
    foreach f $::InfoFrameList {
	pack forget $f;
	bind $f <Button-1> "";
    }
    set ::RotateInfoStart [expr ($::RotateInfoStart + $IndexIncrement) % $Total]
    set Max [expr $::PanelsToShow -1];
    for {set i 0} {$i <= $Max} {incr i} {
	set k [expr ($i + $::RotateInfoStart) % $Total];
	set w [lindex $::InfoFrameList  $k]; 
	pack $w -side right -expand 1 -fill both -padx 6;
	if {$i == 0} {
	    bind $w.title <Button-1> "RotateInfo right"
	} elseif {$i == $Max} {
	    bind $w.title <Button-1> "RotateInfo left"
	} else {
	    bind $w.title <Button-1> "";
	}
    }
}

proc UnlockedRotateInfo {d} {
    pack propagate .info 1
    RotateInfo $d;
    after idle {
	update idletasks
	pack propagate .info 0
    }
}

proc ToggleInfoItem {item} {
   set k [lsearch -exact $::InfoFrameList $item]
    if { $k >= 0} {
	set ::InfoFrameList [lreplace $::InfoFrameList $k $k];
	pack forget $item;
    } else {
	lappend ::InfoFrameList $item;
	RotateInfo left;
	RotateInfo right;
    }
}

#Returns a list of init file commands representing the current color settings.
proc SaveColorSettings {} {
    set cl [list]
    foreach cs [array names ::ColorSpecs] {
	set csl [split $cs ","]
	set obj   [lindex $csl 0]
	set which [lindex $csl 1]
	set ps $::ColorSpecs($cs)
	if {[string index $ps 0] == "\#"} {
	    set ps \\$::ColorSpecs($cs)
	} else {
	    set ps [list $ps];
	}
	lappend cl [format "%s%sColor %s" $obj $which $ps]
    }
    return [lsort $cl];
}

#Check whether the argument represents a Boolean value
#and interpret it if it is.
proc Boolean {s} {
     switch -regexp $s {
	 1	{return 1}
	 T.*	{return 1}
	 t.*	{return 1}
	 Y.*	{return 1}
	 y.*	{return 1}
	 ok	{return 1}
	 on	{return 1}
	 0 	{return 0}
	 F.*	{return 0}
	 f.*	{return 0}
	 N.*	{return 0}
	 n.*	{return 0}
	 off	{return 0}
	 default {error}
     }
}

proc GetInitCommands {} {
    # We want a fresh interpreter so that we don't
    # list any commands defined in a user's init file.
    if { [interp exists init]} {
	interp delete init
    }
    InitFileSetup;
    #We rely on the fact that all builtin commands have lower-case
    #case names to separate the commands we provide from the builtins.
    return [interp eval init {lsort [info commands \[A-Z\]*]}]
}

proc SaveInitCommands {} {
    set SaveFile [tk_getSaveFile -initialfile [_ "InitFileCommands"]];
    if {[string equal $SaveFile ""]} {
	return ;
    } else {
        if { [catch {open $SaveFile "w+"} fh] != 0} {
	    ShowMessage [format \
		     [_ "Unable to open file %s in which to save init commands."] \
		     $SaveFile];
	    return ;
        }
    }
    set n 0;
    foreach l [GetInitCommands] {
	incr n;
	puts $fh [format "\[%03d\] %s" $n $l]
    }
    close $fh;
}

proc PopupInitCommandList {} {
    if {[PopupDown InitCommandList] ==1} {return}
    set po  [CreateTextDisplay [_ "Initialization File Commands"] 65 10];
    set ::PopupList(InitCommandList) $po;
    BindKeys $po;
    set n 0;
    foreach l [GetInitCommands] {
	incr n;
	AppendToTextDisplay $po [format "\[%03d\] %s\n" $n $l];
    }
}

proc PopupInitTclCommandList {} {
    if {[PopupDown InitTclCommandList] ==1} {return}
    set po  [CreateTextDisplay [_ "Initialization File Tcl Commands"] 65 10];
    set ::PopupList(InitTclCommandList) $po;
    BindKeys $po;
    set n 0;
    foreach l [GetInitTclCommands] {
	incr n;
	AppendToTextDisplay $po [format "\[%03d\] %s\n" $n $l];
    }
}

proc GetScriptCommands {} {
    if { [interp exists script]} {
	interp delete script
    }
    ScriptFileSetup;
    #We rely on the fact that all builtin commands have lower-case
    #case names to separate the commands we provide from the builtins.
    return [interp eval script {lsort [info commands \[A-Z\]*]}]
}

proc SaveScriptCommands {} {
    set SaveFile [tk_getSaveFile -initialfile [_ "ScriptFileCommands"]];
    if {[string equal $SaveFile ""]} {
	return ;
    } else {
        if { [catch {open $SaveFile "w+"} fh] != 0} {
	    ShowMessage [format \
		     [_ "Unable to open file %s in which to save script commands."] \
		     $SaveFile];
	    return ;
        }
    }
    set n 0;
    foreach l [GetScriptCommands] {
	incr n;
	puts $fh [format "\[%03d\] %s" $n $l]
    }
    close $fh;
}

proc PopupScriptCommandList {} {
    if {[PopupDown ScriptCommandList] ==1} {return}
    set po  [CreateTextDisplay [_ "Script File Commands"] 65 10];
    set ::PopupList(ScriptCommandList) $po;
    BindKeys $po;
    set n 0;
    foreach l [GetScriptCommands] {
	incr n;
	AppendToTextDisplay $po [format "\[%03d\] %s\n" $n $l];
    }
}

proc GetInitTclCommands {} {
    # We want a fresh interpreter so that we don't
    # list any commands defined in a user's init file.
    if { [interp exists init]} {
	interp delete init
    }
    interp create -safe -- init
    #We rely on the fact that all builtin commands have lower-case
    #case names to separate the commands we provide from the builtins.
    return [interp eval init {lsort [info commands \[a-z\]*]}]
}

proc SaveInitTclCommands {} {
    set SaveFile [tk_getSaveFile -initialfile [_ "InitFileTclCommands"]];
    if {[string equal $SaveFile ""]} {
	return ;
    } else {
        if { [catch {open $SaveFile "w+"} fh] != 0} {
	    ShowMessage [format \
		     [_ "Unable to open file %s in which to save Tcl commands."] \
		     $SaveFile];
	    return ;
        }
    }
    set n 0;
    foreach l [GetInitTclCommands] {
	incr n;
	puts $fh [format "\[%03d\] %s" $n $l]
    }
    close $fh;
}

proc SaveMiscellaneousSettings {} {
    set MiscellaneousInitCommandList \
	[list \
	     [SlaveName SetAutoLoadOutFileNamesP]               $::AutoLoadOutFileNamesP \
	     [SlaveName SetAutoPlayP]				$::AutoPlayP \
	     [SlaveName SetAutoPlayWritesP]			$::AutoPlayWritesP \
	     [SlaveName SetAutoComputeSilencesP]		$::AutoComputeSilencesP \
	     [SlaveName SetAutoScaleSoundP]			$::AutoScaleSoundP \
	     [SlaveName SetBalloonHelpShowP]			$::BalloonHelpP \
	     [SlaveName SetDefaultBrowser]			$::DefaultBrowser \
	     [SlaveName SetCloseupHeight]			$::CloseupHeight \
	     [SlaveName SetCloseupResolution]			$::CloseupSamplesPerPixel \
	     [SlaveName SetDisplayCloseupsP]			$::DisplayCloseupsP \
	     [SlaveName SetDisplayDeltaBarP]			$::DisplayDeltaBarP \
	     [SlaveName SetDisplaySegmentBarP]			$::DisplaySegmentBarP \
	     [SlaveName SetDisplaySilenceBarP]			$::DisplaySilenceBarP \
	     [SlaveName SetDisplayWriteBarP]			$::DisplayWriteBarP \
	     [SlaveName SetDisplayConsonantChartColumnLabelsP]	[ipaentry::SetDisplayConsonantChartColumnLabelsP] \
	     [SlaveName SetDisplayConsonantChartRowLabelsP]	[ipaentry::SetDisplayConsonantChartRowLabelsP] \
	     [SlaveName SetDisplayVowelChartColumnLabelsP]	[ipaentry::SetDisplayVowelChartColumnLabelsP] \
	     [SlaveName SetDisplayVowelChartRowLabelsP]		[ipaentry::SetDisplayVowelChartRowLabelsP] \
	     [SlaveName SetDrawCutMarksP]			$::DrawCutMarksP \
	     [SlaveName SetJournalHomeP]			$::JournalHomeP \
	     [SlaveName SetOutFileIndex]			$::OutFileIndex \
	     [SlaveName SetOutFilePrefix]			$::OutFilePrefix \
	     [SlaveName SetOutFileSuffix]			$::OutFileSuffix \
	     [SlaveName SetOutFileExtension]			$::OutFileExtension \
	     [SlaveName SetUseOutFileNameListP]			$::UseOutFileNameListP \
	     [SlaveName SetNeighborhoodHeight]			$::MainWindowHeight \
	     [SlaveName SetNeighborhoodWindowRatio]		$::NeighborhoodWindowRatio \
	     [SlaveName SetPanelsToShowAtOnce]			$::PanelsToShow \
	     [SlaveName SetPauseFrameSize]			$::PauseParameters(FrameSize) \
	     [SlaveName SetPauseMinimumDuration]		$::PauseParameters(MinimumDuration) \
	     [SlaveName SetPauseThreshold]			$::PauseParameters(Threshold) \
	     [SlaveName SetSetLeftEdgeWavebarImmediateP]	$::SetLeftEdgeOverviewImmediateP \
	     [SlaveName SetSilenceThreshold]			$silence::SilenceThresholdSeconds \
	     [SlaveName SetSilencesInSecondsP]			$::SilencesInSecondsP\
	     [SlaveName SetUseScrollbarsP]			$::UseScrollbarsP \
	     [SlaveName SetWavebarHeight]			$::WavebarHeight \
	     [SlaveName SetWavebarPixelsPerSecond]		$::WavebarPixelsPerSecond \
	     [SlaveName SetWriteMargin]                         $::WriteMargin]
    set cl [list]
    if {[info exists ::AccentedLettersPerRow]} {
	lappend MiscellaneousInitCommandList [SlaveName SetAccentedLetterColumns]
	lappend MiscellaneousInitCommandList $::AccentedLettersPerRow
    }
    foreach {command value} $MiscellaneousInitCommandList {
	lappend cl [format "%s %s" $command $value]
    }
    foreach title [array names ::SpecialCharacterPalette] {
	set info $::SpecialCharacterPalette($title);
	if {[llength $info] > 2} {
	    lappend cl [list ReadCharacterChart [lindex $info 2]];
	} else {
	    lappend cl [ReconstructCharacterChartDefinition $title];
	}
    }
    return $cl;
}

proc ReconstructCharacterChartDefinition {Title} {
    set info $::SpecialCharacterPalette($Title);
    set txt DefineCharacterChart;
    append txt " \{\n"
    append txt [format "%s|%s\n" [lindex $info 1] [Quote $Title]];
    #Each entry consists of a unicode string and a gloss
    foreach x [lindex $info 0] {
	set string [lindex $x 0]
	set gloss  [lindex $x 1]
	append txt [format "%s|%s\n" [UnicodeStringToHex $string] [Quote $gloss]];
    }
    append txt "\}"
    return  $txt;
}

#This is a kludge but I encountered quoting hell trying to use (\\s) -> \\ \\1
#e.g.   regsub -all "\\s" $s {\ } r

#Escape spaces and tabs
proc Quote {s} {
    regsub -all "\u0020" $s {\ } r
    regsub -all "\t" $r {\	} ret
    return $ret
}

proc UnicodeStringToHex {s} {
    set rv "";
    foreach c [split $s ""] {
	scan $c "%c" t
	if {$t <= 0xFF} {
	    append rv $c;
	} else {
	    append rv [format "\\u%04X" $t];
	}
    }
    return $rv;
 }

#This package defines a routine IsColorSpecQ that validates X11 color specifications.
#It returns 1 if its argument is either a recognized X11 color name or
#a well formed hexadecimal RGB specification. If so desired, the two routines on
#which it is based, IsColorNameQ and IsColorNumericQ can also be exported.
namespace eval validcolor {
    namespace export IsColorSpecQ;
    namespace export GetColorNames;
    variable CN;

    set CN([list ghost white]) 1
    set CN([list white smoke]) 1
    set CN([list floral white]) 1
    set CN([list antique white]) 1
    set CN([list old lace]) 1
    set CN([list papaya whip]) 1
    set CN([list blanched almond]) 1
    set CN([list peach puff]) 1
    set CN([list navajo white]) 1
    set CN([list lemon chiffon]) 1
    set CN([list mint cream]) 1
    set CN([list alice blue]) 1
    set CN([list lavender blush]) 1
    set CN([list misty rose]) 1
    set CN([list dark slate gray]) 1
    set CN([list dark slate grey]) 1
    set CN([list dim gray]) 1
    set CN([list dim grey]) 1
    set CN([list slate gray]) 1
    set CN([list slate grey]) 1
    set CN([list light slate gray]) 1
    set CN([list light slate grey]) 1
    set CN([list light grey]) 1
    set CN([list light gray]) 1
    set CN([list midnight blue]) 1
    set CN([list navy blue]) 1
    set CN([list cornflower blue]) 1
    set CN([list dark slate blue]) 1
    set CN([list slate blue]) 1
    set CN([list medium slate blue]) 1
    set CN([list light slate blue]) 1
    set CN([list medium blue]) 1
    set CN([list royal blue]) 1
    set CN([list dodger blue]) 1
    set CN([list deep sky blue]) 1
    set CN([list sky blue]) 1
    set CN([list light sky blue]) 1
    set CN([list steel blue]) 1
    set CN([list light steel blue]) 1
    set CN([list light blue]) 1
    set CN([list powder blue]) 1
    set CN([list pale turquoise]) 1
    set CN([list dark turquoise]) 1
    set CN([list medium turquoise]) 1
    set CN([list light cyan]) 1
    set CN([list cadet blue]) 1
    set CN([list medium aquamarine]) 1
    set CN([list dark green]) 1
    set CN([list dark olive green]) 1
    set CN([list dark sea green]) 1
    set CN([list sea green]) 1
    set CN([list medium sea green]) 1
    set CN([list light sea green]) 1
    set CN([list pale green]) 1
    set CN([list spring green]) 1
    set CN([list lawn green]) 1
    set CN([list medium spring green]) 1
    set CN([list green yellow]) 1
    set CN([list lime green]) 1
    set CN([list yellow green]) 1
    set CN([list forest green]) 1
    set CN([list olive drab]) 1
    set CN([list dark khaki]) 1
    set CN([list pale goldenrod]) 1
    set CN([list light goldenrod yellow]) 1
    set CN([list light yellow]) 1
    set CN([list light goldenrod]) 1
    set CN([list dark goldenrod]) 1
    set CN([list rosy brown]) 1
    set CN([list indian red]) 1
    set CN([list saddle brown]) 1
    set CN([list sandy brown]) 1
    set CN([list dark salmon]) 1
    set CN([list light salmon]) 1
    set CN([list dark orange]) 1
    set CN([list light coral]) 1
    set CN([list orange red]) 1
    set CN([list hot pink]) 1
    set CN([list deep pink]) 1
    set CN([list light pink]) 1
    set CN([list pale violet red]) 1
    set CN([list medium violet red]) 1
    set CN([list violet red]) 1
    set CN([list medium orchid]) 1
    set CN([list dark orchid]) 1
    set CN([list dark violet]) 1
    set CN([list blue violet]) 1
    set CN([list medium purple]) 1
    set CN(snow) 1
    set CN(GhostWhite) 1
    set CN(WhiteSmoke) 1
    set CN(gainsboro) 1
    set CN(FloralWhite) 1
    set CN(OldLace) 1
    set CN(linen) 1
    set CN(AntiqueWhite) 1
    set CN(PapayaWhip) 1
    set CN(BlanchedAlmond) 1
    set CN(bisque) 1
    set CN(PeachPuff) 1
    set CN(NavajoWhite) 1
    set CN(moccasin) 1
    set CN(cornsilk) 1
    set CN(ivory) 1
    set CN(LemonChiffon) 1
    set CN(seashell) 1
    set CN(honeydew) 1
    set CN(MintCream) 1
    set CN(azure) 1
    set CN(AliceBlue) 1
    set CN(lavender) 1
    set CN(LavenderBlush) 1
    set CN(MistyRose) 1
    set CN(white) 1
    set CN(black) 1
    set CN(DarkSlateGray) 1
    set CN(DarkSlateGrey) 1
    set CN(DimGray) 1
    set CN(DimGrey) 1
    set CN(SlateGray) 1
    set CN(SlateGrey) 1
    set CN(LightSlateGray) 1
    set CN(LightSlateGrey) 1
    set CN(gray) 1
    set CN(grey) 1
    set CN(LightGrey) 1
    set CN(LightGray) 1
    set CN(MidnightBlue) 1
    set CN(navy) 1
    set CN(NavyBlue) 1
    set CN(CornflowerBlue) 1
    set CN(DarkSlateBlue) 1
    set CN(SlateBlue) 1
    set CN(MediumSlateBlue) 1
    set CN(LightSlateBlue) 1
    set CN(MediumBlue) 1
    set CN(RoyalBlue) 1
    set CN(blue) 1
    set CN(DodgerBlue) 1
    set CN(DeepSkyBlue) 1
    set CN(SkyBlue) 1
    set CN(LightSkyBlue) 1
    set CN(SteelBlue) 1
    set CN(LightSteelBlue) 1
    set CN(LightBlue) 1
    set CN(PowderBlue) 1
    set CN(PaleTurquoise) 1
    set CN(DarkTurquoise) 1
    set CN(MediumTurquoise) 1
    set CN(turquoise) 1
    set CN(cyan) 1
    set CN(LightCyan) 1
    set CN(CadetBlue) 1
    set CN(MediumAquamarine) 1
    set CN(aquamarine) 1
    set CN(DarkGreen) 1
    set CN(DarkOliveGreen) 1
    set CN(DarkSeaGreen) 1
    set CN(SeaGreen) 1
    set CN(MediumSeaGreen) 1
    set CN(LightSeaGreen) 1
    set CN(PaleGreen) 1
    set CN(SpringGreen) 1
    set CN(LawnGreen) 1
    set CN(green) 1
    set CN(chartreuse) 1
    set CN(MediumSpringGreen) 1
    set CN(GreenYellow) 1
    set CN(LimeGreen) 1
    set CN(YellowGreen) 1
    set CN(ForestGreen) 1
    set CN(OliveDrab) 1
    set CN(DarkKhaki) 1
    set CN(khaki) 1
    set CN(PaleGoldenrod) 1
    set CN(LightGoldenrodYellow) 1
    set CN(LightYellow) 1
    set CN(yellow) 1
    set CN(gold) 1
    set CN(LightGoldenrod) 1
    set CN(goldenrod) 1
    set CN(DarkGoldenrod) 1
    set CN(RosyBrown) 1
    set CN(IndianRed) 1
    set CN(SaddleBrown) 1
    set CN(sienna) 1
    set CN(peru) 1
    set CN(burlywood) 1
    set CN(beige) 1
    set CN(wheat) 1
    set CN(SandyBrown) 1
    set CN(tan) 1
    set CN(chocolate) 1
    set CN(firebrick) 1
    set CN(brown) 1
    set CN(DarkSalmon) 1
    set CN(salmon) 1
    set CN(LightSalmon) 1
    set CN(orange) 1
    set CN(DarkOrange) 1
    set CN(coral) 1
    set CN(LightCoral) 1
    set CN(tomato) 1
    set CN(OrangeRed) 1
    set CN(red) 1
    set CN(HotPink) 1
    set CN(DeepPink) 1
    set CN(pink) 1
    set CN(LightPink) 1
    set CN(PaleVioletRed) 1
    set CN(maroon) 1
    set CN(MediumVioletRed) 1
    set CN(VioletRed) 1
    set CN(magenta) 1
    set CN(violet) 1
    set CN(plum) 1
    set CN(orchid) 1
    set CN(MediumOrchid) 1
    set CN(DarkOrchid) 1
    set CN(DarkViolet) 1
    set CN(BlueViolet) 1
    set CN(purple) 1
    set CN(MediumPurple) 1
    set CN(thistle) 1
    set CN(snow1) 1
    set CN(snow2) 1
    set CN(snow3) 1
    set CN(snow4) 1
    set CN(seashell1) 1
    set CN(seashell2) 1
    set CN(seashell3) 1
    set CN(seashell4) 1
    set CN(AntiqueWhite1) 1
    set CN(AntiqueWhite2) 1
    set CN(AntiqueWhite3) 1
    set CN(AntiqueWhite4) 1
    set CN(bisque1) 1
    set CN(bisque2) 1
    set CN(bisque3) 1
    set CN(bisque4) 1
    set CN(PeachPuff1) 1
    set CN(PeachPuff2) 1
    set CN(PeachPuff3) 1
    set CN(PeachPuff4) 1
    set CN(NavajoWhite1) 1
    set CN(NavajoWhite2) 1
    set CN(NavajoWhite3) 1
    set CN(NavajoWhite4) 1
    set CN(LemonChiffon1) 1
    set CN(LemonChiffon2) 1
    set CN(LemonChiffon3) 1
    set CN(LemonChiffon4) 1
    set CN(cornsilk1) 1
    set CN(cornsilk2) 1
    set CN(cornsilk3) 1
    set CN(cornsilk4) 1
    set CN(ivory1) 1
    set CN(ivory2) 1
    set CN(ivory3) 1
    set CN(ivory4) 1
    set CN(honeydew1) 1
    set CN(honeydew2) 1
    set CN(honeydew3) 1
    set CN(honeydew4) 1
    set CN(LavenderBlush1) 1
    set CN(LavenderBlush2) 1
    set CN(LavenderBlush3) 1
    set CN(LavenderBlush4) 1
    set CN(MistyRose1) 1
    set CN(MistyRose2) 1
    set CN(MistyRose3) 1
    set CN(MistyRose4) 1
    set CN(azure1) 1
    set CN(azure2) 1
    set CN(azure3) 1
    set CN(azure4) 1
    set CN(SlateBlue1) 1
    set CN(SlateBlue2) 1
    set CN(SlateBlue3) 1
    set CN(SlateBlue4) 1
    set CN(RoyalBlue1) 1
    set CN(RoyalBlue2) 1
    set CN(RoyalBlue3) 1
    set CN(RoyalBlue4) 1
    set CN(blue1) 1
    set CN(blue2) 1
    set CN(blue3) 1
    set CN(blue4) 1
    set CN(DodgerBlue1) 1
    set CN(DodgerBlue2) 1
    set CN(DodgerBlue3) 1
    set CN(DodgerBlue4) 1
    set CN(SteelBlue1) 1
    set CN(SteelBlue2) 1
    set CN(SteelBlue3) 1
    set CN(SteelBlue4) 1
    set CN(DeepSkyBlue1) 1
    set CN(DeepSkyBlue2) 1
    set CN(DeepSkyBlue3) 1
    set CN(DeepSkyBlue4) 1
    set CN(SkyBlue1) 1
    set CN(SkyBlue2) 1
    set CN(SkyBlue3) 1
    set CN(SkyBlue4) 1
    set CN(LightSkyBlue1) 1
    set CN(LightSkyBlue2) 1
    set CN(LightSkyBlue3) 1
    set CN(LightSkyBlue4) 1
    set CN(SlateGray1) 1
    set CN(SlateGray2) 1
    set CN(SlateGray3) 1
    set CN(SlateGray4) 1
    set CN(LightSteelBlue1) 1
    set CN(LightSteelBlue2) 1
    set CN(LightSteelBlue3) 1
    set CN(LightSteelBlue4) 1
    set CN(LightBlue1) 1
    set CN(LightBlue2) 1
    set CN(LightBlue3) 1
    set CN(LightBlue4) 1
    set CN(LightCyan1) 1
    set CN(LightCyan2) 1
    set CN(LightCyan3) 1
    set CN(LightCyan4) 1
    set CN(PaleTurquoise1) 1
    set CN(PaleTurquoise2) 1
    set CN(PaleTurquoise3) 1
    set CN(PaleTurquoise4) 1
    set CN(CadetBlue1) 1
    set CN(CadetBlue2) 1
    set CN(CadetBlue3) 1
    set CN(CadetBlue4) 1
    set CN(turquoise1) 1
    set CN(turquoise2) 1
    set CN(turquoise3) 1
    set CN(turquoise4) 1
    set CN(cyan1) 1
    set CN(cyan2) 1
    set CN(cyan3) 1
    set CN(cyan4) 1
    set CN(DarkSlateGray1) 1
    set CN(DarkSlateGray2) 1
    set CN(DarkSlateGray3) 1
    set CN(DarkSlateGray4) 1
    set CN(aquamarine1) 1
    set CN(aquamarine2) 1
    set CN(aquamarine3) 1
    set CN(aquamarine4) 1
    set CN(DarkSeaGreen1) 1
    set CN(DarkSeaGreen2) 1
    set CN(DarkSeaGreen3) 1
    set CN(DarkSeaGreen4) 1
    set CN(SeaGreen1) 1
    set CN(SeaGreen2) 1
    set CN(SeaGreen3) 1
    set CN(SeaGreen4) 1
    set CN(PaleGreen1) 1
    set CN(PaleGreen2) 1
    set CN(PaleGreen3) 1
    set CN(PaleGreen4) 1
    set CN(SpringGreen1) 1
    set CN(SpringGreen2) 1
    set CN(SpringGreen3) 1
    set CN(SpringGreen4) 1
    set CN(green1) 1
    set CN(green2) 1
    set CN(green3) 1
    set CN(green4) 1
    set CN(chartreuse1) 1
    set CN(chartreuse2) 1
    set CN(chartreuse3) 1
    set CN(chartreuse4) 1
    set CN(OliveDrab1) 1
    set CN(OliveDrab2) 1
    set CN(OliveDrab3) 1
    set CN(OliveDrab4) 1
    set CN(DarkOliveGreen1) 1
    set CN(DarkOliveGreen2) 1
    set CN(DarkOliveGreen3) 1
    set CN(DarkOliveGreen4) 1
    set CN(khaki1) 1
    set CN(khaki2) 1
    set CN(khaki3) 1
    set CN(khaki4) 1
    set CN(LightGoldenrod1) 1
    set CN(LightGoldenrod2) 1
    set CN(LightGoldenrod3) 1
    set CN(LightGoldenrod4) 1
    set CN(LightYellow1) 1
    set CN(LightYellow2) 1
    set CN(LightYellow3) 1
    set CN(LightYellow4) 1
    set CN(yellow1) 1
    set CN(yellow2) 1
    set CN(yellow3) 1
    set CN(yellow4) 1
    set CN(gold1) 1
    set CN(gold2) 1
    set CN(gold3) 1
    set CN(gold4) 1
    set CN(goldenrod1) 1
    set CN(goldenrod2) 1
    set CN(goldenrod3) 1
    set CN(goldenrod4) 1
    set CN(DarkGoldenrod1) 1
    set CN(DarkGoldenrod2) 1
    set CN(DarkGoldenrod3) 1
    set CN(DarkGoldenrod4) 1
    set CN(RosyBrown1) 1
    set CN(RosyBrown2) 1
    set CN(RosyBrown3) 1
    set CN(RosyBrown4) 1
    set CN(IndianRed1) 1
    set CN(IndianRed2) 1
    set CN(IndianRed3) 1
    set CN(IndianRed4) 1
    set CN(sienna1) 1
    set CN(sienna2) 1
    set CN(sienna3) 1
    set CN(sienna4) 1
    set CN(burlywood1) 1
    set CN(burlywood2) 1
    set CN(burlywood3) 1
    set CN(burlywood4) 1
    set CN(wheat1) 1
    set CN(wheat2) 1
    set CN(wheat3) 1
    set CN(wheat4) 1
    set CN(tan1) 1
    set CN(tan2) 1
    set CN(tan3) 1
    set CN(tan4) 1
    set CN(chocolate1) 1
    set CN(chocolate2) 1
    set CN(chocolate3) 1
    set CN(chocolate4) 1
    set CN(firebrick1) 1
    set CN(firebrick2) 1
    set CN(firebrick3) 1
    set CN(firebrick4) 1
    set CN(brown1) 1
    set CN(brown2) 1
    set CN(brown3) 1
    set CN(brown4) 1
    set CN(salmon1) 1
    set CN(salmon2) 1
    set CN(salmon3) 1
    set CN(salmon4) 1
    set CN(LightSalmon1) 1
    set CN(LightSalmon2) 1
    set CN(LightSalmon3) 1
    set CN(LightSalmon4) 1
    set CN(orange1) 1
    set CN(orange2) 1
    set CN(orange3) 1
    set CN(orange4) 1
    set CN(DarkOrange1) 1
    set CN(DarkOrange2) 1
    set CN(DarkOrange3) 1
    set CN(DarkOrange4) 1
    set CN(coral1) 1
    set CN(coral2) 1
    set CN(coral3) 1
    set CN(coral4) 1
    set CN(tomato1) 1
    set CN(tomato2) 1
    set CN(tomato3) 1
    set CN(tomato4) 1
    set CN(OrangeRed1) 1
    set CN(OrangeRed2) 1
    set CN(OrangeRed3) 1
    set CN(OrangeRed4) 1
    set CN(red1) 1
    set CN(red2) 1
    set CN(red3) 1
    set CN(red4) 1
    set CN(DeepPink1) 1
    set CN(DeepPink2) 1
    set CN(DeepPink3) 1
    set CN(DeepPink4) 1
    set CN(HotPink1) 1
    set CN(HotPink2) 1
    set CN(HotPink3) 1
    set CN(HotPink4) 1
    set CN(pink1) 1
    set CN(pink2) 1
    set CN(pink3) 1
    set CN(pink4) 1
    set CN(LightPink1) 1
    set CN(LightPink2) 1
    set CN(LightPink3) 1
    set CN(LightPink4) 1
    set CN(PaleVioletRed1) 1
    set CN(PaleVioletRed2) 1
    set CN(PaleVioletRed3) 1
    set CN(PaleVioletRed4) 1
    set CN(maroon1) 1
    set CN(maroon2) 1
    set CN(maroon3) 1
    set CN(maroon4) 1
    set CN(VioletRed1) 1
    set CN(VioletRed2) 1
    set CN(VioletRed3) 1
    set CN(VioletRed4) 1
    set CN(magenta1) 1
    set CN(magenta2) 1
    set CN(magenta3) 1
    set CN(magenta4) 1
    set CN(orchid1) 1
    set CN(orchid2) 1
    set CN(orchid3) 1
    set CN(orchid4) 1
    set CN(plum1) 1
    set CN(plum2) 1
    set CN(plum3) 1
    set CN(plum4) 1
    set CN(MediumOrchid1) 1
    set CN(MediumOrchid2) 1
    set CN(MediumOrchid3) 1
    set CN(MediumOrchid4) 1
    set CN(DarkOrchid1) 1
    set CN(DarkOrchid2) 1
    set CN(DarkOrchid3) 1
    set CN(DarkOrchid4) 1
    set CN(purple1) 1
    set CN(purple2) 1
    set CN(purple3) 1
    set CN(purple4) 1
    set CN(MediumPurple1) 1
    set CN(MediumPurple2) 1
    set CN(MediumPurple3) 1
    set CN(MediumPurple4) 1
    set CN(thistle1) 1
    set CN(thistle2) 1
    set CN(thistle3) 1
    set CN(thistle4) 1
    set CN(gray0) 1
    set CN(grey0) 1
    set CN(gray1) 1
    set CN(grey1) 1
    set CN(gray2) 1
    set CN(grey2) 1
    set CN(gray3) 1
    set CN(grey3) 1
    set CN(gray4) 1
    set CN(grey4) 1
    set CN(gray5) 1
    set CN(grey5) 1
    set CN(gray6) 1
    set CN(grey6) 1
    set CN(gray7) 1
    set CN(grey7) 1
    set CN(gray8) 1
    set CN(grey8) 1
    set CN(gray9) 1
    set CN(grey9) 1
    set CN(gray10) 1
    set CN(grey10) 1
    set CN(gray11) 1
    set CN(grey11) 1
    set CN(gray12) 1
    set CN(grey12) 1
    set CN(gray13) 1
    set CN(grey13) 1
    set CN(gray14) 1
    set CN(grey14) 1
    set CN(gray15) 1
    set CN(grey15) 1
    set CN(gray16) 1
    set CN(grey16) 1
    set CN(gray17) 1
    set CN(grey17) 1
    set CN(gray18) 1
    set CN(grey18) 1
    set CN(gray19) 1
    set CN(grey19) 1
    set CN(gray20) 1
    set CN(grey20) 1
    set CN(gray21) 1
    set CN(grey21) 1
    set CN(gray22) 1
    set CN(grey22) 1
    set CN(gray23) 1
    set CN(grey23) 1
    set CN(gray24) 1
    set CN(grey24) 1
    set CN(gray25) 1
    set CN(grey25) 1
    set CN(gray26) 1
    set CN(grey26) 1
    set CN(gray27) 1
    set CN(grey27) 1
    set CN(gray28) 1
    set CN(grey28) 1
    set CN(gray29) 1
    set CN(grey29) 1
    set CN(gray30) 1
    set CN(grey30) 1
    set CN(gray31) 1
    set CN(grey31) 1
    set CN(gray32) 1
    set CN(grey32) 1
    set CN(gray33) 1
    set CN(grey33) 1
    set CN(gray34) 1
    set CN(grey34) 1
    set CN(gray35) 1
    set CN(grey35) 1
    set CN(gray36) 1
    set CN(grey36) 1
    set CN(gray37) 1
    set CN(grey37) 1
    set CN(gray38) 1
    set CN(grey38) 1
    set CN(gray39) 1
    set CN(grey39) 1
    set CN(gray40) 1
    set CN(grey40) 1
    set CN(gray41) 1
    set CN(grey41) 1
    set CN(gray42) 1
    set CN(grey42) 1
    set CN(gray43) 1
    set CN(grey43) 1
    set CN(gray44) 1
    set CN(grey44) 1
    set CN(gray45) 1
    set CN(grey45) 1
    set CN(gray46) 1
    set CN(grey46) 1
    set CN(gray47) 1
    set CN(grey47) 1
    set CN(gray48) 1
    set CN(grey48) 1
    set CN(gray49) 1
    set CN(grey49) 1
    set CN(gray50) 1
    set CN(grey50) 1
    set CN(gray51) 1
    set CN(grey51) 1
    set CN(gray52) 1
    set CN(grey52) 1
    set CN(gray53) 1
    set CN(grey53) 1
    set CN(gray54) 1
    set CN(grey54) 1
    set CN(gray55) 1
    set CN(grey55) 1
    set CN(gray56) 1
    set CN(grey56) 1
    set CN(gray57) 1
    set CN(grey57) 1
    set CN(gray58) 1
    set CN(grey58) 1
    set CN(gray59) 1
    set CN(grey59) 1
    set CN(gray60) 1
    set CN(grey60) 1
    set CN(gray61) 1
    set CN(grey61) 1
    set CN(gray62) 1
    set CN(grey62) 1
    set CN(gray63) 1
    set CN(grey63) 1
    set CN(gray64) 1
    set CN(grey64) 1
    set CN(gray65) 1
    set CN(grey65) 1
    set CN(gray66) 1
    set CN(grey66) 1
    set CN(gray67) 1
    set CN(grey67) 1
    set CN(gray68) 1
    set CN(grey68) 1
    set CN(gray69) 1
    set CN(grey69) 1
    set CN(gray70) 1
    set CN(grey70) 1
    set CN(gray71) 1
    set CN(grey71) 1
    set CN(gray72) 1
    set CN(grey72) 1
    set CN(gray73) 1
    set CN(grey73) 1
    set CN(gray74) 1
    set CN(grey74) 1
    set CN(gray75) 1
    set CN(grey75) 1
    set CN(gray76) 1
    set CN(grey76) 1
    set CN(gray77) 1
    set CN(grey77) 1
    set CN(gray78) 1
    set CN(grey78) 1
    set CN(gray79) 1
    set CN(grey79) 1
    set CN(gray80) 1
    set CN(grey80) 1
    set CN(gray81) 1
    set CN(grey81) 1
    set CN(gray82) 1
    set CN(grey82) 1
    set CN(gray83) 1
    set CN(grey83) 1
    set CN(gray84) 1
    set CN(grey84) 1
    set CN(gray85) 1
    set CN(grey85) 1
    set CN(gray86) 1
    set CN(grey86) 1
    set CN(gray87) 1
    set CN(grey87) 1
    set CN(gray88) 1
    set CN(grey88) 1
    set CN(gray89) 1
    set CN(grey89) 1
    set CN(gray90) 1
    set CN(grey90) 1
    set CN(gray91) 1
    set CN(grey91) 1
    set CN(gray92) 1
    set CN(grey92) 1
    set CN(gray93) 1
    set CN(grey93) 1
    set CN(gray94) 1
    set CN(grey94) 1
    set CN(gray95) 1
    set CN(grey95) 1
    set CN(gray96) 1
    set CN(grey96) 1
    set CN(gray97) 1
    set CN(grey97) 1
    set CN(gray98) 1
    set CN(grey98) 1
    set CN(gray99) 1
    set CN(grey99) 1
    set CN(gray100) 1
    set CN(grey100) 1

    proc PopupColorNameList {} {
	if {[PopupDown ColorNameList] ==1} {return}
	set po  [CreateTextDisplay [_ "Color Names"] 65 10];
	set ::PopupList(ColorNameList) $po
	BindKeys $po;
	set n 0;
	foreach l [::validcolor::GetColorNames] {
	incr n;
	AppendToTextDisplay $po [format "\[%03d\] %s\n" $n $l];
	}
    }

    proc GetColorNames {} {
	variable CN
	return [lsort -dictionary [array names CN]]
    }

    proc IsColorNameQ {s} {
	variable CN
	if {[info exists CN($s)]} {
	    return 1;
	} else {
	    return 0;
	}
    }

    proc IsColorNumericQ {s} {
	return [regexp \
		    {^\#([[:xdigit:]]{6}|[[:xdigit:]]{3}|[[:xdigit:]]{9}|[[:xdigit:]]{12})$} $s]
    }
		
    proc IsColorSpecQ {s} {
	if {[IsColorNameQ $s]} {
	    return 1;
	} elseif {[IsColorNumericQ $s]} {
	    return 1;
	} else {
	    return 0;
	}
    }
}
#End of namespace validcolor

#Parse the log file written by Prompter, in whicch each line should consists of:
#timestamp, in milliseconds, uid, headword
#Returns a list of lists, where each sublist consists of the start point, the uid, and the headword
proc ParsePrompterLog {fh Offset} {
    set CommentCharacter "\#"
    set LineNo 0
    set InPreparation [list x y $Offset]
    while {[gets $fh line] >= 0} {
	incr LineNo
	if {[string length $line] == 0} {
	    continue;#blank line 
	}
	set line [string trimleft $line]
	if {[string index $line 0] == $CommentCharacter} {
	    continue;#comment
	}
	if {$LineNo < 3} {
	    continue;#Header lines 
	}
	set line [regsub -all {[ ] +} $line " " ]; #Map more than one space to single space
	set lp [split $line];
	set BeginSeconds [expr {double([string trimleft [lindex $lp 0] 0]) / 1000.0} + $Offset]
	set Begin [SecondsToSamples $BeginSeconds]
	set UID [lindex $lp 1]
	set HeadWord [lindex $lp 2]
	lappend InPreparation $Begin;#Append current start as previous endpoint 
	lappend LogList $InPreparation
	set InPreparation [list $UID $HeadWord $Begin]
    }
    lappend InPreparation $::SoundLastSample;#Use edpoint of file as end of last region
    lappend LogList $InPreparation
    return [lrange $LogList 1 end]
}

proc LoadPrompterLog {args} {
    if {[llength $args] > 0} {
	set FileName [lindex $args 0];
    } else {
	set FileName [tk_getOpenFile -title [_ "Specify Prompter Log File"]]
    }
    if {$FileName == ""} {
	ShowMessage [_ "No file name specified."]
	return ;
    }
    if {[catch {open $FileName "r"} fh] != 0} {
	ShowMessage [format [_ "LoadPrompterLog: Unable to open file %s."] $FileName];
	return ;
    }
    #Note that we're assuming that the sound file has been read at this point. Test? NEEDSWORK
    set SynchPulseLocation [synchpulse::LocateSynchPulse snd]
    dmsg "Offset computed using synch pulse = $SynchPulseLocation"
    set ::PrompterList [ParsePrompterLog $fh $SynchPulseLocation]
    set ::PrompterEntries [llength $::PrompterList]
    close $fh
    UpdatePrompterDisplay a b c
    ShowMessage [format [_ "Loaded %d entries from prompter log %s"] \
	     $::PrompterEntries [MinimizeFileName $FileName]]
}

proc LoadOutFileNameList {args} {
    if {[llength $args]} {
	set fn [lindex $args 0]
    } else {
	set fn [tk_getOpenFile -title [_ "Load Output File Name List"]];
	if {[string equal $fn ""]} {
	    ShowMessage [_ "File selection cancelled."];
	    return ;
	}
    }
    if { [catch {open $fn "r"} fhd ] != 0} {
	ShowMessage [format [_ "Unable to open output file name list file %s."] $fn];
	return ;
    }
    set LineCnt 0
    while { [gets $fhd line] > 0} {
	lappend Lines $line;
	incr LineCnt
    }
    close $fhd;
    if {$LineCnt < 1} {
	ShowMessage [_ "File %s is empty" $fn]
	return "";
    }
    ShowMessage [format [_ "Loaded %d output file names from %s."] $LineCnt $fn]
    set ::OutFileNameList $Lines;
    set ::UseOutFileNameListP 1;
    UpdateNextOutFileName x y z;
}

#This creates a procedure for setting the color of each combination of
#object and feature. The procedure validates the color specification, so
#invalid color specifications are trapped in the slave interpreter.
proc DefineColorSettingProcs {} {
    global ColorProcList;
    foreach cs [array names ::ColorSpecs] {
	set csl [split $cs ","]
	set obj   [lindex $csl 0]
	set which [lindex $csl 1]
	set procname [format "Set%s%sColor" $obj $which]
	lappend ColorProcList $procname
	eval [list "proc" $procname \
		   \
		  "\{cs\}" \
		  "if \{!\[::validcolor::IsColorSpecQ \$cs\]\} \{
		  putstd \[format \[_ \"\\\"%s\\\" is not a valid color specification.\"\] \$cs\]
		  return;
		 \}
		  set ::ColorSpecs($obj,$which) \$cs"]
    }
}

#Ths procedure takes as its sole argument the name
#of an existing procedure in the same interpreter
#and creates a new master level procedure that
#wraps the other procedure with a test for the
#correct argument count.

proc WrapMaster {pn} {
    regsub "^::fontsel::" $pn "" Stem
    set WrappedName Wrapped${Stem};
    set sp [format "proc $WrappedName \{args\} \{\n"];
    set ArgsNeeded [llength [info args $pn]];
    append sp [format "\tif \{\[llength \$args\] != %d\} \{\n" $ArgsNeeded]
    if {$ArgsNeeded == 1} {
	set emsg [format [_ "The command %s in the file %%s expects one argument"] \
	[SlaveName $WrappedName]]
	set cmd [format "\t\tputstd \"$emsg\"\n" \$::InitFile]
	append sp $cmd
    } else {
	set emsg [format [_ "The command %s in the file %%s expects %d arguments\n"] \
	      [SlaveName $WrappedName] $ArgsNeeded]
	set cmd [format "\t\tputstd \"$emsg\"\n" \$::InitFile]; 
	append sp $cmd;
    }
    append sp "\t\treturn;\n\t\}\n\t"
    append sp  $pn
    for {set i 0} {$i < $ArgsNeeded} {incr i} {
	append sp " \[lindex \$args $i\]"
    }
    append sp "\n\}"
    eval $sp;
    return $WrappedName;
}

proc ReadInitFile {name} {
    if { [catch {interp invoke init source $name} msg] } {
	putstd [format [_  "Error on reading init file %s: %s"] $name $msg]
    } else {
	ShowMessage [format [_ "Executed init file %s"] $name]
	putstd [format "Executed init file %s" $name]
    }
    interp delete init
}

proc ReadScriptFile {name} {
    if { [catch {interp invoke script source $name} msg] } {
	putstd [format [_  "Error on reading script file %s: %s"] $name $msg]
    } else {
	ShowMessage [format [_ "Executed script file %s"] $name]
    }
    interp delete script
}

#This is called from the GUI.
proc ExecuteScriptFile {} {
    set ScriptFileName [tk_getOpenFile -title [_ "Script File"]];
    if {[string equal $ScriptFileName ""]} {
	ShowMessage [_ "File selection cancelled."];
	return ;
    }
    ScriptFileSetup;
    ReadScriptFile $ScriptFileName;
}

proc LoadSegmentList {args} {
    if {[llength $args] > 0} {
	set FileName [lindex $args 0];
    } else {
	set FileName [tk_getOpenFile -title [_ "Specify Silence File"]]
    }
    if {$FileName == ""} {
	ShowMessage [_ "No file name specified."]
	return ;
    }
    set FileName [MinimizeFileName $FileName]
    ClearSegmentList
    ScriptFileSetup;
    ReadScriptFile $FileName
    UpdateSegmentDisplay x y z
}

proc SlavePuts {msg} {
    puts $msg;
}

proc SlaveMsgcat {} {
    package require msgcat
    ::msgcat::mcload [file join [file dirname [info script]] msgs];
}

#This is the list of the master init interpreter commands
#other than those generated from data structures (currently
#color- and font-setting) that we wish to expose for use in
#the init file slave interpreter.
set MiscellaneousSlaveInitCommandList {
    AppendToSegmentList
    ClearSegmentList
    DefineShortcut
    LoadOutFileNameList
    LoadSegmentList
    LoadSoundFile
    SaveSegmentList
    WriteSegments
    SetAutoLoadOutFileNamesP
    SetAutoPlayP
    SetAutoPlayWritesP
    SetAutoComputeSilencesP
    SetAutoScaleSoundP
    SetBalloonHelpShowP
    SetDefaultBrowser
    SetCloseupHeight
    SetCloseupResolution
    SetDisplayCloseupsP
    SetDisplayDeltaBarP
    SetDisplaySegmentBarP
    SetDisplaySilenceBarP
    SetDisplayWriteBarP
    SetDrawCutMarksP
    SetJournalHomeP
    SetOutFileIndex
    SetOutFilePrefix
    SetOutFileSuffix
    SetOutFileExtension
    SetUseOutFileNameListP
    SetNeighborhoodHeight
    SetNeighborhoodWindowRatio
    SetPanelsToShowAtOnce
    SetPauseFrameSize
    SetPauseMinimumDuration
    SetPauseThreshold
    SetSetLeftEdgeWavebarImmediateP
    SetSilenceThreshold
    SetSilencesInSecondsP
    SetUseScrollbarsP
    SetUsePauseP
    SetWavebarHeight
    SetWavebarPixelsPerSecond
    SlavePuts
    StoreCustomCharacterChartInPlace
    StoreCustomCharacterChartFileName
    StoreCustomCharacterChartPanelInPlace
    StoreCustomCharacterChartPanelFileName
    SetDisplayConsonantChartColumnLabelsP
    SetDisplayConsonantChartRowLabelsP
    SetDisplayVowelChartColumnLabelsP
    SetDisplayVowelChartRowLabelsP
    SetWriteMargin
}

#This is the list of the master script interpreter commands
#that we wish to expose for use in the script file slave interpreter.
set MiscellaneousSlaveScriptCommandList {
    AppendToSegmentList
    ClearSegmentList
    DefineShortcut
    LoadOutFileNameList
    LoadSegmentList
    SaveSegmentList
    SetAutoLoadOutFileNamesP
    WriteSegments
    NextOutputFile
    ExecutePause
    LoadSoundFile
    PlayWindow
    SecondsToSamples
    SetAutoPlayP
    SetAutoComputeSilencesP
    SetAutoScaleSoundP
    SetOutFileIndex
    SetOutFilePrefix
    SetOutFileSuffix
    SetOutFileExtension
    SetUseOutFileNameListP
    SetPauseFrameSize
    SetPauseMinimumDuration
    SetPauseThreshold
    SetSilenceThreshold
    SetUsePauseP
    SlavePuts
    SamplesToSeconds
    TellSoundFileLengthSamples
    TellWindowLeftEdgeSamples
    TellWindowRightEdgeSamples
    WindowForwardSilence
    WriteRegionToFile
    WriteWindowNoCheck
    UserWindowBounds
    PreviousZeroCrossingLeft
    PreviousZeroCrossingRight
    NextZeroCrossingLeft
    NextZeroCrossingRight
    SetWriteMargin
    SetAccentedLetterColumns
}

#These should perhaps be exposed, but they need to be reviewed
#to make sure they work properly in batch mode.
#    WindowBackwardSilence
#    LeftEdgeBackwardSilence
#    RightEdgeBackwardSilence
#    LeftEdgeForwardSilence
#    RightEdgeForwardSilence
#    WindowBackwardDelta
#    WindowForwardDelta
#    LeftEdgeBackwardDelta
#    RightEdgeBackwardDelta
#    LeftEdgeForwardDelta
#    RightEdgeForwardDelta

#This procedure creates the master procedures that will be exposed
#in the slave interpreter. It takes care of creating the base procedures
#where, as in the case of color and font setting, these are created
#programmatically, then wraps these as well as the manually
#written procedures that are to be exposed.
proc CreateInitProcs {} {
    set ::FontProcList "";
    fontsel::DefineFontSettingProcs
    DefineColorSettingProcs;
    #This is the complete list of commands that we want to expose 
    #in the slave init file interpreter. These are the raw, unwrapped, master
    #level commands.
    set ::MasterCommandsToBeExposedInInitList [concat \
	   [lsort $::ColorProcList] \
	   [lsort $::FontProcList]  \
	   [lsort $::MiscellaneousSlaveInitCommandList]];
    #Now we wrap them all so as to trap valence errors
    set ::WrappedMasterInitCommandList [list]
    foreach c $::MasterCommandsToBeExposedInInitList {
	lappend ::WrappedMasterInitCommandList [WrapMaster $c]
    }
}

proc CreateScriptProcs {} {
    set ::MasterCommandsToBeExposedInScriptList  [lsort $::MiscellaneousSlaveScriptCommandList];
    #Now we wrap them all so as to trap valence errors
    set ::WrappedMasterScriptCommandList [list]
    foreach c $::MasterCommandsToBeExposedInScriptList {
	lappend ::WrappedMasterScriptCommandList [WrapMaster $c]
    }
}

set MasterToSlaveName(UserWindowBounds) WindowBounds;
set MasterToSlaveName(SetDefaultBrowser) Browser;
#set MasterToSlaveName(SetDelta) SetDelta
set MasterToSlaveName(SetOutFileIndex) FileIndex;
set MasterToSlaveName(SetOutFilePrefix) FilePrefix;
set MasterToSlaveName(SetOutFileSuffix) FileSuffix;
set MasterToSlaveName(SetOutFileExtension) FileExtension;
set MasterToSlaveName(SetSetLeftEdgeWavebarImmediateP) SetLeftEdgeWavebarImmediateP
set MasterToSlaveName(SlavePuts) Puts;
set MasterToSlaveName(StoreCustomCharacterChartInPlace) DefineCharacterChart 
set MasterToSlaveName(StoreCustomCharacterChartFileName) ReadCharacterChart 
set MasterToSlaveName(StoreCustomCharacterChartPanelInPlace) DefineCharacterChartPanel 
set MasterToSlaveName(StoreCustomCharacterChartPanelFileName) ReadCharacterChartPanel 
set MasterToSlaveName(WriteWindowNoCheck) WriteWindow
set MasterToSlaveName(ZeroCrossingPrevLeft) LeftWindowEdgeToPreviousZeroCrossing
set MasterToSlaveName(ZeroCrossingNextRight) RightWindowEdgeToNextZeroCrossing

#Given the name of a wrapped command in the master interpreter,
#returns the name that the command is to have when
#exposed in the slave interpreter. In most cases the alias
#is computed from the master name, but in some cases
#the relationship is irregular. 
proc SlaveName {command} {
    regsub "^Wrapped" $command "" Unwrapped
    if {[info exists ::MasterToSlaveName($Unwrapped)]} {
	set EnglishSlaveName $::MasterToSlaveName($Unwrapped);
    } else {
	regsub "^Set" $Unwrapped "" EnglishSlaveName
    }
    return [_ $EnglishSlaveName]
}

proc InitFileSetup {} {
    interp create -safe -- init
    #We use slaveMsgcat rather than SlaveMsgcat so that the name does not
    #appear in the list that the user sees.
    init alias slaveMsgcat SlaveMsgcat
    init eval slaveMsgcat
    init alias mc ::msgcat::mc
    foreach c $::WrappedMasterInitCommandList {
	set sl [SlaveName $c];
	init alias $sl $c;
    }
    #This takes care of errors in the name of commands while still in the
    #slave interpreter, without aborting, and using the user-name in the error-message.
    init eval {
	proc unknown {args} {
	    set cmd [lindex $args 0]
	    Puts [format  [mc "Unknown command %s in script file %s."]  $cmd [info script]];
	    return ;
	}
    }
}

proc ScriptFileSetup {} {
    interp create -safe -- script
    #We use slaveMsgcat rather than SlaveMsgcat so that the name does not
    #appear in the list that the user sees.
    script alias slaveMsgcat SlaveMsgcat
    script eval slaveMsgcat
    script alias mc ::msgcat::mc
    foreach c $::WrappedMasterScriptCommandList {
	set sl [SlaveName $c];
	script alias $sl $c;
    }
    #This takes care of errors in the name of commands while still in the
    #slave interpreter, without aborting, and using the user-name in the error-message.
    script eval {
	proc unknown {args} {
	    set cmd [lindex $args 0]
	    Puts [format  [mc "Unknown command %s in script file %s."]  $cmd [info script]];
#	    Puts [format  [mc "Unknown command %1\$s in script file %2\$s."]  $cmd [info script]];
	    return ;
	}
    }
}

proc SlaveBoolean {s} {
    switch -regexp $s {
	1	{return 1}
	T.*	{return 1}
	t.*	{return 1}
	Y.*	{return 1}
	y.*	{return 1}
	ok	{return 1}
	on	{return 1}
	0 	{return 0}
	F.*	{return 0}
	f.*	{return 0}
	N.*	{return 0}
	n.*	{return 0}
	off	{return 0}
	default {
	    puts [format [msgcat::mc "%s is not a Boolean argument."] $s]
	    return -1; 
	}
    }
}

set CustomCharacterChartFileNameList "";
proc StoreCustomCharacterChartFileName {fn} {
    lappend ::CustomCharacterChartFileNameList $fn;
}

set CustomCharacterChartDataList "";
proc StoreCustomCharacterChartInPlace {dl} {
    lappend ::CustomCharacterChartDataList $dl;
}

set CustomCharacterChartPanelFileNameList "";
proc StoreCustomCharacterChartPanelFileName {fn} {
    lappend ::CustomCharacterChartPanelFileNameList $fn;
}

set CustomCharacterChartPanelDataList "";
proc StoreCustomCharacterChartPanelInPlace {dl} {
    lappend ::CustomCharacterChartPanelDataList $dl;
}

#Write out a list of init file commands that will reconstruct
#the current configuration 
proc SaveState {{SaveFile Ask}} {
    if {[string equal $SaveFile Ask]} { 
	set SaveFile [tk_getSaveFile -initialfile [_ "SavedState"]];
	if {$SaveFile == ""} {
	    ShowMessage [_ "File selection cancelled."]
	    return ;
	}
    }
    if {[catch {open $SaveFile "w"} fh ] != 0} {
	ShowMessage [format [_ "Unable to open file %s."] $SaveFile];
	return ;
    }
    set cl [concat \
	[list [format "\#%s" [clock format [clock seconds]]]] \
	[list [format "\#%s" [_ Fonts]]] \
	[fontsel::SaveFontSettings] \
	[list [format "\#%s" [_ Colors]]] \
	[SaveColorSettings] \
	[list [format "\#%s" [_ Miscellaneous]]] \
	[SaveMiscellaneousSettings]];
    foreach x $cl {
	puts $fh $x;
    }
    close $fh;
}



putstd "SndBite $Version";
putstd "Copyright (C) 2005-2008 William J. Poser.";
putstd [_ "This program is free software; you can redistribute
it and/or modify it under the terms of version 3 of
the GNU General Public License as published by the
Free Software Foundation."];

if {!$SegmenterP} {
    set PauseAvailableP [PauseAvailableQ]
}
set sts [split $TimeStamp]
set ts "[lindex $sts 0] [lindex $sts 1]"
if {$SegmenterP} {
    wm title . [format "Segmenter %s \[%s\]" $SegmenterVersion $ts];
} else {
    if {$PauseAvailableP && $UsePauseP} {
	wm title . [format "SndBite %s \[%s\]   pause %s" $Version $ts $::PauseVersion];
    } else {
	wm title . [format "SndBite %s \[%s\]" $Version $ts];
    }
}
set HomeDir [GetHomeDir];
set ScriptPath [info script];
if {([string match ".*" $ScriptPath] == 1) || \
	([file dirname $ScriptPath] eq ".")} {
    set ScriptPath [file join [pwd] [string range $ScriptPath 2 end] ];
}

if {$DebugP} {
    set ManualPath [file join [file dir $ScriptPath] Manual Manual.html];
} else {
    set ManualPath [file join $NonBinPath Manual Manual.html];
}
set ManualURL [format "file://%s" $ManualPath];

SetCommandGlosses;
CreateInitProcs;
if {$ReadInitFileP} {
    InitFileSetup;
    #Look first in current directory, then in home directory.
    if { [file exists $InitFile] } {
	ReadInitFile $InitFile;
    } else {
	set cwd [pwd];
	cd;
	if {[file exists $InitFile] } {
	    ReadInitFile $InitFile;
	}
	cd $cwd;
    }
}

if {$JournalHomeP} {
    set JournalFullPath [file join $HomeDir $JournalFile];
} else {
    set JournalFullPath [file join [pwd] $JournalFile];
}
if {[catch {open $JournalFullPath "a"} JournalHandle ] != 0} {
    puts [format [_ "Unable to open journal file %s."] $JournalFullPath];
    exit 2;
}
WriteJournal [format [_ "Session started: %s\n\tby %s in %s"] \
	  [clock format [clock seconds]] [GetUser]  [pwd]];


CreateScriptProcs;
switch -exact -- $::PanelsToShow {
    2 {
	set RotateInfoStart 2;
    }
    3 {
	set RotateInfoStart 1;
    }
    4 {
	set RotateInfoStart 0;
    }
    5 {
	set RotateInfoStart -1;
    }
}


proc ZeroCrossingLeftCursor {x} {
    set X [PixelToSample $::CLUPL $x]
    if {$X < $::WindowLeftEdge} {
	ZeroCrossingPrevLeft;
    } else {
	ZeroCrossingNextLeft;
    }
}

proc ZeroCrossingRightCursor {x} {
    set X [PixelToSample $::CLUPR $x]
    if {$X < $::WindowRightEdge} {
	ZeroCrossingPrevRight;
    } else {
	ZeroCrossingNextRight;
    }
}

proc ToggleShowPauseCommandLineMenuButton {n e o} {
    if {[set ::$n]} {
	.menubar.file entryconfigure $::ShowPauseCommandLineMenuIndex -state normal
    } else {
	.menubar.file entryconfigure $::ShowPauseCommandLineMenuIndex -state disabled
    }
}

proc UserSetWindow {args} {
    set OldWLE $::WindowLeftEdge;
    set OldWRE $::WindowRightEdge;
    if {[llength $args]} {
	set wle [lindex $args 0]
	set wre [lindex $args 1]
    } else {
	set wle [.info.setwin.main.entwle get];
	set wre [.info.setwin.main.entwre get]
    }
    if {$::WindowSetSecondsP} {
	if {[string first "." $wle] < 0} {
	    ShowMessage [format [_ "%s is not in seconds."] $wle]
	    return ;
	}
	if {[string first "." $wre] < 0} {
	    ShowMessage [format [_ "%s is not in seconds."] $wre]
	    return ;
	}
	set wle [SecondsToSamples $wle]
	set wre [SecondsToSamples $wre]
    } else {
	if {[string first "." $wle] >= 0} {
	    ShowMessage [format [_ "%s not in samples."] $wle]
	    return ;
	}
	if {[string first "." $wre] >= 0} {
	    ShowMessage [format [_ "%s not in samples."] $wre]
	    return ;
	}
    }
    set ::WindowRightEdge $wre
    set ::WindowLeftEdge  $wle
    CheckWindowBounds;
    if {!$::BatchModeP} {
	ShowWavebar;
	if { ($::WindowLeftEdge <= $::NeighborhoodLeftEdge) || \
		 ($::WindowRightEdge >= $::NeighborhoodRightEdge)} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateLeftCut;
	UpdateRightCut;
	set Delta [expr $::SamplingRate * 0.001]
	if { abs($::WindowLeftEdge - $OldWLE) > $Delta} {
	    silence::UntagSilenceLeft;
	}
	if { abs($::WindowRightEdge - $OldWRE) > $Delta} {
	    silence::UntagSilenceRight;
	}
    }
    AnnounceWindowBounds;
    #AutoPlayWindow;
}


if {!$BatchModeP} {
    DetermineGraphicsSystem
    set ::TkEightFivePlusOnX11P [CheckTkEightFivePlusOnX11]
    if {$::TkEightFivePlusOnX11P} {
	set FontInfo(MainFont,size) 10
	set FontInfo(HistoryListFont,size) 10
	set FontInfo(SilenceListFont,size) 9
	set FontInfo(MenuFont,size) 10
	set FontInfo(CharacterEntryLabelFont,size) 11
	set FontInfo(CharacterEntryFont,size) 12
	set FontInfo(PanelCharacterEntryFont,size) 11
	set FontInfo(AccentedLetterFont,size) 12
	set FontInfo(BalloonHelpFont,size) 11
    }
    SetupEvents $System;
    SetupImages;
    SetCharacterEntryOptions
    fontsel::SetFontInfoDefaults;
    fontsel::CreateFonts;
    wm withdraw [fontsel::CreateFontControlPanel]
    fontsel::SetFontSelectionDefaults
    fontsel::RecordDefaults

    #Create the user interface

    option add *background \#BEBAD5 80
    option add *Menu.font MenuFont 100
    option add *selectFont*Font FontControlPanelFont 100
    option add *Label.Font MainFont 100
    option add *Menu.Font MenuFont 100
    option add *Radiobutton.Font MainFont 100
    option add *Scale.Font MainFont 100

    SetupBalloonHelp

    set m [menu .menubar -tearoff 0 -font MenuFont\
	       -bg $ColorSpecs(Menubar,Background)\
	       -fg $ColorSpecs(Menubar,Foreground)\
	      ];
    set TopIndex 0;
    incr TopIndex;
    $m add cascade -label [_ "File"]   -menu [menu $m.file];

    set FileIndex 0
    incr FileIndex;
    $m.file add command -label [_ "Load Sound File"] -command LoadSoundFile;

    incr FileIndex;
    $m.file add command -label [_ "Save Window to File"] -command SaveRegionToFile;

    incr FileIndex;
    $m.file add separator

    incr FileIndex;
    $m.file add command -label [_ "Compute Silences"] -command ComputeSilences

    incr FileIndex;
    $m.file add command -label [_ "Load Silence List"] -command silence::LoadSilenceList;

    incr FileIndex;
    $m.file add command -label [_ "Save Silence List"] -command silence::SaveDisplayedSilenceList;

    incr FileIndex;
    $m.file add separator

    if {$::SegmenterP} {
    incr FileIndex;
    $m.file add command -label [_ "Clear Segment List"] -command ClearSegmentList

    incr FileIndex;
    $m.file add command -label [_ "Load Segment List"] -command LoadSegmentList

    incr FileIndex;
    $m.file add command -label [_ "Save Segment List"] -command SaveSegmentList

    incr FileIndex;
    $m.file add command -label [_ "Write Segments"] -command WriteSegments

    incr FileIndex;
    $m.file add separator
    }
    
    incr FileIndex;
    $m.file add command -label [_ "Load Output File Name List"] -command LoadOutFileNameList;

    if {$::SegmenterP} {
	incr FileIndex;
	$m.file add command -label [_ "Load Prompter Log"] -command LoadPrompterLog
    }

    incr FileIndex;
    $m.file add command -label [_ "Execute Script File"] -command ExecuteScriptFile;

    incr FileIndex;
    $m.file add separator

    incr FileIndex;
    $m.file add command -label [_ "Show Pause Command Line"] -command ShowCommandLine;
    set ::ShowPauseCommandLineMenuIndex $FileIndex

    incr FileIndex;
    $m.file add separator

    incr FileIndex;
    $m.file add command -label [_ "Quit"]  -command ShutDown

    incr TopIndex;
    set CharacterEntryIndex 0;
    $m add cascade -label [_ "Character Entry"] -menu [menu $m.charentry];

    incr CharacterEntryIndex;
    set CustomCharacterChartPanelIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Load Custom Character Chart Definition for Panel"] \
	-command ReadCustomCharacterChartPanel;

    incr CharacterEntryIndex;
    set CustomCharacterChartIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Load Custom Character Chart Definition for Popup"] \
	-command ReadCustomCharacterChartPopup;

    incr CharacterEntryIndex;
    set ToggleIPAAIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Display Accented Letter Chart"] -command ToggleIPAA;

    incr CharacterEntryIndex;
    set ToggleIPACIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Display IPA Consonant Chart"] -command ToggleIPAC;

    incr CharacterEntryIndex;
    set ToggleIPADIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Display IPA Diacritic Chart"] -command ToggleIPAD;

    incr CharacterEntryIndex;
    set ToggleIPAVIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Display IPA Vowel Chart"] -command ToggleIPAV;

    incr CharacterEntryIndex;
    set ToggleCharEntryByCodeIndex $CharacterEntryIndex;
    $m.charentry add command -label [_ "Display Widget for Entering Characters by Unicode Code"] -command ToggleCharEntryByCode;

    set ::LastFixedCEMIndex $CharacterEntryIndex;

    if {!$AquaP} {
	incr TopIndex;
	$m add command -label [_ "Rotate Clockwise"]  -command {RotateInfo left}

	incr TopIndex;
	$m add command -label [_ "Rotate Counterclockwise"]  -command {RotateInfo right}
    }

    incr TopIndex;
    $m add cascade -label [_ "Configure"]  -menu [menu $m.configure];

    $m.configure add cascade -label [_ "Main Components"]  -menu [menu $m.configure.major]

    $m.configure.major add checkbutton -label [_ "Closeups"]  -command ToggleCloseups \
	-onvalue 1 -offvalue 0 -variable MainToggleA
    set MainToggleA $DisplayCloseupsP

    $m.configure.major add checkbutton -label [_ "Closeup Region Markers"]  \
	-command ToggleDrawCutMarks \
	-onvalue 1 -offvalue 0 -variable DrawCutMarksToggle
    set DrawCutMarksToggle $DrawCutMarksP

    $m.configure.major add checkbutton -label [_ "\u0394 Bar"]  -command ToggleDeltaBar \
	-onvalue 1 -offvalue 0 -variable MainToggleB
    set MainToggleB $DisplayDeltaBarP

    $m.configure.major add checkbutton -label [_ "Play Bar"]  -command TogglePlayBar \
	-onvalue 1 -offvalue 0 -variable MainToggleC
    set MainToggleC $DisplayPlayBarP

    if {$::SegmenterP} {
    $m.configure.major add checkbutton -label [_ "Segment Bar"]  -command ToggleSegmentBar \
	-onvalue 1 -offvalue 0 -variable MainToggleG
    set MainToggleG $DisplaySegmentBarP
    }

    $m.configure.major add checkbutton -label [_ "Silence Bar"]  -command ToggleSilenceBar \
	-onvalue 1 -offvalue 0 -variable MainToggleD
    set MainToggleD $DisplaySilenceBarP

    $m.configure.major add checkbutton -label [_ "Write Bar"]  -command ToggleWriteBar \
	-onvalue 1 -offvalue 0 -variable MainToggleH
    set MainToggleH $DisplayWriteBarP

    $m.configure.major add checkbutton -label [_ "Scrollbars"]  -command ToggleScrollbars \
	-onvalue 1 -offvalue 0 -variable MainToggleE
    set MainToggleE $UseScrollbarsP

    $m.configure.major add checkbutton -label [_ "Zero-Crossing Buttons"]  -command ToggleZeroCrossingButtons \
	-onvalue 1 -offvalue 0 -variable MainToggleF
    set MainToggleF $DisplayZeroCrossingButtonsP

    set PanelConfigIndex 0;
    $m.configure add cascade -label [_ "Panel"]  -menu [menu $m.configure.panel]


    incr PanelConfigIndex;
    $m.configure.panel add cascade -label [_ "Number of Components To Show At Once"] \
	-menu [menu $m.configure.panel.num]
    $m.configure.panel.num add radiobutton -variable PanelsToShow -command {UnlockedRotateInfo right} \
	-value 2 -label 2
    $m.configure.panel.num add radiobutton -variable PanelsToShow -command {UnlockedRotateInfo right} \
	-value 3 -label 3
    $m.configure.panel.num add radiobutton -variable PanelsToShow -command {UnlockedRotateInfo right} \
	-value 4 -label 4
    $m.configure.panel.num add radiobutton -variable PanelsToShow -command {UnlockedRotateInfo right} \
	-value 5 -label 5

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Closeup Resolution"] \
	-command {ToggleInfoItem .info.closeup} -onvalue 1 -offvalue 0 -variable PanelToggleA
    set PanelToggleA 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Neighborhood Ratio to Window"] \
	-command {ToggleInfoItem .info.nbrhd}    -onvalue 1 -offvalue 0 -variable PanelToggleB
    set PanelToggleB 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Notes"] \
	-command {ToggleInfoItem .info.notes} -onvalue 1 -offvalue 0 -variable PanelToggleC
    set PanelToggleC 1;

    incr PanelConfigIndex;
    set CharacterEntryIndex $PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Character Entry"] \
	-command {ToggleInfoItem .info.charentry} -onvalue 1 -offvalue 0 -variable PanelToggleL \
	-state disabled
    set PanelToggleL 0;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Pause Parameters"] \
	-command {ToggleInfoItem .info.pause} -onvalue 1 -offvalue 0 -variable PanelToggleD
    set PanelToggleD 1;

    if {$::SegmenterP} {
    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Prompter List"] \
	-command {ToggleInfoItem .info.prli} -onvalue 1 -offvalue 0 -variable PanelToggleM
    set PanelToggleM 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Segment File Info"] \
	-command {ToggleInfoItem .info.sfname} -onvalue 1 -offvalue 0 -variable PanelToggleE
    set PanelToggleE 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Segment List"] \
	-command {ToggleInfoItem .info.segli} -onvalue 1 -offvalue 0 -variable PanelToggleN
    set PanelToggleN 1;
    }

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Set Window"] \
	-command {ToggleInfoItem .info.setwin} -onvalue 1 -offvalue 0 -variable PanelToggleF
    set PanelToggleF 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Silence Info"] \
	-command {ToggleInfoItem .info.silence} -onvalue 1 -offvalue 0 -variable PanelToggleG
    set PanelToggleG 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Silence List"] \
	-command {ToggleInfoItem .info.sili} -onvalue 1 -offvalue 0 -variable PanelToggleH
    set PanelToggleH 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Sound File Info"] \
	-command {ToggleInfoItem .info.sfile} -onvalue 1 -offvalue 0 -variable PanelToggleI
    set PanelToggleI 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Wavebar Pixels Per Second"] \
	-command {ToggleInfoItem .info.wavebar} -onvalue 1 -offvalue 0 -variable PanelToggleJ
    set PanelToggleJ 1;

    incr PanelConfigIndex;
    $m.configure.panel add checkbutton -label [_ "Window Motion Increment"] \
	-command {ToggleInfoItem .info.wdelta} -onvalue 1 -offvalue 0 -variable PanelToggleK
    set PanelToggleK 1;

    $m.configure add cascade -label [_ "Character Entry"] -menu [menu $m.configure.charentry]

    $m.configure.charentry add command -label [_ "Remove Consonant Chart Column Labels"] \
	-command ipaentry::UnpackConsonantColumnLabels;

    $m.configure.charentry add command -label [_ "Remove Consonant Chart Row Labels"] \
	-command ipaentry::UnpackConsonantRowLabels;

    $m.configure.charentry add command -label [_ "Remove Vowel Chart Column Labels"] \
	-command ipaentry::UnpackVowelColumnLabels;

    $m.configure.charentry add command -label [_ "Remove Vowel Chart Row Labels"] \
	-command ipaentry::UnpackVowelRowLabels;

    $m.configure add cascade -label [_ "Miscellaneous"] -menu [menu $m.configure.misc]
    

    set MiscEntry 0
    $m.configure.misc add checkbutton -label [_ "Autoload Output File Name List"] \
	-onvalue 1 -offvalue 0 -variable AutoLoadOutFileNamesP
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Autoplay"]  -command ToggleAutoPlay \
	-onvalue 1 -offvalue 0 -variable AutoPlayP
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Autoplay Writes"] \
	-onvalue 1 -offvalue 0 -variable AutoPlayWritesP
    set AutoPlayWritesP $AutoPlayWritesP
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Automatically Compute Silences"] \
	-onvalue 1 -offvalue 0 -variable AutoComputeSilencesP
    set AutoComputeSilencesP $AutoComputeSilencesP
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Autoscale"]  -onvalue 1 -offvalue 0 -variable AutoScaleSoundP
    set AutoScaleSoundP $AutoScaleSoundPDefault;
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Display History List"] \
	-onvalue 1 -offvalue 0 -variable DisplayHistoryPopupP 
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Left Edge Wavebar Immediate Update"] \
	-onvalue 1 -offvalue 0 -variable SetLeftEdgeOverviewImmediateP
    set SetLeftEdgeOverviewImmediateP $SetLeftEdgeOverviewImmediateP
    incr MiscEntry

    $m.configure.misc add checkbutton -label [_ "Show Amplitude at Pointer"] \
	-onvalue 1 -offvalue 0 -variable AmplitudeModeP -command {ToggleAmplitudeMode $AmplitudeModeP}
    incr MiscEntry

    if {$PauseAvailableP} {
	$m.configure.misc add checkbutton -label [_ "Use Pause"] \
	    -onvalue 1 -offvalue 0 -variable UsePauseP;
	set ::UsePauseP $::UsePauseP;
	incr MiscEntry
    }

    $m.configure.misc add checkbutton -label [_ "Use Output File Name List"] \
	-onvalue 1 -offvalue 0 -variable UseOutFileNameListP
	set ::UseOutFileNameListP $::UseOutFileNameListP
    incr MiscEntry

    $m.configure add command -label [_ "Select Font"] -command fontsel::CreateFontControlPanel;

    $m.configure add command -label [_ "Save Configuration"] -command {SaveState};

    $m.configure add checkbutton -label [_ "Defer Writes"] -onvalue 1 -offvalue 0 \
	-variable DeferWritesP

    $m.configure add checkbutton -label [_ "Balloon Help"]  -command ControlBalloonHelp \
	-onvalue 1 -offvalue 0 -variable BalloonHelpToggle
    set BalloonHelpToggle $BalloonHelpP
    ControlBalloonHelp;

    #Help Menu
    incr TopIndex;
    set HelpIndex 0;
    $m add cascade -label [_ "Help"]   -menu [menu $m.help];

    incr HelpIndex;
    $m.help add command -label [_ "About"] -command About;
    incr HelpIndex;
    $m.help add command -label [_ "Bug Reports"] -command BugReports;
    incr HelpIndex;
    $m.help add command -label [_ "Color Names"] -command validcolor::PopupColorNameList;
    incr HelpIndex;
    $m.help add command -label [_ "Command Line Options"] -command CommandLineOptions;
    incr HelpIndex;
    $m.help add command -label [_ "Home Page"] -command {ShowWebPage http://www.billposer.org/Software/sndbite.html}
    incr HelpIndex;
    $m.help add command -label [_ "Illustrated Web Manual"] -command WebManual;
    incr HelpIndex;
    $m.help add cascade -label [_ "Initialization File"] -menu [menu $m.help.ifc];
    $m.help.ifc add command -label [_ "Color Names"] -command PopupColorNameList;
    $m.help.ifc add command -label [_ "Commands for which Shortcuts may be Defined "] \
	-command PopupShortcutCommands
    $m.help.ifc add command -label [_ "SndBite Commands - Popup"] -command PopupInitCommandList;
    $m.help.ifc add command -label [_ "SndBite Commands - Save to File"] -command SaveInitCommands;
    $m.help.ifc add command -label [_ "Tcl Commands - Popup"] -command PopupInitTclCommandList;
    $m.help.ifc add command -label [_ "Tcl Commands - Save to File"] -command SaveInitTclCommands;
    incr HelpIndex;
    $m.help add command -label [_ "Key Bindings"] -command DescribeKeyBindings;
    incr HelpIndex;
    $m.help add command -label [_ "License"] -command ShowGPL;
    incr HelpIndex;
    $m.help add cascade -label [_ "Script File Commands"]  -menu [menu $m.help.sfc];
    $m.help.sfc add command -label [_ "Popup List"] -command PopupScriptCommandList;
    $m.help.sfc add command -label [_ "Save to File"] -command SaveScriptCommands;
    . configure -menu .menubar

    text $::MSG -bg $ColorSpecs(MessageRegion,Background) -fg $ColorSpecs(MessageRegion,Foreground) \
	-relief ridge -border 2 \
	-height 1 -font MainFont -state disabled -exportselection 1

    frame .play -bg $ColorSpecs(Control,Background)
    if {$AquaP} {
	button .play.b1 -text [_ "Stop"] -command StopPlay \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b2 -text [_ "File"] -command PlayFile \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b3 -text [_ "Wavebar"]  -command PlayWavebar \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b4 -text [_ "Neighborhood"]  -command PlayNeighborhood \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b5 -text [_ "Window"] -command PlayWindow \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
    } else {
	button .play.b1 -text [_ "Stop"] -command StopPlay \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b2 -text [_ "File"] -command PlayFile \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b3 -text [_ "Wavebar"]  -command PlayWavebar \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	#Play\nNeighborhood
	button .play.b4 -text [_ "Region"]  -command PlayNeighborhood \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
	button .play.b5 -text [_ "Window"] -command PlayWindow \
	    -bg $ColorSpecs(PlayButton,Background) \
	    -fg $ColorSpecs(PlayButton,Foreground) \
	    -highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	    -highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	    -activebackground $ColorSpecs(PlayButton,ActiveBackground) \
	    -activeforeground $ColorSpecs(PlayButton,ActiveForeground) \
	    -font MainFont
    }
    scale  .play.vol -label "" -orient h -digit 1 -from 0 -to 100 -tickinterval 50 \
	-variable Volume -command SetPlaybackVolume -showvalue 1 \
	-troughcolor $::ColorSpecs(Volume,Trough) \
	-bg $ColorSpecs(PlayButton,Background) \
	-fg $ColorSpecs(PlayButton,Foreground) \
	-highlightbackground $ColorSpecs(PlayButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PlayButton,Highlight) \
	-activebackground $ColorSpecs(PlayButton,ActiveBackground) -length 65  \
	-font MainFont

    bind .play.vol <<B3>> "ScaleMoveBigIncrement .play.vol 10 %x %y"

    #scale  .play.sca -label "" -orient h -digit 1 -from 1 -to 10 -tickinterval 2 \
	-length 75 -variable AudioScaleFactor -command SetPlaybackScale -showvalue 0 -resolution 0.1
    #set AudioScaleFactor 1.0

    proc SetPlaybackVolume {v} {
	audio play_gain $v
    }

    set VolumeIncrement 1
    proc IncreaseVolume {} {
	set CurrentValue [audio play_gain]
	set NewValue [expr $CurrentValue + $::VolumeIncrement]
	if {$NewValue > 100} {
	    set NewValue 100
	}
	audio play_gain $NewValue
	set ::Volume $NewValue
    }

    proc DecreaseVolume {} {
	set CurrentValue [audio play_gain]
	set NewValue [expr $CurrentValue - $::VolumeIncrement]
	if {$NewValue < 0} {
	    set NewValue 0
	}
	audio play_gain $NewValue
	set ::Volume $NewValue
    }

    #proc SetPlaybackScale {s} {
    #    audio scaling $s;
    #}

    set msg [_ "Stop playing the sound that is currently being played."]
    balloonhelp_for .play.b1 $msg
    set msg [_ "Play the entire file."]
    balloonhelp_for .play.b2 $msg
    set msg [_ "Play the region displayed in the Wavebar. If the file is short
enough this is the same as playing the entire file, but if the
file is longer, only the region currently displayed will be played."]
    balloonhelp_for .play.b3 $msg
    set msg [_ "Play the region displayed in the Neighborhood window."]
    balloonhelp_for .play.b4 $msg
    set msg [_ "Play the contents of the current window."]
    balloonhelp_for .play.b5 $msg
    set msg [_ "Set the playback volume. The unit is percent of maximum."]
    balloonhelp_for .play.vol $msg

    pack .play.b1  -side left -expand 1 -fill both
    pack .play.b2  -side left -expand 1 -fill both
    pack .play.vol -side left -expand 1 -fill both
    pack .play.b3  -side left -expand 1 -fill both
    pack .play.b4  -side left -expand 1 -fill both
    pack .play.b5  -side left -expand 1 -fill both
    #pack .play.sca -side left -expand 1 -fill both

    frame .cntls -bg $ColorSpecs(Control,Background);
    button .cntls.b1 -text [_ "Write Window"] -command {WriteWindow 1} \
	-bg $ColorSpecs(WriteButton,Background) \
	-fg $ColorSpecs(WriteButton,Foreground) \
	-highlightbackground $ColorSpecs(WriteButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(WriteButton,Highlight) \
	-activebackground $ColorSpecs(WriteButton,ActiveBackground) \
	-activeforeground $ColorSpecs(WriteButton,ActiveForeground) \
	-font MainFont
    label .cntls.b2 -text [_ "Overwrite Previous File"]  -relief raised \
	-bg $ColorSpecs(WritePreviousButton,Background) \
	-fg $ColorSpecs(WritePreviousButton,Foreground) \
	-highlightbackground $ColorSpecs(WritePreviousButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(WritePreviousButton,Highlight) \
	-activebackground $ColorSpecs(WritePreviousButton,ActiveBackground) \
	-activeforeground $ColorSpecs(WritePreviousButton,ActiveForeground) \
	-font MainFont

    pack   .cntls.b1  -side right -expand 1 -fill both -padx 4

    if {$::SegmenterP} {
	button   .cntls.nex -command {NextStamp 1}  -text [_ "Next Stamp"]
	button   .cntls.pre -command {NextStamp -1} -text [_ "Previous Stamp"]
	pack   .cntls.nex  -side right -expand 1 -fill both -padx 0
	pack   .cntls.pre  -side right -expand 1 -fill both -padx 0
    } else {
	label   .cntls.sep -bg $ColorSpecs(Control,Background) -relief ridge -border 2 -image $::GrassImage
	pack   .cntls.sep  -side right -expand 0 -fill y -padx 0
    }
    pack   .cntls.b2  -side left  -expand 1 -fill both -padx 4

    bind .cntls.b2 <Double-Button-1>  OverWritePreviousFile;
    set msg [_ "Write the current window to a file.
The name of the file will be generated automatically
unless you specify otherwise. To control the filename,
use the 'Next Segment File Name' panel on the lazy susan."]
    balloonhelp_for .cntls.b1 $msg
    set msg [_ "Double click here to overwrite the last file
written with the contents of the current window."]
    balloonhelp_for .cntls.b2 $msg
    set msgs [list [_ "This space for rent"] [_ "Your command could be here."] \
		  [_ "Get back to work."]]
    balloonhelp_for .cntls \
	[lindex $msgs [expr int([TrimLeadingZeroes [clock format [clock seconds] -format %S]]) % 3]]
    frame .delmov -bg $ColorSpecs(Control,Background)
    button .delmov.b1 -text [_ "\[ \u21D0  \u0394"] -command LeftEdgeBackwardDelta \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    button .delmov.b2 -text [_ "\[ \u21D2 \u0394"] -command LeftEdgeForwardDelta  \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    button .delmov.b3 -text [_ "\[\] \u21D0 \u0394"] -command WindowBackwardDelta \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    button .delmov.b4 -text [_ "\[\] \u21D2 \u0394"] -command WindowForwardDelta   \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    button .delmov.b5 -text [_ "\] \u21D0 \u0394"] -command RightEdgeBackwardDelta \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    button .delmov.b6 -text [_ "\] \u21D2 \u0394"] -command RightEdgeForwardDelta   \
	-bg $ColorSpecs(DeltaButton,Background) \
	-fg $ColorSpecs(DeltaButton,Foreground) \
	-highlightbackground $ColorSpecs(DeltaButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(DeltaButton,Highlight) \
	-activebackground $ColorSpecs(DeltaButton,ActiveBackground) \
	-activeforeground $ColorSpecs(DeltaButton,ActiveForeground) \
	-font MainFont
    frame  .delmov.sep1 -width 8
    frame  .delmov.sep2 -width 8
    set xp 2
    pack .delmov.b1   -side left -expand 1 -fill both -padx $xp
    pack .delmov.b2   -side left -expand 1 -fill both -padx $xp
    pack .delmov.b3   -side left -expand 1 -fill both -padx $xp
    pack .delmov.b4   -side left -expand 1 -fill both -padx $xp
    pack .delmov.b5   -side left -expand 1 -fill both -padx $xp
    pack .delmov.b6   -side left -expand 1 -fill both -padx $xp

    set msg [_ "Move the left edge of the window backward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]
    balloonhelp_for .delmov.b1 $msg
    set msg [_ "Move the left edge of the window forward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]
    balloonhelp_for .delmov.b2 $msg
    set msg [_ "Move both edges of the window backward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]
    balloonhelp_for .delmov.b3 $msg
    set msg [_ "Move both edges of the window forward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]
    balloonhelp_for .delmov.b4 $msg
    set msg [_ "Move the right edge of the window backward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]
    balloonhelp_for .delmov.b5 $msg
    set msg [_ "Move the right edge of the window forward by a fixed increment.
The value of the increment can be found and changed on the
'Window Motion Increment' panel of the lazy susan."]

    balloonhelp_for .delmov.b6 $msg

#Segment controls
    frame .segmov -bg $ColorSpecs(Control,Background)
    button .segmov.b1 -text [_ "Delete\nSegment"] -command DeleteCurrentSegment \
	-bg $ColorSpecs(SegmentButton,Background) \
	-fg $ColorSpecs(SegmentButton,Foreground) \
	-highlightbackground $ColorSpecs(SegmentButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SegmentButton,Highlight) \
	-activebackground $ColorSpecs(SegmentButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SegmentButton,ActiveForeground) \
	-font MainFont
    button .segmov.b2 -text [_ "Previous Segment"] -command {GotoNextSegment -1} \
	-bg $ColorSpecs(SegmentButton,Background) \
	-fg $ColorSpecs(SegmentButton,Foreground) \
	-highlightbackground $ColorSpecs(SegmentButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SegmentButton,Highlight) \
	-activebackground $ColorSpecs(SegmentButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SegmentButton,ActiveForeground) \
	-font MainFont
    button .segmov.b3 -text [_ "Next Segment"] -command {GotoNextSegment 1} \
	-bg $ColorSpecs(SegmentButton,Background) \
	-fg $ColorSpecs(SegmentButton,Foreground) \
	-highlightbackground $ColorSpecs(SegmentButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SegmentButton,Highlight) \
	-activebackground $ColorSpecs(SegmentButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SegmentButton,ActiveForeground) \
	-font MainFont
    button .segmov.b4 -text [_ "Replace\nSegment"] -command ReplaceCurrentSegment   \
	-bg $ColorSpecs(SegmentButton,Background) \
	-fg $ColorSpecs(SegmentButton,Foreground) \
	-highlightbackground $ColorSpecs(SegmentButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SegmentButton,Highlight) \
	-activebackground $ColorSpecs(SegmentButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SegmentButton,ActiveForeground) \
	-font MainFont
    frame  .segmov.sep1 -width 8
    frame  .segmov.sep2 -width 8
    set xp 2
    pack .segmov.b1   -side left -expand 1 -fill both -padx $xp
    pack .segmov.b2   -side left -expand 1 -fill both -padx $xp
    pack .segmov.b3   -side left -expand 1 -fill both -padx $xp
    pack .segmov.b4   -side left -expand 1 -fill both -padx $xp

    set msg [_ "Delete the current entry from the segment list."]
    balloonhelp_for .segmov.b1 $msg
    set msg [_ "Move the window to the previous entry on the segment list"]
    balloonhelp_for .segmov.b2 $msg
    set msg [_ "Move the window to the next entry on the segment list"]
    balloonhelp_for .segmov.b3 $msg
    set msg [_ "Replace the current entry in the segment list with the current window."]
    balloonhelp_for .segmov.b4 $msg

    set silsim \u7121\u8A00
    frame .silmov -bg $ColorSpecs(Control,Background)
    button .silmov.b1 -text [_ "\[ \u21D0 $silsim"] -command LeftEdgeBackwardSilence \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    button .silmov.b2 -text [_ "\[ \u21D2 $silsim"] -command LeftEdgeForwardSilence  \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    button .silmov.b3 -text [_ "\[\] \u21D0 $silsim"] -command WindowBackwardSilence \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    button .silmov.b4 -text [_ "\[\] \u21D2 $silsim"] -command WindowForwardSilence  \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    button .silmov.b5 -text [_ "\] \u21D0 $silsim"] -command RightEdgeBackwardSilence \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    button .silmov.b6 -text [_ "\] \u21D2 $silsim"] -command RightEdgeForwardSilence \
	-bg $ColorSpecs(SilenceButton,Background) \
	-fg $ColorSpecs(SilenceButton,Foreground) \
	-highlightbackground $ColorSpecs(SilenceButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(SilenceButton,Highlight) \
	-activebackground $ColorSpecs(SilenceButton,ActiveBackground) \
	-activeforeground $ColorSpecs(SilenceButton,ActiveForeground) \
	-font MainFont
    frame  .silmov.sep1 -width 8
    frame  .silmov.sep2 -width 8
    set xp 2
    pack .silmov.b1   -side left -expand 1 -fill both -padx $xp
    pack .silmov.b2   -side left -expand 1 -fill both -padx $xp
    #pack .silmov.sep1 -side left -expand 1 -fill both -padx $xp
    pack .silmov.b3   -side left -expand 1 -fill both -padx $xp
    pack .silmov.b4   -side left -expand 1 -fill both -padx $xp
    #pack .silmov.sep2 -side left -expand 1 -fill both -padx $xp
    pack .silmov.b5   -side left -expand 1 -fill both -padx $xp
    pack .silmov.b6   -side left -expand 1 -fill both -padx $xp

    set msg [_ "Move the left edge of the window to the
right edge of the preceding silent interval."]
    balloonhelp_for .silmov.b1 $msg
    set msg [_ "Move the left edge of the window to the
right edge of the following silent interval."]
    balloonhelp_for .silmov.b2 $msg
    set msg [_ "Move the window so that it straddles the
preceding non-silent interval."]
    balloonhelp_for .silmov.b3 $msg
    set msg [_ "Move the window so that it straddles the
following non-silent interval."]
    balloonhelp_for .silmov.b4 $msg
    set msg [_ "Move the right edge of the window to the
left edge of the preceding silent interval."]
    balloonhelp_for .silmov.b5 $msg
    set msg [_ "Move the right edge of the window to the
left edge of the following silent interval."]
    balloonhelp_for .silmov.b6 $msg


    canvas .ov -width $MainWindowWidth -height $WavebarHeight \
	-xscrollcommand {.ovsb set} -border 2 -bg $ColorSpecs(Wavebar,Background) \
	-relief raised -border 2
    scrollbar .ovsb -command {.ov xview} -orient horizontal \
	-troughcolor $::ColorSpecs(WavebarScrollbar,Trough);
    bind .ovsb <<B3>> "ScrollbarMoveBigIncrement .ovsb .20 %x %y"
    #set ::PackCommand(.ovsb) [list pack .ovsb -before .ovccsep top -expand 1 -fill x]
    balloonhelp_for .ov "\
This window displays the entire waveform. If the file is
short enough, the entire waveform will be shown at once.
Otherwise, the window must be scrolled. The current window
is shown in red. You may change its left edge by
left-clicking on the waveform, its right edge by
right-clicking on the waveform."

    #option add .info*.background $ColorSpecs(LazySusan,Background) 100
    #option add *info*title.background coral 100;

    frame .info -bg $ColorSpecs(LazySusan,Background) -relief ridge -border 2

    frame   .info.notes  -bg $ColorSpecs(LazySusan,Background)
    label   .info.notes.title -text [_ "Notes"] \
	-bg $::ColorSpecs(PanelNotePadTitle,Background) \
	-fg $::ColorSpecs(PanelNotePadTitle,Foreground) 
    text    .info.notes.txt -font UserTechnicalTextFont -height 2 -width 26
    frame  .info.notes.cntl -bg $ColorSpecs(LazySusan,Background)
    button .info.notes.cntl.b1 -text [_ "Clear"] -command {ClearNotes} \
	-bg $ColorSpecs(PanelNotePadButton,Background) \
	-fg $ColorSpecs(PanelNotePadButton,Foreground) \
	-highlightbackground $ColorSpecs(PanelNotePadButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PanelNotePadButton,Highlight) \
	-activebackground $ColorSpecs(PanelNotePadButton,ActiveBackground) \
	-activeforeground $ColorSpecs(PanelNotePadButton,ActiveForeground) \
	-font MainFont
    button .info.notes.cntl.b2 -text [_ "Save"] -command {EnterNote} \
	-bg $ColorSpecs(PanelNotePadButton,Background) \
	-fg $ColorSpecs(PanelNotePadButton,Foreground) \
	-highlightbackground $ColorSpecs(PanelNotePadButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PanelNotePadButton,Highlight) \
	-activebackground $ColorSpecs(PanelNotePadButton,ActiveBackground) \
	-activeforeground $ColorSpecs(PanelNotePadButton,ActiveForeground) \
	-font MainFont

    pack   .info.notes.cntl.b1 -side left  -expand 1 -fill none -padx 12 -pady 4
    pack   .info.notes.cntl.b2 -side right -expand 1 -fill none -padx 12 -pady 4
    pack  .info.notes.title -side top -expand 1 -fill both
    pack  .info.notes.txt   -side top -expand 1 -fill both -pady 3
    pack  .info.notes.cntl  -side top -expand 1 -fill both

    set InsertionTarget .info.notes.txt
    set CharByCodeInsertionTarget .info.notes.txt
    set msg "Enter a note here to be added to the journal.
Press  the Save button to insert the note into the journal."
    balloonhelp_for .info.notes $msg
    balloonhelp_for .info.notes.title $msg
    balloonhelp_for .info.notes.txt   $msg
    balloonhelp_for .info.notes.cntl   $msg
    balloonhelp_for .info.notes.cntl.b1   $msg
    balloonhelp_for .info.notes.cntl.b2   $msg
    bind .info.notes.txt <Control-v> InsertSelection
    bind .info.notes.txt <FocusIn> {SetInsertionTargets .info.notes.txt}

    proc InsertSelection {} {
	if {[catch {set sel [selection get -selection CLIPBOARD -type UTF8_STRING]}]} {
	    ShowMessage [_ "The clipboard is empty."];
	    return;
	} else {
	    $::InsertionTarget insert insert $sel;
	}
    }

    proc EnterNote {} {
	WriteJournal [.info.notes.txt get 1.0 end]
	.info.notes.txt delete 1.0 end
    }

    proc ClearNotes {} {
	.info.notes.txt delete 1.0 end
    }


    frame  .info.wavebar -bg $ColorSpecs(PanelWavebarResolution,Background)
    label  .info.wavebar.title -text [_ "Wavebar"] -anchor n \
	-bg $::ColorSpecs(PanelWavebarResolutionTitle,Background) \
	-fg $::ColorSpecs(PanelWavebarResolutionTitle,Foreground)
    scale  .info.wavebar.scale -label [_ "Pixels Per Second"] -orient h \
	-digit 1 -from 25 -to 200 -variable WavebarPixelsPerSecond -tickinterval 50 \
	-length 150 -command ShowWavebar \
	-bg $::ColorSpecs(PanelWavebarResolution,Background) \
	-fg $::ColorSpecs(PanelWavebarResolution,Foreground) \
	-activebackground $::ColorSpecs(PanelWavebarResolution,ActiveBackground) \
	-highlightcolor $::ColorSpecs(PanelWavebarResolution,Highlight) \
	-highlightbackground $::ColorSpecs(PanelWavebarResolution,HighlightBackground) \
	-troughcolor $::ColorSpecs(PanelWavebarResolution,Trough) -border 2 -relief flat
    #frame  .info.wavebar.sep -bg $::ColorSpecs(PanelWavebarResolution,Background)
    pack   .info.wavebar.title -side top -expand 0 -fill x    -pady 0
    #pack   .info.wavebar.sep   -side top -expand 1 -fill both -pady 2
    pack   .info.wavebar.scale -side top -expand 1 -fill none -pady 5 -ipadx 6 -ipady 6
    bind .info.wavebar.scale <<B3>> {ScaleMoveBigIncrement .info.wavebar.scale 20 %x %y}
    balloonhelp_for .info.wavebar "Use this slider to control the resolution of the wavebar.\n\
			       Larger values show more detail but let you see less of the\n\
                               waveform at once."

    frame  .info.closeup  -bg $ColorSpecs(PanelCloseupResolutionMain,Background)
    label  .info.closeup.title -text [_ "Closeup Resolution"] -anchor n \
	-bg $::ColorSpecs(PanelCloseupResolutionTitle,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionTitle,Foreground) 
    frame  .info.closeup.brf -bg $ColorSpecs(LazySusan,Background) \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background)
    radiobutton .info.closeup.brf.rdb1 -variable CloseupSamplesPerPixel -value -1 \
	-text [_ "\u00BD"] -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb2 -variable CloseupSamplesPerPixel -value 1 \
	-text 1 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb3 -variable CloseupSamplesPerPixel -value 2 \
	-text 2 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb4 -variable CloseupSamplesPerPixel -value 3 \
	-text 3 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb5 -variable CloseupSamplesPerPixel -value 4 \
	-text 4 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb6 -variable CloseupSamplesPerPixel -value 5 \
	-text 5 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb7 -variable CloseupSamplesPerPixel -value 10 \
	-text 10 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb8 -variable CloseupSamplesPerPixel -value 15 \
	-text 15 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdb9 -variable CloseupSamplesPerPixel -value 20 \
	-text 20 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)
    radiobutton .info.closeup.brf.rdbA -variable CloseupSamplesPerPixel -value 25 \
	-text 25 -anchor w -justify l \
	-bg $::ColorSpecs(PanelCloseupResolutionMain,Background) \
	-fg $::ColorSpecs(PanelCloseupResolutionMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelCloseupResolutionMain,Selected)

    set xp 8
    grid .info.closeup.brf.rdb1 -row 0 -column 0 -sticky we -padx $xp
    grid .info.closeup.brf.rdb2 -row 1 -column 0 -sticky we -padx $xp
    grid .info.closeup.brf.rdb3 -row 2 -column 0 -sticky we -padx $xp
    grid .info.closeup.brf.rdb4 -row 3 -column 0 -sticky we -padx $xp
    grid .info.closeup.brf.rdb5 -row 4 -column 0 -sticky we -padx $xp
    grid .info.closeup.brf.rdb6 -row 0 -column 1 -sticky we -padx $xp
    grid .info.closeup.brf.rdb7 -row 1 -column 1 -sticky we -padx $xp
    grid .info.closeup.brf.rdb8 -row 2 -column 1 -sticky we -padx $xp
    grid .info.closeup.brf.rdb9 -row 3 -column 1 -sticky we -padx $xp
    grid .info.closeup.brf.rdbA -row 4 -column 1 -sticky we -padx $xp

    pack   .info.closeup.title -side top -expand 1 -fill both
    pack   .info.closeup.brf -side top -expand 1 -fill both -pady 2

    proc SetCloseupPixelsPerSample {n e o} {
	if {$::CloseupSamplesPerPixel > 0} {
	    set ::WaveformInfo(Closeup,PixelsPerSample) [expr 1.0 / $::CloseupSamplesPerPixel]  
	} else {
	    set ::WaveformInfo(Closeup,PixelsPerSample) 2.0;   
	}
	if {$::SoundSamples < 1} {return}
	SetNeighborhood;
	ShowNeighborhood;
	UpdateLeftCut;
	UpdateRightCut;
    }

    trace add variable CloseupSamplesPerPixel write SetCloseupPixelsPerSample 

    set CloseupSamplesPerPixel $CloseupSamplesPerPixel;

    balloonhelp_for .info.closeup "\
These buttons control the resolution of the two closeup\n\
windows. The numbers are in units of samples per pixel.\n\
A larger value means that you see a larger neighborhood\n\
of the window edge with less detail. The default is 0.5\n\
samples per pixel, that is, two pixels per sample."

    frame  .info.nbrhd  -bg $ColorSpecs(PanelNeighborhoodRatioMain,Background)
    label  .info.nbrhd.title -text [_ "Neighborhood/Window"] -anchor n \
	-bg $::ColorSpecs(PanelNeighborhoodRatioTitle,Background) \
	-fg $::ColorSpecs(PanelNeighborhoodRatioTitle,Foreground) 
    frame  .info.nbrhd.brf  -bg $ColorSpecs(LazySusan,Background) \
	-bg $::ColorSpecs(PanelNeighborhoodRatioMain,Background)
    radiobutton .info.nbrhd.brf.rdb1 -variable NeighborhoodWindowRatio -value 2 -text 2 \
	-text 2 -justify l \
	-bg $::ColorSpecs(PanelNeighborhoodRatioMain,Background) \
	-fg $::ColorSpecs(PanelNeighborhoodRatioMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelNeighborhoodRatioMain,Selected)
    radiobutton .info.nbrhd.brf.rdb2 -variable NeighborhoodWindowRatio -value 3 -text 3 \
	-text 3 -justify l \
	-bg $::ColorSpecs(PanelNeighborhoodRatioMain,Background) \
	-fg $::ColorSpecs(PanelNeighborhoodRatioMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelNeighborhoodRatioMain,Selected)
    radiobutton .info.nbrhd.brf.rdb3 -variable NeighborhoodWindowRatio -value 4 -text 4 \
	-text 4 -justify l \
	-bg $::ColorSpecs(PanelNeighborhoodRatioMain,Background) \
	-fg $::ColorSpecs(PanelNeighborhoodRatioMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelNeighborhoodRatioMain,Selected)
    radiobutton .info.nbrhd.brf.rdb4 -variable NeighborhoodWindowRatio -value 5 -text 5 \
	-text 5 -justify l \
	-bg $::ColorSpecs(PanelNeighborhoodRatioMain,Background) \
	-fg $::ColorSpecs(PanelNeighborhoodRatioMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelNeighborhoodRatioMain,Selected)
    pack .info.nbrhd.brf.rdb1 .info.nbrhd.brf.rdb2 .info.nbrhd.brf.rdb3 \
	.info.nbrhd.brf.rdb4 -side top -expand 1 -fill both
    pack .info.nbrhd.title -side top -expand 1 -fill x
    pack .info.nbrhd.brf -side top -expand 1 -fill both -pady 3
    .info.nbrhd.brf.rdb1 select

    balloonhelp_for .info.nbrhd "\
These buttons control how much of the waveform is\n\
displayed in the neighborhood window. By default\n\
this window is twice as long as the current window,\n\
with the current window center. A larger value shows\n\
you more of the context of the window at a lower\n\
resolution."

    trace add variable NeighborhoodWindowRatio write SetNeighborhood;

    frame   .info.silence  -bg $::ColorSpecs(PanelSilencesMain,Background);
    label   .info.silence.title    -text [_ "Silences"] \
	-bg $::ColorSpecs(PanelSilencesTitle,Background) \
	-fg $::ColorSpecs(PanelSilencesTitle,Foreground) 
    label   .info.silence.fnamelab -text [_ "File"] -anchor w \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label   .info.silence.totallab -text [_ "Total"] -anchor w \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label   .info.silence.activelab -text [_ "Active"] -anchor w \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label   .info.silence.thrlab    -text [_ "Threshold"] -anchor w \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label   .info.silence.filename -textvariable SilenceFileNameTxt -anchor w \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label .info.silence.mastercnt -textvariable MasterSilenceCntTxt -anchor e \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    label .info.silence.activecnt -textvariable ActiveSilenceCntTxt -anchor e \
	-bg $::ColorSpecs(PanelSilencesMain,Background) \
	-fg $::ColorSpecs(PanelSilencesMain,Foreground) 
    entry   .info.silence.threshold -width 5 \
	-bg $::ColorSpecs(PanelSilencesEntry,Background) \
	-fg $::ColorSpecs(PanelSilencesEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelSilencesEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelSilencesEntry,DisabledBackground) \
	-vcmd {IsDouble %P} -validate key
    .info.silence.threshold insert end [format "%4.3f" $silence::SilenceThresholdSeconds]
    bind    .info.silence.threshold <Return> {silence::SetSilenceThreshold}

    grid .info.silence.title      -row 0 -column 0 -columnspan 2 -sticky wen -pady 0
    grid .info.silence.fnamelab   -row 1 -column 0 -sticky we -padx 4 -pady 2
    grid .info.silence.filename   -row 1 -column 1 -sticky we -padx 4 -pady 2
    grid .info.silence.totallab   -row 2 -column 0 -sticky we -padx 4 -pady 2
    grid .info.silence.mastercnt  -row 2 -column 1 -sticky we -padx 4 -pady 2
    grid .info.silence.activelab  -row 3 -column 0 -sticky we -padx 4 -pady 2
    grid .info.silence.activecnt  -row 3 -column 1 -sticky we -padx 4 -pady 2
    grid .info.silence.thrlab     -row 4 -column 0 -sticky we -padx 4 -pady 2
    grid .info.silence.threshold  -row 4 -column 1 -sticky we -padx 4 -pady 2

    balloonhelp_for .info.silence "\
Only silences longer than a certain threshold\n\
are put on the active list and used. This box\n\
shows how many silences there are in total,\n\
how many are on the active list, and what\n\
the threshold is. You may change the threshold."

    balloonhelp_for .info.silence.threshold "\
This is the threshold in seconds for silences\n\
to be put on the active list. You may change\n\
it by editing the value in this box and\n\
then pressing Enter."

    set w [frame .info.sili  -bg $ColorSpecs(PanelSilenceListMain,Background)]
    label     $w.title -text "" \
	-bg $::ColorSpecs(PanelSilenceListTitle,Background) \
	-fg $::ColorSpecs(PanelSilenceListTitle,Foreground) 
    frame     $w.lsf
    text   $w.lsf.txt -yscrollcommand [list $w.lsf.sb set] -height $SilenceListHeight -width 27 \
	-bg $::ColorSpecs(PanelSilenceListEntry,Background) \
	-fg $::ColorSpecs(PanelSilenceListEntry,Foreground) -font SilenceListFont
    set sb  [scrollbar $w.lsf.sb -command [list $w.lsf.txt yview] \
		 -bg $::ColorSpecs(PanelSilenceListMain,Background) \
		 -troughcolor $::ColorSpecs(PanelSilenceListMain,Trough) \
		 -highlightcolor $::ColorSpecs(PanelSilenceListMain,Highlight) \
		 -highlightbackground $::ColorSpecs(PanelSilenceListMain,HighlightBackground) \
		 -activebackground $::ColorSpecs(PanelSilenceListMain,ActiveBackground)]
    lappend ScrollbarList $sb
    set PackCommand($sb) [list pack $w.lsf.sb -side left -expand 0 -fill y]
    bind $sb <<B3>> "ScrollbarMoveBigIncrement $sb 0.1 %x %y"
    pack $w.lsf.txt -side left  -expand 1 -fill both -padx 2
    pack $w.lsf.sb  -side left  -expand 0 -fill y    -padx 1

    frame  $w.cntls
    radiobutton $w.cntls.rb1 -variable ::WhichList -value Master -text "Master" \
	-bg $::ColorSpecs(PanelSilenceListMain,Background) \
	-fg $::ColorSpecs(PanelSilenceListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSilenceListMain,Selected) -indicatoron 0
    radiobutton $w.cntls.rb2 -variable ::WhichList -value Active -text "Active" \
	-bg $::ColorSpecs(PanelSilenceListMain,Background) \
	-fg $::ColorSpecs(PanelSilenceListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSilenceListMain,Selected) -indicatoron 0
    label  $w.cntls.sep1 -text "" -width 1
    radiobutton $w.cntls.rb3 -variable ::SilencesInSecondsP -value 0 -text "Samples" \
	-bg $::ColorSpecs(PanelSilenceListMain,Background) \
	-fg $::ColorSpecs(PanelSilenceListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSilenceListMain,Selected)
    radiobutton $w.cntls.rb4 -variable ::SilencesInSecondsP -value 1 -text "Seconds" \
	-bg $::ColorSpecs(PanelSilenceListMain,Background) \
	-fg $::ColorSpecs(PanelSilenceListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSilenceListMain,Selected)
    label  $w.cntls.sep2 -text "" -width 1

    silence::PackSilenceListButtons [list 2 3 4];
    $w.cntls.rb2 select;
    $w.cntls.rb4 select;

    pack $w.title   -side top -expand 1 -fill both
    pack $w.lsf   -side top -expand 1 -fill both -pady 4
    pack $w.cntls -side top -expand 1 -fill both

    balloonhelp_for .info.sili "\
This box contains a current list of silent intervals.\n\
The first column is the beginning of the interval,\n\
the second column the end, and the third column the duration.\n\n\
The first highlighted line is the silence whose right edge\n\
is the left boundary of the window. The second highlighted\n\
line is the silence whose left edge is the right boundary of\n\
the window.\n\n\
The buttons below the box to the right allow you to choose\n\
whether the unit is samples or seconds. The buttons below\n\
the box to the left allow you to decide whether to see the\n\
entire list of silences or only those on the active list."

    frame  .info.sfname -bg $ColorSpecs(LazySusan,Background)
    label  .info.sfname.title  -text [_ "Next Segment File Name"] \
	-bg $::ColorSpecs(PanelFileNameTitle,Background) \
	-fg $::ColorSpecs(PanelFileNameTitle,Foreground)
    label  .info.sfname.plabel -text [_ "Prefix"] -anchor w \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)
    entry  .info.sfname.prefix -width 10 \
	-bg $::ColorSpecs(PanelFileNameEntry,Background) \
	-fg $::ColorSpecs(PanelFileNameEntry,Foreground)
    label  .info.sfname.indlabel -text [_ "Index"] \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)
    entry  .info.sfname.index -width 3 \
	-bg $::ColorSpecs(PanelFileNameEntry,Background) \
	-fg $::ColorSpecs(PanelFileNameEntry,Foreground)
    label  .info.sfname.suflabel -text [_ "Suffix"] \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)
    entry  .info.sfname.suffix -width 6 \
	-bg $::ColorSpecs(PanelFileNameEntry,Background) \
	-fg $::ColorSpecs(PanelFileNameEntry,Foreground)
    label  .info.sfname.extlabel -text [_ "Ext."] \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)
    entry  .info.sfname.ext -width 6 \
	-bg $::ColorSpecs(PanelFileNameEntry,Background) \
	-fg $::ColorSpecs(PanelFileNameEntry,Foreground)

    entry  .info.sfname.next -width 18 \
	-bg $::ColorSpecs(PanelFileNameEntry,Background) \
	-fg $::ColorSpecs(PanelFileNameEntry,Foreground)
    label  .info.sfname.lasttit  -text [_ "Last Segment File Written"] \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)
    label  .info.sfname.last  -textvariable LastSegmentFileWritten \
	-borderwidth 1 -relief raised -anchor c \
	-bg $::ColorSpecs(PanelFileNameMain,Background) \
	-fg $::ColorSpecs(PanelFileNameMain,Foreground)

#    bind .info.sfname.prefix <Return> {UpdateNextOutFileName x y z}
#    bind .info.sfname.suffix <Return> {UpdateNextOutFileName x y z}
#    bind .info.sfname.index  <Return> {UpdateNextOutFileName x y z}
#    bind .info.sfname.ext    <Return> {UpdateNextOutFileName x y z}

    proc ClearNextSegmentFileName {} {
	.info.sfname.next delete 0 end
    }

    bind .info.sfname.next <<B3>> {ClearNextSegmentFileName}

    bind .info.sfname.prefix <Return> {SetOutFilePrefixFromEntry}
    bind .info.sfname.index  <Return> {SetOutFileIndexFromEntry}
    bind .info.sfname.suffix <Return> {SetOutFileSuffixFromEntry}
    bind .info.sfname.ext <Return> {SetOutFileExtensionFromEntry}

    grid   .info.sfname.title    -row 0 -column 0 -columnspan 4 -sticky wen
    grid   .info.sfname.plabel   -row 1 -column 0 -sticky we
    grid   .info.sfname.prefix   -row 2 -column 0 -sticky we
    grid   .info.sfname.indlabel -row 1 -column 1 -sticky we
    grid   .info.sfname.index    -row 2 -column 1 -sticky we
    grid   .info.sfname.suflabel -row 1 -column 2 -sticky we
    grid   .info.sfname.suffix   -row 2 -column 2 -sticky we
    grid   .info.sfname.extlabel -row 1 -column 3 -sticky we
    grid   .info.sfname.ext      -row 2 -column 3 -sticky we
    grid   .info.sfname.next     -row 3 -column 0 -columnspan 4 -sticky we
    grid   .info.sfname.lasttit  -row 4 -column 0 -columnspan 4 -sticky we
    grid   .info.sfname.last     -row 5 -column 0 -columnspan 4 -sticky we

    .info.sfname.prefix insert end $OutFilePrefix
    .info.sfname.suffix insert end $OutFileSuffix
    .info.sfname.ext    insert end $OutFileExtension

#    trace add variable OutFileIndex write UpdateOutFileIndex
#    trace add variable OutFileIndex write UpdateNextOutFileName
#    set OutFileIndex $OutFileIndex;
#    trace add variable UseOutFileNameListP write UpdateNextOutFileName

    trace add variable OutFileIndex write UpdateOutFileIndex
    trace add variable OutFileIndex write UpdateNextOutFileName
    set OutFileIndex $OutFileIndex;
    trace add variable OutFilePrefix    write  UpdateNextOutFileName
    trace add variable OutFileSuffix    write  UpdateNextOutFileName
    trace add variable OutFileExtension write UpdateNextOutFileName
    trace add variable UseOutFileNameListP write UpdateNextOutFileName

    balloonhelp_for .info.sfname "\
This contains information about the names of the\n\
files to which audio segments are witten out.\n\
The first line contains the components from which\n\
filenames are automatically generated. You may\n\
change them by editing the three entry boxes\n\
and pressing Enter when you are done. The next\n\
line contains the file name that will be used\n\
the next time you write the window to a file.\n\
By default, it is the concatenation of the\n\
specified prefix, index, and suffix. However,\n\
you may change it by editing this box. The\n\
last line contains the name of the file to\n\
which the last window was written. This will\n\
normally be the same as the name to be used\n\
next except for an index smaller by one, but\n\
it may be different if you have overriden\n\
the auotomatic file name generation."

balloonhelp_for .info.sfname.next "Right click to clear"
    set MasterSilenceCntTxt "  0"
    set ActiveSilenceCntTxt "  0"

    #message .info.wbrdout -aspect 1000 -textvariable InfoBar(.ov) -foreground \#FF0030
    message .ov.info -aspect 1000 -textvariable InfoBar(.ov) \
	-fg $ColorSpecs(WavebarCursor,Foreground) \
	-bg $ColorSpecs(WavebarCursor,Background) \
	-borderwidth 1 -relief sunken

    balloonhelp_for .ov.info  "This gives the position of the pointer.\n\
                           Click on it to toggle between seconds and samples\n\
                           If in amplitude mode, the time/sample is followed by\n\
                           the amplitude of the frame containing the pointer"

    frame .info.sfile \
	-bg $ColorSpecs(PanelSoundFileMain,Background)  -relief ridge -border 1
    set SoundFileNameTxt   [_ "Sound File: None Loaded"]
    label .info.sfile.title     -textvariable SoundFileNameTxt   -anchor nw \
	-bg $ColorSpecs(PanelSoundFileTitle,Background) \
	-fg $ColorSpecs(PanelSoundFileTitle,Foreground)
    label .info.sfile.sratelab  -text [format "%-17s" [_ "Sampling Rate"]]  -anchor w \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lenseclab -text [format "%-17s" [_ "Seconds"]]  -anchor w \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lenmsclab -text [format "%-17s" [_ "hr:min:sec"]]  -anchor w \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lensamlab -text [format "%-17s" [_ "Samples"]]  -anchor w \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.chanlab   -text [format "%-17s" [_ "Channels"]]  -anchor w \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.srate  -textvariable SamplingRateText \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lensec -textvariable SoundSecondsText  \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lenmsc -textvariable SoundHoursMinutesSeconds  \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.lensam -textvariable SoundSamplesText \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.chan   -textvariable SoundChannels \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)
    label .info.sfile.enc    -textvariable SoundEncoding \
	-bg $ColorSpecs(PanelSoundFileMain,Background) \
	-fg $ColorSpecs(PanelSoundFileMain,Foreground)

    balloonhelp_for .info.sfile "This gives information about the current sound file."

    set SamplingRate $SamplingRate;
    set SoundSeconds $SoundSeconds;
    set SoundSamples $SoundSamples;
    set SoundChannels $SoundChannels;
    set SoundEncoding $SoundEncoding;
    set SoundFileFormat $SoundFileFormat;

    frame .info.sfile.blank  -bg \#FF9494;
    pack .info.sfile.title  -side top    -expand 0 -fill x
    pack .info.sfile.blank  -side bottom -expand 1 -fill both 
    trace add variable SoundFileNameTxt write PostSoundFileInfo
    proc PostSoundFileInfo {n e o} {
	pack forget .info.sfile.title;
	pack forget .info.sfile.blank;
	grid .info.sfile.title     -row 0 -column 0 -sticky wen -columnspan 2
	grid .info.sfile.sratelab  -row 1 -column 0 -sticky w
	grid .info.sfile.lenmsclab -row 2 -column 0 -sticky w
	grid .info.sfile.lenseclab -row 3 -column 0 -sticky w
	grid .info.sfile.lensamlab -row 4 -column 0 -sticky w
	grid .info.sfile.chanlab   -row 5 -column 0 -sticky w
	
	grid .info.sfile.srate  -row 1 -column 1 -sticky w
	grid .info.sfile.lenmsc -row 2 -column 1 -sticky w
	grid .info.sfile.lensec -row 3 -column 1 -sticky w
	grid .info.sfile.lensam -row 4 -column 1 -sticky w
	grid .info.sfile.chan   -row 5 -column 1 -sticky w
    }

    frame .info.wdelta  -bg $ColorSpecs(LazySusan,Background)
    label  .info.wdelta.title -text [_ "Window Motion Increment"] \
	-bg $::ColorSpecs(PanelWindowDeltaTitle,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaTitle,Foreground) 
    frame  .info.wdelta.bg -bg $ColorSpecs(LazySusan,Background) \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background)
    radiobutton .info.wdelta.bg.b1    -text "  10 ms"    -variable MSDelta -value 10 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b2    -text "  25 ms"    -variable MSDelta -value 25 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b3    -text "  50 ms"    -variable MSDelta -value 50 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b4    -text " 100 ms"   -variable MSDelta -value 100 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b5    -text " 250 ms"   -variable MSDelta -value 250 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b6    -text " 500 ms"   -variable MSDelta -value 500 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    radiobutton .info.wdelta.bg.b7    -text "1000 ms"  -variable MSDelta -value 1000 -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground)  \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    frame .info.wdelta.bg.ef -bg $ColorSpecs(LazySusan,Background) \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background)
    radiobutton .info.wdelta.bg.ef.b8    -text ""         -variable MSDelta -value "-1"  -anchor w \
	-bg $::ColorSpecs(PanelWindowDeltaMain,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelWindowDeltaMain,Selected)
    entry  .info.wdelta.bg.ef.ent   -width 5 \
	-bg $::ColorSpecs(PanelWindowDeltaEntry,Background) \
	-fg $::ColorSpecs(PanelWindowDeltaEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelWindowDeltaEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelWindowDeltaEntry,DisabledBackground) 
    .info.wdelta.bg.ef.ent insert end [format "%4d" [expr int(1000 * $::DeltaSeconds)]]
    bind    .info.wdelta.bg.ef.ent <Return> {SetDeltaFromMSDelta a b c}
    .info.wdelta.bg.ef.ent configure -state disabled
    label  .info.wdelta.bg.ef.pad -text "";
    pack   .info.wdelta.bg.ef.b8  -side left -expand 1 -fill both 
    pack   .info.wdelta.bg.ef.ent -side left -expand 1 -fill both
    set gxp 16
    grid .info.wdelta.bg.b1 -row 0 -column 0 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b2 -row 0 -column 1 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b3 -row 1 -column 0 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b4 -row 1 -column 1 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b5 -row 2 -column 0 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b6 -row 2 -column 1 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.b7 -row 3 -column 0 -padx $gxp -pady 0 -sticky we
    grid .info.wdelta.bg.ef -row 3 -column 1 -padx $gxp -pady 0 -sticky we

    pack   .info.wdelta.title -side top -expand 1 -fill both -pady 1
    pack   .info.wdelta.bg    -side top -expand 1 -fill both -pady 1

    set msg [_ "Use this dialog to set the value of the increment\nof window motion."]
    balloonhelp_for .info.wdelta            $msg
    balloonhelp_for .info.wdelta.bg         $msg
    balloonhelp_for .info.wdelta.title      $msg
    balloonhelp_for .info.wdelta.bg.ef      $msg
    balloonhelp_for .info.wdelta.bg.b1      $msg 
    balloonhelp_for .info.wdelta.bg.b2      $msg 
    balloonhelp_for .info.wdelta.bg.b3      $msg 
    balloonhelp_for .info.wdelta.bg.b4      $msg 
    balloonhelp_for .info.wdelta.bg.b5      $msg 
    balloonhelp_for .info.wdelta.bg.b6      $msg 
    balloonhelp_for .info.wdelta.bg.b7      $msg 
    balloonhelp_for .info.wdelta.bg.ef.b8   $msg 
    balloonhelp_for .info.wdelta.bg.ef.ent \
	[_ "Enter the desired value for the increment in milliseconds.\nIt should be a positive integer."]

    trace add variable MSDelta write ToggleDeltaEntryActive
    trace add variable MSDelta write SetDeltaFromMSDelta


#Prompter log info

    set w [frame .info.prli  -bg $ColorSpecs(PanelPrompterListMain,Background)]
    set ::PRLI $w
    label     $w.title -text "Prompter Log" \
	-bg $::ColorSpecs(PanelPrompterListTitle,Background) \
	-fg $::ColorSpecs(PanelPrompterListTitle,Foreground) 
    frame     $w.lsf
    text   $w.lsf.txt -yscrollcommand [list $w.lsf.sb set] -height $PrompterListHeight -width 27 \
	-bg $::ColorSpecs(PanelPrompterListEntry,Background) \
	-fg $::ColorSpecs(PanelPrompterListEntry,Foreground) -font SilenceListFont
    set sb  [scrollbar $w.lsf.sb -command [list $w.lsf.txt yview] \
		 -bg $::ColorSpecs(PanelPrompterListMain,Background) \
		 -troughcolor $::ColorSpecs(PanelPrompterListMain,Trough) \
		 -highlightcolor $::ColorSpecs(PanelPrompterListMain,Highlight) \
		 -highlightbackground $::ColorSpecs(PanelPrompterListMain,HighlightBackground) \
		 -activebackground $::ColorSpecs(PanelPrompterListMain,ActiveBackground)]
    lappend ScrollbarList $sb
    set PackCommand($sb) [list pack $w.lsf.sb -side left -expand 0 -fill y]
    bind $sb <<B3>> "ScrollbarMoveBigIncrement $sb 0.1 %x %y"
    pack $w.lsf.txt -side left  -expand 1 -fill both -padx 2
    pack $w.lsf.sb  -side left  -expand 0 -fill y    -padx 1

    frame  $w.cntls
    radiobutton $w.cntls.rb3 -variable ::SilencesInSecondsP -value 0 -text "Samples" \
	-bg $::ColorSpecs(PanelPrompterListMain,Background) \
	-fg $::ColorSpecs(PanelPrompterListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelPrompterListMain,Selected)
    radiobutton $w.cntls.rb4 -variable ::SilencesInSecondsP -value 1 -text "Seconds" \
	-bg $::ColorSpecs(PanelPrompterListMain,Background) \
	-fg $::ColorSpecs(PanelPrompterListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelPrompterListMain,Selected)
    label  $w.cntls.sep2 -text "" -width 1

    pack $w.cntls.rb3 -side left -expand 1 -fill both
    pack $w.cntls.rb4 -side left -expand 1 -fill both

    $w.cntls.rb4 select;

    pack $w.title   -side top -expand 1 -fill both
    pack $w.lsf   -side top -expand 1 -fill both -pady 4
    pack $w.cntls -side top -expand 1 -fill both


    balloonhelp_for .info.prli "\
This box contains the information recorded\n\
by the Prompter program.\n\
The first column after the index is the beginning\n\
of the interval, the second column the end,\n\
the third column the entry's unique identifier\n\
and the fourth the headword. The buttons\n\
below the box to the right allow you to choose\n\
whether the unit is samples or seconds.\n"

    proc ClearPrompterDisplay {} {
	if {$::BatchModeP} {return}
	$::PRLI.lsf.txt configure -state normal
	$::PRLI.lsf.txt delete 1.0 end
	$::PRLI.lsf.txt configure -state disabled
    }

    proc FillPrompterDisplay {} {
	if {$::BatchModeP} {return}
	$::PRLI.lsf.txt configure -state normal
	set num 0
	foreach i $::PrompterList {
	    incr num
	    $::PRLI.lsf.txt insert end [FormatPrompterTxt $i $num]
	}
	$::PRLI.lsf.txt configure -state disabled
    }

    proc FormatPrompterTxt {entry num} {
	set UID		[lindex $entry 0]
	set HeadWord	[lindex $entry 1]
	set BeginSamples    [lindex $entry 2]
	set EndSamples      [lindex $entry 3]
	if {$::SilencesInSecondsP} {
	    set BeginSeconds [SamplesToSeconds $BeginSamples]
	    set EndSeconds   [SamplesToSeconds $EndSamples]
#	    return [format "%3u %6.2f %6.2f %5s %s\n"  $num $BeginSeconds $EndSeconds $UID $HeadWord]
	    return [format "%3u  %s  %s  %5s  %s\n"  $num [SecondsToMSF $BeginSeconds] [SecondsToMSF $EndSeconds] $UID $HeadWord]
	} else {
	    return [format "%3u  %8u  %8u  %5s  %s\n"  $num $BeginSamples $EndSamples $UID $HeadWord]
	}
    }

    proc UpdatePrompterDisplay {n e o} {
	if {$::BatchModeP} {return}
	if {[winfo exists $::PRLI.lsf.txt]} {
	    ClearPrompterDisplay;
	    FillPrompterDisplay;
	}
    }

    proc ScrollPrompterDisplay {} {
	if {$::BatchModeP} {return}
	UntagPrompter
	TagPrompter [expr $::CurrentPrompterIndex + 1]
	if {$::CurrentPrompterIndex >= 0} {
	    $::PRLI.lsf.txt yview $::CurrentPrompterIndex
	}
    }

    proc TagPrompter {Line} {
	$::PRLI.lsf.txt tag delete lhl
	$::PRLI.lsf.txt tag configure lhl -background $::ColorSpecs(PrompterHighlight,Foreground);
	$::PRLI.lsf.txt tag add lhl $Line.0 $Line.end
    }

    proc UntagPrompter {} {
	$::PRLI.lsf.txt tag delete lhl
    }

#Segment list

    set w [frame .info.segli  -bg $ColorSpecs(PanelSegmentListMain,Background)]
    set ::SEGLI $w
    label     $w.title -text "Segment List" \
	-bg $::ColorSpecs(PanelSegmentListTitle,Background) \
	-fg $::ColorSpecs(PanelSegmentListTitle,Foreground) 
    frame     $w.lsf
    text   $w.lsf.txt -yscrollcommand [list $w.lsf.sb set] -height $SegmentListHeight -width 27 \
	-bg $::ColorSpecs(PanelSegmentListEntry,Background) \
	-fg $::ColorSpecs(PanelSegmentListEntry,Foreground) -font SilenceListFont
    set sb  [scrollbar $w.lsf.sb -command [list $w.lsf.txt yview] \
		 -bg $::ColorSpecs(PanelSegmentListMain,Background) \
		 -troughcolor $::ColorSpecs(PanelSegmentListMain,Trough) \
		 -highlightcolor $::ColorSpecs(PanelSegmentListMain,Highlight) \
		 -highlightbackground $::ColorSpecs(PanelSegmentListMain,HighlightBackground) \
		 -activebackground $::ColorSpecs(PanelSegmentListMain,ActiveBackground)]
    lappend ScrollbarList $sb
    set PackCommand($sb) [list pack $w.lsf.sb -side left -expand 0 -fill y]
    bind $sb <<B3>> "ScrollbarMoveBigIncrement $sb 0.1 %x %y"
    pack $w.lsf.txt -side left  -expand 1 -fill both -padx 2
    pack $w.lsf.sb  -side left  -expand 0 -fill y    -padx 1

    frame  $w.cntls
    radiobutton $w.cntls.rb3 -variable ::SegmentsInSecondsP -value 0 -text "Samples" \
	-bg $::ColorSpecs(PanelSegmentListMain,Background) \
	-fg $::ColorSpecs(PanelSegmentListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSegmentListMain,Selected)
    radiobutton $w.cntls.rb4 -variable ::SegmentsInSecondsP -value 1 -text "Seconds" \
	-bg $::ColorSpecs(PanelSegmentListMain,Background) \
	-fg $::ColorSpecs(PanelSegmentListMain,Foreground) \
	-selectcolor $::ColorSpecs(PanelSegmentListMain,Selected)
    label  $w.cntls.sep2 -text "" -width 1

    pack $w.cntls.rb3 -side left -expand 1 -fill both
    pack $w.cntls.rb4 -side left -expand 1 -fill both

    $w.cntls.rb4 select;

    pack $w.title   -side top -expand 1 -fill both
    pack $w.lsf   -side top -expand 1 -fill both -pady 4
    pack $w.cntls -side top -expand 1 -fill both


    balloonhelp_for .info.segli "\
This box contains the segment list.\n\
The first column is the beginning\n\
of the interval, the second column the end,\n\
and the third column the headword. The buttons\n\
below the box to the right allow you to choose\n\
whether the unit is samples or seconds.\n"

    proc ClearSegmentDisplay {} {
	if {$::BatchModeP} {return}
	$::SEGLI.lsf.txt configure -state normal
	$::SEGLI.lsf.txt delete 1.0 end
	$::SEGLI.lsf.txt configure -state disabled
    }

    proc FillSegmentDisplay {} {
	if {$::BatchModeP} {return}
	$::SEGLI.lsf.txt configure -state normal
	set num 0
	foreach i $::SegmentList {
	    incr num
	    $::SEGLI.lsf.txt insert end [FormatSegmentTxt $i $num]
	}
	$::SEGLI.lsf.txt configure -state disabled
    }

    proc FormatSegmentTxt {entry num} {
	set BeginSeconds    [lindex $entry 0]
	set EndSeconds      [lindex $entry 1]
	set FileName	   [lindex $entry 2]
	if {$::SegmentsInSecondsP} {
	    return [format "%3d  %s  %s  %s\n"  $num [SecondsToMSF $BeginSeconds] \
			[SecondsToMSF $EndSeconds] $FileName]
	} else {
	    set BeginSamples [SecondsToSamples $BeginSeconds]
	    set EndSamples [SecondsToSamples $EndSeconds]
	    return [format "%3u %8u %8u  %s\n"  $num $BeginSamples $EndSamples $FileName]
	}
    }

    proc UpdateSegmentDisplay {n e o} {
	if {$::BatchModeP} {return}
	if {[winfo exists $::SEGLI.lsf.txt]} {
	    ClearSegmentDisplay;
	    FillSegmentDisplay;
	}
    }

    frame .info.pause 
    label .info.pause.title -text [_ "Pause Parameters"] \
	-bg $::ColorSpecs(PanelPauseParametersTitle,Background) \
	-fg $::ColorSpecs(PanelPauseParametersTitle,Foreground) 
    frame .info.pause.main \
	-bg $::ColorSpecs(PanelPauseParametersMain,Background);
    label .info.pause.main.flab -text [_ "Frame Size"] \
	-bg $::ColorSpecs(PanelPauseParametersMain,Background) \
	-fg $::ColorSpecs(PanelPauseParametersMain,Foreground)
    label .info.pause.main.mlab -text [_ "Minimum Duration"] \
	-bg $::ColorSpecs(PanelPauseParametersMain,Background) \
	-fg $::ColorSpecs(PanelPauseParametersMain,Foreground)
    label .info.pause.main.tlab -text [_ "Amplitude Threshold"] \
	-bg $::ColorSpecs(PanelPauseParametersMain,Background) \
	-fg $::ColorSpecs(PanelPauseParametersMain,Foreground)
    entry .info.pause.main.fent -width 6 \
	-bg $::ColorSpecs(PanelPauseParametersEntry,Background) \
	-fg $::ColorSpecs(PanelPauseParametersEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelPauseParametersEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelPauseParametersEntry,DisabledBackground) \
	-vcmd {IsDouble %P} -validate key
    entry .info.pause.main.ment -width 6 \
	-bg $::ColorSpecs(PanelPauseParametersEntry,Background) \
	-fg $::ColorSpecs(PanelPauseParametersEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelPauseParametersEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelPauseParametersEntry,DisabledBackground) \
	-vcmd {IsDouble %P} -validate key 
    entry .info.pause.main.tent -width 6 \
	-bg $::ColorSpecs(PanelPauseParametersEntry,Background) \
	-fg $::ColorSpecs(PanelPauseParametersEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelPauseParametersEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelPauseParametersEntry,DisabledBackground) 
    frame .info.pause.cntl \
	-bg $::ColorSpecs(PanelPauseParametersMain,Background)
    button .info.pause.cntl.b1 -text [_ "Reset"] -command ResetPauseParameters \
	-bg $ColorSpecs(PanelPauseParametersButton,Background) \
	-fg $ColorSpecs(PanelPauseParametersButton,Foreground) \
	-highlightbackground $ColorSpecs(PanelPauseParametersButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PanelPauseParametersButton,Highlight) \
	-activebackground $ColorSpecs(PanelPauseParametersButton,ActiveBackground) \
	-activeforeground $ColorSpecs(PanelPauseParametersButton,ActiveForeground) \
	-font MainFont
    button .info.pause.cntl.b2 -text [_ "Save"] -command GetPauseParameters \
	-bg $ColorSpecs(PanelPauseParametersButton,Background) \
	-fg $ColorSpecs(PanelPauseParametersButton,Foreground) \
	-highlightbackground $ColorSpecs(PanelPauseParametersButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PanelPauseParametersButton,Highlight) \
	-activebackground $ColorSpecs(PanelPauseParametersButton,ActiveBackground) \
	-activeforeground $ColorSpecs(PanelPauseParametersButton,ActiveForeground) \
	-font MainFont
    pack .info.pause.cntl.b1 -side left -expand 1 -fill y -padx 5 -pady 3
    pack .info.pause.cntl.b2 -side left -expand 1 -fill y -padx 5 -pady 3
    pack .info.pause.title  -side top -expand 1 -fill both
    pack .info.pause.main  -side top -expand 1 -fill both -pady 3
    pack .info.pause.cntl  -side top -expand 1 -fill both

    grid .info.pause.main.flab -row 0 -column 0 -sticky w -padx 3
    grid .info.pause.main.mlab -row 1 -column 0 -sticky w -padx 3
    grid .info.pause.main.tlab -row 2 -column 0 -sticky w -padx 3
    grid .info.pause.main.fent -row 0 -column 1 -sticky w -padx 3
    grid .info.pause.main.ment -row 1 -column 1 -sticky w -padx 3
    grid .info.pause.main.tent -row 2 -column 1 -sticky w -padx 3

    .info.pause.main.fent insert end $PauseParameters(FrameSize)
    .info.pause.main.ment insert end $PauseParameters(MinimumDuration)
    .info.pause.main.tent insert end $PauseParameters(Threshold)
    set msg [_ "Reset the parameters to their default values."]
    balloonhelp_for .info.pause.cntl.b1 $msg
    set msg [_ "Save the values shown in the entry boxes."]
    balloonhelp_for .info.pause.cntl.b2 $msg;

    set msg [_ "This box shows the current values of the parameters
passed to pause when it is executed. You may
change these parameters by editing the values
shown and clicking the Save button."];
    balloonhelp_for .info.pause $msg;
    balloonhelp_for .info.pause.title $msg;
    set msg [_ "This field is for the frame size. Pause
divides its input into frames, small regions
over which it computes a measure of amplitude
and for which it decides whether the region
represents silence or sound. A smaller frame
size increases the temporal resolution.
However, too small a frame size runs the risk
of effectively picking out high frequency
signal components rather than overall
fluctuations in the amplitude envelope."];
    balloonhelp_for .info.pause.main.flab $msg;
    balloonhelp_for .info.pause.main.fent $msg;
    set msg [_ "This field is for the minimum duration of silence to
include in the output. The value should be a non-negative
real number with dimensions of milliseconds."];
    balloonhelp_for .info.pause.main.mlab $msg;
    balloonhelp_for .info.pause.main.ment $msg;
    set msg [_ "This field is for the amplitude threshold that pause uses
to decide whether a frame contains silence or sound.
A larger value will increase the number of putative silences
found. Its value is a non-negative integer, dimensionless
but proportional to sound pressure by an unknown constant."]
    balloonhelp_for .info.pause.main.tlab $msg;
    balloonhelp_for .info.pause.main.tent $msg;

    set w [frame .info.setwin]
    label $w.title -text [_ "Window Boundaries"] -anchor n \
	-bg $::ColorSpecs(PanelWindowBoundariesTitle,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesTitle,Foreground) 
    frame $w.main -bg $::ColorSpecs(PanelWindowBoundariesMain,Background);
    label $w.main.labwle -text [_ "Left Edge"]  -anchor w \
	-bg $::ColorSpecs(PanelWindowBoundariesMain,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesMain,Foreground)
    label $w.main.labwre -text [_ "Right Edge"] -anchor e \
	-bg $::ColorSpecs(PanelWindowBoundariesMain,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesMain,Foreground)
    entry $w.main.entwle -width 9 \
	-bg $::ColorSpecs(PanelWindowBoundariesEntry,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelWindowBoundariesEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelWindowBoundariesEntry,DisabledBackground) \
	-vcmd {IsDouble %P} -validate key
    entry $w.main.entwre -width 9 \
	-bg $::ColorSpecs(PanelWindowBoundariesEntry,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesEntry,Foreground) \
	-disabledforeground $::ColorSpecs(PanelWindowBoundariesEntry,DisabledForeground) \
	-disabledbackground $::ColorSpecs(PanelWindowBoundariesEntry,DisabledBackground) \
	-vcmd {IsDouble %P} -validate key
    frame $w.main.rb
    radiobutton $w.main.rb.rb1 -variable WindowSetSecondsP -value 0 -text [_ "Samples"] \
	-command {UpdateSetwin x y z} \
	-bg $::ColorSpecs(PanelWindowBoundariesButton,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesButton,Foreground) \
	-selectcolor $::ColorSpecs(PanelWindowBoundariesMain,Selected) -justify left -indicatoron 0
    radiobutton $w.main.rb.rb2 -variable WindowSetSecondsP -value 1 -text [_ "Seconds"] \
	-command {UpdateSetwin x y z} \
	-bg $::ColorSpecs(PanelWindowBoundariesButton,Background) \
	-fg $::ColorSpecs(PanelWindowBoundariesButton,Foreground) \
	-selectcolor $::ColorSpecs(PanelWindowBoundariesMain,Selected) -justify left -indicatoron 0
    $w.main.rb.rb2 select;
    pack $w.main.rb.rb1 -side top -expand 1 -fill both -anchor w
    pack $w.main.rb.rb2 -side top -expand 1 -fill both -anchor w
    #grid $w.main.rb.rb1 -row 0 -column 0 -sticky we
    #grid $w.main.rb.rb2 -row 1 -column 0 -sticky we
    button $w.main.go -text [_ "Go"]  -command UserSetWindow \
	-bg $ColorSpecs(PanelWindowBoundariesButton,Background) \
	-fg $ColorSpecs(PanelWindowBoundariesButton,Foreground) \
	-highlightbackground $ColorSpecs(PanelWindowBoundariesButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(PanelWindowBoundariesButton,Highlight) \
	-activebackground $ColorSpecs(PanelWindowBoundariesButton,ActiveBackground) \
	-activeforeground $ColorSpecs(PanelWindowBoundariesButton,ActiveForeground) \
	-font MainFont

    grid $w.main.labwle  -row 0 -column 0 -padx 3
    grid $w.main.labwre  -row 0 -column 1 -padx 3
    grid $w.main.entwle  -row 1 -column 0 -padx 3
    grid $w.main.entwre  -row 1 -column 1 -padx 3
    grid $w.main.rb      -row 2 -column 0 -padx 3 -pady 5
    grid $w.main.go      -row 2 -column 1 -padx 3 -pady 5
    pack $w.title   -side top -expand 1 -fill both -pady 2
    pack $w.main    -side top -expand 1 -fill both -pady 2

    set msg [_ "This panel allows you to set the bounds of the
window explicitly. The current bounds are shown in
the two entry boxes. You may change them by editing
the text in the boxes and then pressing the Go button."];
    balloonhelp_for .info.setwin $msg;
    set msg [_ "These buttons determine whether the window
bounds will be shown in units of seconds or
of samples and whether new values that you
enter will be interpreted as in seconds or
samples"];
    balloonhelp_for .info.setwin.main.rb $msg
    balloonhelp_for .info.setwin.main.rb.rb1 $msg
    balloonhelp_for .info.setwin.main.rb.rb2 $msg

    set msg [_ "Press this button to make the new window
bounds you have entered take effect."];
    balloonhelp_for .info.setwin.main.go $msg

    proc UpdateSetwin {n e o} {
	.info.setwin.main.entwle delete 0 end
	.info.setwin.main.entwre delete 0 end
	if {$::WindowSetSecondsP} {
	    set wle [format "%4.3f" [SamplesToSeconds $::WindowLeftEdge]]
	    set wre [format "%4.3f" [SamplesToSeconds $::WindowRightEdge]]
	} else {
	    set wle $::WindowLeftEdge;
	    set wre $::WindowRightEdge;
	}
	.info.setwin.main.entwle insert end $wle
	.info.setwin.main.entwre insert end $wre
    }

    proc BindSoundWindows {} {
	bind .ov <Button-1> {SetLeftEdgeOverview %x}
	bind .ov <<B3>> {SetRightEdgeOverview %x}
	bind .ov <Motion>   {SetCoords %W %x %y}
	bind .ov <Expose> {RePositionWavebarInfo}
	bind .c  <Button-1> {SetLeftEdgeNeighborhood %x}
	bind .c  <<B3>> {SetRightEdgeNeighborhood %x}
	bind .c   <Motion>   {SetCoords %W %x %y}
	bind $::CLUPL <Button-1> {SetLeftEdgeCloseup %x}
	bind $::CLUPR <Button-1> {SetRightEdgeCloseup %x}
	bind $::CLUPL <Motion> {SetCoords %W %x %y}
	bind $::CLUPR <Motion> {SetCoords %W %x %y}
    }

    RotateInfo right;
    frame .ovccsep -height 3 -border 1 -relief raised
    frame .infosep -height 3 -border 1 -relief raised

    canvas .c -width $MainWindowWidth -height $MainWindowHeight \
	-bg $ColorSpecs(Neighborhood,Background)  -relief ridge -border 2
    message .c.info -aspect 1000 -textvariable InfoBar(.c) \
	-background $::ColorSpecs(NeighborhoodCursor,Background) \
	-foreground $::ColorSpecs(NeighborhoodCursor,Foreground) \
	-borderwidth 1 -relief sunken

    label .c.wldg -textvariable WindowBoundsLeft \
	-border 1 -relief sunken -fg $ColorSpecs(WindowCoordinates,Foreground) \
	-bg $ColorSpecs(WindowCoordinates,Background)
    label .c.wdur -textvariable WindowDuration \
	-border 1 -relief sunken -fg $ColorSpecs(WindowCoordinates,Foreground) \
	-bg $ColorSpecs(WindowCoordinates,Background)
    label .c.wrdg  -textvariable WindowBoundsRight \
	-border 1 -relief sunken -fg $ColorSpecs(WindowCoordinates,Foreground) \
	-bg $ColorSpecs(WindowCoordinates,Background)
    bind .c.wldg <Button-1> {ToggleUseSeconds %W}
    bind .c.wdur <Button-1> {ToggleUseSeconds %W}
    bind .c.wrdg <Button-1> {ToggleUseSeconds %W}

    proc UpdateExpansionFactor {} {
	set NewWidth [lindex [split [wm geometry .] x] 0]
	set ::ExpansionFactor [expr {double($NewWidth) / double($::MainWindowWidth)}]
	dmsg "UpdateExpansionFactor: NewWidth = $NewWidth  ExpansionFactor = $::ExpansionFactor"
    }

#    bind .c <Configure> UpdateExpansionFactor

    balloonhelp_for .c.info  "This gives the position of the pointer.\n\
                           Click on it to toggle between seconds and samples\n\
                           If in amplitude mode, the time/sample is followed by\n\
                           the amplitude of the frame containing the pointer"


    balloonhelp_for .c.wldg "This gives the position of the left edge of the window.\n\
                         Click on it to toggle between seconds and samples"

    balloonhelp_for .c.wrdg "This gives the position of the right edge of the window.\n\
                         Click on it to toggle between seconds and samples"

    balloonhelp_for .c.wdur "This gives the duration of the window.\n\
                         Click on it to toggle between seconds and samples"

    balloonhelp_for .c "This window displays the neighborhood of the window, that is,\n\
                        the window together with some of the sound on either side.\n\
                        By default equal amounts of window and context are shown,\n\
                        but you can adjust the ratio of context to window to show\n\
                        more context if you wish. The window is shown in red.\n\
                        You may change its left edge by left-clicking on the\n\
                        waveform, its right edge by right-clicking on the waveform.\n\
                        Changes that you make here are immediately reflected in the\n\
                        closeup windows but not in the wavebar window. The two\n\
                        pairs of vertical lines, if present (they are optional),\n\
                        delimit the regions shown in the two closeup windows."

    set WindowBoundsLeft "0.0";
    set WindowBoundsRight "0.0";
    set WindowDuration "0.0";

    frame .clup   -relief raised -border 2 -bg $::ColorSpecs(Closeup,Background)
    frame .clup.l -relief ridge  -border 2
    frame .clup.r -relief ridge  -border 2
    frame .clup.l.cntrls
    frame .clup.r.cntrls
    canvas $CLUPL -height $CloseupHeight -widt $CloseupWidth -bg $ColorSpecs(Closeup,Background)
    canvas $CLUPR -height $CloseupHeight -widt $CloseupWidth -bg $ColorSpecs(Closeup,Background)

    button .clup.l.cntrls.b1 -text [format "\u21D0 %s" [_ "0-Crossing"]] \
	-command {ZeroCrossingPrevLeft} \
	-bg $ColorSpecs(ZeroCrossingButton,Background) \
	-fg $ColorSpecs(ZeroCrossingButton,Foreground) \
	-highlightbackground $ColorSpecs(ZeroCrossingButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(ZeroCrossingButton,Highlight) \
	-activebackground $ColorSpecs(ZeroCrossingButton,ActiveBackground) \
	-activeforeground $ColorSpecs(ZeroCrossingButton,ActiveForeground) \
	-font MainFont
    button .clup.l.cntrls.b2 -text [format "%s \u21D2" [_ "0-Crossing"]] -command {ZeroCrossingNextLeft} \
	-bg $ColorSpecs(ZeroCrossingButton,Background) \
	-fg $ColorSpecs(ZeroCrossingButton,Foreground) \
	-highlightbackground $ColorSpecs(ZeroCrossingButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(ZeroCrossingButton,Highlight) \
	-activebackground $ColorSpecs(ZeroCrossingButton,ActiveBackground) \
	-activeforeground $ColorSpecs(ZeroCrossingButton,ActiveForeground) \
	-font MainFont
    pack .clup.l.cntrls.b1 -side left  -expand 1 -fill both
    pack .clup.l.cntrls.b2 -side right -expand 1 -fill both

    bind $CLUPL <<B3>> {ZeroCrossingLeftCursor %x};

    button .clup.r.cntrls.b1 -text [format "\u21D0 %s" [_ "0-Crossing"]] -command {ZeroCrossingPrevRight} \
	-bg $ColorSpecs(ZeroCrossingButton,Background) \
	-fg $ColorSpecs(ZeroCrossingButton,Foreground) \
	-highlightbackground $ColorSpecs(ZeroCrossingButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(ZeroCrossingButton,Highlight) \
	-activebackground $ColorSpecs(ZeroCrossingButton,ActiveBackground) \
	-activeforeground $ColorSpecs(ZeroCrossingButton,ActiveForeground) \
	-font MainFont
    button .clup.r.cntrls.b2 -text [format "%s \u21D2" [_ "0-Crossing"]] \
	-command {ZeroCrossingNextRight} \
	-bg $ColorSpecs(ZeroCrossingButton,Background) \
	-fg $ColorSpecs(ZeroCrossingButton,Foreground) \
	-highlightbackground $ColorSpecs(ZeroCrossingButton,HighlightBackground) \
	-highlightcolor      $ColorSpecs(ZeroCrossingButton,Highlight) \
	-activebackground $ColorSpecs(ZeroCrossingButton,ActiveBackground) \
	-activeforeground $ColorSpecs(ZeroCrossingButton,ActiveForeground) \
	-font MainFont
    pack .clup.r.cntrls.b1 -side left  -expand 1 -fill both
    pack .clup.r.cntrls.b2 -side right -expand 1 -fill both

    bind $CLUPR <<B3>> {ZeroCrossingRightCursor %x};


    message $CLUPL.info -aspect 1000 -textvariable InfoBar($CLUPL) \
	-borderwidth 1 -relief sunken \
	-bg $ColorSpecs(CloseupCursor,Background) \
	-fg $ColorSpecs(CloseupCursor,Foreground) 

    message $CLUPR.info -aspect 1000 -textvariable InfoBar($CLUPR) \
	-borderwidth 1 -relief sunken \
	-bg $ColorSpecs(CloseupCursor,Background) \
	-fg $ColorSpecs(CloseupCursor,Foreground) 

    message $CLUPL.cwid -aspect 1000 -textvariable WaveformInfo($CLUPL,CloseupRegionWidth) \
	-borderwidth 1 -relief flat \
	-bg $ColorSpecs(CloseupRegionWidth,Background) \
	-fg $ColorSpecs(CloseupRegionWidth,Foreground) 

    message $CLUPR.cwid -aspect 1000 -textvariable WaveformInfo($CLUPR,CloseupRegionWidth) \
	-borderwidth 1 -relief flat \
	-bg $ColorSpecs(CloseupRegionWidth,Background) \
	-fg $ColorSpecs(CloseupRegionWidth,Foreground) 

    set InfoBar($CLUPL) "0.0"
    set InfoBar($CLUPR) "0.0"

    $CLUPL create window $CloseupWidth $CloseupHeight -window $CLUPL.cwid -anchor se
    $CLUPR create window 1 $CloseupHeight -window $CLUPR.cwid -anchor sw
    $CLUPL create window 0 0 -window $CLUPL.info -anchor nw
    $CLUPR create window $CloseupWidth 0 -window $CLUPR.info -anchor ne
    pack .clup.l.canvas -side top -expand 1 -fill both
    pack .clup.l.cntrls -side top -expand 1 -fill both
    pack .clup.r.canvas -side top -expand 1 -fill both
    pack .clup.r.cntrls -side top -expand 1 -fill both

    balloonhelp_for $CLUPL "\
This window provides a closeup view of the\n\
region containing the left edge of the window.\n\
You can move the left edge of the window\n\
by clicking in it. You can move the\n\
window edge to a zero-crossing by pressing\n\
the two zero-crossing buttons or by right-clicking.\n\
A right click to the left of the current cut mark\n\
moves to the preceding zero-crossing. A right click\n\
to the right of the current cut-mark moves to the\n\
following zero-crossing. Changes in the\n\
window edge that you make here are not automatically\n\
reflected in the wavebar and neighborhood windows."

    balloonhelp_for $CLUPR "\
This window provides a closeup view of the\n\
region containing the right edge of the window.\n\
You can move the right edge of the window\n\
by clicking in it. You can move the\n\
window edge to a zero-crossing by pressing\n\
the two zero-crossing buttons or by right-clicking.\n\
A right click to the left of the current cut mark\n\
moves to the preceding zero-crossing. A right click\n\
to the right of the current cut-mark moves to the\n\
following zero-crossing. Changes in the\n\
window edge that you make here are not automatically\n\
reflected in the wavebar and neighborhood windows."


    set msg "This gives the position of the pointer.\n\
                           Click on it to toggle between seconds and samples\n\
                           If in amplitude mode, the time/sample is followed by\n\
                           the amplitude of the frame containing the pointer"

    balloonhelp_for $CLUPL.info  $msg
    balloonhelp_for $CLUPR.info  $msg


    set msg  [_ "This gives the current width of the region displayed.\n\
	Click to toggle between milliseconds and samples."]
    balloonhelp_for $CLUPL.cwid $msg 
    balloonhelp_for $CLUPR.cwid $msg 

    set msg [_ "Move the left window edge to the nearest
zero-crossing preceding its current position, if any."]
    balloonhelp_for .clup.l.cntrls.b1 $msg
    set msg [_ "Move the right window edge to the nearest
zero-crossing preceding its current position, if any."]
    balloonhelp_for .clup.r.cntrls.b1 $msg
    set msg [_ "Move the left window edge to the nearest
zero-crossing following its current position, if any."]
    balloonhelp_for .clup.l.cntrls.b2 $msg
    set msg [_ "Move the right window edge to the nearest
zero-crossing following its current position, if any."]
    balloonhelp_for .clup.r.cntrls.b2 $msg

    frame .sepcc -width $MainWindowWidth -height 6 -borderwidth 2 -relief flat

    pack .clup.l    -side left -expand 1 -fill y -anchor w -padx 1
    frame .clup.sep -width 4 -relief ridge
    pack .clup.sep -side left -expand 1 -fill y
    pack .clup.r    -side right -expand 1 -fill y -anchor e -padx 1

    frame .cclupsep -height 3 -border 2 -relief flat -bg \#CC00DD

    PackMain;
#    .info.setwin.main.rb.rb2 invoke
#    .info.setwin.main.go invoke

    bind $OV.info <Button-1> {ToggleUseSeconds %W}
    bind $C.info <Button-1> {ToggleUseSeconds %W}
    bind $CLUPL.info <Button-1> {ToggleUseSeconds %W}
    bind $CLUPR.info <Button-1> {ToggleUseSeconds %W}
    bind $CLUPL.info <Button-1> {+ComputeCloseupRegion $::WindowLeftEdge  $::CLUPL}
    bind $CLUPR.info <Button-1> {+ComputeCloseupRegion $::WindowRightEdge $::CLUPR}
    bind $CLUPL.cwid <Button-1> {ToggleUseSeconds %W}
    bind $CLUPR.cwid <Button-1> {ToggleUseSeconds %W}
    bind $CLUPL.cwid <Button-1> {+ComputeCloseupRegion $::WindowLeftEdge  $::CLUPL}
    bind $CLUPR.cwid <Button-1> {+ComputeCloseupRegion $::WindowRightEdge $::CLUPR}

    trace add variable WindowLeftEdge  write SetNeighborhoodChangeThreshold
    trace add variable WindowRightEdge write SetNeighborhoodChangeThreshold
    trace add variable WindowLeftEdge  write ScrollWavebar
    trace add variable WindowRightEdge write ScrollWavebar
    trace add variable WindowLeftEdge  write UpdateSetwin
    trace add variable WindowRightEdge write UpdateSetwin

    #We want the default browser to be set before this code is executed.
    #If the default browser is on the list, remove it.
    set di [lsearch -exact $BrowserList $DefaultBrowser]
    if {$di >= 0} {
	set BrowserList [lreplace $BrowserList $di $di]
    }
    #Add the default browser to the beginning of the list.
    set BrowserList [linsert $BrowserList 0 $DefaultBrowser];

    foreach fn $CustomCharacterChartFileNameList {
	wm withdraw [ReadCustomCharacterChartPopup $fn]
    }

    foreach dl $CustomCharacterChartDataList {
	wm withdraw [DefineCustomCharacterChartPopup $dl]
    }

    foreach fn $CustomCharacterChartPanelFileNameList {
	ReadCustomCharacterChartPanel $fn;
    }
    foreach dl $CustomCharacterChartPanelDataList {
	DefineCustomCharacterChartPanel $dl;
    }

    trace add variable UsePauseP write ToggleShowPauseCommandLineMenuButton
    set ::UsePauseP $::UsePauseP
    BindKeys .
    after idle {
	update
	pack propagate .info 0
    }
    ToggleAmplitudeMode 0
}

ConstructHistoryPopup
trace add variable DisplayHistoryPopupP write ToggleHistoryPopup
trace add variable ::SilencesInSecondsP write UpdatePrompterDisplay
trace add variable ::SegmentsInSecondsP write UpdateSegmentDisplay


if { [llength $argv] > 0} {
    LoadSoundFile [lindex $argv 0];
}

if {!$BatchModeP} {
    update;
}
if {$ReadScriptFileP} {
    ScriptFileSetup;
    ReadScriptFile $ScriptFileName;
    if {$BatchModeP} {
	exit 0;
    }
}

if {!$::BatchModeP} {
    set ::InteractiveP 1
}

proc NextStamp {dir} {
    incr ::CurrentPrompterIndex $dir
    set Regions [llength $::PrompterList]
    if {!(($::CurrentPrompterIndex < $Regions) && ($::CurrentPrompterIndex >= 0))} {return}
    set RegionInfo [lindex $::PrompterList $::CurrentPrompterIndex]
    set lb [lindex $RegionInfo 2]
    set rb [lindex $RegionInfo 3]
    set OldWLE $::WindowLeftEdge;
    set OldWRE $::WindowRightEdge;
    set ::WindowRightEdge $lb
    set ::WindowLeftEdge  $rb
    CheckWindowBounds;
    if {!$::BatchModeP} {
	ShowWavebar;
	if { ($::WindowLeftEdge <= $::NeighborhoodLeftEdge) || \
		 ($::WindowRightEdge >= $::NeighborhoodRightEdge)} {
	    SetNeighborhood;
	} else {
	    ShowNeighborhood;
	}
	UpdateLeftCut;
	UpdateRightCut;
	set Delta [expr $::SamplingRate * 0.001]
	if { abs($::WindowLeftEdge - $OldWLE) > $Delta} {
	    silence::UntagSilenceLeft;
	}
	if { abs($::WindowRightEdge - $OldWRE) > $Delta} {
	    silence::UntagSilenceRight;
	}
    }
    AnnounceWindowBounds;
    ScrollPrompterDisplay
    #AutoPlayWindow;
}

