			

				Tcl/Tk for XSPECT
MJF 3/01/99
    3/02/03
    1/02/04
    1/10/05
    1/11/13
	-----------------------------------------------------------------

tcl: 
	Tcl, which stands for Tool Command Language, is an open source
	scripting language similar to other modern script lanquages such
	as Perl or Python. It is substantially more powerful than
	UNIX shell script lanquages such as the
	Bourne Shell (sh), the C Shell (csh), or the Korn Shell (ksh).
	Tcl and its associated graphical user interface
	toolkit, Tk, were developed by John Ousterhout of the University
	of California. Ousterhout's group subsequently continued
	development of Tcl/Tk while at Sun Microsystems and at Scriptics
	(www.scriptics.com). The language has become extremely popular
	for developing applications with scripts and is available as
	public domain software for almost all computer systems
	(Linux, Windows and MacOS).

Installation:

	Software for free download can be found at:

		http://www.activestate.com/activetcl

	Binary Windows installers are available from this site
	for both 32 and 64 bit systems (Vers 8.5.13, 19-NOV-2012)
	as a Free Community Edition.

	Unless Tcl has already been installed on the system being used,
	download and install the software from ActiveState.
	The installer should be run with administrative privledges.
	On Windows7, you should right click and 'run as administrator.
	Installing with elevated priviledge will allow the registry
	changes that map .tcl extensions and will configure the
	uninstaller database, making removing ActiveTcl later on easier.

	The ActiveState default installation directory i C:/Tcl.
	During the installation, the installer will ask if you want
	this changed. I perfer installation in C:/Program Files/Tcl.
	Installing to this directory also requires elevated priviledge.
		Note: Tcl general uses a forward slash for paths
		      rather than the backward slash used in Windows.


Console interpreter:

	Unlike a programming lanquage, tcl interprets each command
	as it is issued. As such it can be used interactively from a
	console window much like csh in Unix or DOS commands in Windows.
	
	For Windows, executing tclsh or wish from the START menu will open
	a console window from which tcl or tcl/tk commands can be issued.
	Wish includes the tk commands that place widgets in a window frame.
	In general, it is best to always use the Wish interpreter.

	If a command is not a part of the tcl/tk command set but is a
	part of the system command set, the command will be executed.
	Thus the command dir for Windows will list the contents of the current
	directory.  Frequently, when working interactively in tclsh the
	cd command will be used to change directories.

	For tclsh, the '\' character is an escape character. Thus
	interpreting path strings such as C:\XIRL\mikef.. in windows
	is not possible. Tclsh interprets directory paths using the
	traditional Unix construction, C:/XIRL/mikef ...
	Alternatively the command;
		'file join dir1 dir2 dir3'
	will assemble the indicated directory names into the proper
	path expression for the operating system being used.

Scripts:

	As with other shell languages, tcl commands can be stored in a 
	file and executed as if the file was a program.  
	For the ActiveState windows installation,
	if the script file has an a .tcl extension it will
	be interpreted as tcl/tk commands when the file icon is executed.

	As an example, open a text editor (i.e. notepad, wordpad, emacs, ..)
	and enter two lines with:

		console show
		puts "hello myself"

	Using 'save as', save the file as temp.tcl.
	Now execute this file (double click). 
	You should see a small gray window that appears because the
        script interpreter included Tk graphic commands (ie. the Wish interpreter).
	You should also see a command window with 'Hellow Me' on the first
	line. This was output by the put string command, puts.
	At the command prompt that will end with %, type

		puts "hello you"

	and the interpreter will respons.
	Exit the application by closing the graphic Tk window.

	To permit execution on a Unix/Linux system with tcl/tk,
	the mode of the file must be changed
	using the command 'chmod 755 scriptfile'.
	The first line of the file should also have the
	path to the interpreter; 

		#!/usr/um/bin/wish

	Simply typing the filename of the script will then execute the 
	commands in the script.

Tcl commands:

	Commands in tcl will in general always have the following form;

		command arg1 arg2 arg3 ...

	where command is either one of the standard tcl commands or may
	be the name of a procedure defined in the script.
	White space separates the command name and its arguments
	and a newline or a semicolon is used to terminate the command.

	Tcl uses the pound character, #, for comments.
	The # specifically must appear at the beginning of a command;

		#this is a comment
		puts "hello myself" ;# a semicolon ends the line

Interactive tcl:

	For Unix systems, Tcl can be run interactively simply by typing
	tclsh at the normal command prompt.
	The system will respond with a modified
	prompt, usually the percent character, %,
	and the interpreter will be running in the same directory
	that the user was in when the command was given.

	For Windows systems, execute tclsh (or wish) from the START menu.
	A window will appear in which tcl (or tcl/tk) commands can be issued.
	The command window will start in the directory that the
	tclsh or wish program is installed (C:\Program Files\tcl\...).

	Any of the tcl commands can be issued for direct interpretation.
	In the following we will use a % when suggesting that
	commands be tested interactively.
	The interactive mode of tcl is often useful to test command
	constructions before entering them into an executable script.
 
Variables within scripts:

	Variables can be defined within a script and their value
	substituted as an argument in a command. To define the
	value of an argument;

		%set something  1.234

	The expression $something will then be replaced with 1.234 
	when used in a command line. For example,

		%set something  1.234
		%puts $something

	will print 1.234 on the screen. You will also notice that
	tcl echos the command result on the screen when running in
	the interactive mode.

Grouping:

	The concept of grouping is fundamental in the tcl language.
	Either {...} or "..." is used to group words together into
	one aguement that will be a part of a tcl command.
	The two forms of grouping behave differently with respect to
	the substitution of variables:

		{...} => no variable substitution in grouping words
		"..." => variables are subsituted in grouping words

	For example;

		%set something 1.234
		%puts "The value is $something"
		%puts {The value is $something}

	will be seen to produce different results.
	
	{...} expressions are often used as a part of control loops
	such as the if command where the bracketed argument may 
	contain many lines of commands. 
	"..." expressions are often used to prepare text strings for output.

	Another type of bracketed expression is of the form [...].
	In this case, the bracketed words are interpreted as a command
	and the expression [...] is replaced with the results of the
	command. For example;

		%set time [clock format [clock seconds] -format %T]
		%puts "The time is $time"

	The tcl clock command has several forms. [clock seconds] returns the
	number of seconds since a reference time. [clock format ..]
	formats the value in referenced seconds to a designated format.
	This example illustrates the nesting of executed commands.


Executing xspect programs within a script:

	The various programs in the xspect package for
	modeling x-ray systems are intended for use within scripts.
	In general, the arguments to a particular program can be
	passed to the program as a variable. For example, the program
	to generate an x-ray spectrum requires five values to be entered;

		set input "74  12  1 118 1.0 \n" 

	Since the program reads the five values from a line
	after the return key, a return is placed in the text string
	by using the \n at the end.

	The program can then be executed with the tcl exec command;

		set message [exec spect_gen << $input]

	Normally, the programs only return text if there is
	an error. Tcl provides a command to catch the text returned
	as a part of standard error reporting;

		if [catch {exec spect_gen << $input} result] {
        		puts stderr "ERROR in SPECT_GEN:\n $result"}

	In this example the logical value returned by the catch command
	is tested by the if command and if true an error message is
	printed with the text from the spect_gen program reported in $result.
	This construction will be used later to build scripts which
	execute the xspect routines.

Numeric expressions:

	To evaluate mathematical expressions, tcl supports a command
	called expr.  For this command all of the text following the
	command name is collected and passed to a special argument
	parser which interprets the mathematic instruction:

		%expr 8/4+5

	In this example, the text string 8/4+5 would normally be considered
	to be one argument to the command but the extra interpreter for
	the expr command evaluates the implied math expressions. 
	The math interpreter recognizes all common arithmetic operators
	as well as many standard function (sin(x), exp(x), pow(x,y) ...).
	For example,

		%set result [expr 1 + sin( exp(2) )]
		%puts "1 plus the sin of e^2 is $result"

	An effective math interpreter distinquishes tcl from many other
	shell script languages. The math functions recognized by expr
	are also implemented as a part of math function commands.

Loops within scripts:

	Several commands are available in tcl to produce looping
	in tcl scripts. The while, foreach, and for constructions 
	are considered below.

    The while command:

	The general form of the while command is;

		while booleanExpr body

	For example;

		set test 2.0
		while {$test <= 100.0} {
			set test [expr $test*2]
			puts $test
		} 

	Notice that the left bracket at the end of the first line and
	the right bracket in the fourth line form the "body" which is
	one argument value which contains multiple lines of code.
	The boolean expression supported
	are documented with the expr command.

    The foreach command:

	Another type of loop can be used to evaluate the body with
	a list of particular values. The general form of the command is

		foreach loopVar valueList body

	For example;

		foreach value {0.1 0.3 1.0 3.0 10.0 30.0 100.0} {
			set result [expr log10($value)]
			puts "$value $result"
		}

	The body appears similary in brackets, {...}. Note that the
	newline within the body that forms the multiple lines is ignored
	when using the curly brackets. When the body is read, substition
	with the value of arguements, arg, is not done when a $arg
	is encountered. However, when the body is executed as
	a part of the loop, the $arg substitutions are performed.

    The for command:

	Finally, the for command has the general form;

		for initial test final body

	For example;

		for {set i 1} {$i <= 15} {incr i 2} {
			puts $i
		}

Conditional execution of commands:

	The tcl script language includes conditional commands
	including if and switch. We note here only the general
	construction of an if command;

		if boolean body1 elseif body2 else body3

	For example;

		if {$flag == 1} {
			.
			.
		} elseif {$flag == 2} {
			.
			.
		} else {
			.
			.
		}

	Note that the syntax of the brackets on the lines with the elseif
	or the else must be maintained for proper interpretation of
	the body of commands within each section. Specifically, the newlines
	are all contained within the brackets of the bodies and thus
	the command appears as one line.
		
Opening a file for output:

	In tcl, a file is opened for output using a command that
	returns a file reference number;

		set fileID [open temp.dat RDWR]

	In this expression, w indicates that the file
	will be created or truncated if it already exists.
	Alternatively, a could be used to append new text to the file.
	The value returned by this command is assigned to the variable
	with the name fileID.

	The file opened by the above command will be created in the
	active directory that the interpreter is running in.
	Recall that for Windows, the interactive command window
	opens in the installation directory.
	Thus the directory needs to be changed (DOS cd command)
	or the full path to the file needs to be specified.

	Once the file is opened, lines may be written using the puts
	command.

		puts $fileID "$value $result"

	In this case, a line is written to the open file that was assigned
	the reference number in the variable fileID.
	The line will have the values of the two variables value and result.
	When all data has been written, the file should be closed.

		close $fileID

Programming with graphic commands:

	Tk extends the tcl language to include commands which can
	create a window with widgets on the screen.
	It is invoked by using the 'wish' interpreter that is the
	default for windows with the ActiveState installation.
	For Windows, the 'wish' interpreter can aslo be initiated
	as an interactive window using the Start menu.
	All of the tcl commands are included in the wish interpreter.
	To illustrate, start the wish interpreter in the start menu.
	A command prompt similar to tclsh should appear
	in a newly created small window.
	Then try the commands;

		%button .hello -text Hello -command {puts stdout "Hi user"}
		%button .quit  -text Quit  -command {destroy .}
		%pack .hello .quit -padx 20 -pady 20

	The tk command button creates button widgets that are referred to
        as .hello and .quit within subsequent tk commands.
        The tk command pack assembles widgets into a window.
        We will defer more detailed discussion of Tk in this document.
	For use of xSpect in the Windows environment, use of tk becomes
	a convenient way to enter variable values into a script and control
	operation.

Write an example script.

	As an example excercise, write a script for to generate a data file
	Open a file for output and use one of the loop constructions to
	generate a file with two columns of data with about a dozen rows.
	Assume that the first column is an independant variable
	and make the value of the second column a dependant value
	equal to the square of the value in the first column.
	The data written to this file can then be plotted
	using a program such as gnuplot.

Further information:

	On Windows systems with the ActiveState installation,
	a link to a tcl/tk help application will be found in the Start menu.
	When opened, first expand the "Active Tcl 8.5.13 Documentation Index".
	Most information of interest will then be in the "TclManual"
	and "Tk Manual" near the middle of the menu items.
	
	On Unix/Linus systems, most tcl installations will support man pages
	describing the execution of the interpreter ( man tclsh )
	as well as man pages for each of the commands.

	An excellant book by Brent B. Welch is now published in the
	fourth edition and covers both introductory as well as advanced
	aspects of the language;

		"Practical Programming in Tcl and Tk"
		ISBN 0-13-038560-3
		Fourth Edition, June, 2003
		www.beedub.com/book

