#!/bin/sh
# the next line restarts using wish \
exec wish c:/cygwin/bin/feaver_gui -- $*

# on PCs:
# adjust the first argument to wish above with the name and
# location of this tcl/tk file on your system, if different.
#
# Cygwin:
# if you use cygwin, do not refer to the file as /usr/bin/feaver
# /usr/bin is a symbolic link to /bin, which really
# lives in c:/cygwin, hence the contortions above
#
# on Unix/Linux/Solaris systems
# replace the first line with something like
#	#!/usr/bin/wish -f
# or
#	#!/opt/default/bin/wish8.3 -f
# using the pathname for the right wish executable on your system
#
# Also adjust some of the settings below if necessary.
#
#======================================================================#
# FeaVer User Interface, Gerard J. Holzmann and Margaret H. Smith      #
# Bell Laboratories, Lucent Technologies, Murray Hill, NJ 07974, USA.  #
# Copyright (c) 2000-2003 by Lucent Technologies. All Rights Reserved. #
# See the Documentation/feaver.pdf for usage.                          #
#======================================================================#

set xversion "1.0 -- 10 January 2003"

# Assumes Tcl/Tk version 8.3 and:
#	modex
#	spin
#	feaver_logo.gif
#	feaver.hlp
#	Unix:	rm,  cp, /lib/cpp
#	PCs:	cmd, cl or gcc

#include <tcl.h>
#include <X11\cursorfont.h>
#include <tk.h>

proc complain {txt} {
	catch { tk_messageBox -icon info -message "$txt" }
}

	if [info exists tcl_platform] {
		set sys $tcl_platform(platform)
		if {$sys == "windows"} {
			set Unix	0
			set idir	c:/cygwin/home/gerard/Tools_Verification/Modex/Commands
			set CPP		"cl /nologo /DMODEX /EP"	;# MS Visual Studio
			set CC		cl

			if {$tcl_platform(os) == "Windows 95"} {
				set CMD  "command.com"	;# Windows95
			} else {
				set CMD  "cmd"		;# WindowsNT,XP
			}
			if {[auto_execok cl] == ""  \
			||  [auto_execok cl] == 0  \
			} {
				set CPP "gcc -DMODEX -E -P"	;# use gcc instead
				set CC	gcc
			}
		} else {
			set Unix	1			;# assume Unix
			set idir	/usr/gerard/bin/fv	;# for feaver.hlp and feaver_logo.gif
			set CPP		"/lib/cpp -DMODEX -E -P"
			set CC		"/lib/cpp"
		}
	} else {
		complain "cannot determine tcl_platform"
		exit 1
	}

set work_dir	[pwd]		;# root directory of prx and vip files
set MODEX	modex
set SPIN	spin
set helpfile	$idir/feaver.hlp
set logo	$idir/feaver_logo.gif

	if {[auto_execok $MODEX] == "" \
	||  [auto_execok $MODEX] == 0  \
	} {	set msg "Error: cannot find $MODEX ..."
		complain $msg
		exit 1
	}
	if {[auto_execok $SPIN] == "" \
	||  [auto_execok $SPIN] == 0  \
	} {	set msg "Error: cannot find $SPIN ..."
		complain $msg
		exit 1
	}
	if {[auto_execok $CC] == "" \
	||  [auto_execok $CC] == 0  \
	} {	set msg "Error: cannot find $CC ..."
		complain $msg
		exit 1
	}

	event add <<Cut>> <Control-Key-x> <Shift-Key-Delete>
	event add <<Copy>> <Control-Key-c> <Control-Key-Insert>
	event add <<Paste>> <Control-Key-v> <Shift-Key-Insert>
	event add <<Cut>>   <Control-Key-x> <Key-F2>
	event add <<Copy>>  <Control-Key-c> <Key-F3>
	event add <<Paste>> <Control-Key-v> <Key-F4>


set textFont	"-*-Helvetica-Bold-R-Normal-*-*-160-*"
set bigFont	"-*-Helvetica-Bold-R-Normal-*-*-220-*"
set smallFont	"-*-Helvetica-Bold-R-Normal-*-*-110-*"

#### start of combobox.tcl

#------------------------------------
# util.tcl --
#
#	This file contains several utility procedures used by
#	the two library. Only part of these are imported
#	into the global namespace.
#
# Copyright (c) 1998 Frank J. Leitner
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Header: /home/ldv/cvs/two/lib/util.tcl,v 1.35 1999/12/08 15:10:22 fjl Exp $

package provide twoUtil 1.0

# Workaround: Tk needs this procedure for tk_messageBox
# but won't load it form inside a namespace (bug in tcl8.0 up to p1)
catch {auto_load tkMessageBox}

namespace eval ::two::util {
    namespace export two_*
    variable Util
    
    # variable Util
    #
    # clipboard -	Contents of replacement clipboard for two_noImportExport
    # PWD -		Current working directory for two_kshPwd
    # OLDPWD -	Previous working directory dor two_kshPwd
}

# ::two::util::two_parseArgs --
#
#	This procedures extracts an argument "arg" and a value
#	from "arg_list", removing both argument and value. The value
#	is stored in "val".
#
# Arguments:
#
#	argsListName	Call by Reference; name of tcl list with arguments
#	valName		Call by Reference; name of variable; takes the value
#	arg		The Argument to be extracted
#
# Results:
#	1 if "arg" was found in "arg_list", otherwise 0.

proc ::two::util::two_parseArgs {argsListName valName arg} {
    upvar $argsListName argsList
    upvar $valName val

    set pos [lsearch -exact $argsList $arg]
    set end [lsearch -exact $argsList "--"]
    if {$pos >= 0 && ($end < 0 || $pos < $end)} {
        set valpos [expr {$pos +1}]
        set val [lindex $argsList $valpos]
        set argsList [lreplace $argsList $pos $valpos]
	return 1
    }
    return 0
}

# ::two::util::two_parseMultiArgs --
#
#	This procedures examines a list of arguments (option-value pairs)
#	which were used when calling a procedure. All arguments whose
#	names are contained as keys in the specsArray will be removed. The
#	value of the specsArray is the name of a variable which should take
#	the value which is associated with the option.
#
# Arguments:
#
#	specsArrayName	Name of Array which should contain the specs for the
#			options
#	argsListName	Name of List of Arguments which should be processed
#
# Results:
#	List of all options which have been eaten by this proc.
#
# Side effects:
#	Modifies the contents of $argsListName.

proc ::two::util::two_parseMultiArgs {specsArrayName argsListName} {
    upvar $specsArrayName specsArray
    upvar $argsListName   argsList

    # will contain all options which have not been eaten by this proc
    set remaining ""
    # will contain the names all options that matched the description
    set matched ""

    # loop through all options, but break at "--"
    set length [llength $argsList]
    for {set idx 0} {$idx < $length} {incr idx} {
        set arg [lindex $argsList $idx]
	if {[string match "--" $arg]} {
	    eval lappend remaining [lrange $argsList $idx end]
	    break
	}
        if {[info exists specsArray($arg)]} {
	    lappend matched $arg
	    set next [lindex $argsList [incr idx]]
            uplevel [list set $specsArray($arg) $next]
	} else {
	    lappend remaining $arg
	}
    }
    set argsList $remaining
    return $matched
}

# ::two::util::two_getOpt --
#
#	Searches the database much the same way the "option get"
#	does. The return value is set to $default if the option
#	get command returns an empty string.
#
# Arguments:
#	w		Widget path
#	name		Name of option to te queried
#	class		Option class
#	default		Default value (if "option get" returns empty value)
#
# Results:
#	The option or the default value.

proc ::two::util::two_getOpt {w name class default} {
    set retval [option get $w $name $class]
    if {![string length $retval]} {
        set retval $default
    }
    return $retval
}

# ::two::util::two_noExportImport --
#
#	Disables all copying to and from the application. Disabling the
#	export function is easy through "exportSelection none", but
#	importing the seletion is a bit trickier. It is achieved here
#	through replacing the "selection" and "clipboard" commands.
#	Caveat: You'll have to call this function before instantiating
#	any widget in order to make the "option add" work.
#
# Side Effects:
#	Replaces the tcl clipboard and selection procedures with
#	fake ones. Those replacements intentinally do only work
#	within the application.

proc ::two::util::two_noExportImport {} {
    variable Util
   
    set Util(clipboard) ""

    # No exportSelection
    option add *exportSelection  false  100

    # Install our replacement commands
    proc ::selection {opt args} "
	return \[uplevel [namespace code FakeSelection] \$opt \$args \]
    "
    proc ::clipboard {opt args} "
	uplevel [namespace code FakeClipboard] \$opt \$args
    "
    return
}

# ::two::util::FakeSelection --
#
#	This is a replacement for the standard tk selection command.
#	See two_noExportImport

proc ::two::util::FakeSelection {opt args} {
    variable Util

    switch $opt {
        clear {
	    set Util(clipboard) ""
	}
        get {
	    return $Util(clipboard)
	}
    }
    return
}

# ::two::util::FakeClipboard --
#
#	This is a replacement for the standard tk clipboard command.
#	See two_noExportImport

proc ::two::util::FakeClipboard {opt args} {
    variable Util

    switch $opt {
        clear {
	    set Util(clipboard) ""
	}
        append {
	    while {[llength $args]} {
	        switch -glob -- [lindex $args 0] {
	            -- {
			append Util(clipboard) [join [lrange $args 1 end] ""]
			set args ""
		    }
		    -* {
			set args [lrange $args 2 end]
		    }
		    default {
			append Util(clipboard) [join $args ""]
			set args ""
		    }
		}
	    }
	}
	default {
	    return -code error "wrong # args: should be \"clipboard option ?arg arg ...?\""
	}
    }
    return
}

# ::two::util::two_kshPwd --
#
#	Workaround for pwd: don't show /tmp_mnt/....
#	This happens on systems using the automounter, which mounts file-
#	systems in /tmp_mnt/ and puts symlinks in place. The problem here
#	is that accessing a path through /tmp_mnt/ will not re-mount the
#	filesystem, and the tcl cd/pwd combination will always show this
#	/tmp_mnt/ path (e.g. in tk_getOpenFile).
#	This implementation behaves much like the Korn shell: whenever you
#	cd into a directory through symlinks it will remember the route
#	you took. Using "cd .." will go up one level in your route, i.e.
#	remove the last part of the pathname, and not go up to the "real"
#	parent directory. Please note that different UNIX shells behave
#	differently in this respect.
#
# Side effects:
#	The tcl cd and pwd commands are renamed into the current namespace
#	and wrapped with a replacement function.

proc ::two::util::two_kshPwd {} {
    variable Util
    global tcl_platform

    if {[info exists Util(PWD)]} {
        return -code error "two_kshPwd has already been installed!"
    }

    if {[string match "unix" $tcl_platform(platform)]} {
	set Util(PWD)    [exec /bin/ksh -c "pwd"]
	set Util(OLDPWD) $Util(PWD)
	rename ::pwd _origPwd
	rename ::cd  _origCd
	proc ::pwd {} [namespace code {
	    return $Util(PWD)
	}]
	proc ::cd {args} "
	    return \[uplevel [namespace code KshCd] \$args\]
	"
    }
    return
}

# ::two::util::KshCd --
#
#	This is a replacement for the standard tk cd command.
#	See two_kshPwd

proc ::two::util::KshCd {{dir ""}} {
    variable Util
    global errorCode

    # special handling for "cd" and "cd -"
    if {![string length $dir]} {
        set dir ~
    } elseif {[string match "-" $dir]} {
        set dir $Util(OLDPWD)
    }

    # tilde substitution
    if {[string match "absolute" [file pathtype $dir]]} {
        set dir [file nativename $dir]
    }

    # calculate name of target directory
    set lpwd [file split $Util(PWD)]
    foreach part [file split $dir] {
        switch -- $part {
            . {
            }
            .. {
                set lpwd [lreplace $lpwd end end]
            }
            default {
                lappend lpwd $part
            }
        }
    }
    if {[llength $lpwd]} {
        set dir [eval file join $lpwd]
    } else {
        set dir [file nativename /]
    }

    # try to change current directory to the target
    if {[set _origCdRetCode [catch {_origCd $dir} _origCdRetVal]]} {
        return -code $_origCdRetCode -errorcode $errorCode $_origCdRetVal
    }

    # cd succeeded; update state
    set Util(OLDPWD) $Util(PWD) 
    set Util(PWD)    $dir
    return $_origCdRetVal
}

# ::two::util::two_invoke --
#
#	Visually invoke button or set focus to next widget if this function
#	is used on a label.
#
# Arguments:
#	w		Widget path to button
#
# Side effects:
#	The button is flashed and the invoked, or the focus is set to the
#	next widget.

proc ::two::util::two_invoke {w} {
    switch -exact -- [winfo class $w] {
	Button {
	    if {![string match "disabled" [$w cget -state]]} {
    		$w configure -state active -relief sunken
    		update idletasks
    		after 100
    		$w configure -state normal -relief raised
		$w invoke
	    }
	}
	Label {
	    set next [tk_focusNext $w]
	    if {[string match Entry [winfo class $next]]} {
		$next selection range 0 end
		$next icursor end
	    }
	    focus $next
	}
	default {
            $w invoke
	}
    }
    return
}

# ::two::util::two_push --
#
#	Push value on stack. Stack is a tcl list. Returns value.
#
# Arguments:
#	stackName	Name of TCL list variable
#	value		Value to be pushed on the stack
#
# Results:
#	The element which is pushed on the stack is returned as well.


proc ::two::util::two_push {stackName value} {
    upvar 1 $stackName stack

    lappend stack $value
    return $value
}

# ::two::util::two_pop --
#
#	Take topmost value from on stack. Stack is a tcl list. Returns value.
#
# Arguments:
#	stackName	Name of TCL list variable
#
# Results:
#	The topmost element is returned.

proc ::two::util::two_pop {stackName} {
    upvar 1 $stackName stack
    
    if {![info exists stack]} {
        return {}
    }
    set value [lindex $stack end]
    set stack [lreplace $stack end end]
    return $value
}

# ::two::util::two_now --
#
#	returns current time as formatted string
#
# Results:
#	the current time...

proc ::two::util::two_now {} {
    return [clock format [clock seconds]]
}

# ::two::util::two_ct --
#
#	returns the current toplevel, i.e. the toplevel which
#	currently contains the focus. If the application doesn't
#	have the focus, "." is returned
#
# Results:
#	A widget path

proc ::two::util::two_ct {} {
    set f [focus]
    if {[string length $f]} {
        return [winfo toplevel $f]
    } else {
        return "."
    }
}

# ::two::util::two_mb --
#
# thin wrapper around tk_messageBox which sets the parent widget to [two_ct]
#
# Arguments:
#	See man page

proc ::two::util::two_mb {args} {
    if {![two_parseArgs args p "-parent"] && ![two_parseArgs args p "-p"]} {
        set p [two_ct]
    }
    return [uplevel tk_messageBox -parent $p $args]
}

# ::two::util::two_center --
#
#	center widget w on top of parent p

proc ::two::util::two_center {w {p ""}} {
    wm withdraw  $w
    if {[string length $p]} {
        set p [winfo toplevel $p]
        wm deiconify $p
    } else {
        set p .
    }
    # center on screen
    update idletasks
    set rw [winfo reqwidth  $w]
    if {[winfo width $w] > $rw} {
        set rw [winfo width $w]
    }
    set rh [winfo reqheight $w]
    if {[winfo height $w] > $rh} {
        set rh [winfo height $w]
    }
    set x [expr {[winfo screenwidth  $p]/2 - $rw/2 - [winfo vrootx $p]}]
    set y [expr {[winfo screenheight $p]/2 - $rh/2 - [winfo vrooty $p]}]
    wm geom      $w ${rw}x${rh}+$x+$y
    wm deiconify $w
    return
}

# ::two::util::two_show --
#
#	show window w (i.e. raise/deiconify/show centered)

proc ::two::util::two_showCenter {w {p ""}} {

    if {[winfo ismapped $w]} {
        raise $w
    } elseif {[string match "iconic" [wm state $w]]} {
        wm deiconify $w
    } else {
        two_center $w $p
    }
    return
}

# ::two::util::two_busy
#
#	block interaction with a toplevel and show a "watch" cursor.
#	This function uses a transparent frame which is placed on
#	top of the toplevel widget.
#
# Know Bug:
#	Transparent frames don't propagate redraw events, so the
#	underlying widgets don't repaint at all. Looks like a
#	blocked application. Won't make any difference if your
#	app really blocks, but if it doesn't... it's ugly.
#
# Arguments:
#	busy		True to make the toplevels busy, false to
#			remove the busy cursor.
#	args		List of Paths to widgets which should be
#			disabled (preferrably toplevels)

proc ::two::util::two_busy {busy args} {
    foreach w $args {
        if {[string compare "." $w] == 0} {
            set f .twoBusyCursorFrame
        } else {
            set f $w.twoBusyCursorFrame
        }
        if {$busy} {
            if {[winfo exists $f]} {
                raise $f
            } else {
                frame $f -background {} -borderwidth 0 -cursor watch
                place $f -x 0 -y 0 -relwidth 1 -relheight 1
            }
        } else {
            if {[winfo exists $f]} {
                destroy $f
            }
        }
    }
    update idletasks
}


# ::two::util::two_readFile --
#
#	Read a given a file and return it's contents. This proc
#	combines the open, read and close calls into one short
#	procedure; errors are "forwarded" (use catch...). One
#	other thing that is handled within this proc is the
#	possibility of slow automounters etc. making an open
#	command fail. In any case, the open is tried twice
#	withing 200 ms.
#
# Arguments:
#	args		?-nonewline? ?-binary? fname
#
# Returns:
#	The contents of this file

proc ::two::util::two_readFile {args} {
    global errorCode

    # parse options
    set fname [lindex $args end]
    set nonewline 0
    set bin 0
    set opts [lreplace $args end end]
    foreach opt $opts {
        switch -exact -- $opt {
            -nonewline {
                set nonewline 1
            }
            -binary {
                set bin 1
            }
            default {
                return -code error "unknown option \"$opt\": must be -nonewline or -binary"
            }
        }
    }

    # Open file: try twice
    set err [catch {set fid [open $fname]}]
    if {$err} {
        # didn't work... try again after 200 ms to work around slow automounter
	after 200
        set err [catch {set fid [open $fname]} errorMsg]
        if {$err} {
            # second try failed as well
            return -code $err -errorcode $errorCode $errorMsg
        }
    }

    # read the file
    # Improve performance: TCL's default buffer size is 4096 and this is used
    # to read the file in "slices" and append them to the txt variable. There
    # are two methods to optimize this: set buffersize to something larger
    # (but it needs to be smaller than 1,000,000), e.g. 2^18, or use the real
    # size of the file as parameter to the open command (only available if
    # -nonewline ain't specified). Timing on a HP C160 (HP-UX 10.20) with two
    # large files (/stand/vmunix: ~6M, /opt/aCC/lib/lib++.a ~1M) reveal:
    #                   6M       1M
    # plain:      64058498  1744060
    # fconfigure:  2661062   151780
    # file size:    794698   115280
    if {$bin} {
        fconfigure $fid -translation binary
    }
    if {$nonewline} {
        fconfigure $fid -buffersize 262144
        set err [catch {set txt [read -nonewline $fid]} errorMsg]
    } else {
        set err [catch {set fs [file size $fname]} errorMsg]
        if {! $err} {
            set err [catch {set txt [read $fid $fs]} errorMsg]
        }
    }
    
    # closing should always work
    close $fid
    # handle error from above (reading file)
    if {$err} {
        return -code $err -errorcode $errorCode $errorMsg
    }
    
    # usually you would insert "return $txt" at this palce, but the following
    # should be faster (said to be due to less error checking?)
    set txt
}

namespace import ::two::util::two_noExportImport
namespace import ::two::util::two_kshPwd
namespace import ::two::util::two_invoke
namespace import ::two::util::two_ct
namespace import ::two::util::two_mb
namespace import ::two::util::two_center
namespace import ::two::util::two_showCenter
namespace import ::two::util::two_busy
namespace import ::two::util::two_readFile

# end of util.tcl --
#------------------------------------

#------------------------------------
# autosb.tcl --
#
#	Automatic scrollbar. Behaves like a regular scrollbar, but
#	disappears if not needed.
#
# Copyright (c) 1998 Frank J. Leitner
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Header: /home/ldv/cvs/two/lib/autosb.tcl,v 1.19 1999/10/26 13:12:13 fjl Exp $

package provide twoAutosb 1.0
package require twoUtil

option add *TwoAutoSb.borderWidth 0 widgetDefault
option add *TwoAutoSb.takeFocus   0 widgetDefault

namespace eval ::two::autosb {
    namespace export two_autosb
    variable Autosb
    
    # variable Autosb
    #
    # $w,shown -	true if scrollbar is on
    # $w,blockS -	true if scrollbar has recently been added and should
    #		stay the same for some time to avoid flicker
    # $w,blockH -	dito for recently hidden scrollbar
}

# ::two::autosb::two_autosb --
#
#	Create widget, parse arguments and install our own widget procedure.
#	The real widget is "$w" (like ".tl.sb"); the original widget procedure
#	is renamed to "_two$w" (like "_cb.tl.sb") and a call to "widget"
#	is put in place. "widget" will extract all additional options and
#	subsequently call "_two$w" with the remaining options.
#
# Arguments:
#	w		Widget path
#	args		Widget arguments and options

proc ::two::autosb::two_autosb {w args} {
    variable Autosb

    # Initialise the globals
    array set Autosb [list \
        $w,shown  0 \
        $w,blockS 0 \
        $w,blockH 0 \
    ]

    # Container frame
    frame $w -class TwoAutoSb

    # the original scrollbar
    uplevel [list scrollbar $w.sb] $args
    
    # Move widget command
    rename $w _two$w

    # Install our replacement command
    namespace eval :: "
        proc $w {opt args} {
	    uplevel [namespace code Widget] $w \$opt \$args
	}
    "
    
    # catch widget destruction in order to clean up Autosb
    bind $w <Destroy> [namespace code "_Destroy $w"]

    # Return the correct result...
    return $w
}

# ::two::autosb::Widget --
#
#	replacement for widget command.
#	One tricky part here is that we block changes in the state
#	of the autosb (i.e. show/hide) for 200 ms after each change.
#	This is needed e.g. for horizintal scrollbars in text widgets:
#	Take a horizontal scrollbar whose heigth is at least that of
#	a text line, so showing the scrollbar will cover the bottom
#	visible line. Make this bottom line the only one which is
#	long enough to require a horizontal scrollbar. So, showing
#	the scrollbar removes the need for a scrollbar, and making it
#	disappear again creates the need for a scrollbar. Bummer -
#	infinit flicker. The 200 ms blocking time is just a wild
#	guess, on a very slow machine (or slow X connection, maybe
#	with -sync) this might not work. But in those cases the whole
#	application would be ratther "jumpy".
#
# Arguments:
#	w		Path to real widget
#	opt		Widget command...
#	args		optional args

proc ::two::autosb::Widget {w opt args} {
    variable Autosb

    # See if this option is for us...
    if {[string match "set" $opt] && [llength $args] == 2} {
	set off [expr {[lindex $args 0] == 0 && [lindex $args 1] == 1}]
	if {$off && $Autosb($w,shown) && !$Autosb($w,blockS)} {
	    pack forget $w.sb
	    _two$w configure -width 1 -height 1
	    set Autosb($w,shown)  0
	    set Autosb($w,blockS) 1
	    after 200 [list set [namespace current]::Autosb($w,blockS) 0]
	} elseif {!$off && !$Autosb($w,shown) && !$Autosb($w,blockH)} {
	    pack $w.sb -fill both -expand 1
	    set Autosb($w,shown)  1
	    set Autosb($w,blockH) 1
	    after 200 [list set [namespace current]::Autosb($w,blockH) 0]
	}
    }
    return [uplevel [list $w.sb $opt] $args]
}

# ::two::autosb::_Destroy --
#
#	Call this procedure when the autosb widget is destroyed.
#	Will destroy the original widget command.
#
# Arguments:
#	w		Path to Widget

proc ::two::autosb::_Destroy {w} {
    variable Autosb

    # clear Autosb
    foreach key [array names Autosb "$w,*"] {
        unset Autosb($key)
    }
    # remove the original widget command
    rename $w ""
    return
}

namespace import ::two::autosb::*

# end of autosb.tcl --
#------------------------------------

#------------------------------------
# combobox.tcl --
#
#	Combobox widget. A combobox is like an editable option menu.
#	Consists of an entry, a button and a dropdown list.
#
# Copyright (c) 1998, 1999 Frank J. Leitner
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Header: /home/ldv/cvs/two/lib/combobox.tcl,v 1.43 2000/01/13 14:51:18 fjl Exp $

package provide twoCombobox 1.0
package require twoUtil
package require twoAutosb

option add *TwoComboBox.borderWidth               2       widgetDefault
option add *TwoComboBox.drop.borderWidth          0
option add *TwoComboBox.drop.highlightThickness   1
option add *TwoComboBox.drop.highlightColor       black
option add *TwoComboBox.drop.relief               flat
option add *TwoComboBox.relief                    sunken  widgetDefault
option add *TwoComboBox.Button.highlightThickness 1
option add *TwoComboBox.Entry.borderWidth         0

# Workaround: Tk needs these procedures for focus traversion
# but won't load it form inside the namespace (bug in tcl8.0 up to p1)
catch {auto_load tk_focusNext}
catch {auto_load tk_focusPrev}

namespace eval ::two::combobox {
    namespace export two_combobox
    variable Combobox
    
    namespace import ::two::util::two_parseArgs
    
    # variable Combobox
    #
    # current -	path to currently opened combobox
    # buttonPress -	remember if buttonPress-1 has happend after opening drop
    # $w,command -	command that will be executed when opening the combobox
    # $w,state -	current state {normal|fixed|disabled}
    # $w,takefocus - should the combobox take part in keyboard focus traversal?
    # $w,style -	look of the combobox {windows|unix}
    
    array set Combobox {
        Drag	0
        buttonPress 0
        current	""
    }
}

image create bitmap comboBoxArrowWin -data {
\#define cbwin_width 9
\#define cbwin_height 10
static unsigned char cbwin_bits[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x7c, 0x00, 0x38, 0x00,
  0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
}

image create bitmap comboBoxArrowX -data {
\#define cbarrow_width 9
\#define cbarrow_height 12
static unsigned char cbarrow_bits[] = {
  0x38, 0x00, 0x38, 0x00, 0x38, 0x00, 0x38, 0x00, 0xff, 0x01, 0xfe, 0x00,
  0x7c, 0x00, 0x38, 0x00, 0x10, 0x00, 0x00, 0x00, 0xff, 0x01, 0xff, 0x01,
  };
}

# ::two::combobox::two_combobox --
#
#	Create widget, parse arguments and install our own widget procedure.
#	The real widget is "$w" (like ".tl.cb"); the original widget procedure
#	is renamed to "_two$w" (like "_two.tl.cb") and a call to "widget"
#	is put in place. "widget" will extract all additional options and
#	subsequently call "_two$w" with the remaining options.
#	combobox creates a toplevel widget "$w.drop" for the drop box.
#	Arguments are passed to entry widget.
#
# Arguments:
#	w		Widget path
#	args		Widget arguments and options

proc ::two::combobox::two_combobox {w args} {
    variable Combobox
    global tcl_platform

    # Initialise the globals
    array set Combobox "
	$w,command  {}
	$w,state    normal
	$w,style    $tcl_platform(platform)
	$w,takefocus 1
	$w,insertentrycommand  {}
    "
    
    # This is a multi-style widget
    set ::two::SetStyleCmds($w) [list $w configure -style]

    # See if this option is for us...
    two_parseArgs args Combobox($w,command)   "-command"
    two_parseArgs args Combobox($w,state)     "-state"
    two_parseArgs args Combobox($w,style)     "-style"
    two_parseArgs args Combobox($w,takefocus) "-takefocus"
    two_parseArgs args Combobox($w,insertentrycommand)   "-insertentrycommand"

    # Container frame
    frame $w -class TwoComboBox
    set tl [winfo toplevel $w]
    uplevel [list entry $w.entry] $args
    if {![string match "unix" $Combobox($w,style)]} {
        button $w.button -image comboBoxArrowWin
    } else {
        button $w.button -image comboBoxArrowX
    }
    switch -exact -- $Combobox($w,state) {
	fixed {
            $w.entry configure  -state "disabled"
	    $w.button configure -takefocus $Combobox($w,takefocus)
	}
	disabled {
            $w.entry  configure -state "disabled"
            $w.button configure -state "disabled"
	}
	normal -
	default {
            $w.entry  configure -takefocus $Combobox($w,takefocus)
	    $w.button configure -takefocus 0
	}
    }
    pack $w.button -fill both -side right
    pack $w.entry -expand true -fill both -side left
    # Use our own bindings
    bindtags $w.entry  [list $w.entry  TwoComboBoxEntry  Entry $tl all]
    bindtags $w.button [list $w.button TwoComboBoxButton       $tl all]

    # Accompaining dropdown (toplevel widget)
    set d $w.drop
    toplevel $d -class TwoComboBox
    wm withdraw $d
    wm overrideredirect $d 1
    two_autosb $d.sx -command [list $d.lb xview] -orient horizontal
    two_autosb $d.sy -command [list $d.lb yview]
    listbox $d.lb -exportselection 0 -bd 0 \
        -xscrollcommand [list $d.sx set] \
        -yscrollcommand [list $d.sy set]
    frame $d.handle -height 4 -cursor bottom_side -bd 0

    grid $d.lb $d.sy -sticky nsew
    grid $d.sx       -sticky ew
    grid $d.handle   -sticky ew -columnspan 2
    grid rowconfigure    $d 0 -weight 1
    grid columnconfigure $d 0 -weight 1

    # Use our own bindings
    # Caveat: combobox bindings have to appear after normal widget bindings
    bindtags $d.lb [list $d.lb Listbox TwoComboBoxList TwoComboBox $tl all]
    # Handle for drop down list uses only its own bindings
    bindtags $d.handle [list $d.handle TwoComboBoxHandle $tl all]

    # Move widget command
    rename $w _two$w

    # Install our replacement command
    namespace eval :: "
        proc $w {opt args} {
	    uplevel [namespace code Widget] $w \$opt \$args
	}
    "
    
    # catch widget destruction in order to clean up Combobox
    bind $w <Destroy> [namespace code "_Destroy $w"]

    # Return the correct result...
    return $w
}

# ::two::combobox::Widget --
#
#	replacement for widget command
#
# Arguments:
#	w		Path to real widget
#	opt		Widget command...
#	args		optional args

proc ::two::combobox::Widget {w opt args} {
    variable Combobox

    # See if this option is for us...
    switch -exact -- $opt {
	configure {
	    two_parseArgs args Combobox($w,command)   "-command"
	    two_parseArgs args Combobox($w,state)     "-state"
	    two_parseArgs args Combobox($w,takefocus) "-takefocus"
	    switch -exact -- $Combobox($w,state) {
		fixed {
        	    $w.entry  configure -state "disabled" -takefocus 0
        	    $w.button configure -state "normal"   -takefocus $Combobox($w,takefocus)
		}
		disabled {
        	    $w.entry  configure -state "disabled" -takefocus 0
        	    $w.button configure -state "disabled" -takefocus 0
		}
		normal -
	        default {
        	    $w.entry  configure -state "normal" -takefocus $Combobox($w,takefocus)
        	    $w.button configure -state "normal" -takefocus 0
		}
	    }
	    if {[two_parseArgs args Combobox($w,style) "-style"]} {
		if {![string match "unix" $Combobox($w,style)]} {
		    $w.button configure -image comboBoxArrowWin
		} else {
		    $w.button configure -image comboBoxArrowX
		}
	    }

	    if {[llength $args]} {
		return [eval [list _two$w $opt] $args]
	    }
	}
	cget {
	    switch -exact -- $args {
	        -command { return $Combobox($w,command) }
	        -state   { return $Combobox($w,state)   }
	        -style   { return $Combobox($w,style)   }
		default  { return [eval [list _two$w $opt] $args] }
	    }
	}
	setFocus {
	    switch -exact -- $Combobox($w,state) {
		fixed {
		    focus $w.button
		}
		disabled {
		    focus $w
		}
		normal -
	        default {
        	    focus $w.entry
		}
	    }
	}
	get {
	    return [$w.entry get]
	}
	set {
    	    set state [$w.entry cget -state]
	    $w.entry configure -state normal
	    $w.entry delete 0 end
	    $w.entry insert 0 [lindex $args 0]
	    $w.entry configure -state $state
	}
	setlist {
	    $w.drop.lb delete 0 end
	    eval [list $w.drop.lb insert end] $args
	}
	getlist {
	    return [$w.drop.lb get 0 end]
	}
	add {
	    eval [list $w.drop.lb insert end] $args
	}
	open {
	    Open $w
	}
	entry {
	    return $w.entry
	}
	listbox {
	    return $w.drop.lb
	}
	default {
            return [eval [list _two$w $opt] $args]
	}
    }
    return
}

# ::two::combobox::_Destroy --
#
#	Call this procedure when the combobox widget is destroyed.
#	Will clean widget-specific Elements of Combobox.
#
# Arguments:
#	w		Path to Widget

proc ::two::combobox::_Destroy {w} {
    variable Combobox

    unset ::two::SetStyleCmds($w)

    # clear Combobox
    foreach key [array names Combobox "$w,*"] {
        unset Combobox($key)
    }
    # remove the original widget command
    rename $w ""
    return
}

#-------------------------------------------------------------------------
# The code below creates the TwoComboBox-class bindings
#-------------------------------------------------------------------------

# Entry widget in combobox

bind TwoComboBoxEntry <1> {
    if {[string match "fixed" $::two::combobox::Combobox([winfo parent %W],state)]} {
        ::two::combobox::Open [winfo parent %W]
    }
}
bind TwoComboBoxEntry <Next> {
    ::two::combobox::Open [winfo parent %W]
}

# drop down button

bind TwoComboBoxButton <1> {
    if {![string match "disabled" [%W cget -state]]} {
        %W configure -relief sunken
        ::two::combobox::Open [winfo parent %W]
        set ::two::combobox::Combobox(buttonPress) 0
    }
}
bind TwoComboBoxButton <space> {
    %W configure -relief sunken
    ::two::combobox::Open [winfo parent %W]
    set ::two::combobox::Combobox(buttonPress) 0
}
bind TwoComboBoxButton <Next> {
    %W configure -relief sunken
    ::two::combobox::Open [winfo parent %W]
    set ::two::combobox::Combobox(buttonPress) 0
}
bind TwoComboBoxButton <Enter> {
    if {![string match "disabled" [%W cget -state]]} {
        %W configure -state active
    }
}
bind TwoComboBoxButton <Leave> {
    if {![string match "disabled" [%W cget -state]]} {
        %W configure -state normal
    }
}

# Listbox widget in dropped down combobox

bind TwoComboBoxList <Return> {
    ::two::combobox::Close $::two::combobox::Combobox(current)
    break
}
bind TwoComboBoxList <Escape> {
    %W selection clear 0 end
    ::two::combobox::Close $::two::combobox::Combobox(current)
    break
}

# Handle for resizing drop-down list

bind TwoComboBoxHandle <Enter> {
    ::two::combobox::HandleMotion %W %x
}
bind TwoComboBoxHandle <Motion> {
    ::two::combobox::HandleMotion %W %x
}
bind TwoComboBoxHandle <1> {
    ::two::combobox::HandleB1 %W %x %y
}
bind TwoComboBoxHandle <ButtonRelease-1> {
    set ::two::combobox::Combobox(Drag) 0
}

bind TwoComboBoxHandle <B1-Motion> {
    ::two::combobox::HandleB1Motion %W %x %X %y %Y
}

# Bindings to the frames only trigger when the listbox is
# opened (dropped down)

bind TwoComboBox <ButtonPress> {
    set w [winfo containing [winfo pointerx .] [winfo pointery .]]
    if {[string match $w $::two::combobox::Combobox(current).button]} {
        set ::two::combobox::Combobox(buttonPress) 1
    }
}
bind TwoComboBox <ButtonRelease-1> {
    set w [winfo containing [winfo pointerx .] [winfo pointery .]]
    if {$::two::combobox::Combobox(buttonPress) ||
        ![string match $w $::two::combobox::Combobox(current).button]} {
        if {[winfo exists $::two::combobox::Combobox(current)]} {
            ::two::combobox::Close $::two::combobox::Combobox(current)
        }
    }
}

#-------------------------------------------------------------------------
# Helper functions
#-------------------------------------------------------------------------

# ::two::combobox::HandleMotion --
#
#	handle mouse cursor motion events within handle frame. Set
#	the mouse cursor shape according to the relative position.
#
# Arguments:
#	h		Path to handle
#	x		relative X Position of mouse cursor within handle (%x)

proc ::two::combobox::HandleMotion {h x} {
    variable Combobox

    if {!$Combobox(Drag)} {
        if {$x > [winfo width $h] - 10} {
            $h configure -cursor bottom_right_corner
        } elseif {$x < 10} {
            $h configure -cursor bottom_left_corner
        } else {
            $h configure -cursor bottom_side
        }
    }
    return
}

# ::two::combobox::HandleB1 --
#
#	handle mosue button press within within handle frame.
#
# Arguments:
#	h		Path to handle
#	x		relative X Position of mouse cursor within handle (%x)
#	y		relative Y Position (%y)

proc ::two::combobox::HandleB1 {h x y} {
    variable Combobox

    set p [winfo toplevel $h]
    set ht [$p cget -highlightthickness]
    set Combobox(Drag) 1
    set Combobox(Cursor) [$h cget -cursor]
    set Combobox(dxl) [expr {$x + $ht}]
    set Combobox(dxr) [expr {[winfo width  $h] - $x + $ht}]
    set Combobox(x) [expr {[winfo rootx $p] + [winfo width  $h] + $x + 3 * $ht}]
    set Combobox(y) [expr {[winfo rooty $p] - [winfo height $h] + $y - $ht}]

    return
}

# ::two::combobox::HandleB1Motion --
#
#	handle interactive resizing of dropdown list.
#	This relies on the mouse cursor's shape set in the
#	HandleMotion procedure!
#
# Arguments:
#	h		Path to handle
#	relX		relative X Position of mouse cursor within border (%x)
#	absX		absolute X Positino (%X)
#	relY		relative Y Position (%y)
#	absY		absolute Y Position (%Y)

proc ::two::combobox::HandleB1Motion {h relX absX relY absY} {
    variable Combobox

    if {$Combobox(Drag)} {
        set p [winfo parent $h]

	if {[string match "*right*" $Combobox(Cursor)]} {
	    set width [expr {$relX + $Combobox(dxr)}]
	} else {
	    set width [winfo width $p]
	}
	if {[string match "*left*" $Combobox(Cursor)]} {
	    set x [expr {$absX - $Combobox(dxl)}]
	    set width [expr {$Combobox(x) - $absX}]
	} else {
	    set x [winfo rootx $p]
	}
        set y [winfo rooty $p]
        set height [expr {$absY - $Combobox(y)}]
        if {$width < 50} {
            set width 50
        }
        if {$height < 50} {
            set height 50
        }
        wm geometry $p ${width}x${height}+${x}+${y}
    }
    return
}

# ::two::combobox::Open --
#
#	Open the combobox, i.e. show the dropdown listbox.
#
# Arguments:
#	c		Pathname of combobox widget

proc ::two::combobox::Open {c} {
    variable Combobox
    
    if {[string match "disabled" $Combobox($c,state)]} {
        return
    }

    set Combobox(current) $c
    if {[string length $Combobox($c,command)]} {
        namespace eval :: $Combobox($c,command)
    }

    set x [winfo rootx $c]
    set y [expr {[winfo rooty $c] + [winfo height $c]}]
    set w [winfo width $c]
    set h 200

    wm geometry $c.drop "${w}x${h}+${x}+${y}"
    update idletasks
    wm deiconify $c.drop
    raise $c.drop
    focus $c.drop.lb
    grab set -global $c.drop
    return
}

# ::two::combobox::Close --
#
#	Close the combobox, i.e. withdraw the dropdown listbox and
#	insert the current selection into the entry field.
#
# Arguments:
#	c		Pathname of combobox widget

proc ::two::combobox::Close {c} {
    variable Combobox
    
    if {[string length [$c.drop.lb curselection]]} {
    	set state [$c.entry cget -state]
	$c.entry configure -state normal
        $c.entry delete 0 end
        $c.entry insert end [$c.drop.lb get active]

	#to customize what happens when active listbox item is inserted in entry,
	#use the -insertentrycommand to activate a command that will be invoked
	#when the user selects an item from the drop down list
	#the active list item is appended to the arbitrary command given
	if {$Combobox($c,insertentrycommand) != {}} {
		set comd $Combobox($c,insertentrycommand)
		lappend comd [$c.drop.lb get active]
		# puts "about to eval $comd"
		eval $comd
		}
	$c.entry configure -state $state
    }
    grab release $c.drop
    wm withdraw  $c.drop
    focus [tk_focusNext $c]
    $c.button configure -relief raised
    return
}

namespace import ::two::combobox::*

#### end of combobox.tcl

#### start of itimeedit.tcl

###constants###

set yo 135		;#y offset
set xo 0		;#x offset
set x_spacing 90 	;#space between marksp
set y_spacing 50 	;#space between constraints
set ylen_def [expr $yo + (1.5 * $y_spacing)] ;# a default length for vertical mark bars
set offx 20		;#offset for excluded endpoints of constraints
set or 5		;#radius of include oval
set rh 6		;#1/2 height of exclude rectangle
set rw 1		;#1/2 width of exclude rectangle
set empty_string \"\" ;# used with '-fill' this causes an object to be transparent

###variables###

set nob 0		;#highest prefix of objects on the canvas - lowest is 1
set nmark 0		;#location of a new mark to be inserted
set dirty ""		;#indication of whether current vip file has been modified
set ned 0
set ncd 0
set select_item ""
set open_dir	$work_dir
set write_dir	$work_dir

### variables needed to support common code ###

set settingsfile ""
set featfile ""

set symdef("") {}

# bitmap images

set file_active_data "#define file_active_width 36
#define file_active_height 28
static unsigned char file_active_bits[] = {
   0x87, 0xff, 0xff, 0xff, 0xff, 0x7b, 0xff, 0xff, 0xff, 0xff, 0x7c, 0x00,
   0x00, 0x00, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xfe, 0x06, 0x00, 0x00, 0x00,
   0xf0, 0xf6, 0xff, 0xff, 0xff, 0xf7, 0xf6, 0xff, 0xff, 0xff, 0xf7, 0xf6,
   0xff, 0xff, 0xff, 0xf7, 0xf6, 0xe1, 0xff, 0xff, 0xf7, 0xf6, 0xc0, 0x9f,
   0xff, 0xf7, 0xf6, 0xcc, 0x9f, 0xff, 0xf7, 0xf6, 0xfc, 0x9f, 0xff, 0xf7,
   0xf6, 0x7c, 0x9e, 0xff, 0xf7, 0xf6, 0x7c, 0x9e, 0xff, 0xf7, 0xf6, 0xfc,
   0x9f, 0x87, 0xf7, 0x36, 0xe0, 0x9f, 0x03, 0xf7, 0x36, 0x60, 0x9e, 0x79,
   0xf6, 0xf6, 0x7c, 0x9e, 0x79, 0xf6, 0xf6, 0x7c, 0x9e, 0x01, 0xf6, 0xf6,
   0x7c, 0x9e, 0x01, 0xf6, 0xf6, 0x7c, 0x9e, 0xf9, 0xf7, 0xf6, 0x7c, 0x9e,
   0xf9, 0xf7, 0xf6, 0x7c, 0x9e, 0x79, 0xf6, 0xf6, 0x7c, 0x9e, 0x03, 0xf7,
   0xf6, 0x7c, 0x9e, 0x87, 0xf7, 0xf6, 0xff, 0xff, 0xff, 0xf7, 0xf6, 0xff,
   0xff, 0xff, 0xf7, 0x00, 0x00, 0x00, 0x00, 0xf0};"

set file_active_img [image create bitmap -data $file_active_data]

set file_data "#define file_width 36
#define file_height 28
static unsigned char file_bits[] = {
   0x78, 0x00, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x83, 0xff,
   0xff, 0xff, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0xf9, 0xff, 0xff, 0xff,
   0x0f, 0x09, 0x00, 0x00, 0x00, 0x08, 0x09, 0x00, 0x00, 0x00, 0x08, 0x09,
   0x00, 0x00, 0x00, 0x08, 0x09, 0x1e, 0x00, 0x00, 0x08, 0x09, 0x3f, 0x60,
   0x00, 0x08, 0x09, 0x33, 0x60, 0x00, 0x08, 0x09, 0x03, 0x60, 0x00, 0x08,
   0x09, 0x83, 0x61, 0x00, 0x08, 0x09, 0x83, 0x61, 0x00, 0x08, 0x09, 0x03,
   0x60, 0x78, 0x08, 0xc9, 0x1f, 0x60, 0xfc, 0x08, 0xc9, 0x9f, 0x61, 0x86,
   0x09, 0x09, 0x83, 0x61, 0x86, 0x09, 0x09, 0x83, 0x61, 0xfe, 0x09, 0x09,
   0x83, 0x61, 0xfe, 0x09, 0x09, 0x83, 0x61, 0x06, 0x08, 0x09, 0x83, 0x61,
   0x06, 0x08, 0x09, 0x83, 0x61, 0x86, 0x09, 0x09, 0x83, 0x61, 0xfc, 0x08,
   0x09, 0x83, 0x61, 0x78, 0x08, 0x09, 0x00, 0x00, 0x00, 0x08, 0x09, 0x00,
   0x00, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0x0f};"

set file_img [image create bitmap -data $file_data]

### variables not used by itimeedit, but must be set for code reuse ###

set symfile ""

set types { {
	{ {VIP Files}	.vip }
	{ {All Files}	*    }
}	}

#### start of common.tcl

set event_data "#define event_width 30
#define event_height 30
static unsigned char event_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x70, 0x20,
   0x05, 0xc0, 0x88, 0x20, 0x03, 0xc0, 0xf8, 0x20, 0x05, 0xc0, 0x08, 0x20,
   0x03, 0xc0, 0x88, 0x20, 0x05, 0xc0, 0x70, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc8, 0x04, 0x20,
   0x03, 0xf0, 0x03, 0x20, 0x05, 0xf0, 0x01, 0x20, 0x03, 0xe0, 0x01, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0x00, 0x00, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set event_img [image create bitmap -data $event_data]

set event_active_data "#define event_active_width 30
#define event_active_height 30
static unsigned char event_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0x8f, 0xdf,
   0xfa, 0x3f, 0x77, 0xdf, 0xfc, 0x3f, 0x07, 0xdf, 0xfa, 0x3f, 0xf7, 0xdf,
   0xfc, 0x3f, 0x77, 0xdf, 0xfa, 0x3f, 0x8f, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x37, 0xfb, 0xdf,
   0xfc, 0x0f, 0xfc, 0xdf, 0xfa, 0x0f, 0xfe, 0xdf, 0xfc, 0x1f, 0xfe, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0xff, 0xff, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set event_active_img [image create bitmap -data $event_active_data]

set revent_data "#define revent_width 30
#define revent_height 30
static unsigned char revent_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x68, 0x20,
   0x05, 0xc0, 0x98, 0x20, 0x03, 0xc0, 0x08, 0x20, 0x05, 0xc0, 0x08, 0x20,
   0x03, 0xc0, 0x08, 0x20, 0x05, 0xc0, 0x08, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc8, 0x04, 0x20,
   0x03, 0xf0, 0x03, 0x20, 0x05, 0xf0, 0x01, 0x20, 0x03, 0xe0, 0x01, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0x00, 0x00, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set revent_img [image create bitmap -data $revent_data]


set revent_active_data "#define revent_active_width 30
#define revent_active_height 30
static unsigned char revent_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0x97, 0xdf,
   0xfa, 0x3f, 0x67, 0xdf, 0xfc, 0x3f, 0xf7, 0xdf, 0xfa, 0x3f, 0xf7, 0xdf,
   0xfc, 0x3f, 0xf7, 0xdf, 0xfa, 0x3f, 0xf7, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x37, 0xfb, 0xdf,
   0xfc, 0x0f, 0xfc, 0xdf, 0xfa, 0x0f, 0xfe, 0xdf, 0xfc, 0x1f, 0xfe, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0xff, 0xff, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set revent_active_img [image create bitmap -data $revent_active_data]

set fail_event_data "#define fail_event_width 30
#define fail_event_height 30
static unsigned char fail_event_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0xc0, 0x00, 0x20, 0x05, 0xc8, 0x04, 0x20, 0x03, 0xf0, 0x03, 0x20,
   0x05, 0xf0, 0x01, 0x20, 0x03, 0xe0, 0x01, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0x06, 0x18, 0x20, 0x05, 0x0e, 0x1c, 0x20, 0x03, 0x1c, 0x0e, 0x20,
   0x05, 0x38, 0x07, 0x20, 0x03, 0xf0, 0x03, 0x20, 0x05, 0xe0, 0x01, 0x20,
   0x03, 0xe0, 0x01, 0x20, 0x05, 0xf0, 0x03, 0x20, 0x03, 0x38, 0x07, 0x20,
   0x05, 0x1c, 0x0e, 0x20, 0x03, 0x0e, 0x1c, 0x20, 0x05, 0x06, 0x18, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set fail_event_img [image create bitmap -data $fail_event_data]

set fail_event_active_data "#define fail_event_active_width 30
#define fail_event_active_height 30
static unsigned char fail_event_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x37, 0xfb, 0xdf, 0xfc, 0x0f, 0xfc, 0xdf,
   0xfa, 0x0f, 0xfe, 0xdf, 0xfc, 0x1f, 0xfe, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0xf9, 0xe7, 0xdf, 0xfa, 0xf1, 0xe3, 0xdf, 0xfc, 0xe3, 0xf1, 0xdf,
   0xfa, 0xc7, 0xf8, 0xdf, 0xfc, 0x0f, 0xfc, 0xdf, 0xfa, 0x1f, 0xfe, 0xdf,
   0xfc, 0x1f, 0xfe, 0xdf, 0xfa, 0x0f, 0xfc, 0xdf, 0xfc, 0xc7, 0xf8, 0xdf,
   0xfa, 0xe3, 0xf1, 0xdf, 0xfc, 0xf1, 0xe3, 0xdf, 0xfa, 0xf9, 0xe7, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set fail_event_active_img [image create bitmap -data $fail_event_active_data]

set cond_data "#define cond_width 30
#define cond_height 30
static unsigned char cond_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0x05, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x20,
   0x05, 0x00, 0x00, 0x20, 0x43, 0x00, 0x80, 0x20, 0x45, 0xc0, 0x81, 0x20,
   0x43, 0x20, 0x82, 0x20, 0x45, 0x20, 0x80, 0x20, 0x43, 0x20, 0x80, 0x20,
   0x45, 0x20, 0x82, 0x20, 0x43, 0xc0, 0x81, 0x20, 0x45, 0x00, 0x80, 0x20,
   0x43, 0x00, 0x80, 0x20, 0x45, 0x00, 0x80, 0x20, 0xe3, 0x00, 0xc0, 0x21,
   0xf5, 0x01, 0xe0, 0x23, 0xf3, 0xff, 0xff, 0x23, 0xf5, 0x01, 0xe0, 0x23,
   0xe3, 0x00, 0xc0, 0x21, 0x45, 0x00, 0x80, 0x20, 0x43, 0x00, 0x80, 0x20,
   0x45, 0x00, 0x80, 0x20, 0x43, 0x00, 0x80, 0x20, 0x05, 0x00, 0x00, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set cond_img [image create bitmap -data $cond_data]

set cond_active_data "#define cond_active_width 30
#define cond_active_height 30
static unsigned char cond_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0xfa, 0xff, 0xff, 0xdf, 0xfc, 0xff, 0xff, 0xdf,
   0xfa, 0xff, 0xff, 0xdf, 0xbc, 0xff, 0x7f, 0xdf, 0xba, 0x3f, 0x7e, 0xdf,
   0xbc, 0xdf, 0x7d, 0xdf, 0xba, 0xdf, 0x7f, 0xdf, 0xbc, 0xdf, 0x7f, 0xdf,
   0xba, 0xdf, 0x7d, 0xdf, 0xbc, 0x3f, 0x7e, 0xdf, 0xba, 0xff, 0x7f, 0xdf,
   0xbc, 0xff, 0x7f, 0xdf, 0xba, 0xff, 0x7f, 0xdf, 0x1c, 0xff, 0x3f, 0xde,
   0x0a, 0xfe, 0x1f, 0xdc, 0x0c, 0x00, 0x00, 0xdc, 0x0a, 0xfe, 0x1f, 0xdc,
   0x1c, 0xff, 0x3f, 0xde, 0xba, 0xff, 0x7f, 0xdf, 0xbc, 0xff, 0x7f, 0xdf,
   0xba, 0xff, 0x7f, 0xdf, 0xbc, 0xff, 0x7f, 0xdf, 0xfa, 0xff, 0xff, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set cond_active_img [image create bitmap -data $cond_active_data]

set mark_data "#define mark_width 30
#define mark_height 30
static unsigned char mark_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0x05, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00, 0x20,
   0xe5, 0xff, 0xff, 0x21, 0xe3, 0xff, 0xff, 0x21, 0xe5, 0xff, 0xff, 0x21,
   0xe3, 0xff, 0xff, 0x21, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20,
   0x03, 0xc0, 0x00, 0x20, 0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20,
   0x05, 0xc0, 0x00, 0x20, 0x03, 0xc0, 0x00, 0x20, 0x05, 0x00, 0x00, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set mark_img [image create bitmap -data $mark_data]

set mark_active_data "#define mark_active_width 30
#define mark_active_height 30
static unsigned char mark_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0xfa, 0xff, 0xff, 0xdf, 0xfc, 0xff, 0xff, 0xdf,
   0x1a, 0x00, 0x00, 0xde, 0x1c, 0x00, 0x00, 0xde, 0x1a, 0x00, 0x00, 0xde,
   0x1c, 0x00, 0x00, 0xde, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf,
   0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf,
   0xfa, 0x3f, 0xff, 0xdf, 0xfc, 0x3f, 0xff, 0xdf, 0xfa, 0xff, 0xff, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set mark_active_img [image create bitmap -data $mark_active_data]

set auto_data "#define auto_width 30
#define auto_height 30
static unsigned char auto_bits[] = {
   0xff, 0xff, 0xff, 0x3f, 0xab, 0xaa, 0xaa, 0x2a, 0x55, 0x55, 0x55, 0x25,
   0x03, 0x00, 0x00, 0x20, 0xc5, 0x03, 0x00, 0x20, 0x23, 0xe4, 0x03, 0x20,
   0x95, 0x19, 0x06, 0x20, 0x53, 0x0a, 0x08, 0x20, 0x55, 0x0a, 0x08, 0x20,
   0x93, 0x09, 0x10, 0x20, 0x25, 0x04, 0x10, 0x20, 0xc3, 0x03, 0x20, 0x20,
   0x85, 0x00, 0x60, 0x20, 0xc3, 0x01, 0x40, 0x20, 0xe5, 0x03, 0x50, 0x21,
   0xa3, 0x02, 0xf0, 0x21, 0x85, 0x00, 0xe0, 0x20, 0x03, 0x01, 0x40, 0x20,
   0x05, 0x01, 0xf0, 0x20, 0x03, 0x02, 0x08, 0x21, 0x05, 0x02, 0x04, 0x22,
   0x03, 0x04, 0x04, 0x22, 0x05, 0x04, 0x04, 0x22, 0x03, 0x18, 0x06, 0x22,
   0x05, 0xf0, 0x09, 0x21, 0x03, 0x00, 0xf0, 0x20, 0x05, 0x00, 0x00, 0x20,
   0x03, 0x00, 0x00, 0x20, 0x01, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x3f};"

set auto_img [image create bitmap -data $auto_data]


set auto_active_data "#define auto_active_width 30
#define auto_active_height 30
static unsigned char auto_active_bits[] = {
   0x00, 0x00, 0x00, 0xc0, 0x54, 0x55, 0x55, 0xd5, 0xaa, 0xaa, 0xaa, 0xda,
   0xfc, 0xff, 0xff, 0xdf, 0x3a, 0xfc, 0xff, 0xdf, 0xdc, 0x1b, 0xfc, 0xdf,
   0x6a, 0xe6, 0xf9, 0xdf, 0xac, 0xf5, 0xf7, 0xdf, 0xaa, 0xf5, 0xf7, 0xdf,
   0x6c, 0xf6, 0xef, 0xdf, 0xda, 0xfb, 0xef, 0xdf, 0x3c, 0xfc, 0xdf, 0xdf,
   0x7a, 0xff, 0x9f, 0xdf, 0x3c, 0xfe, 0xbf, 0xdf, 0x1a, 0xfc, 0xaf, 0xde,
   0x5c, 0xfd, 0x0f, 0xde, 0x7a, 0xff, 0x1f, 0xdf, 0xfc, 0xfe, 0xbf, 0xdf,
   0xfa, 0xfe, 0x0f, 0xdf, 0xfc, 0xfd, 0xf7, 0xde, 0xfa, 0xfd, 0xfb, 0xdd,
   0xfc, 0xfb, 0xfb, 0xdd, 0xfa, 0xfb, 0xfb, 0xdd, 0xfc, 0xe7, 0xf9, 0xdd,
   0xfa, 0x0f, 0xf6, 0xde, 0xfc, 0xff, 0x0f, 0xdf, 0xfa, 0xff, 0xff, 0xdf,
   0xfc, 0xff, 0xff, 0xdf, 0xfe, 0xff, 0xff, 0xdf, 0x00, 0x00, 0x00, 0xc0};"

set auto_active_img [image create bitmap -data $auto_active_data]


#-----end bitmaps-----


set debug_on 0 ;# 0 is off, 1 is on
set empty_string \"\" ;# used with '-fill' this causes an object to be transparent
set bind_on ""

set symfile ""

set types {{
	 	{{VIP Files}	.vip	}
		{{All Files}	*	}
		}}


proc complain {txt} {
	catch { tk_messageBox -icon info -message "$txt" }
}

if {$debug_on} {
	toplevel .debug ;   #debugging window
	text .debug.txt -width 80 -height 60 -relief raised -bd 2 \
		-yscrollcommand ".debug.scroll set"
	scrollbar .debug.scroll -command ".debug.txt yview"
	pack .debug.scroll -side right -fill y
	pack .debug.txt -side left
	}

proc debug {txt} {
	global debug_on
	if {$debug_on} {
		catch {.debug.txt insert end "\n$txt"}
		}
}

proc mode {} {
	global TW_Vip
	#clear bindings on buttons and call for cleanup of canvas

	clean_up_canvas

	bind $TW_Vip <1> 	{}	;#clear all bindings for button 1
	bind $TW_Vip <3> 	{}	;#clear all bindings for button 3
	bind $TW_Vip <Motion> 	{}	;#clear bindings on canvas motion	
}

proc update_dir {which path_with_filename} {
	global TW_Vip
	global open_dir write_dir

	debug "entering update_dir with which=$which, path_with_filename=$path_with_filename"
	set fullpath [split $path_with_filename /]
	set nlen [llength $fullpath]
	if {$nlen > 1} {
		set fullpath [lrange $fullpath 0 [expr $nlen - 2]] 	;# get rid of file directory
		if {[llength $fullpath] == 1} {
			append fullpath "/"
			}
		}
	set nd [join $fullpath /] 				;#put path back together
 	switch $which {
		open {set open_dir $nd}
		write {set write_dir $nd}
	}
}

proc readvipfile {from} {
	global TW_Vip
	global data nob event const dirty Vip_Fname
	global prov npa npl para nfe
	global feat settingsfile featfile symfile whats_on_top
	global ned ncd elab clab edef cdef
	global select_item
	
	if [catch {set fd [open $from r]} errmsg] {
    		catch { tk_messageBox -icon info -message $errmsg }
    		return 0
  	}

	set err_log ""
	set npa 0 ;# number of parameters
	set npl 0  ;# number of feature provisioning lines
	set nob 0 ;# number of event + const objects
	set settingsfile ""
	set featfile ""

	gets $fd line
	if {$line != "<VIP>"} {
		set ermsg "$from is not a VIP file"
		catch { tk_messageBox -icon info -message $ermsg }
		return 0
	}
		
	while {[gets $fd line] >=0} {
		set firstchar [string index $line 0]
		set firstfour [string range $line 0 3]
		if {$firstfour == "NOTE"} {
			continue ;# backwards compatibility - ignore notes
		} elseif {$firstfour == "PROV"} {
			set hold_prov $line
			set hold_prov [split $hold_prov " 	"]
			set wrong_num [check_num $hold_prov 4]
			if {$wrong_num} {
				append err_log "Ignoring bad provisioning specification - wrong number of entries:\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_prov string int string char]
			if {$bad_content} {
				append err_log "ignoring corrupted provisioning specification:\n\t$line\n"
				continue
			}
			set h [lindex $hold_prov 3]
			if {($h != 0) && ($h != 1) && ($h != "?")} {
				append err_log "ignoring corrupted provisioning specification:\n\t$line\n"
				continue
			}
			incr npl 1
			set prov($npl) $hold_prov
		} elseif {$firstfour == "PARA"} {
			set hold_para $line
			set hold_para [split $hold_para " 	"]
			set wrong_num [check_num $hold_para 4]
			if {$wrong_num} {
				append err_log "Ignoring bad setting specification - wrong number of entries:\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_para string int string]
			if {$bad_content} {
				append err_log "ignoring corrupted provisioning specification:\n\t$line\n"
				continue
			}
			incr npa 1
			set para($npa) $hold_para
			debug "para($npa) just set to $hold_para"
		} elseif {$firstfour == "OUTC"} {
			#left here for backwards compatibility
			set hold_outcome $line
			set hold_outcome [split $hold_outcome "	  "]
			if {[llength $hold_outcome] == 3} {
				set tmp1 [lindex $hold_outcome 0]
				set tmp2 [lindex $hold_outcome 2] ;# backwards compatibility
				set tmp3 ""
				lappend tmp3 $tmp1 $tmp2
				set hold_outcome $tmp3
			}
			set wrong_num [check_num $hold_outcome 2]
			if {$wrong_num} {
				append err_log "bad outcome spec - wrong nr of entries:\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_outcome string char]
			if {$bad_content} {
				append err_log "corrupted outcome:\n\t$line\n"
				continue
			}
			set o [lindex $hold_outcome 1]
			if {$o == 1} {set o "p"} ;#backwards compatibility
			if {$o == 0} {set o "f"} ;#backwards compatibility
			if {($o != "p") && ($o != "f")} {
				append err_log "corrupted outcome:\n\t$line\n"
				continue
			}
			set outcome $o
		} elseif {$firstfour == "AUTO"} {
			continue ;#backwards compatibility with vips that have an automata type
		} elseif {$firstfour == "SEFI"} {
			set hold_settingsfile $line
			set hold_settingsfile [split $hold_settingsfile " 	"]
			set wrong_num [check_num $hold_settingsfile 2]
			if {$wrong_num} {
				append err_log "Ignoring bad setting file - wrong number of entries:\n\t$line\n"
				continue
				}
			set bad_content [check_contents $hold_settingsfile string string]
			if {$bad_content} {
				append err_log "ignoring corrupted settings filename:\n\t$line\n"
				continue
			}
			set settingsfile [lindex $hold_settingsfile 1]
			debug "settingsfile just set to $settingsfile"
		} elseif {$firstfour == "PRFI"} {
			set hold_featfile $line
			set hold_featfile [split $hold_featfile " 	"]
			set wrong_num [check_num $hold_featfile 2]
			if {$wrong_num} {
				append err_log "Ignoring bad setting file - wrong number of entries:\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_featfile string string]
			if {$bad_content} {
				append err_log "ignoring corrupted provisioning file name:\n\t$line\n"
				continue
			}
			set featfile [lindex $hold_featfile 1]
		} elseif {$firstfour == "SYMB"} {
			set hold_symfile $line
			set hold_symfile [split $hold_symfile " 	"]
			set wrong_num [check_num $hold_symfile 2]
			if {$wrong_num} {
				append err_log "Ignoring bad symbols file - wrong number of entries:\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_symfile string string]
			if {$bad_content} {
				append err_log "ignoring corrupted symbols file name:\n\t$line\n"
				continue
			}
			set symfile [lindex $hold_symfile 1]
		} elseif {($firstchar != "#") && ($firstchar != "")} {
			set hold_spec $line
			set wrong_num [check_num $hold_spec 4]
			debug "wrong_num is: $wrong_num"
			if {$wrong_num} {
				append err_log "Ignoring bad event/constraint specification - wrong number of entries\n\t$line\n"
				continue
			}
			set bad_content [check_contents $hold_spec int int char string]
			if {$bad_content} {
				append err_log "ignoring corrupted event/constraint specification:\n\t$line\n"
				continue
			}
			set t [lindex $line 2]
			if {($t != "c") && ($t != "e") && ($t != "r") && ($t != "f") && ($t != "t")} {
				append err_log "ignoring event/constraint specification with invalid type $t:\n\t$line\n"
				continue
			}
			set spec $hold_spec
			set type [lindex $spec 2]
			switch -regexp $type {
				c {
					incr nob 1
					if {[lindex $spec 0] < 0} {
						set spec [lreplace $spec 0 0 [expr 0 - [lindex $spec 0]]]
						lappend spec "no"
					} else {
						lappend spec "yes"
					}
					if {[lindex $spec 1] < 0} {
						set spec [lreplace $spec 1 1 [expr 0 - [lindex $spec 1]]]
						lappend spec "no"
					} else {
						lappend spec "yes"
					}
					set const($nob) $spec
					set event($nob) ""
					debug "readvipfile: const($nob) is $const($nob)"
					#start - next lines add constraint name to label list if not already there
					set unique 1
					for {set i 1} {$i <= $ncd} {incr i 1} {
						if {[lindex $spec 3] == $clab($i)} {
							set unique 0
							break
							}
						}
					if $unique {
						if {[lindex $spec 3] != "?"} {
							incr ncd 1
							set clab($ncd) [lindex $spec 3]
							set cdef($ncd) ""
							}
						}
					#end
				}
				e|r|f|t { # retain t for backwards compatibility
					if {[lindex $spec 2] == "t"} { ;#this is so we can still read files with target events
						set spec [lreplace $spec 2 2 "r"]
					}
					incr nob 1
					set event($nob) $spec
					set const($nob) ""
					debug "readvipfile: event($nob) is $event($nob)"

					#start - next lines add event name to label list if not already there
					set unique 1
					for {set i 1} {$i <= $ned} {incr i 1} {
						if {[lindex $spec 3] == $elab($i)} {
							set unique 0
							break
							}
						}
					if $unique {
						if {[lindex $spec 3] != "?"} {
							incr ned 1
							set elab($ned) [lindex $spec 3]
							set edef($ned) ""
							}
						}
					#end
				}
			}
		} else {
			append err_log "Unrecognized line in vip file: $from was ignored:\n\t$$line \n"
		}
		if {$err_log != ""} {complain $err_log}		
	}
	close $fd
	debug "just before layout 'open' in readvipfile, nob= $nob"
	layout "open"
	debug "in readvipfile, settingsfile = $settingsfile, and featfile = $featfile"
	if {($settingsfile != "") || ($featfile != "")} {
		catch {destroy .p}
		catch {destroy .t}
		debug "calling make_prov_frame"
		make_prov_frame
	}
	set whats_on_top ""
	if {$settingsfile != ""} {
		read_settings ;# this puts settings on canvas, then calls populate_settings
		set whats_on_top "Settings"
	}
	if {$featfile != ""} {
		read_features ;# this puts features on canvas, then calls populate_features
		set whats_on_top "Features"
	}
	if {$symfile != ""} {
		read_symbol_file $symfile
	}
	debug "leaving readvipfile of $from with nob=$nob"
	return 1
}

proc save_vip_fileselect {{curr 1} {mode "none"}} {
	global TW_Vip
#-
#- Save spec to a file.
#-
#- If 'curr' is true then we save to the current file. Otherwise, a file
#- selection dialog is presented. If a file is selected (note that the
#- dialog can be canceled) then we try to write to it.
#-
# curr, save and hm are used only if this proc is called to generate an automaton

	global Vip_Fname work_dir write_dir dirty
	
	switch $mode {
		none {
			set save_types { {
			{ {VIP Files}	.vip }
			{ {Automata Files}	.aut }
			{ {GIF Files}   .gif }
			{ {Postscript Files}   .ps }
			}	}
		}
		aut {
			set save_types { {
			{ {Automata Files}	.aut }
			}	}
		}
	}

	debug "entering save_vip_fileselect with curr=$curr, mode=$mode"

	if $curr {
		switch -- $Vip_Fname "" {
			complain "no file to save to, try: Save as ..."
      			return
    		}
    		writevipfile $Vip_Fname
		complain "write occurred to $Vip_Fname"
  	} else {
    		set fileselect "tk_getSaveFile"
  
    		# get the file (return if the file selection dialog canceled)
    		switch -- [set file [eval $fileselect -initialdir $write_dir -filetypes $save_types]] "" return
		set suffix [split $file .]
		set parts [llength $suffix]
		set suffix [lindex $suffix [expr $parts - 1]]
		switch $suffix {
			vip	{}
			aut	{}
			gif	{}
			ps	{}
			default {set suffix ".vip"
				 append file $suffix
				}
		}
	
		switch $suffix {
			vip	{
				if [writevipfile $file] {
      					set Vip_Fname $file
					update_dir write $file
					set_path $Vip_Fname
    				} else {
	   				complain "write error"
					return
				}	}
			aut	{get_automaton_file 0 1 $file}
			gif	{print gif $file}
			ps	{print postscript $file}
		}
    		# write the file and update Vip_Fname if the file written successfully
    		
  	}
}

proc writevipfile {to} {
	global TW_Vip
	global event const nob sorted_indices dirty

	global prov para
	global settingsfile featfile
	global whats_on_top npa npl

	if ![file_ok $to] { return 0 }

	if [catch {set fd [open $to w]} errmsg] {
		complain $errmsg
		catch { tk_messageBox -icon info -message $ermsg }
		return 0
	}

	puts $fd "<VIP>"
	gendata
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$event($i) != ""} {
			puts $fd $event($i)
			}
		}
	#constraints must be sorted by ycoordinate so that user layout of constraints is preserved
	set list ""
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) == ""} { ;#must preserve all list entries in order to make sense of indices in sorted_indices
			lappend list -1 ;#dummy value -lower than real values
		} else {
			lappend list [lindex [$TW_Vip coords const$i] 1]
			}
		}
	sort $list
	foreach i $sorted_indices {
		debug "considering item $i in sorted_indices"
		set p [expr $i + 1] ;# sort uses list indices from 0, so must increment since const uses indices from 1
		if {$const($p) != ""} { 
			set temp ""
			set b [lindex $const($p) 0]
			set e [lindex $const($p) 1]
			set include_b [lindex $const($p) 4]
			set include_e [lindex $const($p) 5]
			if {$include_b == "no"} {
				set b [expr 0 - $b]
				}
			if {$include_e == "no"} {
				set e [expr 0 - $e]
				}
			set txt [lindex $const($p) 3]
			lappend temp $b $e c $txt
			puts $fd $temp
			}
		}
	if {$featfile != ""} {
		puts $fd "PRFI\t$featfile"
		if {$whats_on_top == "f"} {
			rescue Features 0 ;# 0 means do not destroy frame contents
		}
		for {set i 1} {$i <= $npl} {incr i 1} {
			 puts $fd $prov($i)
		}
	}
	if {$settingsfile != ""} {
		puts $fd "SEFI\t$settingsfile"
		if {$whats_on_top == "s"} {
			rescue Settings 0 ;# get most current values - 0 means do not destroy frame contents
		}
		for {set i 1} {$i <= $npa} {incr i 1} {
			puts $fd $para($i)
		}
	}
	consider_write_symfile $fd $to
	
	close $fd
	set dirty no
	return 1
}

proc file_ok {f} {
	global TW_Vip
	debug "entering file_ok with f=$f"
	if {[file exists $f]} {
		if {![file isfile $f] || ![file writable $f]} {
			set m "File $f is not writable"
			catch { tk_messageBox -icon info -message $m }
			return 0
	}	}
	return 1
}

proc check_num {spec n} {
	global TW_Vip
	#debug "entering check_num with spec=$spec, and n=$n"
	set wrong_num 0
	if {[llength $spec] != $n} {
		set wrong_num 1
		}
	return $wrong_num
}

proc check_contents {spec {type1 "none"} {type2 "none"} {type3 "none"} {type4 "none"}} {
	global TW_Vip
	set bad_content 0
	set n [llength $spec]
	set types ""
	set result 1
	lappend types $type1 $type2 $type3 $type4
	for {set i 0} {$i < $n} {incr i 1} {
		set var [lindex $spec $i]
		set type [lindex $types $i]
		switch $type {
			int	{set result [catch {incr var 1} details]
				}
			char	{set result [catch {string index $var 0} details]
				set len [catch {string length $var} details]
				}
			string	{set result [catch {string index $var 0} details]
				}
			default {debug "unrecognized type: $type in check_contents"
				}
			}
		if {$result != 0} {set bad_content 1}
		}
	return $bad_content
}

#----end of open-save stuff

#set path to directory given in Vip_Fname
proc set_path {Vip_Fname} {
	global TW_Vip
	global work_dir
	debug "entering set_path with Vip_Fname=$Vip_Fname"
	set fullpath [split $Vip_Fname /]
	set nlen [llength $fullpath]
	set fullpath [lrange $fullpath 0 [expr $nlen - 2]] 	;# get rid of filename
	set wd [join $fullpath /] 				;#put path back together
 	catch {cd $work_dir}
}

proc layout {mode} {
	global TW_Vip
	global event const ne nc sm lm bigFont smallFont textFont
	global x_spacing xo yo y_spacing y yc sv n ylen_def nob
	configure_menus on
	set yc $yo
	set y_spacing 40
	if {$mode == "open"} {
		#find largest mark
		set lmspec 0 ;#largest mark
		for {set i 1} {$i <= $nob} {incr i 1} {
			if {$event($i) != ""} {
				if {$lmspec < [lindex $event($i) 1]} {
					set lmspec [lindex $event($i) 1]
					}
				continue
				}
			if {$const($i) != ""} {
				if {$lmspec < [lindex $const($i) 1]} {
					set lmspec [lindex $const($i) 1]
					}
				continue
				}
			}
		debug "in layout - open branch, final lmspec is: $lmspec"
	} elseif {$mode == "new"} {
		set Vip_Fname ""
		set lmspec 7
		}
	set sm 0 ;# was 1
	#draw timeline - marks are 'x_spacing' apart
	set tlen [expr $x_spacing * [expr $lmspec - $sm]]
	set ylen_def [expr $yc + (2 * $y_spacing)]
	set sv [expr $xo + (.5 * $x_spacing)]
	$TW_Vip create text $sv [expr $yo - 2] -text START -anchor s -font $smallFont -fill #aaa -tags starttext
	$TW_Vip create line $sv $yo [expr $xo + ($tlen)] $yo -tags markline -width 2
	$TW_Vip create rect $sv [expr $yo + 1] \
		[expr $xo + $tlen] [expr $yo + 17] -fill #fff -outline #fff \
		-tags timeline1

	$TW_Vip create polygon $sv [expr $yo + 1] \
		[expr $xo + $x_spacing] [expr $yo + 1] \
		[expr $xo + $x_spacing + 10] [expr $yo + 9] \
		[expr $xo + $x_spacing] [expr $yo + 17] \
		$sv [expr $yo + 17] -outline gray -fill gray \
		-tags timeline2
	$TW_Vip create polygon [expr $xo + $x_spacing] [expr $yo + 1] \
		[expr $xo + $x_spacing + 10] [expr $yo + 9] \
		[expr $xo + $x_spacing] [expr $yo + 17] \
		[expr $xo + $x_spacing + 4] [expr $yo + 17] \
		[expr $xo + $x_spacing + 10 + 4] [expr $yo + 9] \
		[expr $xo + $x_spacing + 4] [expr $yo + 1] \
		-tags arrowtip -fill white -outline white
	for {set i $sm} {$i <= $lmspec} {incr i 1} {
		draw_new_mark $i "end" 
		}
	$TW_Vip create text [expr $xo + (.5 * $x_spacing) + 5] [expr $yo + 1] \
		-text "TIME" -font $textFont -fill white -anchor nw -tags timetext
	if {$mode == "open"} {
		debug "layout - in mode=open part, with nob=$nob"
		set y $yo ;# initialize
		for {set i 1} {$i <= $nob} {incr i 1} {
			if {$event($i) != ""} {
				set type [lindex $event($i) 2]
				debug "in layout, $type for event($i)=$event($i) is: type=$type"
				set b [lindex $event($i) 0]
				set begin_x [expr $sv + ($x_spacing * ($b - $sm))]
				set end_x $begin_x
				set desc [lindex $event($i) 3]
				draw $type $begin_x $end_x $yo $desc "" "" $i
				continue
				}	
			if {$const($i) != ""} {
				set b [lindex $const($i) 0]
				set e [lindex $const($i) 1]
				set begin_x [expr $sv + ($x_spacing * ($b - $sm))]
				set end_x [expr $sv + ($x_spacing * ($e - $sm))]
				set desc [lindex $const($i) 3]
				set include_b [lindex $const($i) 4]
				set include_e [lindex $const($i) 5]
				incr y $y_spacing
				draw c $begin_x $end_x $y $desc $include_b $include_e $i	
				}
			}
		adj_vline_len
		}
	configure_menus on
	toolbar on
	}

proc draw {type begin_x end_x y desc include_b include_e n} {
	global TW_Vip
	global yo x_spacing y_spacing smallFont bigFont mode sm lm
	debug "entering draw for: $type $begin_x $end_x $desc $include_b $include_e n = $n"
	switch -regexp $type {
		c {	set bm [lindex [get_mark $begin_x none] 3]
			set em [lindex [get_mark $end_x none] 3]
			if {$bm == $em} {
				if {$bm == $sm} {
					set end_x [expr $end_x + $x_spacing] ;#disallow constraints that begin & end at sm
				}
			}
			if {$include_b == "yes"} {
				set offbx 0
			} else {
				set offbx 20
			}
			if {$include_e == "yes"} {
				set offex 0
			} else {
				set offex 20
			}
			$TW_Vip create line [expr $begin_x + $offbx] $y \
				[expr $end_x - $offex] $y -tags "ob$n const$n"
			if {$include_b == "yes"} {
				$TW_Vip create oval [expr $begin_x - 5] [expr $y - 5] \
					[expr $begin_x + 5] [expr $y + 5] \
					-fill black -tags "ob$n heads$n"
			} else {
				$TW_Vip create rect [expr $begin_x + $offbx] [expr $y - 6] \
					[expr $begin_x + $offbx + 2] [expr $y + 6] \
					-fill black -tags "ob$n heads$n"
			}
			if {$include_e == "yes"} {
				$TW_Vip create oval [expr $end_x - 5] [expr $y - 5] \
					[expr $end_x + 5] [expr $y + 5] \
					-fill black -tags "ob$n heade$n"
			} else {
				$TW_Vip create rect [expr $end_x - $offex] [expr $y - 6] \
					[expr $end_x - $offex + 2] [expr $y + 6] \
					-fill black -tags "ob$n heade$n"
			}	
			$TW_Vip create text [expr $begin_x + $offbx + 4] [expr $y - 18] \
				-text $desc -font $smallFont -anchor nw -tags "ob$n label$n label"
		
			catch { destroy ${TW_Vip}.m$n }
			menu ${TW_Vip}.m$n -tearoff 0
			${TW_Vip}.m$n add command -label "Include begin mark" \
				-command "mark_include 1 begin $n"
			${TW_Vip}.m$n add command -label "Exclude begin mark" \
				-command "mark_include 0 begin $n"
			${TW_Vip}.m$n add command -label "Include end mark" \
				-command "mark_include 1 end $n"
			${TW_Vip}.m$n add command -label "Exclude end mark" \
				-command "mark_include 0 end $n"
			${TW_Vip}.m$n add command -label "delete" -command "delete_object $n; select_near"
			${TW_Vip}.m$n add command -label "edit" -command "edit_object $n"
			}
		e|r|f {	$TW_Vip create line $begin_x [expr $yo - 25] $begin_x $yo -arrow last -tags "ob$n event$n"
			$TW_Vip create text [expr $begin_x + 10] [expr $yo - 15] \
				-text $type -font $bigFont -anchor w -tags "ob$n type$n"
			$TW_Vip create text $begin_x [expr $yo - 30] -font $smallFont \
				-anchor s -width $x_spacing -justify center -text $desc -tags "ob$n label$n label"
			if {$type == "f"} {
				$TW_Vip create line [expr $begin_x - 10] [expr $yo - 10] \
					[expr $begin_x + 10] [expr $yo + 10] \
					-fill red -width 2 -tags "fail_event$n"
				$TW_Vip create line [expr $begin_x + 10] [expr $yo - 10] \
					[expr $begin_x - 10] [expr $yo + 10] \
					-fill red -width 2 -tags "fail_event$n"
			}
			catch { destroy ${TW_Vip}.m$n }
			menu ${TW_Vip}.m$n -tearoff 0
			${TW_Vip}.m$n add command -label "delete" -command "delete_object $n; select_near"
			${TW_Vip}.m$n add command -label "edit" -command "edit_object $n"
		}
	}
	$TW_Vip bind ob$n <Double-Button-1> "edit_object $n"
	debug "exiting draw"
}

proc edit_object {cn} {
	global TW_Vip
	global mydata ned ncd elab clab edef cdef nob select_item
	debug "entering edit_object"
	set select_item $cn
	set_selection_guides $cn ;# they should be on, and $cn should be selected already, so this is just in case
	set bgr "gray"
	set font {Helvetica 12}
	gendata ;# to get highest object prefix - nob
	# destroy all other edit window that are up
	for {set i 1} {$i <=$nob} {incr i 1} {
		if [winfo exists .ec$i] {
			destroy .ec$i
		}
	}
	gen_mydata $cn
	set type [lindex $mydata 2]
	set txt [lindex $mydata 3]
	set indice [match_symbol $type "$txt"]
	set begin [lindex $mydata 0]
	set end   [lindex $mydata 1]
	set included_b [lindex $mydata 4]
	set included_e [lindex $mydata 5]

	switch -regexp $type {
		e|r|f	{set c [$TW_Vip coords event$cn]
			 set name "Event"
		}
		c	{set c [$TW_Vip coords const$cn]
			 set name "Constraint"
		}
	}
	set x1 [lindex $c 0]
	set y1 [lindex $c 1]
	set x2 [lindex $c 2]
	set y2 [lindex $c 3]

	set def ""

	catch {destroy .ec$cn}

	toplevel .ec$cn -bg $bgr
	wm title .ec$cn "Edit $name -- .ec$cn"
	bind $TW_Vip <1> "" ;# no selection while edit box is up
	bind .ec$cn <Destroy> "select_near"

	frame .ec$cn.ri -bg $bgr
	pack .ec$cn.ri -side right -fill y -expand 1

	frame .ec$cn.ri.t -bg $bgr
	pack .ec$cn.ri.t -side top

	button .ec$cn.ri.t.button -text "Define Symbols" \
		-bg black -fg gold -width 10 -bd 3 \
		-activeforeground black -activebackground gold \
		-command "labels edit $type"
	pack .ec$cn.ri.t.button -side top -fill x
	
	frame .ec$cn.ri.b -bg $bgr
	pack .ec$cn.ri.b -side bottom

	button .ec$cn.ri.b.ok -text "OK" \
		-bg black -fg gold -width 5 -bd 3 \
		-activeforeground black -activebackground gold \
		-command "
			catch {destroy .f.er}
			validate_data $cn
			"
	button .ec$cn.ri.b.cancel -text "Cancel" \
		-bg black -fg gold -width 5 -bd 3 \
		-activeforeground black -activebackground gold \
		-command "destroy .ec$cn"

	pack .ec$cn.ri.b.cancel -side right 
	pack .ec$cn.ri.b.ok -side right 

	frame .ec$cn.h1 -bg $bgr
	pack .ec$cn.h1 -fill x -expand 1 -side top

	label .ec$cn.h1.ldesc -width 12 \
		-text "Name:" -anchor w -bg $bgr

	pack .ec$cn.h1.ldesc -side left -expand 0

	two_combobox .ec$cn.h1.cb1 -width 30 -bg black \
		-fg white -font {Helvetica 10 bold} \
		-relief sunken -insertbackground gold \
		-selectbackground gold -state fixed \
		-insertentrycommand "get_description $cn"

	pack .ec$cn.h1.cb1 -expand 1 -side left -fill x -anchor e
	
	switch -regexp $type {
		e|r|f {	for {set i 1} {$i <= $ned} {incr i 1} {
				.ec$cn.h1.cb1 add "$elab($i)"
			}
		    }
		c   {	for {set i 1} {$i <= $ncd} {incr i 1} {
				.ec$cn.h1.cb1 add "$clab($i)"
			}
		    }
	}

	frame .ec$cn.h2 -bg $bgr
	pack .ec$cn.h2 -fill x -expand 1 -side top

	label .ec$cn.h2.ldesc -width 12 \
		-text "Definition  :" \
		-anchor w -bg $bgr \
		-justify left
	label .ec$cn.h2.edesc -width 30 -bg black -fg white \
		 -font {Helvetica 10 bold} \
		 -anchor w

	pack .ec$cn.h2.ldesc -side left -expand 0
	pack .ec$cn.h2.edesc -expand 1 -side left -fill x -anchor e

	frame .ec$cn.h3 -height 60 -bg $bgr
	pack .ec$cn.h3 -side top -fill x

	switch -regexp $type {
		e|r|f {	radiobutton .ec$cn.h3.e \
				-text "Regular" -variable ev($cn) -value e -bg $bgr \
				-highlightcolor gray
			radiobutton .ec$cn.h3.r \
				-text "Required" -variable ev($cn) -value r -bg $bgr -highlightcolor gray

			radiobutton .ec$cn.h3.f \
				-text "Fail" -variable ev($cn) -value f -bg $bgr -highlightcolor gray

			pack .ec$cn.h3.e -side left
			pack .ec$cn.h3.r -side left
			pack .ec$cn.h3.f -side left

			switch $type {
				"e" {	.ec$cn.h3.e select}
				"r" {	.ec$cn.h3.r select}
				"f" {	.ec$cn.h3.f select}	}

			if {$indice > 0} {
				.ec$cn.h2.edesc configure -text $edef($indice)
				}
		    }
	
		c   {	frame .ec$cn.h3.hBegin -bg $bgr
			pack .ec$cn.h3.hBegin -side top -fill x
			frame .ec$cn.h3.hBegin.left -bg $bgr
			frame .ec$cn.h3.hBegin.right -bg $bgr
			pack .ec$cn.h3.hBegin.left -side left
			pack .ec$cn.h3.hBegin.right -side left
			label .ec$cn.h3.hBegin.left.linclude -text "Begin mark:" -bg $bgr
			pack .ec$cn.h3.hBegin.left.linclude -side left -anchor w 
			foreach t {included excluded} {
   				radiobutton .ec$cn.h3.hBegin.right.$t \
					-width 10 \
					-text $t -variable Begin($cn) \
					-relief flat -value $t -bg $bgr
   				pack .ec$cn.h3.hBegin.right.$t -side right -anchor e
			}

			frame .ec$cn.h3.hEnd -bg $bgr
			pack .ec$cn.h3.hEnd -side top -fill x
			frame .ec$cn.h3.hEnd.left -bg $bgr
			frame .ec$cn.h3.hEnd.right -bg $bgr
			pack .ec$cn.h3.hEnd.left -side left
			pack .ec$cn.h3.hEnd.right -side left
			label .ec$cn.h3.hEnd.left.linclude -text "End    mark:" -bg $bgr
			pack .ec$cn.h3.hEnd.left.linclude -side left -anchor w
			foreach t {included excluded} {
   				radiobutton .ec$cn.h3.hEnd.right.$t \
					-width 10 \
					-text $t -variable End($cn) \
					-relief flat -value $t -bg $bgr
   				pack .ec$cn.h3.hEnd.right.$t -side right -anchor e
			}

			if {$included_b == "no"} {
				.ec$cn.h3.hBegin.right.excluded select
				set included_b "excluded"
			} else {
				.ec$cn.h3.hBegin.right.included select
				set included_b "included"
			}
			if {$included_e == "no"} {
				.ec$cn.h3.hEnd.right.excluded select
				set included_e "excluded"
			} else {
				.ec$cn.h3.hEnd.right.included select
				set included_e "included"
			}
			if {$indice > 0} {
				.ec$cn.h2.edesc configure -text $cdef($indice)
			}
		}
	}


	bind .ec$cn <KeyPress-Return> "
		catch {destroy .f.er}
		validate_data $cn
		"
	focus .ec$cn
	.ec$cn.h1.cb1 set $txt
	update
}

proc get_description {cn str} {
	global TW_Vip
	global edef elab cdef clab ned ncd
	set type [wm title .ec$cn]
	set type [lindex $type 1]
	switch -regexp $type {
		"Event" {   for {set i 1} {$i <= $ned} {incr i 1} {
				#.d.t insert end "does $str == $elab($i)\n"
				if {$str == $elab($i)} {
					update
					.ec$cn.h2.edesc configure -text $edef($i)
					return 1
				}
			
			}
		    }
		"Constraint"   {   for {set i 1} {$i <= $ncd} {incr i 1} {
				if {$str == $clab($i)} {
					.ec$cn.h2.edesc configure -text $cdef($i)
					return 1
				}
			
			}
		    }
	}
	return 1
}



proc validate_data {cn} {
	global TW_Vip
	global Begin End sm lm ev mydata
	debug "entering validate_data with cn=$cn ..."

	gen_mydata $cn

	if {$mydata == ""} { ;# object was deleted while edit window was open
		catch {destroy .ec$cn}
		return
	}
	set old_type [lindex $mydata 2] 
	set type $old_type

	set new_name [.ec$cn.h1.cb1 get] ;#combobox

	if {$new_name == ""} {
		complain "Select a name"
		return
	}

	set old_name [lindex $mydata 3]

	if {$type == "c"} {
		set old_include_b [lindex $mydata 4]
		set old_include_e [lindex $mydata 5]
		set new_include_b $Begin($cn)
		set new_include_e $End($cn)

		if {$new_name != $old_name} {
			update_const $cn text $new_name
		}
		if {$new_include_b != $old_include_b} {
			switch $new_include_b {
				included {update_const $cn ib }
				excluded {update_const $cn eb }
		}	}
		if {$new_include_e != $old_include_e} {
			switch $new_include_e {
				included {update_const $cn ie }
				excluded {update_const $cn ee }
		}	}
	} else {
		set old_type [lindex $mydata 2]
		set new_type $ev($cn)
		if {$new_type != $old_type} {
			update_event $cn type $new_type 
		}
		if {$new_name != $old_name} {
			update_event $cn text $new_name
	}	}

	set_selection_guides $cn
	catch {destroy .ec$cn}
}

proc update_const {n how {var ""}} {
	global TW_Vip
	global const mydata offx sm or rh rw mydata sv x_spacing
	debug "entering update_const n=$n how=$how var=$var"
	gen_mydata $n ;# get data for ob$n - gets put in mydata

	# some default values, which may get overridden
	set b [lindex $mydata 0]
	set e [lindex $mydata 1] 
	set include_b [lindex $mydata 4]
	set include_e [lindex $mydata 5]
	set c [$TW_Vip coords const$n]

	switch $how {
		begin {	set b $var
			debug "update_const - begin branch"
			set begin_x [expr $sv + ($x_spacing * ($b - $sm))]
			if {$include_b == "no"} {
				set begin_x [expr $begin_x + $offx]
				}
			set old_begin_x [lindex $c 0]
			set difx [expr $begin_x - $old_begin_x] ;#how much has x coordinate changed?
			set y [lindex $c 1]
			set end_x [lindex $c 2]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			$TW_Vip move heads$n $difx 0 ;#move begin rect or oval
			$TW_Vip move label$n $difx 0 ;#move text label
			}
		end {	set e $var
			set end_x [expr $sv + ($x_spacing * ($e - $sm))]
			if {$include_e == "no"} {
				set end_x [expr $end_x - $offx]
				}
			set old_end_x [lindex $c 2]
			set difx [expr $end_x - $old_end_x]
			set y [lindex $c 1]
			set begin_x [lindex $c 0]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			$TW_Vip move heade$n $difx 0 ;#move end rect or oval
			}
		ycoord {
			set dify [expr $var - [lindex $c 1]]
			$TW_Vip move ob$n 0 $dify
			distribute_constraints
			}
		eb {	set begin_x [expr $sv + ($x_spacing * ($b - $sm)) + $offx]
			set y [lindex $c 1]
			set end_x [lindex $c 2]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			catch {$TW_Vip delete heads$n} ;# delete start oval
			$TW_Vip create rect [expr $begin_x - $rw] [expr $y - $rh] \
				[expr $begin_x + $rw] [expr $y + $rh] -tags "ob$n heads$n" -fill black
			set old_begin_x [lindex $c 0]
			set difx [expr $begin_x - $old_begin_x] ;#how much has x coordinate changed?
			$TW_Vip move label$n $difx 0 ;#move text label
			}
		ee {	set end_x [expr $sv + ($x_spacing * ($e - $sm)) - $offx]
			debug "update_const - ee branch"
			set y [lindex $c 1]
			set begin_x [lindex $c 0]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			catch {$TW_Vip delete heade$n} ;# delete end oval
			$TW_Vip create rect [expr $end_x - $rw] [expr $y - $rh] \
				[expr $end_x + $rw] [expr $y + $rh] -tags "ob$n heade$n" -fill black
			}
		ib {	set begin_x [expr $sv + ($x_spacing * ($b - $sm))]
			set y [lindex $c 1]
			set end_x [lindex $c 2]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			catch {$TW_Vip delete heads$n} ;# delete begin rect
			$TW_Vip create oval [expr $begin_x - $or] [expr $y - $or] \
				[expr $begin_x + $or] [expr $y + $or] -tags "ob$n heads$n" -fill black
			set old_begin_x [lindex $c 0]
			set difx [expr $begin_x - $old_begin_x] ;#how much has x coordinate changed?
			$TW_Vip move label$n $difx 0 ;#move text label
			}
		ie {	set end_x [expr $sv + ($x_spacing * ($e - $sm))]
			set y [lindex $c 1]
			set begin_x [lindex $c 0]
			$TW_Vip coords const$n $begin_x $y $end_x $y
			catch {$TW_Vip delete heade$n} ;# delete end rect
			$TW_Vip create oval [expr $end_x - $or] [expr $y - $or] \
				[expr $end_x + $or] [expr $y + $or] -tags "ob$n heade$n" -fill black
			}
		text {	$TW_Vip itemconfigure label$n -text $var
			}
		}
		dirty
}

proc mark_include {new_set tip n} {
	global TW_Vip
	global mydata sm
	debug "entering mark_include"
	gen_mydata $n; debug "gen_mydata call - from mark_include"
	if {$tip == "begin"} {
		set cur_set [lindex $mydata 4] ;#include_b
	} else {
		set cur_set [lindex $mydata 5] ;#include_e
		}
	debug "cur_set is: $cur_set"
	switch $new_set {
		0 { 			;#exclude
			if {$cur_set == "no"} {
				return ;# request to exclude, but already excluded
			} else {
				set end [lindex $mydata 1] ;#we know begin x is positive
				set begin [lindex $mydata 0]
				if {$tip == "begin"} {
					if {$begin == $end} {
						complain \
					 		"If the begin mark is not included in the constraint,\n \
								then the end mark must be larger than begin mark."
						return
					}
					if {($begin == $sm) && ($end == [expr $sm + 1])} {
						return
					} else {
						update_const $n eb
						}
				
				} elseif {$tip == "end"} {
					if {$begin == $end} {
						complain \
					 		"If the end mark is not included in the constraint,\n \
							then the end mark must be larger than begin mark."
						return
					} else {
						update_const $n ee
						}
					}
					dirty
				}
			}
		1 {			;#include
			if {$cur_set == "yes"} {
				return
			} else {
				set begin [lindex $mydata 0]
				set end [lindex $mydata 0]
				if {$tip == "begin"} {
					update_const $n ib
				} elseif {$tip == "end"} {
					update_const $n ie
					}		
				}
				dirty
			}
	}		
}


proc update_event {n how var} {
	global TW_Vip
	global event mydata offx sv x_spacing  yo sm
	debug "entering update_event, for object $n, how=$how, var=$var"
	gen_mydata $n ;# get data for ob$n - gets put in mydata

	# some default values, which may get overridden
	set mark [lindex $mydata 0]
	set x [expr $sv + ($x_spacing * ($mark - $sm))]
	set c [$TW_Vip coords event$n]

	switch $how {
		mark {	set cur_x [lindex $c 0]
			set new_x [expr $sv + ($x_spacing * ($var - $sm))]
			set difx [expr $new_x - $cur_x]
			$TW_Vip move ob$n $difx 0
			catch {$TW_Vip move fail_event$n $difx 0}
			}
		type {  $TW_Vip itemconfigure type$n -text $var
			switch -regexp $var {
				e|r	{
					catch {$TW_Vip delete fail_event$n}
					}
				f	{
					$TW_Vip create line [expr $x - 10] [expr $yo - 10] \
						[expr $x + 10] [expr $yo + 10] \
						-fill red -width 2 -tags "fail_event$n"
					$TW_Vip create line [expr $x + 10] [expr $yo - 10] \
						[expr $x - 10] [expr $yo + 10] \
						-fill red -width 2 -tags "fail_event$n"
					}
				}
			}
		text {  $TW_Vip itemconfigure label$n -text $var }
	}
	dirty
}

proc clear {next_step {arg ""}} {
	global TW_Vip
	global Vip_Fname nmark lm choice dirty
	if {$dirty == "yes"} {
		set ch "Changes have not been saved"
		set q "Would you like to save first?"

		catch {destroy .f.ch}
		toplevel .f.ch
		bind .f.ch <KeyPress-Return> {
			destroy .f.ch
			set choice "yes"
		}
		wm title .f.ch $ch
		label .f.ch.lb -text $q
		button .f.ch.yes -text "Yes" -command "
			set choice \"yes\"
			destroy .f.ch
			clear1 $next_step $arg
			"
		button .f.ch.no -text "No" -command "
			 set choice 'no'
			destroy .f.ch
			 clear1 $next_step $arg
			 "
		button .f.ch.cancel -text "Cancel" -command "
			destroy .f.ch
			"
		pack .f.ch.lb .f.ch.yes .f.ch.no .f.ch.cancel -side left -padx 4
		focus .f.ch
	} else {
		set choice "no"
		clear1 $next_step $arg
	}
}



proc add_event {type} {
	global TW_Vip
	global yo nob n select_item
	debug "entering add_event"
	if {$select_item != ""} {
		set_object_bindings $select_item off off
		}
	unselect

	if {[check_empty_mark]} {
		complain "Add at least one Mark first"
		mode
		select_near
		toolbar_bind
		return
	}
	$TW_Vip config -cursor sb_down_arrow

	bind $TW_Vip <ButtonPress-1> "
		set cx \[$TW_Vip canvasx %x]
		add_event1 $type \$cx
		"

	update_help "Select an empty mark"
}

proc add_event1 {type cx} {
	global TW_Vip
	global yo sm xo x_spacing

	debug "\nENTERING add_event1 with type=$type, and cx=$cx"

	$TW_Vip config -cursor arrow
	set rval [get_mark $cx none]
	set x [lindex $rval 1]
	set mark [lindex $rval 3]
	set x_begin $x
 	if {[check_dup_event $mark]} {
	 	complain {Duplicate mark -- select another mark}
		mode
		select_near
		toolbar_bind
	 	return
	}
	if {$mark == $sm} {
		set mark [first_empty_mark]
		set x_begin [expr $xo + (.5 * $x_spacing) + (($mark - $sm) * $x_spacing)]
	}
	$TW_Vip create line \
		$x_begin [expr $yo - 25] \
		$x_begin $yo -arrow last \
		-fill red \
		-tags guide_event

	labels add $type
	select_near
	toolbar_bind
}

proc first_empty_mark {} {
	global sm lm event nob
	gendata
	set ocmarks ""
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$event($i) != ""} {
			lappend ocmarks [lindex $event($i) 0]
		}
	}
	for {set i [expr $sm + 1]} {$i <= $lm} {incr i 1} {
		set occupied($i) ""
	}
	foreach i $ocmarks {
		set occupied($i) $i
	}
	for {set i [expr $sm + 1]} {$i <= $lm} {incr i 1} {
		if {$occupied($i) == ""} {
			return $i
		}
	}
}

proc check_empty_mark {} {
	global sm lm event nob
	debug "entering check_empty_mark"
	gendata
	for {set j [expr $sm + 1]} {$j <= $lm} {incr j 1} {
		set occupied($j) 0
		}
	for {set i 1} {$i <= $nob} {incr i 1} {	;#check if mark already has an event - disallow if so
		if {$event($i) == ""} {
			continue
		} else {
			set occupied([lindex $event($i) 0]) 1
	 		}
		}
	for {set j [expr $sm + 1]} {$j <= $lm} {incr j 1} {
		if {$occupied($j) == 0} {
			return 0
			}
		}
	return 1
}

proc check_dup_event {mark} {
	global TW_Vip
	global nob event
	debug "\nENTERING check_dup_event"
	gendata
	for {set i 1} {$i <= $nob} {incr i 1} {	;#check if mark already has an event - disallow if so
		if {$event($i) == ""} {
			continue
			}
	 	if {[lindex $event($i) 0] == $mark} {
			return 1
			}
		}
	return 0
}

proc fail_event {} {
	global TW_Vip
	global yo nob n select_item
	debug "entering fail_event with TW_Vip=$TW_Vip"
	if {$select_item != ""} {
		set_object_bindings $select_item off off
		}
	unselect
	$TW_Vip config -cursor iron_cross

	bind $TW_Vip <ButtonPress-1> "
		set cx \[$TW_Vip canvasx %x]
		fail_event1 \$cx
		"

	update_help "Select an event"
}

proc fail_event1 {cx} {
	global TW_Vip
	global yo sm xo x_spacing nob event

	debug "\nENTERING fail_event1 with cx=$cx"

	$TW_Vip config -cursor arrow
	set rval [get_mark $cx none]
	set mark [lindex $rval 3]
	set x [lindex $rval 1]
	gendata
	set found ""
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$event($i) == ""} {continue}
		set b [lindex $event($i) 0]
		if {$b == $mark} {
			set found $i
			break
		}
	}
	if {$found == ""} {
		complain "there is no event at mark $mark, try again"
		fail_event
		return
	} else {
		set type [lindex $event($found) 2]
		if {$type == "f"} {
			complain "this event is already a fail event"
			mode
			select_near
			toolbar_bind
			return
		}	
	}
	$TW_Vip itemconfigure type$found -text "f"
	$TW_Vip create line [expr $x - 10] [expr $yo - 10] \
		[expr $x + 10] [expr $yo + 10] \
		-fill red -width 2 -tags "fail_event$found"
	$TW_Vip create line [expr $x + 10] [expr $yo - 10] \
		[expr $x - 10] [expr $yo + 10] \
		-fill red -width 2 -tags "fail_event$found"		
	select_near
	toolbar_bind
	debug "at end of fail_event1"
}


proc add_constraint {} {
	global TW_Vip
	debug "entering add_constraint"
	update_help "Select the start mark for the constraint"
	$TW_Vip config -cursor sb_h_double_arrow
	bind $TW_Vip <ButtonPress-1> "
		set cx \[$TW_Vip canvasx %x]
		set cy \[$TW_Vip canvasy %y]
		add_constraint1 \$cx \$cy
		add_constraint2
		"
}

proc add_constraint1 {cx cy} {
	global TW_Vip
	debug "ENTERING add_constraint1"
	set x [lindex [get_mark $cx none] 1]
	$TW_Vip create line $x $cy $x $cy -fill red -tags con_line
}

proc add_constraint2 {} {
	global TW_Vip
	debug "entering add_constraint2"

	bind $TW_Vip <ButtonPress-1> ""

	bind $TW_Vip <Motion> "
		set cx \[$TW_Vip canvasx %x]
		add_constraint3 \$cx
		"

	bind $TW_Vip <ButtonRelease-1> "
		$TW_Vip config -cursor arrow
		bind $TW_Vip <Motion> {}
		set cx \[$TW_Vip canvasx %x] 
		add_constraint4 \$cx
		labels add c
		select_near
		toolbar_bind
		"
}

proc add_constraint3 {cx} {
	global TW_Vip
	debug "entering add_constraint3 - to change coords of con_line"
	set x [lindex [$TW_Vip coords con_line] 0]
	set y [lindex [$TW_Vip coords con_line] 1]
	$TW_Vip coords con_line $x $y $cx $y
	update
}

proc add_constraint4 {cx} {
	global TW_Vip
	set x_begin [lindex [$TW_Vip coords con_line] 0]
	set y [lindex [$TW_Vip coords con_line] 1]
	set x [lindex [get_mark $cx "none"] 1]
	$TW_Vip coords con_line $x_begin $y $x $y
}



proc move_ghost {new_cx new_cy} {
	global TW_Vip
	global last_cx last_cy
	debug "entering move_ghost"
	set mx [expr $new_cx - $last_cx]
	set my [expr $new_cy - $last_cy]
	$TW_Vip move ghost $mx $my
	set last_cx $new_cx
	set last_cy $new_cy
	update
}

proc move {n x y} {
	global TW_Vip
	global xo x_spacing yo y_spacing mode nl mark mydata sm last_cx last_cy

	debug "\n\nentering move with n=$n, x=$x, y=$y"
	if [winfo exists .ec$n] {
		bind $TW_Vip <Motion> ""
		return ;# edit window is up for this object so don't move
	}
	gen_mydata $n

	$TW_Vip bind ob$n <ButtonPress-1> ""
	set last_cx $x
	set last_cy $y
	$TW_Vip config -cursor sb_h_double_arrow
	set type [lindex $mydata 2]
	set crd [$TW_Vip coords ob$n]
	set x1 [lindex $crd 0]
	set y1 [lindex $crd 1]
	set x2 [lindex $crd 2]
	set y2 [lindex $crd 3]

	#create ghost thing here
	$TW_Vip create line $x1 $y1 $x2 $y2 -fill gray -tags ghost

	#move ghost
	bind $TW_Vip <Motion> "
		set cx \[$TW_Vip canvasx %x]
		set cy \[$TW_Vip canvasy %y]
		move_ghost \$cx \$cy ;# show new position of ghost
		update
		"
	set lenx [expr $x2 - $x1]
	set begin [lindex $mydata 0]
	set end [lindex $mydata 1]
	set include_b "yes"
	if {$begin < 0} {
		set include_b "no"
		set begin [expr 0 - $begin]
		}
	set include_e "yes"
	if {$end < 0} {
		set include_e "no"
		set end [expr 0 - $end]
		}
	set x1_dist [lindex $crd 0]
	set off_x [expr $x - $x1_dist]
	set xdiff [expr $end - $begin]
	debug "in move, xdiff=$xdiff = ($end - $begin)"
 
	bind $TW_Vip <ButtonRelease-1> "
		catch {$TW_Vip delete ghost}
		set cx \[$TW_Vip canvasx %x]
		set cy \[$TW_Vip canvasy %y]
		if {(\$cx != $x) || (\$cy != $y)} {
			#move object to new position and update data
			move2 $type $n $xdiff \$cx \$cy $off_x $include_b $include_e $begin
		} else {
			set_object_bindings $n off off ;# object off, move off
			catch {$TW_Vip delete ghost}
			unselect
			select_near
			}
		"
}

proc bind_guideline {type n direction} {
	global TW_Vip
	debug "entering bind_guideline with type=$type, n=$n, and direction = $direction"
	switch $direction {
		right	{
			$TW_Vip bind br <ButtonPress-1> "
				guideline $type $n $direction
				"
			}
		left	{
			$TW_Vip bind bl <ButtonPress-1> "
				guideline $type $n $direction
				"
			}
	}
}

proc select_near {} {
	global TW_Vip
	global bind_on
	debug "entering select_near"
	$TW_Vip config -cursor arrow
	bind $TW_Vip <ButtonRelease-1> ""
	bind $TW_Vip <ButtonPress-1> "
		unselect
		set x1 \[$TW_Vip canvasx %x]
		set y1 \[$TW_Vip canvasy %y]
		what_is_it \$x1 \$y1
		"
}

proc what_is_it {x y} {
	global TW_Vip
	global select_item spec mydata
	debug "entering what_is_it with x=$x, and y=$y"
	set tag_caught [$TW_Vip itemcget [$TW_Vip find closest $x $y] -tags]
	set tag_caught [lindex $tag_caught 0] ;# get most specific tag
	set fi [string index $tag_caught 0]
	append fi [string index $tag_caught 1]
	if {$fi != "ob"} {
		select_near
		return
	} else {
		set c [eval $TW_Vip coords $tag_caught]
		set x1 [lindex $c 0]
		set y1 [lindex $c 1]
		set x2 [lindex $c 2]
		set y2 [lindex $c 3]
		set n [string range $tag_caught 2 end]
		gen_mydata $n

		set select_item $n
		set type [lindex $mydata 2]
		set_selection_guides $n
		set_object_bindings $n on on ;#object on, move on
		}
} 

proc set_object_bindings {n object_how move_how} {
	global TW_Vip
	global select_item mydata bind_on
	debug "entering set_object_bindings for object=$n, object_how=$object_how, move_how=$move_how"
	gen_mydata $n
	set type [lindex $mydata 2]

	if {($bind_on != "") && ($bind_on != $n)} {
		set was_on $bind_on
		set bind_on ""
		set_object_bindings $was_on off off ;#object off, move off
	}
	
	switch $object_how {
	"on"	{
		set bind_on $n
		$TW_Vip bind ob$n <Button-3> "
			tk_popup $TW_Vip.m$n %X %Y
			bind $TW_Vip <Motion> {}
			"

		bind $TW_Vip <ButtonPress-1> "
			unselect
			set x1 \[$TW_Vip canvasx %x]
			set y1 \[$TW_Vip canvasy %y]
			what_is_it \$x1 \$y1
			"

		if {$type == "c"} {
			$TW_Vip bind br <Enter> "
				$TW_Vip config -cursor diamond_cross
				bind_guideline $type $n right
				"
			$TW_Vip bind br <Leave> "
				$TW_Vip config -cursor arrow
				"
			$TW_Vip bind bl <Enter> "
				$TW_Vip config -cursor diamond_cross
				bind_guideline $type $n left
				"
			$TW_Vip bind bl <Leave> "
				$TW_Vip config -cursor arrow 
				"
			}
		}
	"off"	{
		$TW_Vip config -cursor arrow
		update
		set bind_on ""
		set select_item ""
		$TW_Vip bind ob$n <Button-3> ""
		$TW_Vip bind ob$n <ButtonPress-1> ""

		bind $TW_Vip <ButtonRelease-1> ""
		bind $TW_Vip <Motion> "" ;#new
		$TW_Vip bind label$n <Enter> {}
		$TW_Vip bind ob$n <Enter> {}
		$TW_Vip bind label$n <Leave> {}
		$TW_Vip bind ob$n <Leave> {}
		select_near
		}
	default {}
		}
	switch $move_how {
	"on"	{	bind $TW_Vip <Motion> "
				bind $TW_Vip <ButtonPress-1> {} ;#new
				set cx \[$TW_Vip canvasx %x]
				set cy \[$TW_Vip canvasy %y]
				move $n \$cx \$cy
				"
			bind $TW_Vip <ButtonRelease-1> "
				bind $TW_Vip <Motion> {}
				"
	
		}
	"off"	{	bind $TW_Vip <Motion> ""
			bind $TW_Vip <ButtonRelease-1> ""
		}
	}			
					
}

proc unselect {} {
	global TW_Vip select_item 
	debug "entering unselect"
	$TW_Vip bind br <Enter> ""
	$TW_Vip bind br <Leave> ""
	$TW_Vip bind bl <Enter> ""
	$TW_Vip bind bl <Leave> ""
	$TW_Vip bind br <ButtonPress-1> ""
	$TW_Vip bind br <ButtonRelease-1> ""
	bind $TW_Vip <Motion> ""
	catch {$TW_Vip delete br}
	catch {$TW_Vip delete bl}
	catch {$TW_Vip delete gl} ;# used when constraint is resized
	catch {$TW_Vip delete con_line} ;#used for move or add constraint
	catch {$TW_Vip delete guide_event} ;# used for move or add event

	# get rid of any bindings on canvas as a whole
	bind $TW_Vip <ButtonPress-1> ""
	bind $TW_Vip <ButtonRelease-1> ""
	bind $TW_Vip <Motion> ""
	#select_near

	#get rid of bindings on ob
	$TW_Vip bind ob$select_item <ButtonPress-1> ""
	$TW_Vip bind ob$select_item <Button-3> ""
	#select_near
}

proc move2 {type n xdiff x y off_x include_b include_e old_begin} {
	global TW_Vip
	global event const nob lm xo sm x_spacing mydata
	debug "\n\nentering move2 type=$type n=$n xdiff=$xdiff x=$x, off_x=$off_x, etc... mydata is: $mydata"
	gen_mydata $n
	bind $TW_Vip <Motion> {}
	set x [expr $x - $off_x]
	set rval [get_mark $x none]
	set mark [lindex $rval 3]
	set x_frac [lindex $rval 5]
	set begin $mark
	set end [expr $begin + $xdiff]
	if {$end > $lm} {
		set begin [expr $begin - ($end - $lm)] ;# move object back if it extends beyond largest mark
		}
	
	set end [expr $begin + $xdiff]

	debug "in move2, begin set to $begin, and end = $end = ($begin + $xdiff)"
	switch -regexp $type {
		e|r|f	{
			if {$begin == $old_begin} {
				catch {$TW_Vip delete ghost}
				$TW_Vip config -cursor arrow
				$TW_Vip raise br
				$TW_Vip raise bl
				select_near
				set_object_bindings $n on off
				return ;# user has not moved cursor
			}
			if {[check_dup_event $begin]} {
				complain "There is already an event assigned to that mark"
				catch {$TW_Vip delete ghost}
				$TW_Vip config -cursor arrow
				$TW_Vip raise br
				$TW_Vip raise bl
				select_near
				set_object_bindings $n on off ;#object on, move off
				return
			}
			if {$mark == $sm} {
				if [check_empty_mark] {
					complain "There is no empty mark"
					return
				} else {
					set begin $old_begin
				}
			}
		update_event $n mark $begin
		}
		c {
			#make sure if begin=sm, then begin is included and end is at least sm+1
			if {$begin == $sm} {
				if {[lindex $mydata 4] == "no"} {
					update_const $n ib ;#include begin mark
				}
				if {$end == $sm} {
					set end [expr $sm + 1] ;# increment end mark to be sm+1
				}
			}	
			update_const $n begin $begin
			update_const $n end $end
			update_const $n ycoord $y
	}	}
	set_selection_guides $n
	catch {$TW_Vip delete ghost}
	if {$type == "c"} {
		distribute_constraints
		}
	$TW_Vip config -cursor arrow
	select_near
	set_object_bindings $n on off
}

proc guideline {type n side} { ;#only called for constraints
	global TW_Vip
	global spec co x_spacing xo sm mydata
	debug "entering guideline with type=$type, n=$n, side=$side"
	gen_mydata $n
	bind $TW_Vip <ButtonPress-1> ""
	bind $TW_Vip <ButtonRelease-1> ""
	set bm [lindex $mydata 0]
	set em [lindex $mydata 1]
	set include_b [lindex $mydata 4]
	set include_e [lindex $mydata 5]
	set bc [expr $xo + (.5 * $x_spacing) + (($bm - $sm) * $x_spacing)]
	set ec [expr $xo + (.5 * $x_spacing) + (($em - $sm) * $x_spacing)]
	set old_coords "[$TW_Vip coords const$n]"
	set yc [lindex $old_coords 1]
	$TW_Vip create line $bc $yc $ec $yc -fill gray -tags gl

	# update size of guidebar when mouse moves
	bind $TW_Vip <Motion> "
		set cx \[$TW_Vip canvasx %x]
		update_guideline $type $n $side \$cx $bc $ec $yc
		"
	# reset condition
	bind $TW_Vip <ButtonRelease-1> " 
		set cx \[$TW_Vip canvasx %x]
		resize_constraint $n $side \$cx $bm $em
		"
}

proc update_guideline {type n side x bc ec yc} {
	global TW_Vip
	global xo x_spacing lm sm
	debug "entering update_guideline"
	#constrain guideline to be between smallest mark and largest mark
	if {$side == "right"} {
		set lc [expr $xo + (.5 * $x_spacing) + (($lm - $sm) * $x_spacing)]
		if {$x > $lc} {
			set x $lc
			}
		if {$x <= $bc} {
			set x [expr $bc + 4]
			}
		set ec $x 
	} elseif {$side == "left"} {
		set sc [expr $xo + (.5 * $x_spacing)]
		if {$x < $sc} {
			set x $sc
			}
		if {$x >= $ec} {
			set x [expr $ec - 4]
			}
		set bc $x
		}
	$TW_Vip coords gl $bc $yc $ec $yc
	update
}

proc resize_constraint {n side x bm em} {
	global TW_Vip
	global spec xo x_spacing lm sm offx mydata
	debug "entering resize_constraint"
	gen_mydata $n

	set begin [lindex mydata 0]
	set end [lindex mydata 1]
	set include_b [lindex mydata 4]
	set include_e [lindex mydata 5]

	#mark is mark closest to cur x-coord
	set mark [lindex [get_mark $x "none"] 3]
	set sc [expr $xo + (.5 * $x_spacing)]
	if {$side == "right"} {
		set alter_begin 0
		if {$mark <= $bm} {
			set em $bm
			set bm $mark
			set alter_begin 1
			update_const $n ib
			update_const $n ie 
		} else {
			set em $mark
			}
		if {$bm == $sm} {
			if {[lindex $mydata 4] == "no"} {
				update_const $n ib ;#include begin mark
			}
			if {$bm == $sm} {
				set em [expr $sm + 1] ;# increment end mark to be sm+1
			}
		}
		if $alter_begin {
			update_const $n begin $bm
		}
		update_const $n end $em
	} elseif {$side == "left"} {
		if {$mark >= $em} {
			set bm $em
			set em $mark
			set alter_begin 1
			update_const $n ib
			update_const $n ie
		} else {
			set bm $mark
			}
		if {$bm == $sm} {
			if {[lindex $mydata 4] == "no"} {
				update_const $n ib ;#include begin mark
			}
			if {$bm == $sm} {
				set em [expr $sm + 1] ;# increment end mark to be sm+1
			}
		}
		update_const $n begin $bm
		}
	set_selection_guides $n
	bind $TW_Vip <Motion> {}
	bind $TW_Vip <ButtonRelease-1> {}
	catch {$TW_Vip delete gl}
	set_object_bindings $n on off ;# object on, move off
}

proc set_selection_guides {n} { ;#little red boxes that show which obj is selected - used to create and to move them
	global TW_Vip
	global mydata
	debug "entering set_selection_guides with n=$n"
	gen_mydata $n
	catch {$TW_Vip delete br}
	catch {$TW_Vip delete bl}
	set type [lindex $mydata 2]
	switch -regexp $type {
		e|r|f	{set c [$TW_Vip coords event$n]
			set x1 [lindex $c 0]
			set y1 [expr [lindex $c 1] - 2]
			set x2 [lindex $c 2]
	        	set y2 [expr [lindex $c 3] + 2]
			}
		c	{set c [$TW_Vip coords const$n]
			set x1 [expr [lindex $c 0] - 20]
			set y1 [lindex $c 1]
			set x2 [expr [lindex $c 2] + 20]
			set y2 [lindex $c 3]
			}
		}

	$TW_Vip create rect \
		[expr $x1 - 2] [expr $y1 - 2] [expr $x1 + 2] [expr $y1 + 2] \
		-tags {bb0 bl} -fill red -outline red
	$TW_Vip create rect \
		[expr $x1 - 2] [expr $y2 - 2] [expr $x1 + 2] [expr $y2 + 2] \
		-tags {bb1 bl} -fill red -outline red
	$TW_Vip create rect \
		[expr $x2 - 2] [expr $y1 - 2] [expr $x2 + 2] [expr $y1 + 2] \
		-tags {bb2 br} -fill red -outline red
	$TW_Vip create rect \
		[expr $x2 - 2] [expr $y2 - 2] [expr $x2 + 2] [expr $y2 + 2] \
		-tags {bb3 br} -fill red -outline red
	$TW_Vip raise bl
	$TW_Vip raise br
}



proc new_mark {} {
	global TW_Vip
	global yo yc desc atype nl spec select_item
	debug "\nENTERING new_mark"
	if {$select_item != ""} {
		set_object_bindings $select_item off off
		}
	unselect
	set help_msg ""
		append help_msg "To insert a new mark, select a location between two marks,"
		append help_msg " before the first mark, or after the last mark."
		append help_msg " Select anywhere if there are no other marks."
	update_help $help_msg
	$TW_Vip config -cursor sb_down_arrow
	set mb "Add_Mark"
	bind $TW_Vip <ButtonPress-1> "
		set cx \[$TW_Vip canvasx %x]
		new_mark1 \$cx $mb
		"
}

proc new_mark1 {cx mb} {
	global TW_Vip
	global sm
	debug "ENTERING new_mark1"
	$TW_Vip config -cursor arrow
	set mark [lindex [get_mark $cx down] 3]
	if {$mark >= [expr $sm - 1]} {
		draw_new_mark $mark unknown
		dirty
		}
	select_near
	toolbar_bind
}

proc adj_for_new_mark {nm pos} {
	global TW_Vip
	global lm sm sv x_spacing ylen_def xo yo event const nob
	debug "entering adj_for_new_mark with nm=$nm, pos=$pos"
	gendata

	#don't need to adjust events and constraints if new mark is larger than largest mark
	if {$nm >= [expr $lm - 1]} {
		return
		}

	#adjust events
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$event($i) == ""} { 
			continue
			}
		set b [lindex $event($i) 0]
		if {$nm < $b} {
			incr b 1
			update_event $i mark $b
			}
		}

	#adjust constraints
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) == ""} {
			continue
			}
		set b [lindex $const($i) 0]
		set e [lindex $const($i) 1]
	
		if {$nm < $b} {
			incr b 1
			update_const $i begin $b
			}
		if {$nm < $e} {
			incr e 1
			update_const $i end $e
			}
	
		}

	bind $TW_Vip <ButtonPress-1> {}
}

proc draw_new_mark {nm pos} {
	global TW_Vip
	global lm sm sv x_spacing ylen_def xo yo smallFont nmark
	debug "entering draw_new_mark with nm=$nm and pos=$pos, sm=$sm"
	update_help ""
	#adjust nm to allow a new mark to be inserted in first mark position
	
	if {$pos == "unknown"} {
		if {$nm >= $lm} {
			set pos "end"
		} elseif {$nm < $sm} {
			set pos "begin"
		} elseif {($nm >= $sm) && ($nm < $lm)} {
			set pos "middle"
			}
		}

	#make a new mark at the end always
	incr lm 1 ;# incr largest mark on the canvas -- this is the only place lm is incremented
	incr nmark 1 ;# the internal number used to identify the mark -- not the same as lm
	set tlen [expr $x_spacing * ($lm - $sm + 1)]
	set mk [$TW_Vip find withtag markline]
	$TW_Vip coords markline [expr $xo + (.5 * $x_spacing)] $yo [expr $xo + $tlen] $yo
	set tl1 [$TW_Vip find withtag timeline1]
	$TW_Vip coords timeline1 [expr $xo + (.5 * $x_spacing)] [expr $yo + 1] [expr $xo + $tlen] [expr $yo + 17]
	debug "in draw_new_mark, coords of timeline1 set to [expr $xo + (.5 * $x_spacing)] [expr $yo + 1] [expr $xo + $tlen] [expr $yo + 17]"
	$TW_Vip create line [expr $sv + (($lm - $sm) * $x_spacing)] $yo \
		[expr $sv + (($lm - $sm) * $x_spacing)] $ylen_def -fill blue -tags "vert$nmark vline$nmark"
	#quotes were needed around the multiple tags -- {} didn't work
	$TW_Vip create text [expr $xo + (.5 * $x_spacing) + (($lm - $sm) * $x_spacing)] [expr $ylen_def + 5] \
		-text $lm -font $smallFont -anchor n -tags "vert$nmark vtext$nmark" -fill blue

	set items [$TW_Vip find all]
	foreach i $items {
		# make all marks blue
		set tags [$TW_Vip gettags $i]
		foreach j $tags {
			set f5 ""
			catch {set f5 [string range $j 0 4]}
			if {$f5 == "vline"} {
				set c [$TW_Vip coords $j]
				set x [lindex $c 0]
				catch {destroy ${TW_Vip}.mv$nmark}
				if {$x != [expr $xo + (.5 * $x_spacing)]} {
					$TW_Vip itemconfigure $j -fill blue
					menu $TW_Vip.mv$nmark -tearoff 0
					$TW_Vip.mv$nmark add command -label "delete mark" \
						-command "delete_mark $nmark"
					$TW_Vip bind vert$nmark <Button-3> "
						tk_popup $TW_Vip.mv$nmark %X %Y 1
						"	
				} else {
					$TW_Vip itemconfigure $j -fill gray
				}
			} elseif {$f5 == "vtext"} {
				set c [$TW_Vip coords $j]
				set x [lindex $c 0]
				if {$x != [expr $xo + (.5 * $x_spacing)]} {
					$TW_Vip itemconfigure $j -fill blue
				} else { 
					$TW_Vip itemconfigure $j -fill gray
				}
			}
		}
	}

	if {($pos == "begin") || ($pos == "middle")} {
		adj_for_new_mark $nm $pos
	}
}

proc delete_mark {dm} {
	global TW_Vip
	global lm sm sv x_spacing ylen_def xo yo event const nob
	debug "entering delete_mark with dm=$dm"
	#figure out which display mark this is:
	set dmcoords "[$TW_Vip coords vert$dm]"
	set xc [lindex $dmcoords 0]
	set rval [get_mark $xc "none"] ;#call this to get the screen mark
	set mpd [lindex $rval 3] ;#mpd stands for mark pending deletion
	gendata ;# debug "gendata call - from delete_mark"
	#adjust events and constraints
	for {set i 1} {$i <= $nob} {incr i 1} { ;# cycle through all events
		
		#delete an event that is assigned to the mark to be deleted
		if {$event($i) == ""} {
			continue
			}
		set b [lindex $event($i) 0]
		if {$b == $mpd} {
			delete_object $i
		} elseif {$b > $mpd} {
			incr b -1
			update_event $i mark $b
			}
		}
			
	for {set i 1} {$i <= $nob} {incr i 1} {  ;# cycle through all constraints
		if {$const($i) == ""} {
			continue
			} 

		set this_way "do not know yet"
		set b [lindex $const($i) 0]
		set bm $b
		set e [lindex $const($i) 1]
		set em $e
		set include_b [lindex $const($i) 4]
		set include_e [lindex $const($i) 5]
	
		if {($mpd < $b) && ($b > $sm)} { ;#mark is less than begin mark but larger than smallest mark
			incr bm -1
			update_const $i begin $bm
			}
		if {($mpd == $b) && ($include_b == "no")} {
			set include_b "yes"
			update_const $i ib
			}	
		if {($mpd <= $e) && ($e > $sm)} { ;#mark is less than or equal to end mark and end mark is larger than smallest mark
			incr em -1
			update_const $i end $em
			}
		if {($mpd == $e) && ($include_e == "no")} {
			set include_e "yes"
			update_const $i ie
			}
		if {($e == $mpd) && ($b == $mpd)} { ;#end mark == begin mark, and is the same as mark pending deletion
			delete_object $i
			continue
			}
		if {$bm == $em} { ;#adjusted begin and end marks are the same and one or both ends are excluded
			if {($include_b == "no") || ($include_e == "no")} {
				delete_object $i
				}
			}
		}

	#find and delete last mark, decrement lm
	set target_xc [expr $sv + (($lm - $sm) * $x_spacing)]
	set target_yc [expr $yo + $ylen_def - 5]
	set lm_id [$TW_Vip find closest $target_xc $target_yc]
	$TW_Vip delete $lm_id
	set target_yc [expr $yo + $ylen_def + 5]
	set lm_id [$TW_Vip find closest $target_xc $target_yc]
	$TW_Vip delete $lm_id
	incr lm -1
	$TW_Vip coords markline [expr $xo + (.5 * $x_spacing)] $yo \
			[expr $sv + (($lm - $sm) * $x_spacing) + (.5 * $x_spacing)] $yo
	$TW_Vip coords timeline1 [expr $xo + (.5 * $x_spacing)] [expr $yo + 1] \
		[expr $sv + (($lm - $sm) * $x_spacing) + (.5 * $x_spacing)] [expr $yo + 17]
	debug "new coords of timeline1 (in delete_mark) are: [expr $xo + (.5 * $x_spacing)] [expr $yo + 1] [expr $sv + (($lm - $sm) * $x_spacing) + (.5 * $x_spacing)] [expr $yo + 17]"
	dirty
}

#remove undesirable characters: " and backslash and tab and carriage return and trailing spaces
proc cleanup_string {dirty} {
	global TW_Vip
	global clean_string
	debug "entering cleanup_string with dirty = $dirty"
	set clean_string ""
	set n [string length $dirty]
	for {set i 0} {$i < $n} {incr i 1} {
		set c [string index $dirty $i]
		set cmod $c
		if {($c == "\"")} {
			set cmod ""
		} elseif {$c == "\'"} {
			set cmod ""
		} elseif {$c == "\\"} {
			set cmod ""
		} elseif {$c == "	"} {
			set cmod " "
		} elseif {$c == "\n"} {
			set cmod " "
			}
		append clean_string $cmod
		}
	debug "before looking for extra spaces, clean_string is: $clean_string XXXX"
	for {set i [expr [string length $clean_string] - 1]} {$i >= 0} {incr i -1} {
		debug "in cleanup_string: considering char $i - [string index $clean_string $i]"
		if {[string index $clean_string $i] == " "} {
			set clean_string [string range $clean_string 0 [expr $i - 1]]
			debug "after removing char $i, clean_string is: $clean_string XXXX"
		} else {
			break
			}
		}
			
	debug "exiting cleanup_string"
}

proc adj_vline_len {} {
	global TW_Vip
	# adjust mark line lengths to the 2 * y_spacing longer than lowest constraint
	debug "entering adj_vline_len"
	global ylen_def yo sm lm y_spacing x_spacing xo sv yc nob const ylen_def
	gendata; debug "gendata being called by adj_vline_len"
	set maxy 0
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) == ""} {
			continue
			}
		set y [lindex [$TW_Vip coords const$i] 1]
		if {$y > $maxy} {
			set maxy $y
			}
		}
	set ylen_def [expr $maxy + (1.5 * $y_spacing)] ;# this can be used by other procs
	set ymin [expr $yo + (1.5 * $y_spacing)]
	if {$ylen_def < $ymin} { ;# if there are no constraints
		set ylen_def $ymin
		} 
	set sv [expr $xo + (.5 * $x_spacing)]
	set items [$TW_Vip find all]
	foreach i $items {
		set tags [$TW_Vip gettags $i]
		foreach j $tags {
			set f5 ""
			catch {set f5 [string range $j 0 4]}
			if {$f5 == "vline"} {
				set c [$TW_Vip coords $j]
				set x [lindex $c 0]
				$TW_Vip coords $j $x $yo $x $ylen_def
			} elseif {$f5 == "vtext"} {
				set c [$TW_Vip coords $j]
				set x [lindex $c 0]
				$TW_Vip coords $j $x [expr $ylen_def + 5]
			}
		}
	}
}

proc find_lowest_constraint {} {
	global TW_Vip
	global nob const ymax yo
	# find y-coordinate of the lowest constraint - puts it in ymax 
	debug "entering find_lowest_constraint"
	gendata
	set ymax $yo
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) == ""} {
			continue
		}
		set y [lindex [$TW_Vip coords const$i] 1]
		if {$y > $ymax} {
			set ymax $y
		}
	}
}

proc distribute_constraints {} {
	global TW_Vip
	global yo y_spacing const nob sorted_indices
	debug "entering distribute_constraints"
	#constraints must be sorted by ycoordinate so that user layout of constraints is preserved
	gendata; debug "calling gendata from distribute_constraints"
	set list ""
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) == ""} { ;#must preserve all list entries in order to make sense of indices in sorted_indices
			debug "const($i) == null, appending '-1' to list"
			lappend list -1 ;#dummy value -lower than real values
		} else {
			debug "const($i) == $const($i), appending it to list"
			lappend list [lindex [$TW_Vip coords const$i] 1]
			}
		}
	debug "in distribute_constraints - calling sort with list=$list"
	sort $list
	debug "in distribute_constraints, after sort, sorted_indices are: $sorted_indices"
	set yc $yo
	foreach i $sorted_indices {
		set p [expr $i + 1] ;# sort uses list indices from 0, so must increment since const uses indices from 1
		if {$const($p) != ""} {
			set oldy [lindex [$TW_Vip coords const$p] 1]
			incr yc $y_spacing
			set ydif [expr $yc - $oldy]
			$TW_Vip move ob$p 0 $ydif
			}
		}	
}


proc get_mark {x_in round_mode} { ;# find x coordinate of nearest marker to spot clicked
	global TW_Vip
	# if called with round_mode == 'down', rounds down
	# 'x' will contain the x coordinate of nearest marker to location clicked
	# 'mark' will contain the mark # nearest to location clicked

	debug "entering get_mark with x_in=$x_in, round_mode=$round_mode"
	global xo x_spacing lm sm
	set x $x_in
	set mark -1
	set x_frac -1
	set num_to_beat [expr (($lm - $sm) * $x_spacing) + ($xo + (.5 * $x_spacing))]
	#round
	if {$x > $num_to_beat} {
		set x $num_to_beat
		set mark $lm
	} elseif {$x < $xo} { ;# if point clicked is left of timeline start point
		set x [expr $xo + (.5 * $x_spacing)]
		set mark $sm
	} else {
		set x [expr $x - ($xo + (.5 * $x_spacing))] ;# remove offset
		set x_frac [expr $x / $x_spacing]
		set mark [expr round($x_frac)] ;#find nearest marker
		if {$round_mode == "down"} {
			if {$x_frac < $mark} {
				set mark [expr $mark - 1]
				}
			}
		incr mark $sm ;# add 'sm' since first marker number is sm.
		
		#convert back to canvas coordinates, and add back in the offset
		set x [expr (($mark - $sm) * $x_spacing) + ($xo + (.5 * $x_spacing))]
	
	}
	set rval(1) $x
	set rval(2) $mark
	set rval(3) $x_frac
	return [array get rval]	
}

proc label_edits {mode} {
	global TW_Vip nob event const
	#turn on and off label edits

	gendata 

	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) != ""} {
			if {$mode == "enable"} {
				$TW_Vip bind label$i <Button-1> "labels edit c $i"
			} elseif {$mode == "disable"} {
				$TW_Vip bind label$i <Button-1> ""
			}
		} elseif {$event($i) != ""} {
			if {$mode == "enable"} {
				$TW_Vip bind label$i <Button-1> "labels edit [lindex $event($i) 2] $i"
			} elseif {$mode == "disable"} {
				$TW_Vip bind label$i <Button-1> ""
	}	}	}
}

#---beginning of label editting---

proc labels {mode type {n -1}} {
	global TW_Vip
	global edef elab cdef clab ned ncd
	global tedef telab tcdef tclab tned tncd
	global mydata select_item SmallFont
	global initsym initdef initindex

	set initsym ""
	set initdef ""
	set initindex ""
	
	# mode is add or edit
	# type is e,r, or c

	label_edits disable

	catch { destroy .labels }

	set selected_type ""
	if {$select_item != ""} {
		gen_mydata $select_item
		set selected_type [lindex $mydata 2] ;#apply will only be active if type and selected_type match
		}
	switch -regexp $type {
	e|r|f	{ set name_singular Event
		  set name Events
		  set tned $ned ;#changes are temporary until "save" selected
		  array set telab [array get elab]
		  array set tedef [array get edef]
		}
	c	{ set name_singular Constraint 
		  set name Constraints
		  set tncd $ncd
		  array set tclab [array get clab]
		  array set tcdef [array get cdef]
		}
	}

	set bgr "gray"

	toplevel .labels -relief flat -bg $bgr

	frame .labels.t -relief raised -bd 2 -bg $bgr
	pack .labels.t -side top -fill x -padx 10 -pady 10 -expand 1

	frame .labels.t.2 -relief sunken -bg white -borderwidth 2 -bg $bgr
	pack .labels.t.2 -side top -fill x -padx 10 -pady 10 -expand 1

	scrollbar .labels.t.2.scroll \
		-command "scrolltwins" -bg $bgr

	pack .labels.t.2.scroll -side right -fill y

	frame .labels.t.2.w -relief flat -bg $bgr
	pack .labels.t.2.w -side left -fill y -expand 1
	
	label .labels.t.2.w.label \
		-text $name_singular \
		-borderwidth 2 -relief sunken -bg black -fg gold

	pack .labels.t.2.w.label -side top -fill x

	listbox .labels.t.2.w.list \
		-bg black -fg white \
		-yscroll ".labels.t.2.scroll set" \
		-relief sunken -height 20 -width 20 \
		-selectforeground black -selectbackground gold
	frame .labels.t.2.e -relief flat
	pack .labels.t.2.e -side left -fill y -expand 1

	label .labels.t.2.e.label \
		-text "Definition" \
		 -borderwidth 2 -relief sunken -bg black -fg gold

	pack .labels.t.2.e.label -side top -fill x


	listbox .labels.t.2.e.list \
		-bg black -fg white \
		-yscroll ".labels.t.2.scroll set" \
		-relief sunken -height 20 -width 35 \
		-exportselection false \
		-selectforeground black -selectbackground gold

	pack .labels.t.2.w.list -side left -fill y -expand 1
	pack .labels.t.2.e.list -side right -fill y -expand 1

	bind .labels.t.2.w.list <<ListboxSelect>> "displaydefinition w $type; selecttwin"
	bind .labels.t.2.w.list <2> ".labels.t.2.w.list scan mark %x %y"
	bind .labels.t.2.w.list <B2-Motion> "
		.labels.t.2.w.list scan dragto 0 %y
		.labels.t.2.e.list scan dragto 0 %y
		.labels.t.2.e.list xview 0
		"
	bind .labels.t.2.e.list <2> ".labels.t.2.e.list scan mark %x %y"
	bind .labels.t.2.e.list <B2-Motion> "
		.labels.t.2.w.list scan dragto 0 %y
		.labels.t.2.e.list scan dragto 0 %y
		"

	bind .labels <<Copy>> "copysymbol $type"
	bind .labels <<Paste>> "pastesymbol $type"
	bind .labels <<Cut>> "copysymbol $type; deletesymbol $type"

	frame .labels.t.3 -relief flat -bg $bgr
	pack .labels.t.3 -side top -fill x -padx 10 -pady 5 -expand 1

	label .labels.t.3.label -text $name_singular -width 10 -bg $bgr
	pack .labels.t.3.label -side left

	entry .labels.t.3.entry -bg black -fg white \
		-selectbackground gold \
		-relief sunken -font {Helvetica 10 bold} \
		-insertbackground gold
	pack .labels.t.3.entry -side left -fill x -expand 1
	
	frame .labels.t.4 -relief flat -bg $bgr
	pack .labels.t.4 -side top -padx 10 -pady 5 -fill x -expand 1

	label .labels.t.4.label -text "Definition" -width 10 -bg $bgr
	pack .labels.t.4.label -side left

	text .labels.t.4.text \
		-yscroll ".labels.t.4.scroll set" \
		-relief sunken -height 4 -width 40 \
		-bg black -fg white \
		-selectbackground gold -font {Helvetica 10 bold} \
		-insertbackground gold
	pack .labels.t.4.text -side left -fill x -expand 1

	scrollbar .labels.t.4.scroll \
		-command ".labels.t.4.text yview"  -bg $bgr

	pack .labels.t.4.scroll -side right -fill y

	frame .labels.t.5 -relief flat -bg $bgr
	pack .labels.t.5 -side top -fill x -expand 1

	button .labels.t.5.apply -text "Apply" -bg black -fg gold -width 5 -bd 3 \
		-activeforeground black -activebackground gold \
		 -state disabled
	button .labels.t.5.set -text "Set" -bg black -fg gold -width 5 -bd 3 \
		-activeforeground black -activebackground gold
	if {$mode == "add"} {
		.labels.t.5.set configure \
			-command "set_symbol_definition $type"
	} elseif {$mode == "edit"} {
		.labels.t.5.set configure \
			-command "
				consider_update_edit_object_window $select_item
				set_symbol_definition $type  
				"
	}
	button .labels.t.5.delete -text "Delete" -bg black -fg gold -width 5 -bd 3 \
		 -activeforeground black -activebackground gold \
		-command "deletesymbol $type"
	
	pack .labels.t.5.apply -side left -padx 10 -pady 4

	frame .labels.b -relief flat -bg $bgr
	pack .labels.b -side bottom -fill x
	
	button .labels.b.ok -text "OK" \
		-bg black -fg gold -bd 3 \
		-activeforeground black -activebackground gold \
		-command "
			symbols_save $type
			catch {destroy .labels}
			symbols_temp_forget
			" 
	button .labels.b.cancel -text "Cancel" \
		-bg black -fg gold -bd 3 \
		 -activeforeground black -activebackground gold \
		-command "
			catch {destroy .labels}
			symbols_temp_forget
			"
	pack .labels.b.cancel .labels.b.ok -side right -padx 4 -pady 4

	switch $mode {
		add {	.labels.t.5.apply configure -state normal \
				-command "
					set_symbol_definition $type
					symbols_save $type
					process_label $type $n
					"
			.labels.b.cancel \
				configure -command "
					catch {destroy .labels}
					symbols_temp_forget
					process_label $type $n
					unselect
					select_near
					"
		}
		edit {
			if {$selected_type == $type} {
				.labels.t.5.apply configure -state normal \
					-command "
						set_symbol_definition $type
						symbols_save $type
						apply_symbol $type
						unselect
						select_near
						"
			}
		}		
	}

	pack .labels.t.5.delete .labels.t.5.set -side right -padx 10 -pady 4

	wm minsize .labels 10 10
	wm title .labels $name

	sortsymbols $type
	focus .labels.t.3.entry
}

proc set_symbol_definition {type} {
	global TW_Vip
	global initsym initdef initindex
	global tned tncd telab tclab tedef tcdef
	set cursym [.labels.t.3.entry get]
	scan [.labels.t.4.text index end] %d nnl
	set curdef [string trimright [.labels.t.4.text get 0.0 [expr $nnl-1].end]]

	#this covers the case where user selects symbol name, 
	set index [match_symbol_temp $type $cursym]
	if {$index != 0} {
		#symbol name matches name of symbol that is already in the list
		switch -regexp $type {
			e|r|f {set tedef($index) $curdef
			    }
			c   {set tcdef($index) $curdef
			    }
		}
		.labels.t.2.e.list delete [expr $index - 1] [expr $index - 1]
		.labels.t.2.e.list insert [expr $index - 1] $curdef
		.labels.t.2.w.list selection set [expr $index - 1] [expr $index - 1]
		.labels.t.2.e.list selection set [expr $index - 1] [expr $index - 1]
		.labels.t.2.w.list see [expr $index - 1]
		.labels.t.2.e.list see [expr $index - 1]
		
		return
	}
	#symbol name is new
	switch -regexp $type {
		e|r|f {incr tned 1
		     set telab($tned) $cursym
		     set tedef($tned) $curdef
		    }
		c   {incr tncd 1
		     set tclab($tncd) $cursym
		     set tcdef($tncd) $curdef
		    }
		}
	
	sortsymbols $type
	set index [match_symbol_temp $type $cursym] ;#find item added in newly sorted list
	if {$index != 0} {
		.labels.t.2.w.list selection set [expr $index - 1] [expr $index - 1]
		.labels.t.2.e.list selection set [expr $index - 1] [expr $index - 1]
		.labels.t.2.w.list see [expr $index - 1]
		.labels.t.2.e.list see [expr $index - 1]
	}
}

proc symbols_save {type} {
	global TW_Vip
	global edef elab cdef clab ned ncd
	global tedef telab tcdef tclab tned tncd
	switch -regexp $type {
	e|r|f	{ set cnt 0 ;# want to get rid of deleted, i.e. empty, array items
		  for {set i 1} {$i <= $tned} {incr i 1} {
			if {$telab($i) != ""} {
				incr cnt 1
				set elab($i) $telab($i)
				set edef($i) $tedef($i)
			}
		  }
		  set ned $cnt
		 
		}
	c	{ set cnt 0
		  for {set i 1} {$i <= $tncd} {incr i 1} {
			if {$tclab($i) != ""} {
				incr cnt 1
				set clab($i) $tclab($i)
				set cdef($i) $tcdef($i)
			}
		  }
		  set ncd $cnt
		}
	}
	write_symbols_file
}

proc process_label {type n} {
	global TW_Vip
	global x_spacing nob yo mydata

	if ![winfo exists .labels] {
		set txt "?"
	} else {
		set txt [.labels.t.3.entry get]
		if {$txt == ""} {set txt "?"}
	}
	
	switch -regexp $type {
		e|r|f	{	set x_begin [lindex [$TW_Vip coords guide_event] 0]
				set x_end $x_begin
			}
		c	{	set x_begin [lindex [$TW_Vip coords con_line] 0]
				set x_end [lindex [$TW_Vip coords con_line] 2]
			}
		}
	if {$x_begin > $x_end} {
		set temp $x_begin
		set x_begin $x_end
		set x_end $temp
			}
	incr nob 1 ;# do it last because gendata sets nob to items found on canvas
	switch -regexp $type {
		e|r|f 	{	$TW_Vip delete guide_event
				draw $type $x_begin $x_end $yo $txt "" "" $nob
				}
		c 	{	set y [lindex [$TW_Vip coords con_line] 1]
				$TW_Vip delete con_line
				draw $type $x_begin $x_end $y $txt yes yes $nob
				distribute_constraints
				adj_vline_len
			}
		}
	#$TW_Vip bind label$nob <ButtonPress-1> "labels edit $type $nob"
	dirty
	$TW_Vip config -cursor arrow
	catch {destroy .labels}
}

proc copysymbol {type} {
	global TW_Vip
	global tedef telab tcdef tclab tned tncd
	#called from labels - copies selected symbol to clipboard
	global clipboard
	set cur [.labels.t.2.w.list curselection]
	if {$cur != ""} {
		set clipboard(1) [.labels.t.2.w.list get active]
		#get active doesn't always work properly for the definition listbox, so find corresponding definition
		set index [match_symbol_temp $type $clipboard(1)]
		if {$index != 0} {
			switch -regexp $type {
				e|r|f {set clipboard(2) $tedef($index)
				    }
				c   {set clipboard(2) $tcdef($index)
				    }
			}
		}
	}
}

proc pastesymbol {type} {
	global TW_Vip
	global clipboard tedef telab tcdef tclab tned tncd

	#called from labels - pastes selected symbol from clipboard to symbol list
	#if nothing on clipboard - error message
	#new copy has incremented number as suffix


	set i 0
	set find 1
	if {$clipboard(1) != ""} {
		#set clipboard_symbol [lindex $clipboard 0]
		if {[match_symbol_temp $type $clipboard(1)] == 0} {
			 # if symbol on clipboard was deleted, new doesn't have to be copy of..
			set new $clipboard(1)
			set find 0
		}
		while $find {
			#symbol on clipboard matches item still in symbol list so must make new symbol, copy of...
			incr i 1
			set match 0
			set new ""
			append new "copy " $i " of $clipboard(1)"
			switch -regexp $type {
				e|r|f {	for {set j 1} {$j <= $tned} {incr j 1} {
						if {$telab($j) == $new} {
							set match 1
							}
						}
					}
				c {	for {set j 1} {$j <= $tncd} {incr j 1} {
						if {$tclab($j) == $new} {
							set match 1
							}
						}
					}
				}
			if !$match {break}
			}
		scan [.labels.t.4.text index end] %d nnl
		.labels.t.4.text delete 0.0 $nnl.end
		.labels.t.3.entry delete 0 end
		.labels.t.3.entry insert end $new
		switch -regexp $type {
			e|r|f	{	incr tned 1
					set telab($tned) $new
					set tedef($tned) $clipboard(2)
					.labels.t.4.text insert end $clipboard(2) 
				}
			c	{	incr tncd 1
					set tclab($tncd) $new
					set tcdef($tncd) $clipboard(2)
					.labels.t.4.text insert end $clipboard(2) 
					set tcdef($tncd) ""
				}
			}

	} else {
		complain "nothing to paste"
		return
		}
	sortsymbols $type ;# no explicit insert because sortsymbols will insert all items in current array
	set index [match_symbol_temp $type $new]
	.labels.t.2.w.list selection clear 0 end
	.labels.t.2.e.list selection clear 0 end
	.labels.t.2.w.list selection set [expr $index - 1]
	.labels.t.2.e.list selection set [expr $index - 1]
	.labels.t.2.w.list see [expr $index - 1]
	.labels.t.2.e.list see [expr $index - 1]

}

proc deletesymbol {type} {
	global TW_Vip
	global tned tncd telab tclab tedef tcdef
	#called from labels - deletes selected symbol and definition from .labels and from temporary symbol list
	
	set cur ""
	lappend cur [.labels.t.2.w.list curselection] ;#indice of currently selected list item
	set cur [lindex $cur 0]
	if {$cur == ""} {
		complain "nothing selected"
		return
		}
	.labels.t.2.w.list delete $cur
	.labels.t.2.e.list delete $cur
	.labels.t.3.entry delete 0 end
	scan [.labels.t.4.text index end] %d nnl
	.labels.t.4.text delete 0.0 $nnl.end
	switch -regexp $type {
		e|r|f 	{ set telab([expr $cur + 1]) ""
			  set tedef([expr $cur + 1]) ""
			}
		c	{ set tclab([expr $cur + 1]) ""
			  set tcdef([expr $cur + 1]) ""
			}
	}
}

proc symbols_temp_forget {} {
	global TW_Vip
	global tedef telab tcdef tclab tned tncd
	catch {unset tedef}
	catch {unset telab}
	catch {unset tcdef}
	catch {unset tclab}
	catch {unset tned}
	catch {unset tncd}
}

proc consider_update_edit_object_window {{n -1}} {
	global TW_Vip
	debug "entering consider_update_edit_object_window with n=$n"
	if {![winfo exists .ec$n]} { return }
	set cursym [.labels.t.3.entry get]
	scan [.labels.t.4.text index end] %d nnl
	set curdef [string trimright [.labels.t.4.text get 0.0 [expr $nnl-1].end]]
	set editwinsym [.ec$n.h1.cb1.entry get]
	if {$cursym == $editwinsym} {
		# if user hasn't changed the name of the symbol, update 
		.ec$n.h2.edesc configure -text $curdef
	}
}

proc displaydefinition {from type} {
	global TW_Vip
	global tned tncd telab tclab tedef tcdef
	global initsym initdef initindex
	#called from labels - displays definition associated with an event or constraint
	#from is "w" (from symbol listbox) or "e" (from definition listbox)
	set cur ""
	switch $from {
		w	{	set temp [.labels.t.2.w.list curselection] ;#indice of currently selected list item
				if {$temp == {}} {return}
				lappend cur [.labels.t.2.w.list curselection]
				.labels.t.2.e.list selection set [lindex $cur 0] [lindex $cur 0]
				
			}
		e	{	set temp [.labels.t.2.e.list curselection] ;#indice of currently selected list item
				if {$temp == {}} {return}
				lappend cur [.labels.t.2.e.list curselection] ;#indice of currently selected list item
				.labels.t.2.w.list selection set [lindex $cur 0] [lindex $cur 0]
			}
		}
	set cur [lindex $cur 0]
	set initindex $cur
	set symbol [.labels.t.2.w.list get $cur]
	.labels.t.3.entry delete 0 end
	.labels.t.3.entry insert end $symbol
	set initsym $symbol

	scan [.labels.t.4.text index end] %d nnl
	.labels.t.4.text delete 0.0 $nnl.end
	set index [match_symbol_temp $type $symbol]
	set initdef ""
	if {$index == 0} {return}
	switch -regexp $type {
		e|r|f {	.labels.t.4.text insert end $tedef($index)
			set initdef $tedef($index)
			}
		c {	.labels.t.4.text insert end $tcdef($index)
			set initdef $tcdef($index)
		}	}
}

proc apply_symbol {type} {
	global TW_Vip
	global tned tncd telab tclab tedef tcdef select_item
	set s $select_item
	if {$s == ""} {
		complain "Select an item on the Vip window first"
		return
	}
	set text [.labels.t.3.entry get]
	if {$text == ""} {
		complain "Nothing to apply"
		return
	}
	switch -regexp $type {
		e|r|f {update_event $select_item text "$text"
		    }
		c   {update_const $select_item text "$text"
		    }
	}
	catch {destroy .labels}
	catch {destroy .ec$s}	
}

proc sortsymbols {type} {
	global TW_Vip
	global tned tncd telab tclab tedef tcdef
	#sorts the temporary symbol lists and redisplays in .labels window
	set tosort ""
	switch -regexp $type {
		e|r|f {	for {set i 1} {$i <= $tned} {incr i 1} {
				if {$telab($i) != ""} {
					lappend tosort "\"$telab($i)\" \"$tedef($i)\""
				}
			}
		    }
		c   {	for {set i 1} {$i <= $tncd} {incr i 1} {
				if {$tclab($i) != ""} {
					lappend tosort "\"$tclab($i)\" \"$tcdef($i)\""
				}
			}
		    }
	}
	set sorted [lsort -dictionary -index 0 $tosort]
	switch -regexp $type {
		e|r|f {	for {set i 1} {$i <= $tned} {incr i 1} {
				set temp [lindex $sorted [expr $i - 1]]
				set telab($i) [lindex $temp 0]
				set tedef($i) [lindex $temp 1]
			}
		    }
		c   {	for {set i 1} {$i <= $tncd} {incr i 1} {
				set temp [lindex $sorted [expr $i - 1]]
				set tclab($i) [lindex $temp 0]
				set tcdef($i) [lindex $temp 1]
			}
		    }
	}
	catch { .labels.t.2.w.list delete 0 end }
	catch { .labels.t.2.e.list delete 0 end }

	switch -regexp $type {
		e|r|f	{
			for {set i 1} {$i <= $tned} {incr i 1} {
				.labels.t.2.w.list insert end "$telab($i)"
				.labels.t.2.e.list insert end "$tedef($i)"
		}	}
		c	{
			for {set i 1} {$i <= $tncd} {incr i 1} {
				.labels.t.2.w.list insert end "$tclab($i)"
				.labels.t.2.e.list insert end "$tcdef($i)"
	}	}	}
}

proc match_symbol {type stringy} {
	global TW_Vip
	global ned ncd elab clab
	# see if a string (stringy) matches any already defined symbols in the saved version of the symbols list
	# returns index greater than 0 if match found, returns 0 if no match found
	set match 0
	switch -regexp $type {
		e|r|f {	for {set i 1} {$i <= $ned} {incr i 1} {
				if {$stringy == $elab($i)} {
					set match $i
					return $i
					}
				}	
			}
		c {	for {set i 1} {$i <= $ncd} {incr i 1} {
				if {$stringy == $clab($i)} {
					set match $i
					return $i
					}
				}
			}
		}
	return $match
}

proc match_symbol_temp {type stringy} {
	global TW_Vip
	global tned tncd telab tclab
	# see if a string (stringy) matches any already defined symbols in the temporary version of the symbols list
	# returns index greater than 0 if match found, returns 0 if no match found
	set match 0
	switch -regexp $type {
		e|r|f {	for {set i 1} {$i <= $tned} {incr i 1} {
				if {$stringy == $telab($i)} {
					set match $i
					return $i
					}
				}	
			}
		c {	for {set i 1} {$i <= $tncd} {incr i 1} {
				if {$stringy == $tclab($i)} {
					set match $i
					return $i
					}
				}
			}
		}
	return $match
}

proc selecttwin {} {
	global TW_Vip
	set index ""
	set temp [.labels.t.2.w.list curselection]
	if {$temp == {}} {return}
	lappend index [.labels.t.2.w.list curselection]
	.labels.t.2.e.list selection clear 0 end
	.labels.t.2.e.list selection set [lindex $index 0]
}

proc scrolltwins {args} {
	global TW_Vip
	eval {.labels.t.2.w.list yview} $args
	eval {.labels.t.2.e.list yview} $args
}

#---end of label editting---

proc clean_up_canvas {} { ;# cleanup of widgets and items related to add event/constraint and relabeling 
	global TW_Vip
	debug "entering clean_up_canvas"
	catch {destroy .f.en}
	catch {$TW_Vip delete con_line}
	catch {$TW_Vip delete guide_event}
}

proc gendata {} {
	global TW_Vip
	global event const ne nc nob
	# if events or constraints have been deleted, some elements of arrays
	# 'event' and 'const' will end up being empty
	debug "entering gendata"
	update
	set nob 0 ;#will end up being the highest object postfix
	foreach i [$TW_Vip find all] {
		set tags [$TW_Vip gettags $i]
		set ptag [lindex $tags 0] ;# if event of constraint, first tag has prefix 'ob'
		if {[string range $ptag 0 1] == "ob"} {
			set stag [lindex $tags 1] 
			set first5 [string range $stag 0 4] ;# prefix of second tag is 'event' or 'const'
			set len [string length $stag]
			set n [string range $stag 5 [expr $len - 1]] ;#number postfix
			if {$n > $nob} {
				set nob $n
				}
			}
		}
	for {set i 1} {$i <= $nob} {incr i 1} {
		set event($i) ""
		set const($i) ""
		}
	foreach i [$TW_Vip find all] {
		set tags [$TW_Vip gettags $i]
		set stag [lindex $tags 1] ;# if event, 2nd tag will be event$n, if const, 2nd tag is const$n
		set f5 [string range $stag 0 4]
		if {($f5 == "event") || ($f5 == "const")} {
			set len [string length $stag]
			set n [string range $stag 5 [expr $len - 1]] ;#number postfix
			set c [$TW_Vip coords $stag]

			# find assigned mark for xo
			set xo [lindex $c 0]
			set rval [get_mark $xo none] ;#mark associated with xo will be in variable 'mark'
			set x [lindex $rval 1]
			set mark [lindex $rval 3]
			
			set txt [$TW_Vip itemcget label$n -text]

			switch $f5 {
				event {
					set type [$TW_Vip itemcget type$n -text]
					lappend event($n) $mark $mark $type $txt
					}
				const {
					set begin_mark $mark
					set include_b "yes"
					if {$x < $xo} {
						set include_b "no"
						}
					
					set x1 [lindex $c 2]
					set rval [get_mark $x1 none]
					set end_mark [lindex $rval 3]
					set x [lindex $rval 1]
					set include_e "yes"
					if {$x > $x1} {
						set include_e "no"
						}
					lappend const($n) $begin_mark $end_mark c $txt $include_b $include_e
					}
				}
			}
		}
}

proc gen_mydata {i} {
	global TW_Vip
	global event const mydata
	debug "entering gen_mydata with i=$i"
	set tags [$TW_Vip gettags ob$i]
	set stag [lindex $tags 1] 
	set first5 [string range $stag 0 4] ;# prefix of second tag is 'event' or 'const'
	set len [string length $stag]
	set n [string range $stag 5 [expr $len - 1]] ;#number postfix
	set c [$TW_Vip coords $stag]

	# find assigned mark for xo
	set xo [lindex $c 0]
	debug "calling get_mark from gen_mydata"
	set rval [get_mark $xo none] ;#mark associated with xo will be in variable 'mark'
	set mark [lindex $rval 3]
	set x [lindex $rval 1]
	set txt [$TW_Vip itemcget label$n -text]
	set mydata ""

	switch [string range $stag 0 4] {
		event {
			set type [$TW_Vip itemcget type$n -text]
			lappend mydata $mark $mark $type $txt
			}
		const {
			set begin_mark $mark
			set include_b "yes"
			if {$x < $xo} {
				set include_b "no"
				}
					
			set x1 [lindex $c 2]
			set rval [get_mark $x1 none]
			set end_mark [lindex $rval 3]
			set x [lindex $rval 1]
			set include_e "yes"
			if {$x > $x1} {
				set include_e "no"
				}
			lappend mydata $begin_mark $end_mark c $txt $include_b $include_e
			}
	}
}

proc dirty {} { ;#was formerly modify_data
	global TW_Vip
	global dirty Vip_Fname nob event const
	debug "entering dirty with Vip_Fname=$Vip_Fname"
	gendata; debug "gendata call - from dirty"
	set empty "yes"
	for {set i 1} {$i <= $nob} {incr i 1} { ;#check if all entries are deleted -- if yes, disable save
		if {($event($i) != "") || ($const($i) != "")} {
			set empty "no"
			break
			}
		}
	if {$empty == "yes"} {
		disable_saves
		set dirty "no"
	} else {
		set dirty "yes"
		if {$Vip_Fname != ""} {
			enable_save
			}
		enable_saveas
	}
}

proc delete_object {n} {
	global TW_Vip
	global nob event const
	global mydata
	gen_mydata $n
	set type [lindex $mydata 2]
	debug "entering delete_object with n=$n, and type=$type"
	dirty
	if [winfo exists .ec$n] {
		destroy .ec$n
	}
	$TW_Vip delete ob$n
	if {$type == "f"} {
		$TW_Vip delete fail_event$n ;# delete x associated with fail event
	}
	catch {destroy .f.{$TW_Vip}.m$n}
	unselect
	gendata
	set empty "yes"
	for {set i 1} {$i <= $nob} {incr i 1} { ;#check if all entries are deleted -- if yes, disable save
		if {($const($i) != "") || ($event($i) != "")} {
			set empty "no"
			break
			}
		}
	if {$empty == "yes"} {
		disable_saves
		set dirty "no"
		}
	if {$type == "c"} {
		distribute_constraints
		}
}


proc gen_gif {Pname pg_h pg_w} {
	global TW_Vip
	global fc oc CMD select_item
	debug "entering gen_gif with Pname=Pname, pg_h=$pg_h, pg_w=$pg_w"
	set fly_loc [find_fly]

	if {$select_item != ""} {
		set_object_bindings $select_item off
		}
	unselect

	set len [string length $Pname]
	set fn [string range $Pname 0 [expr $len - 5]] ;# removes .vip extension
	append fn ".fly"
	if [catch {set fgif [open $fn w]} errmsg] {
    		complain $errmsg
		}
	set fgif [open $fn w]
	puts $fgif "new"
	puts $fgif "size $pg_w,$pg_h"
	set nm $Pname
	puts $fgif "name $nm"
	puts $fgif "fill 1,1,255,255,255"
	set i 0
	foreach item [$TW_Vip find all] {
		incr i 1
		set itemtype [$TW_Vip type $item]
		set crd [$TW_Vip coords $item]

		#defaults for fill and outline colors
		set oc "black"
		set fc "black"

		#see if object has a fill color
		set check_fc [catch {set fc [$TW_Vip itemcget $item -fill]}]
	
		#see if object has an outline color
		set check_oc [catch {set oc [$TW_Vip itemcget $item -outline]}]

		convert_colors $fc $oc
		switch $itemtype {
			line	 	{	update
						set x0 [lindex $crd 0]
						set x1 [lindex $crd 2]
						set y0 [lindex $crd 1]
						set y1 [lindex $crd 3]
						if {($x0 == $x1) && ($y0 < $y1)} {
							if {[$TW_Vip itemcget $item -arrow] == "last"} {
								append arrow($i) "fpoly " $fc "," [expr $x0 - 4] "," [expr $y1 - 8] "," $x0 "," $y1 "," [expr $x0 + 4] "," [expr $y1 - 8] "," [expr $x0 - 4] "," [expr $y1 - 8]
								puts $fgif $arrow($i)
								flush $fgif
							}
						}
						set crd [join $crd ,]
						if {!$check_fc} {
							append fline($i) "line " $crd "," $fc
						} else {
							append fline($i) "na"
						}
						append oline($i) "na"
					}
			rectangle	{	set crd [join $crd ,]
						if {!$check_fc} {
							append fline($i) "frect " $crd "," $fc
						} else {
							append fline($i) "na"
						}
						if {!$check_oc} {
							append oline($i) "rect " $crd "," $oc
						} else {
							append oline($i) "na"
						}
					}
			polygon	{		set crd [join $crd ,]
						if {!$check_fc} {
							append fline($i) "fpoly " $fc "," $crd
						} else {
							append fline($i) "na"
						}
						if {!$check_oc} {
							append oline($i) "poly " $oc "," $crd
						} else {
							append oline($i) "na"
						}	
					}
			text	{		set check_txt [catch {set txt [$TW_Vip itemcget $item -text]}]
						set check_alignment [catch {set alignment [$TW_Vip itemcget $item -anchor]}]
						set wrap [$TW_Vip itemcget $item -width] ;# wrap is measured in pixels
						if {(($alignment == "s") || ($alignment == "w")) && ($wrap > 0)} {
							# maxt is wd in chars
							#10 is pts per char for med txt in fly
							#wrap is maximum width in points
							set maxt [expr $wrap / 10] 
							set x [lindex $crd 0]
							set y [lindex $crd 1]
							set tlist [split $txt " "]
							set nw [llength $tlist]
							set nl 1 	;# initialize number of lines -- nl
							set nc($nl) 0 	;# initialize number of characters assigned to line to 0
							for {set j 0} {$j < $nw} {incr j 1} {
							set wl($j) [string length [lindex $tlist $j]]
							# if word is longer than maxt, the don't increment nl
								if {$wl($j) <= $maxt} {
									if {[expr $nc($nl) + $wl($j)] > $maxt} {
										incr nl 1
										set nc($nl) 0
										}
									}
								if {$nc($nl) > 0} {
									append tect($nl) " "
									}
								append tect($nl) [lindex $tlist $j]
								incr nc($nl) $wl($j)
							}
							for {set j 1} {$j <= $nl} {incr j 1} {
								incr i 1
								if {$alignment == "s"} {
									set xc($j) [expr $x - ($nc($j) * 7 * .5)] ;#each character is 7 pts
									set yc($j) [expr $y - (($nl - $j + 1) * 12)] ;#ht of each char - 13 pts
								} elseif {$alignment == "w"} {
									set xc($j) $x
									set yc($j) [expr $y + (($j - 1) * 12)]
								}
								append fline($i) "string " $fc "," $xc($j) "," $yc($j) ",medium," $tect($j)
								append oline($i) "na"
								set tect($j) ""
								if {$fline($i) != "na"} {
									puts $fgif $fline($i)
									}
								if {$oline($i) != "na"} {			
									puts $fgif $oline($i)
									}
								flush $fgif
							}
						} else {
							set crd [join $crd ,]
							set the_tags [$TW_Vip itemcget $item -tags]
							append fline($i) "string " $fc "," $crd ",medium," $txt
							append oline($i) "na"
						}	
					}
			oval	{	set x1 [lindex $crd 0]
					set x2 [lindex $crd 2]
					set y1 [lindex $crd 1]
					set y2 [lindex $crd 3]
					set x [expr ($x1 + $x2) / 2]
					set y [expr ($y1 + $y2) / 2]
					set w [expr $x2 - $x1]
					set h [expr $y2 - $y1]
					if {!$check_fc} {
						append fline($i) "fcircle " $x "," $y "," $w "," $fc
					} else {
						append fline($i) "na"
					}
					if {!$check_oc} {
						#append oline($i) "circle " $x "," $y "," $w "," $oc
						append oline($i) "na"
					} else {
						append oline($i) "na"
					}
				}
			default	{
					append fline($i) "na"
					append oline($i) "na"
				}
		}
		if {$fline($i) != "na"} {
			puts $fgif $fline($i)
			}
		if {$oline($i) != "na"} {			
			puts $fgif $oline($i)
			}
		
		flush $fgif
	
	}
	update
	set thisiswhy ""
	set did_it_fly [catch {exec $fly_loc <$fn} thisiswhy]
	debug "did_it_fly is: $did_it_fly: if couldn't fly this is why: $thisiswhy"
}

proc convert_colors {fcol ocol} {
	global TW_Vip
	global fc oc
	debug "entering convert_colors with fcol=$fcol, ocol=$ocol"
	set i 1
	append collist $fcol " " $ocol
	foreach clr $collist {
		switch $clr {
			white 	{set color "255,255,255"}
			blue 	{set color "0,0,255"}
			green 	{set color "0,255,0"}
			black 	{set color "0,0,0"}
			red 	{set color "255,0,0"}
			yellow  {set color "255,255,0"}
			gray 	{set color "100,100,100"}
			default {set color "225,225,225"}
			}
		if {$i == 1} {
			set fc $color
		} elseif {$i == 2} {
			set oc $color
		}
	incr i 1
	}
}


#-----------
#generate automata - begin
	
proc assign_symbol {txt type} {
	global TW_Vip
	global sb_count seen_before_txt seen_before_text_type
	debug "entering assign_symbol with txt=$txt"

	for {set j 1} {$j <= $sb_count} {incr j 1} {
		if {$txt == $seen_before_txt($j)} {
			return p$j
	}	}

	incr sb_count
	set seen_before_txt($sb_count) $txt
	set seen_before_text_type($sb_count) $type
	return p$sb_count
}

proc store {draw save {fa ""}} {
	global TW_Vip
	global nl spec lm sm event event_at_mark const nob event_type
	global c_cnt ic_cnt constraint i_constraint sb_count event_symbol

	if $draw {
		catch {.g.m.c delete all}
		}
	
	select_near
	toolbar_bind

	gendata
	if {$nob == 0} {
		return ;#no specification
	}
	set sb_count 0	;# nr events and constraints

	#init counters for nr constraints at each mark, and initial event for each mark
	for {set i $sm} {$i <= $lm} {incr i 1} {
		set c_cnt($i) 0
		if {$i < $lm} {
			set ic_cnt($i,[expr $i+1]) 0
		}
		set event_at_mark($i) ""
		set event_type($i) ""
	}
	set hm $sm ;#initialize highest populated mark
	for {set i 1} {$i <= $nob} {incr i 1} {
		if {$const($i) != ""} {
			set from [lindex $const($i) 0]
			set ff $from
			set cf $from ;# cf used for determining whether constraint holds inbetween two marks
			set upto [lindex $const($i) 1]
			set uu $upto
			set cu $upto ;# cu is largest mark for calculating if constraint holds in between two marks
			set type [lindex $const($i) 2]
			set txt [lindex $const($i) 3]
			set include_b [lindex $const($i) 4]
			set include_e [lindex $const($i) 5]
		} elseif {$event($i) != ""} {
			set from [lindex $event($i) 0]
			set ff $from
			set upto [lindex $event($i) 1]
			set type [lindex $event($i) 2]
			set uu $upto
			set txt [lindex $event($i) 3]
			if {$from > $hm} {
				set hm $from
			}
		} else {
			continue
		}
		set snr [assign_symbol $txt $type]
		switch $type {
			c {	if {$include_b == "no"} {
					set ff [expr $from + 1]
				}
				if {$include_e == "no"} {
					set uu [expr $upto - 1]
				}
			
				# add constraint to matrix for each mark in constraint interval - ff to uu
				for {set j $ff} {$j <= $uu} {incr j 1} {
					incr c_cnt($j) 1
					set tmp $c_cnt($j)
					set constraint($j,$tmp) $snr
				}
				for {set j $cf} {$j < $cu} {incr j 1} {
					incr ic_cnt($j,[expr $j+1]) 1
					set tmp $ic_cnt($j,[expr $j+1])
					set i_constraint($j,[expr $j+1],$tmp) $snr
				}
			  }
			e -
			f -
			r {	if {($from != $upto) || ($from < 0)} {
					break
				}
				if {$event_at_mark($from) != ""} {
					complain "Fatal - found two events at mark $from"
				}
				set event_at_mark($from) $txt
				set event_type($from) $type
				set event_symbol($from) $snr
			  }
			default {
				debug "error encountered in store - bad type $type"
	}	}	  }
	for {set i [expr $sm + 1]} {$i <= $hm} {incr i 1} {
		if {($event_at_mark($i) == "") || ($event_at_mark($i) == "?")} {
			complain "marks [expr $sm + 1] through $hm must have labeled events to generate an automaton"
			catch {destroy .g}
			return
		}
	}
	automaton $draw $save $hm $fa
}

proc spit_symbols {fa draw save} {
	global TW_Vip
	global para prov npa npl
	global sb_count seen_before_txt seen_before_text_type xauto
	global symdef edef cdef
	global settingsfile featfile whats_on_top
	debug "entering spit_symbols with fa=$fa"

	set files 1
	if {($settingsfile == "") && ($featfile == "")} {
		set files 0
	}

	if {$save && $files} {
		#Settings
		puts -nonewline $fa "/* ENV	1	"
		if {$settingsfile != ""} {
			if {$whats_on_top == "s"} {
				rescue Settings 0
			}
			for {set i 1} {$i <= $npa} {incr i 1} {
				puts -nonewline $fa [lindex $para($i) 2]
				puts -nonewline $fa [lindex $para($i) 3]
				puts -nonewline $fa " "
			}
		}
		#Features
		if {$featfile != ""} {
			if {$whats_on_top == "Features"} {
				rescue Features 0
			}
			for {set i 1} {$i <= $npl} {incr i 1} {
				set h [lindex $prov($i) 3]
				if {$h == "?"} {
					continue
				} elseif {$h == 0} {
					set txt [lindex $prov($i) 2]
					puts -nonewline $fa "-${txt} "
				} elseif {$h == 1} {
					set txt [lindex $prov($i) 2]
					puts -nonewline $fa "+${txt} "
				}
			}
		}
		puts $fa " */"	
	}
		
	set xo   20
	set yo   45
	set max   0
	set maxi  1
	if $draw {.g.m.c create rect $xo $yo $xo $xo -fill #eee -outline #fff -tags keybox}
	if $draw  {.g.m.c create text $xo [expr $yo - 16] -text KEY: -anchor w -tags key_header}
	if $draw  {.g.m.c create line $xo [expr $yo - 8] [expr $xo + 25] [expr $yo - 8]}

	for {set i 1} {$i <= $sb_count} {incr i 1} {
		set tmp1 p$i
		set tmp2 $seen_before_txt($i)
		set tmp2 [string trimright $tmp2 "!?"] ;#previous line appears to be long standing bug

		set nc_sbt [string length $tmp2]
		if {$nc_sbt > $max} {
			set max $nc_sbt
			set maxi $i
		}
		set type $seen_before_text_type($i)
		set index [match_symbol $type $seen_before_txt($i)]
		set tmp3 ""
		if {$index != 0} {
			switch -regexp $type {
			e|r|f	{set tmp3 $edef($index)
				}
			c	{set tmp3 $cdef($index)
				}
			}
		}
		if {$tmp3 != ""} {
			if $save {puts $fa "#define $tmp1	$tmp3   /* $tmp2 */"}
		} else {
			if $save {puts $fa "#define $tmp1	$tmp2"}
		}

		if $draw  {
			.g.m.c create text \
			$xo [expr $yo + ($i * 13)] \
			-text "$tmp1	$tmp2" \
			-tags text($i) \
			-anchor w
			}
	}
	if $draw {
		#resize key box to fit contents
		set co [.g.m.c bbox key_header]
		set xo [expr [lindex $co 0] - 3]
		set yo [expr [lindex $co 1] - 3]
		set c1 [.g.m.c bbox text($maxi)]
		set x1 [expr [lindex $c1 2] + 3]
		set c2 [.g.m.c bbox text($sb_count)]
		set y1 [expr [lindex $c2 3] + 3]
		.g.m.c coords keybox $xo $yo $x1 $y1
		set xauto [expr $x1 + (4*16)]	;# x offset for drawing linear part of automaton
	}
}

proc begin_display_never_claim {afile m} {
	global TW_Vip
	catch {destroy .a}
	debug "entering display_never_claim with afile=$afile"
	toplevel .a -bg gray
	set root [string range $afile 0 [expr [string length $afile] - 5]]
	set vipfile ${root}.vip
	wm title .a "Never Claim for $vipfile"
	frame .a.1 -bg gray
	frame .a.3 -bg gray
	
	text .a.1.t \
		-yscrollcommand ".a.1.sv set" \
		-background white
	scrollbar .a.1.sv -orient vertical \
		-command ".a.1.t yview"


	button .a.3.b -text "Close" -bg gray -command {destroy .a}
	pack .a.3 -side bottom -fill x
	pack .a.1 -side top -expand 1 -fill both


	pack .a.3.b -side bottom -expand 0
	pack .a.1.sv -side right -fill y
	pack .a.1.t -side top -expand 1 -fill both

	display_never_claim $afile	
}

proc display_never_claim {afile} {
	global TW_Vip
	.a.1.t delete 1.0 end

	if [catch {set f [open $afile r]} errmsg] {
  		complain $errmsg
  		return 0
	}
	while {[gets $f line] >= 0} {
		.a.1.t insert end $line\n
	}
	catch { close $f }
}

proc begin_graphic_automaton {} {
	global TW_Vip
	global Vip_Fname
	debug "entering begin_graphic_automaton with Vip_Fname=$Vip_Fname"
	catch {destroy .g}
	toplevel .g
	set g ".g"
	if {$Vip_Fname == ""} {
		set Vip_Fname [pwd]/feaver.vip
		set ncfile [pwd]/feaver.aut
	} else {
		set afile [string trimright $Vip_Fname ".vip"]
		set ncfile ${afile}.aut
	}
	
	append titl "Graphical Automaton for $Vip_Fname"

	wm title .g $titl
	set m	[frame .g.m -bg gray -relief flat]
	set b	[frame .g.b -bg gray -relief flat]
	pack $b	-side bottom -fill x
	pack $m	-side top -expand 1 -fill both

	button $b.b -width 10 -bg gray -text "Dismiss" \
		-command "destroy .g"
	pack $b.b -side right
	button $b.t -width 10 -text "See Text" -bg gray\
		-command "
			# store 0 1
			begin_display_never_claim $ncfile $m
		"
	pack $b.t -side right

	scrollbar $m.sv -orient vertical \
		-command "$m.c yview"
	pack $m.sv -side right -fill y
	
	canvas $m.c -width 500 -height 500 \
		-yscrollcommand "$m.sv set" \
		-scrollregion {0 0 200 4000} \
		-background white
	pack $m.c  -side top -expand 1 -fill both
}


proc draw_state {statenr label require} {
	global TW_Vip
	global empty_string xauto

	debug "entering draw_state with statenr=$statenr, label=$label, require=$require"
	set d 16
	set yo [expr 2 * $d]
	set xo [expr $xauto + 2 * $d]
	set yc [expr $yo + ($statenr * 4 * $d)]
	.g.m.c create oval [expr $xo - $d] [expr $yc - $d] \
		[expr $xo + $d] [expr $yc + $d]
	.g.m.c create text $xo $yc -text $label -anchor center
	if {$require} {
		#in next command, needed eval to get empty_string to evaluate at correct time
		eval .g.m.c create oval [expr $xo - $d + 4] [expr $yc - $d + 4] \
			[expr $xo + $d - 4] [expr $yc + $d - 4] \
			-fill $empty_string -outline black
		}			
}

proc draw_transition {statenr label type} {
	global TW_Vip
	global xauto
	debug "entering draw_transition with statenr=$statenr, label=$label, type=$type"
	set d 16
	set yo [expr 2 * $d]
	set xo [expr $xauto + 2 * $d]
	set yc [expr $yo + ($statenr * 4 * $d)]
	switch $type {
		s {	
			set x [expr $d / 1.4142]
			.g.m.c create line [expr $xo + $x] [expr $yc + $x] \
				[expr $xo + (2 * $x)] [expr $yc + $d] \
				[expr $xo + (2 * $x) + $d] $yc \
				[expr $xo + (2 * $x)] [expr $yc - $d] \
				[expr $xo + $x] [expr $yc - $x] \
				-arrow last -smooth 1 -splinesteps 20
			.g.m.c create text [expr $xo + (2 * $x) + $d + 4] $yc\
				-text $label -anchor w
			}
		t {	
			.g.m.c create line $xo [expr $yc + $d] \
					$xo [expr $yc + (3 * $d)] -arrow last
			.g.m.c create text [expr $xo + 4] [expr $yc + (2 * $d)] \
				-text $label -anchor w
			}
		}
}

proc draw_fail_state {failstatenr statenr} {
	global TW_Vip
	global empty_string xauto

	set label "F${failstatenr}"

	debug "entering draw_fail_state with failstatenr=$failstatenr, statenr=$statenr"
	set d 16
	set yo [expr 2 * $d]
	set xo [expr $xauto + (2 * $d) - (4 * $d)]
	set yc [expr $yo + ($statenr * 4 * $d)]
	.g.m.c create oval [expr $xo - $d] [expr $yc - $d] \
		[expr $xo + $d] [expr $yc + $d]
	.g.m.c create text $xo $yc -text $label -anchor center

	eval .g.m.c create oval [expr $xo - $d + 4] [expr $yc - $d + 4] \
		[expr $xo + $d - 4] [expr $yc + $d - 4] \
		-fill $empty_string -outline black			
}

proc draw_fail_transition {statenr label} {
	global TW_Vip
	global xauto
	debug "entering draw_fail_transition with statenr=$statenr, label=$label"
	set d 16
	set yo [expr 2 * $d]
	set xo [expr $xauto + (2 * $d)]
	set yc [expr $yo + ($statenr * 4 * $d)]
	
	.g.m.c create line [expr $xo - $d] $yc \
			[expr $xo - (3 * $d)] $yc -arrow last
	.g.m.c create text [expr $xo - (2 * $d)] [expr $yc + 4] \
		-text $label -anchor n -width [expr 2 * $d]

	#true self loop on fail state	
	set o [expr $d / 1.4142]
	set xc [expr $xo - (4*$d)]

	.g.m.c create line  [expr $xc + $o] [expr $yc + $o] \
		[expr $xc + $d] [expr $yc + (2*$o)] \
		$xc [expr $yc + (2*$o) + $d] \
		[expr $xc - $d] [expr $yc + (2*$o)] \
		[expr $xc - $o] [expr $yc + $o] \
		-arrow last -smooth 1 -splinesteps 20
	.g.m.c create text $xc [expr $yc + (1*$o) + 5]\
		-text true -anchor n
}

proc get_automaton_file {draw save file} {
	global Vip_Fname
	# try to open filename retrieved from file_select, then call automata
	set fa ""
	debug "in get_automaton_file with file=$file"
	if $save {
		debug " in save mode, and about to open file=$file"
		if [catch {set fa [open $file w]} errmsg] {
  			complain $errmsg
  			return 0
		}
	debug "about to call automaton with draw=$draw, save=$save and fa=$fa"
	store $draw $save $fa
	}
}

proc automaton {draw save hm fa} {
	global TW_Vip
	global event event_at_mark c_cnt ic_cnt constraint
	global Vip_Fname sm lm event_type event_symbol
	debug "entering automaton with draw=$draw, and save=$save"

	set statenr 0
	set failstatenr 0

	spit_symbols $fa $draw $save

	set tmp "never {"

	if $save {puts $fa $tmp}

	for {set i [expr $sm + 1]} {$i <= $hm} {incr i 1} {
		set e $event_at_mark($i)
		if {$e == ""} {
			continue ;#skip if not start mark and no event assigned to mark
		}
		set require	0
		set fail	0
		set consume	0

		set l [string length $e]
		set lchar [string index $e [expr $l - 1]] ;# get last character
		switch $lchar {
			? { set consume 1 ;# event must be consumed }
			! { }
		}

		set tmp1 [string trim $event_symbol($i) "!?"]
		if {$event_type($i) == "r"} {
			set require 1 ;# required event
		} elseif {$event_type($i) == "f"} {
			set fail 1 ;# fail event
		}

		if {([expr $sm + 1] == $hm) && $fail} {
			#very special case where there is only one event and it is a fail event
			#for this case need to add an S0, S0 self-loop, and transition from S0 to F0
			set tmp1 [string trim $event_symbol($i) "!?"]
			set c [add_constraints $i]

			if {($tmp1 == "") || ($c == "")} {	set and ""
			} else {	set and " && " }
			
			set pos_ftl $tmp1
			append pos_ftl $and $c
			set neg_ftl !$tmp1
			append neg_ftl $and $c
			if $draw {
				draw_state $statenr S$statenr 0 ;# draws non-accepting state in linear configuration
				draw_fail_transition $statenr $pos_ftl
				draw_transition $statenr "$neg_ftl" "s"
			}
			if $save {
				puts $fa "S$statenr"
				puts $fa "	do"
				puts $fa "	:: $neg_ftl"
				puts $fa "	:: $pos_ftl -> goto acceptF$failstatenr"
				puts $fa "	od;"
			}
			
		}

		#STATE
		if !$fail {
			set sn S$statenr
		} else {
			set sn F$failstatenr
		}	
		if $save {
			if {$require || $fail} {
				puts $fa "accept${sn}:"
			}
			puts -nonewline $fa "${sn}:"
		}

		if $draw {
			if !$fail {
				draw_state $statenr $sn $require ;#draws state in linear configuration
			} else {
				draw_fail_state $failstatenr $statenr ;# this draws "accept" fail state to left of $statenr + 1 
			}
		}

		if $save {
			if $fail {
				puts $fa "	assert(0); 0;" ;#failure if you get here
			}		
		}
		if {$i == $hm} {
			if $fail {
				#special case - last event is a fail event, so add self loop and fail transition here
				set pos_ftl $tmp1
				set c [add_constraints [expr $i - 1]]

				if {($tmp1 == "") || ($c == "")} {	set and ""
				} else {	set and " && " }

				append pos_ftl $and $c
				set neg_ftl !$tmp1
				append neg_ftl $and $c

				if $save {
					puts $fa "S$statenr"
					puts $fa "	do"
					puts $fa "	:: $pos_ftl -> goto acceptF$failstatenr"
					puts $fa "	:: $neg_ftl"
					puts $fa "	od;"
				}
				if $draw {
					draw_state $statenr S$statenr 0
					draw_transition $statenr $neg_ftl "s"
					draw_fail_transition $statenr $pos_ftl
				}
			}
		}
		
		if $fail {
			incr failstatenr 1
			continue
		}

		#TRANSITIONS
		#FOR REGULAR state (not a consume or fail state -- if fail state we don't get to this point)
		#TRANSITION to next state
		if $save {
			puts $fa "	do"
			puts -nonewline $fa "	:: $tmp1 " ;# good case first
			}
		set pos_tl $tmp1
		set c [add_constraints $i]

		if {($pos_tl == "") || ($c == "")} {	set and ""
		} else {	set and " && " }

		append pos_tl $and $c
		set neg_tl !$tmp1
		append neg_tl $and $c
		
		#defaults
		set nextstate [expr $statenr + 1]
		set GOTOSTATE S$nextstate
		
		#if nextevent is fail event, linear transition will be to event after fail event
		#if event after fail event is required, prefix is acceptS, otherwise just S
		if {$i <= [expr $hm - 2]} {
			if {$event_type([expr $i + 1]) == "f"} {
				set j [expr $i + 2]
				if {$event_type($j) == "r"} {
					set GOTOSTATE acceptS$nextstate ;# next state in linear progression is accepting state
				} else {
					set GOTOSTATE S$nextstate ;# next state in linear progression is non-accepting state
				}
			}
		}
		#if next event is required event linear transition to acceptS<nextstate>
		if {$i <= [expr $hm - 1]} {
			if {$event_type([expr $i + 1]) == "r"} {
				set GOTOSTATE acceptS$nextstate 
			}
		}
			
	
		if $save {puts $fa "-> goto $GOTOSTATE"}
		if $draw {draw_transition $statenr $pos_tl "t"}

		#LOOK BACK TO SEE IF PREVIOUS EVENT IS FAIL - IF SO, ADD TRANSITION FOR FAIL EVENT TO FAIL STATE
		if {$event_type([expr $i - 1]) == "f"} {
			set tmp2 [string trim $event_symbol([expr $i - 1]) "!?"]
			set pos_ftl $tmp2
			set c [add_constraints [expr $i - 1]]

			if {($tmp2 == "") || ($c == "")} {set and ""
			} else { 	set and " && "	}

			append pos_ftl $and $c
			if $save { puts $fa "	:: $pos_ftl -> goto acceptF[expr $failstatenr - 1]" }
			if $draw { draw_fail_transition $statenr $pos_ftl }	
		}

		#SELF LOOP to same state
		if $require {
			set neg_tl "!$tmp1"
			set p [add_previous_fail_event $i]
			if {($neg_tl == "") || ($p == "")} {	set and "" 
			} else { 	set and " && "	}
			append neg_tl $and $p
			set c [add_intermediate_constraints [expr $i - 1]]
			if {($neg_tl == "") || ($c == "")} {	set and ""
			} else {	set and " && "	}
			append neg_tl $and $c
			if $save {puts -nonewline $fa "	:: $neg_tl"}
			if $draw {draw_transition $statenr $neg_tl "s"}
		
		} elseif {$ic_cnt([expr $i - 1],$i) != 0} {
			set neg_tl ""
			set p [add_previous_fail_event $i]
			append neg_tl $p
			set c [add_intermediate_constraints [expr $i - 1]]
			if {($c == "") || ($neg_tl == "")} {	set and ""
			} else {				set and " && "	}
			append neg_tl $and $c
			if $save {puts -nonewline $fa "	:: $neg_tl"}
			if $draw {draw_transition $statenr $neg_tl "s"}
		} else {
			set neg_tl ""
			append neg_tl [add_previous_fail_event $i]

			#if transition_label is still null, label it with true
			if {$neg_tl == ""} {
				if $save {puts -nonewline $fa "	:: true"}
				if $draw {draw_transition $statenr "true" "s"	;# s is for self loop}
			} else {
				if $save {puts -nonewline $fa " :: $neg_tl"}
				if $draw {draw_transition $statenr $neg_tl "s"}
			}
		}

		if $save {
			puts $fa "" ;# this should put in just a newline
			puts $fa "	od;"
		}

		#CONSUME state
		if {$consume} {
			incr statenr
			set sn S$statenr
			if $save {
				puts -nonewline $fa $sn
				puts -nonewline $fa ":"
			}
			set pos_tl $tmp1
			set c [add_intermediate_constraints [expr $i - 1]]
			if {($pos_tl == "") || ($c == "")} {	set and ""
			} else {	set and " && "	}
			append pos_tl $and $c
			set neg_tl !$tmp1
			set c [add_constraints $i]
			if {($neg_tl == "") || ($c == "")} {	set and ""
			} else {	set and " && "	}
			append neg_tl $and $c

			# consuming states are never required, so pass a 0 
			if $draw {draw_state $statenr $sn 0} 
			if $save {
				puts $fa "	/* consumption of event from previous state */"
				puts $fa "	do"
				puts -nonewline $fa "	:: $pos_tl "
			}
		
			if $draw {draw_transition $statenr $pos_tl "s"}
			if $save {
				puts $fa "" ;# this should put in just a newline
				puts -nonewline $fa  "	:: $neg_tl "
			}
		
			if $draw {draw_transition $statenr $neg_tl "t"}
			if $save {
				puts $fa " -> break"
				puts $fa "	od;"
			}
		}

		if {$i == $hm} {
			if !$fail {
				#last state
				if $save {
					puts -nonewline $fa "S[expr $statenr + 1]"
					puts $fa ":	0	/*full compliance if reached*/"
				}
				if $draw {draw_state $statenr S$statenr 0
					draw_state [expr $statenr + 1] S[expr $statenr + 1] 0}
			}
		}
		if $save {flush $fa}
		incr statenr 1
	}

	
	set close_brace "}"
	if $save {
		puts $fa $close_brace
		flush $fa
		close $fa
    		catch { tk_messageBox -icon info -message "wrote $afile" }

	}
}

proc add_constraints {j} {
	global TW_Vip
	global c_cnt constraint sm
	debug "entering add_constraints"
	#if considering first mark, j will be 0 -- i.e. will refer to non-existent mark
	set c ""
	if {$j >= $sm} {
		for {set i 1} {$i <= $c_cnt($j)} {incr i 1} {
			if {$c == ""} {set and ""
			} else {set and " && "}
			append c $and $constraint($j,$i)
		}
	}
	return $c
}

proc add_previous_fail_event {i} {
	global sm event_type event_symbol
	if {$i < [expr $sm + 2]} {return; debug "add_previous_fail_event - returning - i=$i"}
	set p ""
	if {$event_type([expr $i - 1]) == "f"} {
		set fe [string trim $event_symbol([expr $i - 1]) "!?"]
		append p "!$fe"
	}
	return $p
}

proc add_intermediate_constraints {j} {
	global TW_Vip
	global ic_cnt i_constraint sm lm
	# adds constraints that apply between mark j and mark j+1
	set ic ""
	debug "entering add_intermediate_constraints with j=$j"
	if {($j >= $sm) && ($j < $lm)} {
		for {set i 1} {$i <= $ic_cnt($j,[expr $j+1])} {incr i 1} {
			if {$ic == ""} {set and ""
			} else {set and " && "}
			append ic $and $i_constraint($j,[expr $j+1],$i) 
		}
	}
	return $ic
}

#### end of common.tcl

#start of what we'll keep

proc absorb {next {x 0} {y 0}} {
	global TW_Vip
	debug "entering absorb with next=$next"
	switch $next {
		event	{
			bind $TW_Vip <ButtonPress-1> {add_event e}
			}
	
		revent	{bind $TW_Vip <ButtonPress-1> {add_event r}
			}
		fail_event {bind $TW_Vip <ButtonPress-1> {fail_event}
			}
		cont	{bind $TW_Vip <ButtonPress-1> add_constraint
			}
		mark	{bind $TW_Vip <ButtonPress-1> new_mark
			}
	
		auto	{bind $TW_Vip <ButtonPress-1> {
				begin_graphic_automaton
				store 1 0 ;#draw but don't save
				
				}
			}
		file	{bind $TW_Vip <ButtonPress-1> "
				popup_file_menu $x $y
				"
			}
		default {}
	}	
}

proc absorb_bp1 {next n} {
	global TW_Vip
	$TW_Vip bind ob$n <ButtonPress-1> ""
	bind $TW_Vip <ButtonPress-1> "eval $next"
}

proc add_to_prx {inpt type} {
	global TW_Prx PrxChanged symdef
	global ned ncd elab edef clab cdef

	if {$type == "c"} {
		set pref "%TC"
	} else {
		set pref "%TE"
	}

	set w $TW_Prx
	$w yview -pickplace [expr $inpt - 1]

	switch -regexp $type {
		e|r {	for {set i 1} {$i <= $ned} {incr i 1} {
				$w insert $inpt.0 "$pref \"$elab($i)\" \"$edef($i)\"\n"
				incr inpt 1
			}
		    }
		c   {	for {set i 1} {$i <= $ncd} {incr i 1} {
				$w insert $inpt.0 "$pref \"$clab($i)\" \"$cdef($i)\"\n"
				incr inpt 1
			}
		    }
	}
	set PrxChanged 1
}

proc change_in_prx {type} {
	global TW_Prx PrxChanged symdef
	set PrxChanged 1

	if {$type == "c"} {
		set pref "%TC"
	} else {
		set pref "%TE"
	}

	set w $TW_Prx
	scan [$w index end] %d numLines

	set inpt $numLines

	for {set i 1} {$i < $numLines} {incr i 1} {
		set line [$w get $i.0 $i.end]
		if {[string first $pref $line] == 0} {
			set inpt $i
			break
		}
	}

	for {set i 1} {$i < $numLines} {incr i 1} {
		set line [$w get $i.0 $i.end]
		if {[string first $pref $line] == 0} {
			set n [expr $i + 1]
			$w delete $i.0 $n.0
			incr i -1
	}	}
	add_to_prx $inpt $type
}

proc clear1 {next_step {arg ""}} {
	global TW_Vip nob Vip_Fname ylen_def nmark lm choice dirty yo yc y_spacing select_item bind_on
	set select_item ""; set bind_on ""
	if {$choice == "yes"} {
		if {$Vip_Fname == ""} {save_vip_fileselect 0
		} else {save_vip_fileselect 1}
	}
	bind $TW_Vip <1> {}
	$TW_Vip config -cursor arrow
	catch {destroy $TW_Vip.mdef}
	catch {destroy .er} ;# get rid of errant error windows		
	$TW_Vip delete all
	set dirty "no"
	for {set i 1} {$i <= $nob} {incr i 1} {catch {destroy $TW_Vip.m$i}}
	set nob 0
	set yc $yo
	set ylen_def [expr $yc + (2 * $y_spacing)]
	for {set i 0} {$i <= $nmark} {incr i 1} {catch {destroy $TW_Vip.mv$i}}
	set nmark 0
	set lm -1
	switch $next_step {
		wait {}
		new {layout new}
		exit {exit}
		open {readvipfile $arg}
		browse {openvipfile}
		}
}

proc file_event {event fname} {
	global TW_Log
	switch $event {
		open	{$TW_Log insert end "Opened Vip specification $fname"}
		close	{$TW_Log insert end "Closed Vip specification $fname"}
	}
}

proc openvipfile {{curr 1}} {
  	global Vip_Fname work_dir types open_dir
	debug "entering openvipfile with work_dir=$work_dir and open_dir=$open_dir"
  	if $curr {
    		# try to use the predefined file selection dialog
    		switch [info commands tk_getOpenFile] {
			"" 	{
      				# some old version of Tk so use our own file selection dialog
      				set fileselect "FileSelect open"
    				}
			default {
      				set fileselect "tk_getOpenFile"
    				}
		}
  	
    		# get the file (return if the file selection dialog canceled)
    		switch -- [set file [eval $fileselect -initialdir $open_dir -filetypes $types]] "" return
  
   		# load the file and update some items if the file loaded successfully
    		if [readvipfile $file] {
      			set Vip_Fname $file
			set_path $Vip_Fname
			update_dir open $Vip_Fname
    		}
  	

  	} else {
    		if {$Vip_Fname == ""} {
			complain "no file to open"
			return
		}
    		if [readvipfile $Vip_Fname] {
      			set Vip_Fname $file
			set_path $Vip_Fname
			update_dir open $Vip_Fname
		}
  	}
}

proc popup_file_menu {x y} {
	global TW_Vip Vip_Fname
	catch {destroy .f.fm}
	menu .f.fm \
		-bg black -fg gold \
		-activebackground gold -activeforeground black \
		-relief flat

	.f.fm add command \
		-label "New Vip" \
		-command "
			clear new
			"
	.f.fm add command \
		-label "Open Vip" \
		-command "
			clear browse
			"
	.f.fm add command \
		-label "Save Vip" \
		-command "save_vip_fileselect 1"
	.f.fm add command \
		-label "Save Vip As" \
		-command "save_vip_fileselect 0"

	.f.fm add command \
		-label "Generate Automata" \
		 -command "save_vip_fileselect 0 aut"
	
	set x [expr round($x)]
	set y [expr round($y)]
	set y [expr $y + 20]
	set x [expr $x - 10]
	
	tk_popup .f.fm $x $y 
	select_near
	toolbar_bind	
}

proc print {how Pname} {
	global TW_Vip
	global Vip_Fname ylen_def yo yp xo lm x_spacing y_spacing CMD
	global sm lm sv event const nob nfe spec ymax
	switch $how {
		postscript {set suf ".ps"}
		gif	   {set suf ".gif"}
	}
	toolbar off ;#deletes toolbar
	debug "entering print with Pname=$Pname"
	if {$Pname == ""} {
		set dir [pwd]/default
		set Pname [pwd]/default{$suf}
	}
	#set page width and height
	set pg_w [expr $xo + ($lm * $x_spacing) + 80]
	set maxc [expr ($pg_w - 30) / 10]
	find_lowest_constraint
	set yp [expr $ymax + (1.5 * $y_spacing) + 40]
	set pg_h [expr $yp + 50]

	#print and pop up status window
	switch $how {
		postscript {
			#for postscript printing 840 seems to be the top of the page, and 0 the left coordinate
			$TW_Vip postscript \
				-colormode color \
				-pageanchor nw \
				-pagey 840 -pagex 1 \
				-width $pg_w \
				-height $pg_h \
				-file $Pname
		    }
		gif {	gen_gif $Pname $pg_h $pg_w
		    }
	}
	toolbar on ;#restores toolbar
}

proc sort {list} {
	global sorted_indices
	debug "entering sort with list=$list"
	update
	set n [llength $list]
	set sorted_indices ""
	set sorted_list ""
	for {set i 0} {$i < $n} {incr i 1} {
		if {$i == 0} {
			lappend sorted_indices $i
			lappend sorted_list [lindex $list $i]
		} else {
			set ns [llength $sorted_indices]
			for {set j 0} {$j < $ns} {incr j 1} {
				if {[lindex $list $i] < [lindex $sorted_list $j]} {
					set sorted_indices [linsert $sorted_indices $j $i] ;#changed this
					set sorted_list [linsert $sorted_list $j [lindex $list $i]]
					break
					}
				if {$j == [expr $ns - 1]} { ;#last item in list
					lappend sorted_indices $i
					lappend sorted_list [lindex $list $i]
					}
				}
			
			}
		}

}

proc toolbar {how} {
	global file_img file_active_img event_img event_active_img revent_img revent_active_img
	global cond_img cond_active_img mark_img mark_active_img auto_img auto_active_img fail_event_img fail_event_active_img
	global TW_Vip
	global state
	$TW_Vip delete op_buttons
	if {$how == "off"} {return}

	$TW_Vip create rect 0 0 460 40 -outline black -fill gray -tags op_buttons
	$TW_Vip create rect 2 2 44 38 -outline gray -fill gray -tags "op_file op_buttons"
	$TW_Vip create line 45 2 45 38 -fill black -tags "op_buttons"
	$TW_Vip create line 46 2 46 38 -fill white -tags "op_buttons"

	$TW_Vip create rect 5 5 41 33 -fill gold -tags op_buttons
	$TW_Vip create image 5 5 \
		-image $file_img \
		-activeimage $file_active_img \
		-anchor nw -tags "file_button op_buttons"
	set x 70
	set ink 35
	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image 70 5 \
		-image $event_img \
		-activeimage $event_active_img \
		-anchor nw -tags "event_button op_buttons"

	incr x $ink
	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image $x 5 \
		-image $revent_img \
		-activeimage $revent_active_img \
		-anchor nw -tags "revent_button op_buttons"
	
	incr x $ink
	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image $x 5 \
		-image $fail_event_img \
		-activeimage $fail_event_active_img \
		-anchor nw -tags "fail_event_button op_buttons"
	
	incr x $ink
	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image $x 5 \
		-image $cond_img \
		-activeimage $cond_active_img \
		-anchor nw -tags "cont_button op_buttons"
	incr x $ink

	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image $x 5 \
		-image $mark_img \
		-activeimage $mark_active_img \
		-anchor nw -tags "mark_button op_buttons"
	incr x $ink

	$TW_Vip create rect $x 5 [expr $x + 30] 35 -fill gold -tags op_buttons
	$TW_Vip create image $x 5 \
		-image $auto_img \
		-activeimage $auto_active_img \
		-anchor nw -tags "auto_button op_buttons"

	#default mode is select
	select_near

	toolbar_bind
}

proc toolbar_bind {} {
	global TW_Vip

	$TW_Vip bind file_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb file %X %Y
		"

	$TW_Vip bind event_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb event
		"

	$TW_Vip bind revent_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb revent
		"

	$TW_Vip bind fail_event_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb failevent
		"

	$TW_Vip bind cont_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb cont
		"

	$TW_Vip bind mark_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb mark
		"

	$TW_Vip bind auto_button <ButtonPress-1> "
		bind $TW_Vip <ButtonPress-1> {}
		absorb auto
		"			
}

#end of what we'll keep

#---empty procs-- these are needed to increase the common code base

proc update_help {stringy} {}
proc disable_saves {} {}
proc enable_save {} {}
proc enable_saveas {} {}
proc configure_menus {how} {}
proc make_prov_frame {} {}
proc read_settings {} {}
proc read_features {} {}
proc read_symbol_file {sfile} {}
proc consider_write_symfile {to} {}
proc write_symbols_file {} {}

#### end of itemeedit.tcl

# can be set with .prx entries

set pseq	{}	;# msc: ...
set hidden	{}	;# hidden 1
set io_only	0	;# io_only: 1
set loops	0	;# loops: 1
set asserts	1	;# asserts: 1
set np_loops	0	;# np_loops: 1
set aut_loops	0	;# always the default
set noend	1	;# noend: 0
set use_vals	0	;# use_vals: 1
set bitstate	0	;# bitstate: 22..30   for -w argument
set Depth	1000	;# maxdepth: 500
set memlim	350	;# memlim: ...
set notfixed	0	;# enable/disable adjustable xFactor
set shortest	0	;# find shortest counterexample?
set bounded	0	;# report depth limit violations?

# non-configurable globals

set PrxChanged	0
set SrcChanged	0
set quality	3	;# 3=medium,  range: -w18 up to -w30
set Fname	""
set Vip_Fname	""
set oFname	""
set Srcname	""
set fnm		""
set BG   	"black"	;# default background color for text
set FG   	"gold"	;# default foreground color for text
set Pattern	""

set width	800	;#initial requested canvas size
set height	600
set old_width	0	;#initial window size - since we don't know
set old_height	0
set SCRstat	0	;# scrollbars off by default
set haslutmenu	0
set MapNr	0
set YSZ		10
set XSZ		80
set xFactor	80	;# default distance between process lines in mscs
set srcfiles	{}
set feaver_logo ""
set lno		1
set Extract	""
set P_Flag	"-P"	;# when set, uses .M intermediate file on modex calls
set z_Flag	""

catch {
	if {[file exists $logo]} {
	set feaver_logo [eval image create photo -file $logo]
	}
}

# ... for directory browsing
set exts {.prx .vip .pml .c} 	;# file extensions filtered
set Xspace 35		;# horizontal space between columns
set arb_off 10		;# an offset
set BoxCol gold 	;# color of outline and fill of boxes
set SymCol black 	;# color of "+" or "-" symbol in boxes
set LineCol white 	;# color of lines
set DTextCol white 	;# color of text of directories
set FTextCol gold 	;# color of text of files
set BGCol black 	;# color of canvas background

set Pink_White	white	;# color for the Advanced panel
set Pink_Ivory	ivory
set beenthere	0	;# activated the Advanced tab at least once
set gui_changed 0	;# changes made in Advanced tab

# set TW_Model	0
  set TW_Info	0
# set TW_Source	0
  set TW_Parse	0
  set TW_Fcts	0
  set TW_Data	0
# set TW_Prx	0
  set TW_Driver	0
  set TW_Out	0
  set TW_Log	0
  set TW_Stats	0
  set TW_Errors	0

# top menu bar
	frame .top \
		-width $width -height 25 \
		-bg darkgrey \
		-relief sunken \
		-border 4
	pack .top -expand 0 -fill both

			# bottom decoration
	label .bot -bg black -fg gold -anchor e \
		-relief sunken -border 4 \
		-text "FeaVer  " \
		-font {Helvetica 14 bold}

	pack .bot -side bottom -fill x

	menubutton .top.file \
		-bg black -fg gold \
		-text "File.." \
		-activeforeground black -activebackground gold \
		-relief raised -menu .top.file.m
	pack .top.file -fill y -side left

	menu .top.file.m -tearoff 0
	.top.file.m add command -label "Browse.." -command "open_c"
	.top.file.m add command -label "Save Src"      -command "save_c 1"
	.top.file.m add command -label "Save Src As.." -command "save_c 0"
	.top.file.m add command -label "Save Prx"      -command "save_prx 1"
	.top.file.m add command -label "Save Prx As.." -command "save_prx 0"
	.top.file.m add command -label "Quit" -command "cleanup 1; exit 0"

	menubutton .top.eop \
		-bg black -fg gold \
		-text "Edit.." \
		-activeforeground black -activebackground gold \
		-relief raised -menu .top.eop.m
	pack .top.eop -fill y -side left
	menu .top.eop.m -tearoff 0
	.top.eop.m add command -label "Populate LUT.." \
		-command "populate_lut"
	.top.eop.m add command -label "Upgrade LUTs.." \
		-command "upgrade_c"

	.top.eop.m add separator

	.top.eop.m add command -label "Edit Event Symbols.." \
		-command {
			set wn [find_path Vip]
			set wn [string range $wn 3 [string length $wn]]
			labels edit e $wn
			}
	.top.eop.m add command -label "Edit Constraint Symbols.." \
		-command {
			set wn [find_path Vip]
			set wn [string range $wn 3 [string length $wn]]
			labels edit c $wn
			}

	menubutton .top.edit \
		-bg black -fg gold \
		-text "Options.." \
		-activeforeground black -activebackground gold \
		-relief raised -menu .top.edit.m
	pack .top.edit -fill y -side left

	menu .top.edit.m -tearoff 0
	.top.edit.m add command -label "Do Not Search for Assertion errors" \
		-command "with_asserts"	;# 0
	.top.edit.m add command -label "Search Acceptance cycles" \
		-command "with_loops"	;# 1
	.top.edit.m add command -label "Search Non-Progress cycles" \
		-command "with_np"	;# 2
	.top.edit.m add command -label "Search Property violations" \
		-command "with_aut"	;# 3

	.top.edit.m add command -label "Report invalid endstates" \
		-command "with_ends"	;# 4

	.top.edit.m add separator

	.top.edit.m add command -label "Show all statements in MSCs" \
		-command "all_stmnts"	;# 6
	.top.edit.m add command -label "Show values in i/o" \
		-command "with_vals"	;# 7

	.top.edit.m add separator

	.top.edit.m add command -label "Force recompilation on modex calls" \
		-command "toggle_pflag"	;# 9
	.top.edit.m add command -label "Do not strip system headers" \
		-command "toggle_zflag"	;# 10

	.top.edit.m add separator

	.top.edit.m add command -label "Get PanInfo.." \
		-command "getpaninfo; showglob"

	menubutton .top.def \
		-bg black -fg gold \
		-text "View.." \
		-activeforeground black -activebackground gold \
		-relief raised -menu .top.def.m
	pack .top.def -fill y -side left

	menu .top.def.m -tearoff 0

	.top.def.m add command -label "Scrollbars" \
		-command "scrollbar_on"

	.top.def.m add command -label "Parsed code.."      \
		-command "place_window new ttsr 2 Parse 1; parse_c"
	.top.def.m add command -label "Functions used.."   \
		-command "place_window new ttsr 2 Fcts  1; fcts_c"
	.top.def.m add command -label "Data types.."       \
		-command "place_window new ttsr 2 Data  1; sym_c"
	.top.def.m add command -label "Test driver code.." \
		-command "place_window new ttsr 2 Driver 1; drv_c"

	.top.def.m add command -label "Refresh Browser View.." \
	        -command "initialize_browse refresh w_1_1"

	scale .top.q -orient horizontal \
		-width 8 \
		-from 0 -to 5 \
		-variable quality \
		-font {Helvetica 8} \
		-showvalue false \
		-label "Speed <-> Quality" \
		-fg white -bg darkgrey \
		-relief flat 
	pack  .top.q -fill y -side left

	frame .top.buts -bg darkgrey
	pack .top.buts -side left
	checkbutton .top.buts.r \
		-variable exhaustive \
		-highlightthickness 0 \
		-anchor s \
		-bg darkgrey \
		-activebackground darkgrey \
		-text "max quality" \
		-relief flat 
	pack .top.buts.r -pady 0 -ipady 0 -anchor w -side top
	checkbutton .top.buts.b \
		-variable bounded \
		-highlightthickness 0 \
		-anchor s \
		-bg darkgrey \
		-activebackground darkgrey \
		-text "bounded" \
		-relief flat 
	pack .top.buts.b -pady 0 -ipady 0 -anchor w -side bottom

	frame .top.ents -bg darkgrey
	pack .top.ents -side left

	frame .top.ents.top -bg darkgrey
	pack .top.ents.top -anchor nw -side top -fill x -pady 4
	label .top.ents.top.depthlab \
		-text "Depth Limit:" -bg darkgrey -fg ivory \
		-relief flat
	pack  .top.ents.top.depthlab -anchor w -side left

	entry .top.ents.top.depth \
		-background ivory -foreground black \
		-relief sunken -textvariable Depth
	pack  .top.ents.top.depth -anchor w -side left -fill x -expand 1

	frame .top.ents.bot -bg darkgrey
	pack .top.ents.bot -anchor sw -side top -fill x

	entry .top.ents.bot.search \
		-background ivory -foreground black \
		-relief sunken -textvariable Pattern
	pack  .top.ents.bot.search -side right -fill x -expand 1
	label .top.ents.bot.searchlab -text "Search:" -bg darkgrey -fg ivory
	pack  .top.ents.bot.searchlab -anchor w -side left
	bind  .top.ents.bot.search <Return> { searchpat $Pattern }

	menubutton .top.help  \
		-border 4 \
		-relief raised \
		-bg black -fg gold \
		-activeforeground black -activebackground gold \
		-font {Helvetica 10 bold} \
		-text "Help.." -relief raised \
		-menu .top.help.m

	menu .top.help.m

	.top.help.m add command -label "About FeaVer" \
		-command "about_feaver"
	.top.help.m add command -label "About Spin" \
		-command "about_spin"
	.top.help.m add command -label "Verification" \
		-command "help_verification"
	.top.help.m add command -label "Timeline Editor" \
		-command "help_timeline"

	pack .top.help -side right -padx 4

	bind .top.help <Any-Enter> {
		.top.help configure -fg black -bg gold
	}
	bind .top.help <Any-Leave> {
		.top.help configure -fg gold -bg black
	}
	button .top.run -bg black -fg red \
		-border 4 \
		-relief raised \
		-activeforeground black -activebackground red \
		-text "Check" \
		-font {Helvetica 10 bold} \
		-command "spin_c"
	pack .top.run -side right -padx 4
	bind .top.run <Any-Enter> {
		.top.run configure -fg black -bg red
	}
	bind .top.run <Any-Leave> {
		.top.run configure -fg red -bg black
	}

	label .top.fnm -textvariable Fname -bg darkgrey -fg white
	pack .top.fnm -side left -fill x

			# main windows area
	frame .f \
		-width $width -height $height \
		-bg black \
		-relief sunken \
		-border 4
	pack .f -side top -expand 1 -fill both

	canvas .f.c \
		-width $width -height [expr $height - 20] \
		-bg gray
	pack .f.c -side top -expand 1 -fill both

proc searchpat {pat} {
	global is_on_top is_current
	global TW_Source TW_Parse TW_Dcts TW_Data
	global TW_Prx TW_Driver TW_Model TW_Out
	global TW_Stats TW_Errors TW_Log

	switch $is_current {
	1	{	complain "select frame to search"
			return
		}
	2	{	switch $is_on_top(2) {
			1	{ set this $TW_Source }
			2	{ set this $TW_Parse  }
			3	{ set this $TW_Fcts   }
			4	{ set this $TW_Data   }
			5	{ set this $TW_Prx    }
			6	{ set this $TW_Driver }
			7	{ set this $TW_Model  }
		}	}
	3	{	switch $is_on_top(3) {
			1	{ set this $TW_Out    }
			2	{ set this $TW_Stats  }
			3	{ set this $TW_Errors }
			4	{ set this $TW_Log    }
	}	}	}

	if {[show_matches $this $pat] == 0} {
		complain "No Match of \"$pat\""
	}
}

proc showglob {} {
	global glob_defines loc_defines TW_Stats

	put_on_top 3 2

	catch { $YW_Stats delete 0.0 end }
	for {set i 0} {$i < [llength $glob_defines]} {incr i} {
		$TW_Stats insert end [lindex $glob_defines $i]\n
	}
	$TW_Stats insert end "\n" 
	for {set i 0} {$i < [llength $loc_defines]} {incr i} {
		$TW_Stats insert end [lindex $loc_defines $i]\n
	}
}

proc find_level {r} {
	set trimmed [string trim $r "/"]
	set splitt [split $trimmed "/"]
	set level 1
	debug "Entering find_level with $r, and split is: $splitt"
	set level [llength $splitt]
	debug "before adjusting for blanks, level is: $level"
	#set l $level
#
	#for {set i 0} {$i < $l} {incr i 1} {
	#	if {[lindex $splitt $i] == ""} {
	#		incr level -1
	#		}
	#	}
	if {$level <= 0} {
		exit 1
	}
	return $level
	
}
set root_level [find_level $work_dir]
debug "after find_level, root_level is: $root_level\n"

proc measure_text {} {
	global pixels_per_char pixels_per_line Cfont
	set t_width 10
	set t_height 10
	text .f.meas \
		-font $Cfont\
		-width $t_width \
		-height $t_height
				
	.f.c create window $t_width $t_height \
		-window .f.meas \
		-anchor nw \
		-tags text_measure
	set bbox [.f.c bbox text_measure]
	set wid [expr [lindex $bbox 2] - [lindex $bbox 0]]
	set hgt [expr [lindex $bbox 3] - [lindex $bbox 1]]
	set pixels_per_char [expr round($wid/$t_width)]
	set pixels_per_line [expr round($hgt/$t_height)]
	destroy .f.meas
	debug "LEAVING measure_text with pixels_per_char=$pixels_per_char, and pixels_per_line=$pixels_per_line"
}

proc get_canvas_size {} {
	global c_width c_height

	debug "ENTERING get_canvas_size"
	set c_width  [.f.c cget -width]
	set c_height [.f.c cget -height]
}

proc static_view {} {
	global order

	foreach {ord name} {1 Browse 2 Info} {
		set order(1,$ord) $name
	}
	foreach {ord name} { \
		1 Source 2 Parse  3 Fcts   4 Data   \
		5 Prx    6 Driver 7 Model  8 Vip   9 Advanced } {

		set order(2,$ord) $name
	}
	foreach {ord name} {1 Out 2 Stats 3 Traces 4 Log} {
		set order(3,$ord) $name
	}

#	set wtag w_2_8 ;# 

	#position 1 - northwest corner
	place_window new tcsa 1 Browse
	place_window new tcsa 1 Info

	#position 2 - northeast corner
	place_window new ttsr 2 Source 1	;# 1	
#	place_window new ttsr 2 Parse  1	;# 2
#	place_window new ttsr 2 Fcts   1	;# 3
#	place_window new ttsr 2 Data   1	;# 4
	place_window new ttsr 2 Prx    1	;# 5	;# replace ttsr with frame
#	place_window new ttsr 2 Driver 1	;# 6
	place_window new ttsr 2 Model  1	;# 7
	place_window new tcsa 2 Vip    1        ;# 8
	place_window new frame 2 Advanced   1	;# 9

	#position 3 - south
	place_window new ttsr 3 Out		;# 1
	place_window new ttsr 3 Stats		;# 2
	place_window new ttsr 3 Traces		;# 3
	place_window new ttsr 3 Log		;# 4

	initialize_browse first w_1_1
}

proc set_window_positions {} {
	global c_width c_height wp

	debug "ENTERING set_window_positions"
	get_canvas_size

	foreach i {1 2 3} { set wp($i) "" }

	set LHS .20
	set RHS .80

	set LWH .3333
	set UWH .6666
	
	set w_width  [expr round($c_width  * $LHS)]
	set w_height [expr round($c_height * $UWH)]
	set w_xo 0
	set w_yo 0
	lappend wp(1) $w_width $w_height $w_xo $w_yo ;# position 1 - northwest corner
	debug "c_width is $c_width, and c_height is: $c_height"
	debug "wp(1) is $wp(1)"

	set w_width  [expr round($c_width  * $RHS)]
	set w_height [expr round($c_height * $UWH)]
	set w_xo     [expr round($c_width  * $LHS)]
	set w_yo     0
	lappend wp(2) $w_width $w_height $w_xo $w_yo ;# position 2 - northeast corner
	debug "wp(2) is $wp(2)"

	set w_width $c_width
	set w_height [expr round($c_height * $LWH)]
	set w_xo 0
	set w_yo     [expr round($c_height * $UWH)]
	lappend wp(3) $w_width $w_height $w_xo $w_yo ;#	position 3 - south
	debug "wp(3) is $wp(3)"
}

proc check_refresh_layout {} {
	global old_width old_height

	debug "ENTERING check_refresh_layout, old_width=$old_width, old_height=$old_height"
	set g [wm geometry .]
	set sg [split $g "x"]
	set w_width [lindex $sg 0]
	set sg [lrange $sg 1 [llength $sg]]
	set sgs [split $sg "+"]
	set w_height [lindex $sgs 0]
	debug "after getting geometry,        cur_width=$w_width, cur_height=$w_height"

	if {($old_width == "") && ($old_height == "")} { ;# first call
		set old_width $w_width
		set old_height $w_height
		return
	}

	if {($old_width != $w_width) || ($old_height != $w_height)} {
		set change_x [expr $w_width - $old_width]
		set change_y [expr $w_height - $old_height]
		debug "change_x=$change_x, change_y=$change_y"
		set old_width $w_width
		set old_height $w_height
		refresh_layout $change_x $change_y
	}
}

proc refresh_layout {{change_x 0} {change_y 0}} {
	global unique_window_num window_type tabs has_lines

	debug "ENTERING refresh_layout"
	set ow [.f.c cget -width]
	set oh [.f.c cget -height]

	bind . <Configure> ""

	.f.c configure -width  [expr $ow + $change_x]
	.f.c configure -height [expr $oh + $change_y]
	
	set_window_positions
	how_many_windows
	foreach i $unique_window_num {
		debug "tabs($i) are: $tabs($i)"
		for {set j 1} {$j <= [llength $tabs($i)]} {incr j 1} {
				set tab_id [lindex $tabs($i) [expr $j - 1]]
				set type $window_type($i,$tab_id)
				set tab_pos [find_tab_spot $tab_id $i]
				debug "\nABOUT TO CALL place_window resize_master $type $i '' 0 $tab_id $tab_pos"
				place_window resize_master $type $i "" 0 $tab_id $tab_pos
				update
	}	}	

	bind . <Configure> {
		check_refresh_layout
	}		
	debug "LEAVING refresh_layout"
}

proc with_asserts {} {
	global asserts

	set asserts [expr 1 - $asserts]
	if {$asserts == 0} {
		.top.edit.m entryconfigure 0 -label "Search for assertion errors"
	} else {
		.top.edit.m entryconfigure 0 -label "Do not search for assertion errors"
	}
}

proc with_loops {} {
	global loops

	set loops [expr 1 - $loops]
	if {$loops == 0} {
		.top.edit.m entryconfigure 1 -label "Search for accept cycles"
	} else {
		.top.edit.m entryconfigure 1 -label "Do not search for accept cycles"
	}
}

proc with_np {} {
	global np_loops

	set np_loops [expr 1 - $np_loops]
	if {$np_loops == 0} {
		.top.edit.m entryconfigure 2 -label "Search for non-progress cycles"
	} else {
		.top.edit.m entryconfigure 2 -label "Do not search for non-progress cycles"
	}
}

set aut_file "feaver.aut"

proc pick_aut {} {
	global aut_file

	set f {}
	catch { set f [lsort [glob *.aut]] }
	if {[llength $f] == 0} {
		return 0
	}

	catch { destroy .aut }
	toplevel .aut
	wm minsize .aut 1 1
	wm title .aut "Property Automata"

	frame .aut.l
	scrollbar .aut.l.scroll \
		-command ".aut.l.list yview"
	listbox .aut.l.list \
		-yscroll ".aut.l.scroll set" \
		-relief raised -height 20 -width 30 \
		-bg white
	button .aut.ok -text "Cancel" \
		-command { destroy .aut } -width 5

	pack .aut.l.scroll -side right -fill y
	pack .aut.l -side top -pady 8 -fill both -expand yes
	pack .aut.l.list -side left -fill both -expand yes
	pack .aut.ok -side bottom -anchor n -pady 3

	foreach i $f {
            	.aut.l.list insert end $i
	}
	bind .aut.l.list <Double-Button-1> {
		set i [.aut.l.list get active]
		set aut_file $i
		destroy .aut
	}
	return 1
}

proc with_aut {} {
	global aut_loops

	set aut_loops [expr 1 - $aut_loops]
	if {$aut_loops == 0} {
		.top.edit.m entryconfigure 3 \
			-label "Search for Property violations"
	} else {
		if {[pick_aut]} {
			.top.edit.m entryconfigure 3 \
				-label "Do not search for Property violations"
		} else {
			set aut_loops [expr 1 - $aut_loops]	;# revert
			complain "no file *.aut files found (e.g. use Vip)"
	}	}
}

proc with_ends {} {
	global noend

	set noend [expr 1 - $noend]
	if {$noend == 0} {
		.top.edit.m entryconfigure 4 -label "Do not search for invalid endstates"
	} else {
		.top.edit.m entryconfigure 4 -label "Search for invalid endstates"
	}
}

proc all_stmnts {} {
	global io_only

	set io_only [expr 1 - $io_only]
	if {$io_only == 0} {
		.top.edit.m entryconfigure 6 -label "Show all statements in MSCs"
	} else {
		.top.edit.m entryconfigure 6 -label "Show only send/recvs in MSCs"
	}
}

proc with_vals {} {
	global use_vals

	set use_vals [expr 1 - $use_vals]
	if {$use_vals == 0} {
		.top.edit.m entryconfigure 7 -label "Show real i/o values in MSCs"
	} else {
		.top.edit.m entryconfigure 7 -label "Show symbolic values in MSCs"
	}
}

proc toggle_pflag {} {
	global P_Flag

	if {$P_Flag == ""} {
		set P_Flag "-P"
		.top.edit.m entryconfigure 9 -label "Force recompilation on modex calls"
	} else {
		set P_Flag ""
		.top.edit.m entryconfigure 9 -label "Avoid recompilation on modex calls"
	}
}

proc toggle_zflag {} {
	global z_Flag

	if {$z_Flag == ""} {
		set z_Flag "-z"
		.top.edit.m entryconfigure 10 -label "Strip system headers from target sources"
	} else {
		set z_Flag ""
		.top.edit.m entryconfigure 10 -label "Do not strip system headers"
	}
}

set TABWIDTH  50

proc scrollbar_on {} {
	global SCRstat window_type tabs TABWIDTH wp
	set SCRstat 1
	.top.def.m entryconfigure 0 \
		-label "Remove scrollbars" \
		-command "scrollbar_off"
	
	refresh_layout
	how_many_windows
	set scr_room 16
	foreach w {1 2 3} {
		set width [lindex $wp($w) 0]
		set height [lindex $wp($w) 1]
		set width [expr $width - $scr_room - 4] ;# leave room for scrollbars (16) & borders
		set height [expr $height - $scr_room - 0] ;# leave room for scrollbars, borders
		set xo [lindex $wp($w) 2]
		set yo [lindex $wp($w) 3]
		set origin_x $xo
		set origin_y $yo
		set to 20
		set end_x [expr $origin_x + $width - 4 - 2] 
		set end_y [expr $origin_y + $height - $to] ;# minus tab offset
		foreach t $tabs($w) {
			set w_tag "";	append w_tag "w" "_" $w "_" $t
			set tabname [find_label $w_tag]
			set hs_tag "";	append hs_tag "hs" "_" $w "_" $t
			set vs_tag "";	append vs_tag "vs" "_" $w "_" $t
			scrollbar .f.$hs_tag -orient horizontal
			scrollbar .f.$vs_tag -orient vertical
			if {$tabname != "Advanced"} {
				#Advanced is a frame so not scrollable
				.f.$hs_tag configure -command ".f.$w_tag xview" -orient horizontal
				.f.$vs_tag configure -command ".f.$w_tag yview" -orient vertical
				.f.$w_tag configure -xscrollcommand ".f.$hs_tag set" \
					-yscrollcommand ".f.$vs_tag set"
			}
		
			set tab_end_coordinate [expr [lindex [.f.c bbox $w_tag] 0] \
				+ 10 + ([llength $tabs($w)] * $TABWIDTH)]
		
			.f.c create window [expr $tab_end_coordinate + 12] $end_y \
				-window .f.$hs_tag \
				-width [expr $end_x - ($tab_end_coordinate + 8)] \
				-anchor nw -tags $hs_tag
	
			.f.c create window $end_x $yo -window .f.$vs_tag -height [expr $end_y - $yo] \
				-anchor nw -tags $vs_tag
			}
		set lc [expr [lindex [.f.c bbox $w_tag] 0] + 10 + ($TABWIDTH * [llength $tabs($w)]) + 5]
		catch {.f.c delete resizer$w}
		.f.c create rect $lc [expr $end_y + 1] [expr $lc + 5] [expr $end_y + 15] \
			-tags resizer$w -outline black -fill gray
		.f.c bind resizer$w <ButtonPress-1> "
			reapportion $w
			"
		}
}

proc scrollbar_off {} {
	global SCRstat tabs

	debug "\nENTERING scrollbar_off"
	set SCRstat 0
	.top.def.m entryconfigure 0 \
		-label "Add scrollbars" \
		-command "scrollbar_on"
		
	foreach w {1 2 3} {
		foreach t $tabs($w) {
			set w_tag "";	append w_tag "w" "_" $w "_" $t
			set tabname [find_label $w_tag]
			set hs_tag "";	append hs_tag "hs" "_" $w "_" $t
			set vs_tag "";	append vs_tag "vs" "_" $w "_" $t
			if {$tabname != "Advanced"} {
				.f.$w_tag configure -xscrollcommand "" -yscrollcommand ""
			}
			destroy .f.$hs_tag
			destroy .f.$vs_tag
			.f.c delete $hs_tag
			.f.c delete $vs_tag
			}
		catch {.f.c delete resizer$w}	
		}
	set items [.f.c find all]
	set ptags ""
	foreach i $items {
		set tags [.f.c gettag $i]
		lappend ptags [lindex $tags 0]
		}
	debug "all primary tags are: $ptags"
	refresh_layout	
}

proc find_label {tag} {	;# same tag as focus_in
	global tab_name

	set label ""
	set split_tag [split $tag "_"]
	set w [lindex $split_tag 1]
	set tab [lindex $split_tag 2]
	catch {set label $tab_name($w,$tab)}
	return $label
}

proc find_path {tabname} {
	global unique_window_num tabs tab_name

	how_many_windows
	set match_win ""
	set match_tab ""
	foreach i $unique_window_num {
		foreach j $tabs($i) {
			if {$tab_name($i,$j) == $tabname} {
				set match_win $i
				set match_tab $j
				break
			}
		}
		if {$match_win != ""} {
			break
	}	}

	if {$match_win != ""} {
		return ".f.w_${match_win}_$match_tab"
	}
	complain "No Tabname $tabname"
	return ""
}

proc how_many_windows {} {
	global wtags unique_tags positions unique_window_num tabs

	debug "ENTERING how_many_windows"
	set nw 0
	set tags [.f.c find all]
	set wtags ""
	foreach i {1 2 3} {
		set tabs($i) ""
		}
	foreach i $tags {
		set p [lindex [.f.c gettags $i] 0]
		if {[string index $p 0] == "w"} {
			lappend wtags $p 
			}
		}
	set unique_tags ""
	set unique_window_num ""
	foreach i $wtags {
		set temp [split $i "_"]
		set win [lindex $temp 1]
		set match 0
		foreach j $unique_window_num {
			if {$win == $j} {
				set match 1
				break
				}
			}
		if {!$match} {
			lappend unique_tags $i
			lappend unique_window_num $win
			}
		}
	foreach i $wtags { ;# get tabs for each window
		set temp [split $i "_"]
		if {[llength $temp] > 2} {
			set win [lindex $temp 1]
			set tab [lindex $temp 2]
			lappend tabs($win) $tab
			}
		}
	foreach i {1 2 3} {
		debug "in how_many_windows, before sort, tabs($i) is $tabs($i)"
		set tabs($i) [sort_tabs $tabs($i)]
		debug "in how_many_windows, sorted tabs($i) is: $tabs($i)"
		}
	foreach i $unique_tags {
		set temp [split $i "_"]
		set win [lindex $temp 1]
		set tags [.f.c gettags $i]
		set position_tag [lindex $tags 1]
		set positions($win) [split $position_tag "_"]
		}
	debug "LEAVING how_many_windows, unique_window_num = $unique_window_num, unique_tags=$unique_tags"
}

proc sort_tabs {list} {
	debug "entering sort_tabs with list=$list"
	update
	set n [llength $list]
	debug " n is $n"
	set sorted_indices ""
	set sorted_list ""
	for {set i 0} {$i < $n} {incr i 1} {
		if {$i == 0} {
			lappend sorted_indices $i
			lappend sorted_list [lindex $list $i]
		} else {
			set ns [llength $sorted_indices]
			for {set j 0} {$j < $ns} {incr j 1} {
				if {[lindex $list $i] < [lindex $sorted_list $j]} {
					set sorted_indices [linsert $sorted_indices $j $i] ;#changed this
					set sorted_list [linsert $sorted_list $j [lindex $list $i]]
					break
					}
				if {$j == [expr $ns - 1]} { ;#last item in list
					lappend sorted_indices $i
					lappend sorted_list [lindex $list $i]
					}
				}
			
			}
		}
	debug "leaving sort_tabs"
	return $sorted_list
}

set Cfont	{FixedSys 9}		;# was {Courier 8}
set Ccol	blue			;# text color
set Scol	red			;# text color when selected
set Bcol	white			;# text background\

proc vip_up {t tabn} {
	global Vip_Fname
	put_on_top $t $tabn
	set tag "w_${t}_${tabn}"
	fill_in $tag
	if {$Vip_Fname == ""} {
		clear new
	}
}

proc place_window {mode win_type {pos -1} {tabname ""} {lines 0} {tabn ""} {tab_pos ""}} {
	global wp
	global window_type n_tabs tabs tab_name
	global unique_window_num SCRstat has_lines
	global pixels_per_line pixels_per_char
	global TABWIDTH order Cfont Ccol Bcol Scol
	global Pink_White Pink_Ivory
	global Vip_Fname

	debug "ENTERING place_window with mode=$mode, win_type=$win_type, pos=$pos, tabname=$tabname, \
			lines=$lines, and tabn=$tabn, and tab_pos = $tab_pos"

	how_many_windows

	set_window_positions
	set width [lindex $wp($pos) 0]
	set height [lindex $wp($pos) 1]
	set xo [lindex $wp($pos) 2]
	set yo [lindex $wp($pos) 3]

	switch $mode {
		new {
			set t $pos
			set tabn [get_tab_number $tabname $pos]
			set window_type($t,$tabn) $win_type
			set has_lines($t,$tabn) $lines
			set tab_name($t,$tabn) $tabname
			set tab_position [find_tab_spot $tabn $pos]
			}
		resize_master {
			set t $pos
			set win_type $window_type($t,$tabn)
			set tab_position $tab_pos
			set tabname $tab_name($t,$tabn)
			}
		}	
	switch $SCRstat {	0	{set scr_room 0}
				1	{set scr_room 16}	}

	set origin_x $xo
	set origin_y $yo
	switch $win_type {
		frame {
			set width [expr $width - $scr_room - 4] ;# leave room for scrollbars (16) & borders
			set height [expr $height - $scr_room - 0] ;# leave room for scrollbars, borders
	
			if {$has_lines($t,$tabn)} {set width [expr $width - (5 * $pixels_per_char)]}
			set t_height [expr ($height - 20)/$pixels_per_line]
			set w_tag "";	append w_tag "w" "_" $t "_" $tabn
			set hs_tag "";	append hs_tag "hs" "_" $t "_" $tabn
			set vs_tag "";	append vs_tag "vs" "_" $t "_" $tabn
			set lines_tag ""; append lines_tag "li_" $t "_" $tabn
			set to 20 ;#offset to leave room for tab labels	
			switch $mode {
				new {	if {$has_lines($t,$tabn)} {
						text .f.$lines_tag \
						-width 4 \
						-height $t_height \
						-relief raised \
						-fg $Ccol \
 						-font $Cfont \
						-selectbackground $Bcol \
						-selectforeground $Scol \
						-wrap none \
						-bg $Bcol \
						-bd 2
						
						.f.c create window \
							$origin_x $origin_y \
							-window .f.$lines_tag \
							-anchor nw -tags $lines_tag
		
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						}
					}
				resize_master {
					if {$has_lines($t,$tabn)} {
						.f.$lines_tag configure -height $t_height
						.f.c coords $lines_tag $origin_x $origin_y
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						}
					}
				}
			
			set end_x [expr $origin_x + $width - 4 - 2] 
			set end_y [expr $origin_y + $height - $to] ;# minus tab offset
			#if new, count tabs and put new tab after last -- assuming they're already compressed
			
			set tx_start [expr $origin_x + 10 + (($tab_position - 1) * $TABWIDTH)]
			set tx_end [expr $origin_x + 10 + ($tab_position * $TABWIDTH)]
			set tab_tag ""
			append tab_tag "tab" "_" $t "_" $tabn
			set xo $origin_x
			set yo $origin_y
			set x1 [expr $end_x + $scr_room]
			set y1 $origin_y
			set x2 [expr $end_x + $scr_room]
			set y2 $end_y
			set x3 [expr $tx_end + 3]
			set y3 $end_y
			set x4 [expr $tx_end - 3]
			set y4 [expr $end_y + 15]
			set x5 [expr $tx_start + 3]
			set y5 [expr $end_y + 15]
			set x6 [expr $tx_start - 3]
			set y6 $end_y
			set x7 $origin_x
			set y7 $end_y
			set x8 $origin_x
			set y8 $origin_y
			switch $mode {
				new {
					.f.c create polygon $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8 \
						-fill gray -outline black -tags $tab_tag -width 1
					}
				resize_master {
					.f.c coords $tab_tag $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8
					}
				}
			set text_tag ""
			append text_tag "text" "_" $t "_" $tabn
				
			set xo [expr $origin_x + 10 + [expr .5 * $TABWIDTH] \
				+ (($tab_position - 1) * $TABWIDTH)]
			set yo [expr $end_y + 7]
					
			set selected_tab $tabn
			
			switch $mode {
				new {
					.f.c create text $xo $yo \
						-text $tabname \
						-anchor center \
						-tags $text_tag
					.f.c bind $text_tag <ButtonPress-1> "
						put_on_top $t $tabn
						fill_in $w_tag
						"
				
					put_on_top $t $tabn
					}
				resize_master {
					.f.c coords $text_tag $xo $yo
					}
				}

			set cheight $height
		
			switch $mode {
				new {   frame .f.$w_tag \
						-width $width \
						-height [expr $cheight - $to] \
						-borderwidth 0 -bg $Pink_White \
						-relief flat -highlightthickness 0
					
					.f.c create window $origin_x $origin_y -window .f.$w_tag \
						-anchor nw -tags $w_tag \
						 -width $width \
						-height [expr $cheight - $to]
					if {$tabname != "Browse"} {
						bind .f.$w_tag <1> "focus_in $w_tag"
					}
					#create them, for appearances, but they are benign
					if $SCRstat {
						scrollbar .f.$hs_tag -command "" -orient horizontal
						scrollbar .f.$vs_tag -command "" -orient vertical
						#.f.$w_tag configure -xscrollcommand ".f.$hs_tag set" \
						#	-yscrollcommand ".f.$vs_tag set"
				}	}

				resize_master {
					.f.$w_tag configure -width $width -height [expr $height - $to]
					.f.c coords $w_tag $origin_x $origin_y
					.f.c itemconfigure $w_tag \
						-width $width \
						-height [expr $cheight - $to] \
				}	}
			

			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				how_many_windows
				set tab_end_coordinate [expr [lindex [.f.c bbox $w_tag] 0] \
					 + 10 + ([llength $tabs($t)] * $TABWIDTH)]
				switch $mode {
					new {	.f.c create window [expr $tab_end_coordinate + 12] $end_y \
							-window .f.$hs_tag \
							-width [expr $end_x - ($tab_end_coordinate + 8)] \
							-anchor nw -tags $hs_tag
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_k_tag [expr $tab_end_coordinate + 12] $y1
							.f.c itemconfigure $hs_k_tag \
								-width [expr $x1 - ($tab_end_coordinate + 8)]
							}
					
						.f.c create window $end_x $yo -window .f.$vs_tag \
							-height [expr $end_y - $yo] \
							-anchor nw -tags $vs_tag
						}
					resize_master {
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_tag [expr $tab_end_coordinate + 12] $end_y
							.f.c itemconfigure $hs_tag \
								-width [expr $end_x - ($tab_end_coordinate + 8)]
							}
						.f.c coords $vs_tag $end_x $yo
						.f.c itemconfigure $vs_tag -height [expr $end_y - $yo]
						}
					}
				}
			set selected_tab $tabn
			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				set lc [expr [lindex [.f.c bbox $w_tag] 0] + 10 + ($TABWIDTH * [llength $tabs($t)]) + 5]
				switch $mode {
					new {
						catch {.f.c delete resizer$t}
						.f.c create rect $lc [expr $end_y + 1] [expr $lc + 5] [expr $end_y + 15] \
							-tags resizer$t -outline black -fill gray
						.f.c bind resizer$t <ButtonPress-1> "
							reapportion $t
							"
						}
					resize_master {
						.f.c coords resizer$t $lc [expr $end_y + 1] \
							[expr $lc + 5] [expr $end_y + 15]
						}
					}
				}
			}
		tcsa {
			set width [expr $width - $scr_room - 4] ;# leave room for scrollbars (16) & borders
			set height [expr $height - $scr_room - 0] ;# leave room for scrollbars, borders
	
			if {$has_lines($t,$tabn)} {set width [expr $width - (5 * $pixels_per_char)]}
			set t_height [expr ($height - 20)/$pixels_per_line]
			set w_tag "";	append w_tag "w" "_" $t "_" $tabn
			set hs_tag "";	append hs_tag "hs" "_" $t "_" $tabn
			set vs_tag "";	append vs_tag "vs" "_" $t "_" $tabn
			set lines_tag ""; append lines_tag "li_" $t "_" $tabn
			set to 20 ;#offset to leave room for tab labels	
			switch $mode {
				new {	if {$has_lines($t,$tabn)} {
						text .f.$lines_tag \
						-width 4 \
						-height $t_height \
						-relief raised \
						-fg $Ccol \
 						-font $Cfont \
						-selectbackground $Bcol \
						-selectforeground $Scol \
						-wrap none \
						-bg $Bcol \
						-bd 2
						
						.f.c create window \
							$origin_x $origin_y \
							-window .f.$lines_tag \
							-anchor nw -tags $lines_tag
		
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						}
					}
				resize_master {
					if {$has_lines($t,$tabn)} {
						.f.$lines_tag configure -height $t_height
						.f.c coords $lines_tag $origin_x $origin_y
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						}
					}
				}
			
			set end_x [expr $origin_x + $width - 4 - 2] 
			set end_y [expr $origin_y + $height - $to] ;# minus tab offset
			#if new, count tabs and put new tab after last -- assuming they're already compressed
			
			set tx_start [expr $origin_x + 10 + (($tab_position - 1) * $TABWIDTH)]
			set tx_end [expr $origin_x + 10 + ($tab_position * $TABWIDTH)]
			set tab_tag ""
			append tab_tag "tab" "_" $t "_" $tabn
			set xo $origin_x
			set yo $origin_y
			set x1 [expr $end_x + $scr_room]
			set y1 $origin_y
			set x2 [expr $end_x + $scr_room]
			set y2 $end_y
			set x3 [expr $tx_end + 3]
			set y3 $end_y
			set x4 [expr $tx_end - 3]
			set y4 [expr $end_y + 15]
			set x5 [expr $tx_start + 3]
			set y5 [expr $end_y + 15]
			set x6 [expr $tx_start - 3]
			set y6 $end_y
			set x7 $origin_x
			set y7 $end_y
			set x8 $origin_x
			set y8 $origin_y
			switch $mode {
				new {
					.f.c create polygon $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8 \
						-fill gray -outline black -tags $tab_tag -width 1
					}
				resize_master {
					.f.c coords $tab_tag $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8
					}
				}
			set text_tag ""
			append text_tag "text" "_" $t "_" $tabn
				
			set xo [expr $origin_x + 10 + [expr .5 * $TABWIDTH] \
				+ (($tab_position - 1) * $TABWIDTH)]
			set yo [expr $end_y + 7]
					
			set selected_tab $tabn
			
			switch $mode {
				new {
					.f.c create text $xo $yo \
						-text $tabname \
						-anchor center \
						-tags $text_tag
					.f.c bind $text_tag <ButtonPress-1> "
						put_on_top $t $tabn
						fill_in $w_tag
						"
					
					if {$tabname == "Vip"} {
						.f.c bind $text_tag <ButtonPress-1> "
							vip_up $t $tabn
						"
					}
					put_on_top $t $tabn
					}
				resize_master {
					.f.c coords $text_tag $xo $yo
					}
				}

			set cheight $height
		
			switch $mode {
				new {	if {$tabname == "Browse"} {
						set cheight [expr $cheight - 25] ;# room for directory changer

						canvas .f.bg$w_tag \
							-width $width -height 25 \
							-bg black -borderwidth 0 \
							-relief flat -highlightthickness 0
						.f.c create window \
							$origin_x [expr $origin_y + $cheight - $to] \
							-window .f.bg$w_tag -anchor nw -tags bg$w_tag

					#	label .f.lab$w_tag -width 6 -text "Drive:" \
					#		-fg white -bg black \
					#		-relief flat
					#	.f.c create window \
					#		$origin_x [expr $origin_y + $cheight - $to] \
					#		-window .f.lab$w_tag -anchor nw -tags lab$w_tag

						two_combobox .f.cb$w_tag \
							-width 10 -bg black -fg white \
							-relief sunken -insertbackground gold \
							-selectbackground gold -state fixed \
							-insertentrycommand "initialize_browse first w_1_1"
						.f.c create window \
							[expr $origin_x + 5] \
							[expr $origin_y + $cheight - $to] \
							-window .f.cb$w_tag -anchor nw -tags cb$w_tag
					} 
					
					canvas .f.$w_tag -width $width -height [expr $cheight - $to] \
						-borderwidth 0 -bg ivory -relief flat -highlightthickness 0 \
						-scrollregion {0 0 1500 1000}
					.f.c create window $origin_x $origin_y -window .f.$w_tag \
						-anchor nw -tags $w_tag
					if {$tabname != "Browse"} {
						bind .f.$w_tag <1> "focus_in $w_tag"
					}
					bind .f.$w_tag <2> ".f.$w_tag scan mark %x %y"
					bind .f.$w_tag <B2-Motion> ".f.$w_tag scan dragto %x %y"
					if $SCRstat {
						scrollbar .f.$hs_tag -command ".f.$w_tag xview" -orient horizontal
						scrollbar .f.$vs_tag -command ".f.$w_tag yview" -orient vertical
						.f.$w_tag configure -xscrollcommand ".f.$hs_tag set" \
							-yscrollcommand ".f.$vs_tag set"
						}
					}
				resize_master {
					.f.$w_tag configure -width $width -height [expr $height - $to]
					.f.c coords $w_tag $origin_x $origin_y
					debug "resize_master branch, tabname == $tabname" 
					if {$tabname == "Browse"} {
						debug "resize_master branch - tabname is: $tabname"
						set cheight [expr $cheight - 25] ;# room for directory changer
						.f.bg$w_tag configure -width $width -height 25
						.f.c coords bg$w_tag $origin_x [expr $origin_y + $cheight - $to]
					#	.f.c coords lab$w_tag $origin_x [expr $origin_y + $cheight - $to]
						.f.c coords cb$w_tag \
							[expr $origin_x + 5] \
							[expr $origin_y + $cheight - $to]
					}
					}
				}

			

			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				how_many_windows
				set tab_end_coordinate [expr [lindex [.f.c bbox $w_tag] 0] \
					 + 10 + ([llength $tabs($t)] * $TABWIDTH)]
				switch $mode {
					new {
						#.f.c create window [expr $tab_end_coordinate + 12] $y1 \
						#	-window .f.$hs_tag \
						#	-width [expr $x1 - ($tab_end_coordinate + 8)] \
						#	-anchor nw -tags $hs_tag
						.f.c create window [expr $tab_end_coordinate + 12] $end_y \
							-window .f.$hs_tag \
							-width [expr $end_x - ($tab_end_coordinate + 8)] \
							-anchor nw -tags $hs_tag
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_k_tag [expr $tab_end_coordinate + 12] $y1
							.f.c itemconfigure $hs_k_tag \
								-width [expr $x1 - ($tab_end_coordinate + 8)]
							}
						#.f.c create window $x1 $yo -window .f.$vs_tag \
						#	-height [expr $y1 - $yo] \
						#	-anchor nw -tags $vs_tag
						.f.c create window $end_x $yo -window .f.$vs_tag \
							-height [expr $end_y - $yo] \
							-anchor nw -tags $vs_tag
						}
					resize_master {
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_tag [expr $tab_end_coordinate + 12] $end_y
							.f.c itemconfigure $hs_tag \
								-width [expr $end_x - ($tab_end_coordinate + 8)]
							}
						.f.c coords $vs_tag $end_x $yo
						.f.c itemconfigure $vs_tag -height [expr $end_y - $yo]
						}
					}
				}
			set selected_tab $tabn
			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				set lc [expr [lindex [.f.c bbox $w_tag] 0] + 10 + ($TABWIDTH * [llength $tabs($t)]) + 5]
				switch $mode {
					new {
						catch {.f.c delete resizer$t}
						.f.c create rect $lc [expr $end_y + 1] [expr $lc + 5] [expr $end_y + 15] \
							-tags resizer$t -outline black -fill gray
						.f.c bind resizer$t <ButtonPress-1> "
							reapportion $t
							"
						}
					resize_master {
						.f.c coords resizer$t $lc [expr $end_y + 1] \
							[expr $lc + 5] [expr $end_y + 15]
						}
					}
				}
			}
			
		ttsr {	set width [expr $width - $scr_room - 4] ;# leave room for scrollbars (16) & borders
			set height [expr $height - $scr_room - 0] ;# leave room for scrollbars, borders

			#for text window, must:
			# convert pixels to characters
			set t_width [expr $width/$pixels_per_char]
			# convert pixels to lines
			set t_height [expr ($height - 20)/$pixels_per_line]
			
			if {$has_lines($t,$tabn)} {set t_width [expr $t_width - 5]}
			set selected_tab $tabn
			set w_tag "";	append w_tag "w" "_" $t "_" $tabn
			set hs_tag "";	append hs_tag "hs" "_" $t "_" $tabn
			set vs_tag "";	append vs_tag "vs" "_" $t "_" $tabn
			set lines_tag ""; append lines_tag "li_" $t "_" $tabn
			set to 20 ;# offset to leave room for tab labels
			switch $mode {
				new {	if {$has_lines($t,$tabn)} {
						text .f.$lines_tag \
						-width 4 \
						-height $t_height \
						-relief raised \
						-fg $Ccol \
						-selectbackground $Bcol \
						-selectforeground $Scol \
						-font $Cfont \
						-wrap none \
						-bg $Bcol \
						-bd 2
						
						.f.c create window \
							$origin_x $origin_y \
							-window .f.$lines_tag \
							-anchor nw -tags $lines_tag

						bind .f.$lines_tag <2> ".f.$lines_tag scan mark %x %y"
				
						bind .f.$lines_tag <B2-Motion> "
							.f.$w_tag scan dragto 0 %y
							.f.$lines_tag scan dragto 0 %y 
							"
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						set decrease_x [expr [lindex $bbox 2] - [lindex $bbox 0] + 4]
						set width [expr $width - $decrease_x]
						}
					}
				resize_master {
					if {$has_lines($t,$tabn)} {
						.f.$lines_tag configure -height $t_height
						.f.c coords $lines_tag $origin_x $origin_y
						set bbox [.f.c bbox $lines_tag]
						set origin_x [expr [lindex $bbox 2] + 4]
						set origin_y [expr [lindex $bbox 1] + 2]
						set decrease_x [expr [lindex $bbox 2] - [lindex $bbox 0] + 4]
						set width [expr $width - $decrease_x]
						}
					}
				}

			set end_x [expr $origin_x + $width - 4 - 2] 
			set end_y [expr $origin_y + $height - $to] ;# minus tab offset
			debug "end_x is $origin_x + $width - 4 - 2 = $end_x"
			#if new, count tabs and put new tab after last -- assuming they're already compressed
			
			set tx_start [expr $origin_x + 10 + (($tab_position - 1) * $TABWIDTH)]
			set tx_end [expr $origin_x + 10 + ($tab_position * $TABWIDTH)]
			set tab_tag ""
			append tab_tag "tab" "_" $t "_" $tabn
			set xo $origin_x
			set yo $origin_y
			set x1 [expr $end_x + $scr_room]
			set y1 $origin_y
			set x2 [expr $end_x + $scr_room]
			set y2 $end_y
			set x3 [expr $tx_end + 3]
			set y3 $end_y
			set x4 [expr $tx_end - 3]
			set y4 [expr $end_y + 15]
			set x5 [expr $tx_start + 3]
			set y5 [expr $end_y + 15]
			set x6 [expr $tx_start - 3]
			set y6 $end_y
			set x7 $origin_x
			set y7 $end_y
			set x8 $origin_x
			set y8 $origin_y

			switch $mode {
				new {
					.f.c create polygon $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8 \
						-fill ivory -outline black -tags $tab_tag -width 1
					}
				resize_master {
					.f.c coords $tab_tag $xo $yo $x1 $y1 $x2 $y2 $x3 $y3 $x4 $y4 \
						$x5 $y5 $x6 $y6 $x7 $y7 $x8 $y8
					}
				}
			set text_tag ""
			append text_tag "text" "_" $t "_" $tabn
			set xo [expr $origin_x + 10 + [expr .5 * $TABWIDTH] \
				+ (($tab_position - 1) * $TABWIDTH)]
			set yo [expr $end_y + 7]
			switch $mode {
				new {
					.f.c create text $xo $yo \
						-text $tabname \
						-anchor center \
						-tags $text_tag
						.f.c bind $text_tag <ButtonPress-1> "
							put_on_top $t $tabn
							fill_in $w_tag
						"
					put_on_top $t $tabn
					}
				resize_master {
					.f.c coords $text_tag $xo $yo
					}
				}
	
			switch $mode {
				new {
					text .f.$w_tag \
						-width $t_width \
						-height $t_height \
						-relief raised \
						-fg $Ccol \
						-font $Cfont \
						-selectbackground $Bcol \
						-selectforeground $Scol \
						-wrap none \
						-bg $Bcol \
						-bd 0

					.f.c create window $origin_x $origin_y -window .f.$w_tag \
						-anchor nw -tags $w_tag
					if {$tabname != "Browse"} {
						bind .f.$w_tag <1> "focus_in $w_tag"
					}
					bind .f.$w_tag <2> ".f.$w_tag scan mark %x %y"
					if {!$has_lines($t,$tabn)} {
						bind .f.$w_tag <B2-Motion> "
							.f.$w_tag scan dragto %x %y
							"
						}
					if {$has_lines($t,$tabn)} {
						bind .f.$w_tag <B2-Motion> "
							.f.$w_tag scan dragto %x %y
							.f.$lines_tag scan dragto 0 %y
							"
						.f.$w_tag configure -yscrollcommand "refresh_lines $t $tabn"
						}
					if $SCRstat {
						.f.$w_tag configure -xscrollcommand ".f.$hs_tag set" \
							-yscrollcommand ".f.$vs_tag set"
						scrollbar .f.$hs_tag -command ".f.$w_tag xview" -orient horizontal
						scrollbar .f.$vs_tag -command ".f.$w_tag yview" -orient vertical
						}
				}
				resize_master {
					.f.$w_tag configure -width $t_width -height $t_height
					.f.c coords $w_tag $origin_x $origin_y
					}
				}
			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				how_many_windows
				set tab_end_coordinate [expr [lindex [.f.c bbox $w_tag] 0] \
					 + 10 + ([llength $tabs($t)] * $TABWIDTH)]
				switch $mode {
					new {
						.f.c create window [expr $tab_end_coordinate + 12] $end_y \
							-window .f.$hs_tag \
							-width [expr $end_x - ($tab_end_coordinate + 8)] \
							-anchor nw -tags $hs_tag
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_k_tag [expr $tab_end_coordinate + 12] $y1
							.f.c itemconfigure $hs_k_tag \
								-width [expr $x1 - ($tab_end_coordinate + 8)]
							}
						.f.c create window $end_x $yo -window .f.$vs_tag \
							-height [expr $end_y - $yo] \
							-anchor nw -tags $vs_tag
						}
					resize_master {
						foreach k $tabs($t) {
							set hs_k_tag ""
							append hs_k_tag "hs_" $t "_" $k
							.f.c coords $hs_tag [expr $tab_end_coordinate + 12] $end_y
							.f.c itemconfigure $hs_tag \
								-width [expr $end_x - ($tab_end_coordinate + 8)]
							}
						.f.c coords $vs_tag $end_x $yo
						.f.c itemconfigure $vs_tag -height [expr $end_y - $yo]
						}
					}
				}	
	
			
			if $SCRstat {
				set bbox [.f.c bbox $w_tag]
				set xo [lindex $bbox 0]
				set yo [lindex $bbox 1]
				set x1 [lindex $bbox 2]
				set y1 [lindex $bbox 3]
				set lc [expr [lindex [.f.c bbox $w_tag] 0] + 10 + ($TABWIDTH * [llength $tabs($t)]) + 5]
				switch $mode {
					new {
						catch {.f.c delete resizer$t}
						.f.c create rect $lc [expr $end_y + 1] [expr $lc + 5] [expr $end_y + 15] \
							-tags resizer$t -outline black -fill gray
						.f.c bind resizer$t <ButtonPress-1> "
							reapportion $t
							"
						}
					resize_master {
						.f.c coords resizer$t $lc [expr $end_y + 1] \
							[expr $lc + 5] [expr $end_y + 15]
						}
					}
				}
			}
		}
	if {$mode == "new"} { ;#if new tab, need to move tabs higher in order to right to make room
		debug "mode is new do we need to move any tabs over?"
		set go 1
		set ctab $tabn
		debug "tabn is: $tabn, initial value of ctab is: $ctab"
		while $go {
			incr ctab 1
			debug "after increment, ctab is: $ctab"
			if [info exists order($t,$ctab)] {
				debug "order($t,$ctab) - info exists"
				set tg ""
				append tg "w_" $t "_" $ctab
				debug "does .f.$tg exist"
				set wex [catch {.f.$tg cget -background}] ;# this will be 0 if the window exists
				if {!$wex} {
					debug "yes it does exist"
					set wtype $window_type($t,$ctab)
					set tab_pos [find_tab_spot $ctab $t]
					debug "about to call place_window resize_master $wtype $t '' 0 $ctab $tab_pos"
					place_window resize_master $wtype $t "" 0 $ctab $tab_pos
					}
			} else {
				debug "order($t,$ctab) - info doesn't exist"
				set go 0
				debug "returning"
				return
				}
			}
		}
}

proc get_tab_number {tabname pos} {
	global order silly_counter
	debug "\nENTERING get_tab_number"
	catch {debug "ENTERING get_tab_number with tabname=$tabname and pos=$pos"}
	set i 1
	set go 1 
	while $go {
		debug "info exists order($pos,$i) = [info exists order($pos,$i)]"
		if [info exists order($pos,$i)] {
			debug "check does order($pos,$i){$order($pos,$i)} == tabname{$tabname}"
			if {$order($pos,$i) == $tabname} {
				debug "yes it does - returning $i"
				return $i
				break
			} else {
				incr i 1
				}
		} else {
			set go 0
			break
			}
		}
}

proc find_tab_spot {tabn pos} {
	global tabs
	debug "\nENTERING find_tab_spot"
	how_many_windows
	for {set i 0} {$i < [llength $tabs($pos)]} {incr i 1} {
		debug "check, is lindex tabs($pos) $i {[lindex $tabs($pos) $i]} < tabn {$tabn}"
		if {[lindex $tabs($pos) $i] < $tabn} {
			debug "yes it is, keep going"
		} else {
			debug "match - returning $i"
			return [expr $i + 1]
			}
		}
	return [expr $i	+ 1]
}

proc refresh_lines {w i {v1 ""} {v2 ""}} {

	debug "ENTERING refresh_lines"
	set lines_tag ""; append lines_tag "li_" $w "_" $i
	set w_tag ""; append w_tag "w_" $w "_" $i
#complain "index: [.f.$w_tag index end]"
	set nnl [expr [.f.$w_tag index end] - 1]
	.f.$lines_tag delete 1.0 end		
	for {set i 1} {$i < $nnl} {incr i 1} {
		.f.$lines_tag insert end $i\n
		}
	.f.$lines_tag insert end $i
	set fr [.f.$w_tag yview]
	.f.$lines_tag yview moveto [lindex $fr 0]
}

proc fill_in {tag} {	;# user hit the tab of obscured window

	focus_in $tag
	set lb [find_label $tag]

	switch $lb {
	"Parse"	{ parse_c   }
	"Fcts"	{ fcts_c    }
	"Data"	{ sym_c     }
	"Prx"	{ harness_c }
	"Advanced"	{ gui_prx   }
	"Driver" { drv_c    }
	"Model"	 { ax_c     }
	"Browse" { initialize_browse refresh $tag }
	default {
		# no auto_fill for this window
	} }
}

proc focus_in {tag} {	;# user hit the window already on top
	global window_type last_focus has_lines beenthere
	global is_on_top is_current Pink_White Pink_Ivory

	#make old focus window ivory
	if {$last_focus != ""} {
		set sl [split $last_focus _]

		#last focus becomes ivory, except if it's "Browse" or "Prx"

		set label [find_label $last_focus]
		if {$label == "Browse"} {
			catch {.f.$last_focus configure -bg black}
		} elseif {$label == "Advanced"} {
			if {$beenthere} { prx_commit 0 }
			catch {.f.$last_focus configure -bg $Pink_Ivory}
		} else {
			catch {.f.$last_focus configure -bg ivory}
		}
	
		if {$has_lines([lindex $sl 1],[lindex $sl 2])} {
			set lines_tag "";
			append lines_tag "li_" [lindex $sl 1] "_" [lindex $sl 2]
			.f.$lines_tag configure -bg ivory
	}	}

	set label [find_label $tag]
	debug "label is $label in focus_in"
	if {$label == "Browse"} {
		.f.$tag configure -bg black
	} elseif {$label == "Model"} {
		.f.$tag configure -state disabled
	} elseif {$label == "Advanced"} {
		.f.$tag configure -bg $Pink_White
		debug "just configured bg of $label to $Pink_White"
	} else {
		debug "just configure bg or $label to white"
		.f.$tag configure -bg white
	}
	focus .f.$tag
	set s [split $tag _]

	set is_current [lindex $s 1]

	if {$has_lines([lindex $s 1],[lindex $s 2])} {  ;#lines box
		set lines_tag ""; append lines_tag "li_" [lindex $s 1] "_" [lindex $s 2]
		.f.$lines_tag configure -bg white
		
		}
	set last_focus $tag	
}

proc reapportion {w} {

	bind .f.c <Motion> "
		set x \[.f.c canvasx %x]
		set c \[.f.c coords resizer$w]
		set xo \[expr \$x - 3]
		set x1 \[expr \$x + 3]
		.f.c coords resizer$w \$xo \[lindex \$c 1] \$x1 \[lindex \$c 3]
		farm_out $w \$xo
		"
	bind .f.c <ButtonRelease-1> "
		bind .f.c <Motion> {}
		"
}

proc farm_out {w xo} {
	global tabs
	#how_many_windows
	debug "ENTERING farm_out with w=$w, xo=$xo"
	set chs [.f.c bbox resizer$w]
	set yo_resizer [lindex $chs 1]
	foreach i $tabs($w) {
		set hs_tag ""
		append hs_tag "hs" "_" $w "_" $i
		set w_tag ""
		append w_tag "w" "_" $w "_" $i
		.f.c coords $hs_tag [expr $xo + 8] $yo_resizer
		set c [.f.c bbox $w_tag]
		set x1 [lindex $c 2]
		.f.c itemconfigure $hs_tag -width [expr $x1 - $xo - 8]
		}
	.f.c raise resizer$w
}

set is_on_top(1) 1
set is_on_top(2) 1
set is_on_top(3) 1
set is_current	1

proc put_on_top {w i} {
	global tabs SCRstat is_on_top is_current

	how_many_windows
	debug "ENTERING put_on_top - with w=$w, and i=$i"
	set tab_i_tag "tab_${w}_$i"
	set text_i_tag "text_${w}_$i"
	set w_i_tag  "w_${w}_$i"
	set hs_i_tag "hs_${w}_$i"
	set vs_i_tag "vs_${w}_$i"
	set li_i_tag "li_${w}_$i"

	set label [find_label $w_i_tag]

	for {set j 1} {$j <= [llength $tabs($w)]} {incr j 1} {
		set tab_id [lindex $tabs($w) [expr $j - 1]]
		set tab_tag "tab_${w}_$tab_id"
		set text_tag "text_${w}_$tab_id"
		set w_tag  "w_${w}_$tab_id"
		set hs_tag "hs_${w}_$tab_id"
		set vs_tag "vs_${w}_$tab_id"
		set li_tag "li_${w}_$tab_id"

		if {$tab_id == $i} {
			.f.c itemconfigure $tab_tag -width 2 -fill white
			raise .f.$w_tag
			.f.c raise $tab_tag
			if $SCRstat {
				raise .f.$hs_tag
				raise .f.$vs_tag
			}
			catch {raise .f.$li_tag}
			set is_on_top($w) $tab_id
			set is_current $w
			if {$label == "Browse"} {
				raise .f.bg$w_tag ;#raise black background canvas
			#	raise .f.lab$w_tag ;#raise "drive" label
				raise .f.cb$w_tag ;#raise drive combobox
			}
		} else {
			.f.c itemconfigure $tab_tag -width 1 -fill gray
			if $SCRstat {
				.f.c lower $vs_tag $vs_i_tag
				.f.c lower $hs_tag $hs_i_tag
			}
			.f.c lower $w_tag $w_i_tag
			.f.c lower $tab_tag $tab_i_tag
			catch {.f.c lower $li_tag $li_i_tag}
		}
		.f.c raise $text_tag
# puts "current $is_current : $is_on_top($is_current)"
	}
	catch { focus_in $w_i_tag }
	debug "LEAVING put_on_top"
	update
}

proc delete_window {w {i ""}} {	
	global window_type unique_window_num tabs

	debug "ENTERING delete_window w=$w i=$i"

	set tab_i_tag ""
	append tab_i_tag "tab" "_" $w "_" $i
	.f.c delete $tab_i_tag
	set text_i_tag ""
	append text_i_tag "text" "_" $w "_" $i
	.f.c delete $text_i_tag
	set w_i_tag ""
	append w_i_tag "w" "_" $w "_" $i
	destroy .f.$w_i_tag
	.f.c delete $w_i_tag
	set hs_i_tag ""
	append hs_i_tag "hs" "_" $w "_" $i
	destroy .f.$hs_i_tag
	.f.c delete $hs_i_tag
	set vs_i_tag ""
	append vs_i_tag "vs" "_" $w "_" $i
	destroy .f.$vs_i_tag
	.f.c delete $vs_i_tag
	append lines_i_tag "lines" "_" $w "_" $i
	catch {destroy .f.$lines_i_tag}
	catch {.f.c delete $vs_i_tag}
	

	how_many_windows
	if {$window_type($w,$i) == "ttsr"} {
		#if ttsr, and last window has been deleted, delete resizer too 
		
		set match 0
		foreach j $unique_window_num {
			if {$j == $w} {
				set match 1
				break
				}
			}		
		if {!$match} {
			.f.c delete resizer$w ;# resizer 
			}
		}
	for {set j 1} {$j <= [llength $tabs($w)]} {incr j 1} {
		set tab_pos $j
		set tab_id [lindex $tabs($w) [expr $j - 1]]
		place_window resize_master $window_type($w,$j) $w "" 0 $tab_id $tab_pos ;#tcsa & ttsr
		}
	if {[llength $tabs($w)] > 0} { ;#put first tab on top
		put_on_top $w 1
		}
}

proc cleanup {how} {
	global CMD Unix
	global PrxChanged SrcChanged

	if {$Unix} {
		catch { set f [glob *.trail]; eval exec rm -f $f }
		if {$how} {
			catch {exec rm -f feaver.tmp}	;# dont match feaver.tcl ...
			catch {exec rm -f feaver.err}
			catch {exec rm -f feaver.out}
			catch {exec rm -f trail.out}
			catch { set f [glob _modex_*]; eval exec rm -f $f }
			catch { set f [glob pan*];  eval exec rm -f $f }
			catch { set f [glob *.lut]; eval exec rm -f $f }
		#	catch { set f [glob *.aut]; eval exec rm -f $f }
			catch { set f [glob *.spn]; eval exec rm -f $f }
			catch { set f [glob *.nlut]; eval exec rm -f $f }
		}
	} else {
		catch {exec $CMD /c del *.trail}
		if {$how} {
			catch {exec $CMD /c del feaver.tmp}
			catch {exec $CMD /c del feaver.err}
			catch {exec $CMD /c del feaver.out}
			catch {exec $CMD /c del trail.out}
			catch {exec $CMD /c del _modex_*}
			catch {exec $CMD /c del pan*}
			catch {exec $CMD /c del *.lut }
		#	catch {exec $CMD /c del *.aut }
			catch {exec $CMD /c del *.spn }
			catch {exec $CMD /c del *.nlut }
	}	}

	if {$how} {
		if {$PrxChanged} {
			switch -- [tk_messageBox \
				-message "Prx file Changed, Save?" \
				-type yesno] {
			yes	{ save_prx 1 }
			default	{}
			}
		}
		if {$SrcChanged} {	;# set how?
			switch -- [tk_messageBox \
				-message "Src file Changed, Save?" \
				-type yesno] {
			yes	{ save_c 1 }
			default	{}
	}	}	}
}

proc clear_names {} {
	global srcfiles TW_Info
	global pid pseq pline Matrix
	global Sent_as Sent_by Sent_at
	global Recv_as Recv_by Recv_at

	set pseq {}
	set srcfiles {}

	$TW_Info delete fnames
	catch { foreach i [array names pid]  { unset pid($i)  } }
	catch { foreach i [array names pline] { unset pline($i) } }
	catch { foreach i [array names Matrix] { unset Matrix($i) } }
	catch { foreach i [array names Sent_as] {
			unset Sent_as($i)
			unset Sent_by($i)
			unset Sent_at($i)
	}	}
	catch { foreach i [array names Recv_as] {
			unset Recv_as($i)
			unset Recv_by($i)
			unset Recv_at($i)
	}	}
}

set firstfree 20	;# firstfree line in Info canvas

proc names_complete {} {
	global srcfiles firstfree

	set firstfree [expr 15*[llength $srcfiles] + 30]
}

set LastTxt 0

proc progress {msg} {
	global firstfree TW_Info LastTxt

	if {[string first "Progress:" $msg] == 0} {
		catch { $TW_Info delete prog }
		names_complete
		return
	}

	set x 25
	set y $firstfree

	catch { $TW_Info create rectangle \
			[expr $x - 6 - 4] [expr $y - 5 - 4] \
			[expr $x + 110 + 4] [expr $y + 15 + 4] \
			-fill "black" \
			-tags prog
	}
	catch { $TW_Info create rectangle \
			[expr $x - 6] [expr $y - 5] \
			[expr $x + 110] [expr $y + 15] \
			-fill "gold" \
			-tags "prog bb"
	}
	catch { set LastTxt [$TW_Info create text \
			$x [expr $y - 2] \
			-text "$msg" \
			-fill black \
			-font {Helvetica 8 bold} \
			-anchor nw \
			-tags "prog bt"]
	}
	incr x [expr 116/2 - 5]
	incr y 20

	if {[string first "Done: " $msg] < 0} {
		catch { $TW_Info create line \
			$x $y \
			$x [expr $y + 18] \
			-width 10 \
			-fill "red" \
			-tags prog \
			-arrow last -arrowshape {5 5 5}
		}
	} else {
		if {[string first "No errors" $msg] > 0} {
			$TW_Info itemconfigure bb -fill "pale green"
		} else {
		#	$TW_Info itemconfigure bt -fill "red"
		}
	}

	incr firstfree 47
	put_on_top 1 2
	update
}

proc hi_lighter {nr} {
	global TW_Info lastcookie

	catch { $TW_Info delete $lastcookie }

	set n [expr 15 * ( $nr + 1 ) - 2]

	set lastcookie [$TW_Info create line \
			8 $n 80 $n \
			-fill red \
			-tags fnames]
}

proc putnewname {nm} {
	global srcfiles TW_Info

	if {[lsearch -exact $srcfiles $nm] != -1} {
		return	;# already there
	}

	set srcfiles [linsert $srcfiles end $nm]
	set nr [llength $srcfiles]
	catch {
		set nr [llength $srcfiles]
		set fn [$TW_Info create text \
			5 [expr 15*$nr] \
			-text "$nr: $nm" \
			-anchor nw \
			-tags fnames]
		$TW_Info bind $fn <Any-Enter> "$TW_Info itemconfigure $fn -fill blue "
		$TW_Info bind $fn <Any-Leave> "$TW_Info itemconfigure $fn -fill black "
		$TW_Info bind $fn <Button-1> "reopen_c $nm; hi_lighter $nr"
	} err
}

proc clear_all_frames {} {
	global TW_Source TW_Out  TW_Prx  TW_Errors TW_Stats
	global TW_Parse  TW_Fcts TW_Data TW_Driver TW_Model TW_Info

	catch { $TW_Info   delete prog }
	catch { $TW_Source delete 0.0 end }
	catch { $TW_Out    delete 0.0 end }
	catch { $TW_Prx    delete 0.0 end }
	catch { $TW_Errors delete 0.0 end }
	catch { $TW_Stats  delete 0.0 end }

	catch { $TW_Parse  delete 0.0 end }
	catch { $TW_Fcts   delete 0.0 end }
	catch { $TW_Data   delete 0.0 end }
	catch { $TW_Driver delete 0.0 end }

	$TW_Model configure -state normal
	catch { $TW_Model  delete 0.0 end }
	$TW_Model configure -state disabled

	catch { destroy .top.trails }
	catch { destroy .top.luts   }
}

proc reopen_c {file} {
	global Fname oFname Srcname fnm SrcChanged PrxChanged
	global pseq Depth srcfiles shortest asserts bounded
	global hidden use_vals io_only quality notfixed
	global loops np_loops noend bitstate exhaustive memlim
	global TW_Source Extract no_prx z_Flag
	global ned elab edef
	global ncd clab cdef
	global symdef prx_lnk
	
	#ned and ncd are reset to 0 when new test harness file read -- and only here
	set ned 0		;# nr defined events from prx file + canvas reads
	set ncd 0		;# nr defined constraints from prx file + canvas reads

	set Extract ""

	set kk [string last "/" $file]
	if {$kk > 0} {
		set path [string range $file 0 $kk]
		set file [string range $file [expr $kk+1] end]
		cd $path
	}

	set pp [string last ".prx" $file]
	if {$pp < 0} {		;# not a prx file
		if {[string last ".pml" $file] > 0} {
			clear_all_frames
			set Extract $file
			set Fname ""
			set fnm ""
			set pseq {}
		}
		set Srcname $file
		readinfile $TW_Source $file
		put_on_top 2 1
		set SrcChanged 0
		return
	}

	clear_all_frames
	set Fname $file
	set oFname $file
	#set pp [string last ".prx" $file]
	set fnm [string range $Fname 0 $pp]

	if [catch {set fd [open $Fname r]} errmsg] {
		complain "open: ${errmsg}. Hint, use: %X -x"
		return 0
	}
	set vis 0
	set PrxChanged 0
	catch { destroy .top.luts }
	set hidden {}
	set pseq {}

	clear_names

	while {[gets $fd line] > -1} {

		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}

		if {[string first "%F" $line] == 0 \
		||  [string first "%H" $line] == 0 \
		||  [string first "%D" $line] == 0 \
		||  [string first "%B" $line] == 0 \
		||  [string first "%C" $line] == 0 \
		||  [string first "%P" $line] == 0} {	;# not for %L yet
			set nm [string range $line 3 end]
			set nm [string trim $nm " 	"]
			if {[string length $nm] > 1} {
				putnewname $nm
		}	}
		if {[string first "%O" $line] == 0} {
			set prx_lnk "[string range $line 3 end]"
			continue
		}

		if {[string first "%F" $line] == 0} {
			set Srcname $nm
			readinfile $TW_Source $nm
			set SrcChanged 0
			continue
		}

		# %TE "description" "definition"
		if {[string first "%TE" $line] == 0} {
			set k [split $line "\""]
			if {[llength $k] != 5} {
				complain "bad entry: $line ([llength $k] fields)"
				continue
			}
			incr ned
			set elab($ned) [lindex $k 1]
			set edef($ned) [lindex $k 3]
			set symdef("[lindex $k 1]") [lindex $k 3]
			continue
		}
		# %TC "description" "definition"
		if {[string first "%TC" $line] == 0} {
			set k [split $line "\""]
			if {[llength $k] != 5} {
				complain "bad entry: $line ([llength $k] fields)"
				continue
			}
			incr ncd
			set clab($ncd) [lindex $k 1]
			set cdef($ncd) [lindex $k 3]
			set symdef("[lindex $k 1]") [lindex $k 3]
			continue
		}

		if {[string first "%GUI" $line] == 0} {
			set vis 1
			continue
		}
		if {[string first "%%" $line] == 0} {
			set vis 0
			continue
		}
		if {$vis == 0} { continue }
		if {[string first "msc:" $line] == 0} {
			set pseq [string range $line 4 end]
		}
		set hidden ""
		if {[string first "hidden:" $line] == 0} {
			set hidden [string range $line 4 end]
		}
		if {[string first "maxdepth:" $line] == 0} {
			scan $line "maxdepth: %d" Depth
		}
		if {[string first "io_only:" $line] == 0} {
			scan $line "io_only: %d" x
			if {$x != $io_only} {
				all_stmnts
		}	}
		if {[string first "asserts:" $line] == 0} {
			scan $line "asserts: %d" x
			if {$x != $asserts} {
				with_asserts
		}	}
		if {[string first "zflag:" $line] == 0} {
			scan $line "zflag: %d" x
			if {($x == 1 && $z_Flag != "-z") \
			||  ($x == 0 && $z_Flag != "")} {
				toggle_zflag
		}	}
		if {[string first "loops:" $line] == 0} {
			scan $line "loops: %d" x
			if {$x != $loops} {
				with_loops
		}	}
		if {[string first "np_loops:" $line] == 0} {
			scan $line "np_loops: %d" x
			if {$x != $np_loops} {
				with_np
		}	}
		if {[string first "noend:" $line] == 0} {
			scan $line "noend: %d" x
			if {$x != $noend} {
				with_ends
		}	}
		if {[string first "use_vals:" $line] == 0} {
			scan $line "use_vals: %d" x
			if {$x != $use_vals} {
				with_vals
		}	}
		if {[string first "bounded:" $line] == 0} {
			scan $line "bounded: %d" bounded
		}
		if {[string first "exhaustive:" $line] == 0} {
			scan $line "exhaustive: %d" exhaustive
		}
		if {[string first "quality:" $line] == 0} {
			scan $line "quality: %d" quality
		}
		if {[string first "memlim:" $line] == 0} {
			scan $line "memlim: %d" memlim
		}
		if {[string first "notfixed:" $line] == 0} {
			scan $line "notfixed: %d" notfixed
		}
		if {[string first "shortest:" $line] == 0} {
			scan $line "shortest: %d" shortest
		}
	}
	menu_toggles
	if {$quality >= 6} {
		set quality 6
		set exhaustive 1
	} else {
		if {$quality <= 0} {
			set quality 0
	}	}
	names_complete
	catch { close $fd }

	if {[llength $srcfiles] == 0} {
		putnewname ${fnm}c
	#	complain "Error: prx file has no %F command"
	}

	put_on_top 1 2	;# shows files
#	put_on_top 3 1	;# Out panel
	set no_prx 1
	harness_c
}

proc open_c {} {
	global TW_Info

	set fileselect "tk_getOpenFile"	;# "FileSelect open"
	switch -- [set file [eval $fileselect]] "" return

	catch { $TW_Info delete prog }
	putnewname $file
	reopen_c $file
}

set glob_defines {}
set loc_defines  {}

proc getpaninfo {} {	;# generate lists of global and local referables
	global SPIN TW_Out TW_Log
	global glob_defines loc_defines

	if {[ax_c] == 0} {	;# creates _modex_out
		return 0
	}
	$TW_Log insert end "$SPIN -a _modex_out\n"
	if [catch { exec $SPIN -a _modex_out >&feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		return 0
	}
	readinfile $TW_Out feaver.err

	if [catch {set fd [open pan.h r]} errmsg] {
		complain "cannot open pan.h"
		return 0
	}
	set glob_defines {}
	set loc_defines {}
	set g_defined 0
	set l_defined 0
	set cur_pnm ""
	while {[gets $fd line] > -1} {
		if {[string first "#" $line] == 0} {
			continue	;# ifdef, endif etc.
		}
		if {[string first "unsigned short _event;" $line] >= 0} {
			set g_defined 1
			continue
		}
		if {[string first "uchar sv\[VECTORSZ];" $line] >= 0 \
		||  [string first "uchar c_state" $line] >= 0} {
			break
		}
		if {$g_defined} {
			lappend glob_defines "[string trim $line " \t;"]"
			## datatype [decorations] varname [decorations]
			## referable as: now.varname[indexing] ...
			## for label refs: Ppname[pid]@labelname
			## >> if declared in format picked up by modex, these
			## >> embeddings would become invisible...
			## >> channel refs would be handled through the lut
			## allow boolean c-fcts as predicates? (locals, labels, chans?)
		}

		if {[string first "typedef struct P" $line] == 0} {
			scan $line "typedef struct %s %c /* %s */" cur_pno curly cur_pnm
			continue
		}
		if {$cur_pnm != ""} {
			if {[string first " $cur_pno;" $line] >= 0} {
				set cur_pnm ""
				set l_defined 0
				continue
			}
			if {[string first "unsigned _p " $line] >= 0} {
				set l_defined 1
				continue
			}
			if {$l_defined} {
				lappend loc_defines "$cur_pnm	[string trim $line " \t;"]"
	}	}	}
	catch { close $fd }

	#
	# the above includes embedded C decls, but cannot recognize channel names
	#
	$TW_Log insert end "$SPIN -d _modex_out\n"
	if [catch { exec $SPIN -d _modex_out >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		return 0
	}
	readinfile $TW_Out feaver.err
	if [catch {set fd [open feaver.tmp r]} errmsg] {
		complain "cannot open feaver.tmp"
		return 0
	}
	set g_defined 0
	set l_defined 0
	set cur_pnm ""
	while {[gets $fd line] > -1} {
		set k [split $line "\t"]
		if {[llength $k] < 4} { continue }

		set tnm [string trim [lindex $k 0] " "]
		if {$tnm == "chan"} {
			set pnm [string trim [lindex $k 3] "<:>"]
			set vnm [lindex $k 1]
			if {[lindex $k 3] == "<:global:>"} {
				lappend glob_defines "chan $vnm"
				set m [lsearch -exact $glob_defines "uchar $vnm"]
				if {$m >= 0} {
					set glob_defines [lreplace $glob_defines $m $m]
				}
			} else {
				lappend loc_defines  "$pnm	chan $vnm"
				set m [lsearch -exact $loc_defines "$pnm	uchar $vnm"]
				if {$m >= 0} {
					set loc_defines [lreplace $loc_defines $m $m]
		}	}	}

		if {$tnm == "label"} {
			set lnm [lindex $k 1]
			if {[string first "C_" $lnm] == 0 \
			||  [string first "L_" $lnm] == 0 \
			||  $lnm == "Return"} {
				continue	;# internal labels from Modex
			}
			set pnm [string trim [lindex $k 3] "<:>"]
			lappend loc_defines "$pnm  	label $lnm"
	}	}
	catch { close $fd }

	set glob_defines [lsort $glob_defines]
	set loc_defines  [lsort $loc_defines]

#	for {set i 0} {$i < [llength $glob_defines]} {incr i} {
#		puts "	global	[lindex $glob_defines $i]"
#	}
#	for {set i 0} {$i < [llength $loc_defines]} {incr i} {
#		puts "	[lindex $loc_defines $i]"
#	}

	return 1
}

proc ax_c {} {
	global MODEX fnm CPP
	global TW_Model TW_Out TW_Log TW_Prx Extract
	global aut_loops aut_file P_Flag z_Flag

	if {$Extract != ""} {	;# source model is a promela file
		$TW_Log insert end "$CPP $Extract\n"
		if [catch { eval exec $CPP $Extract >_modex_out 2>feaver.err} err] {
			common_c _modex_out $TW_Out
			put_on_top 3 1
			complain "$CPP -- $err"
			return 0
		}
	} else {
		if {$fnm == ""} {
			complain "missing prx"
			return 0
		}
		writeoutfile $TW_Prx _modex_in.prx	;# edited version ax_c

		$TW_Log insert end "$MODEX $P_Flag $z_Flag _modex_in.prx\n"
		if [catch { eval exec $MODEX $P_Flag $z_Flag _modex_in.prx >&feaver.err } errmsg] {
			readinfile $TW_Out feaver.err
			put_on_top 3 1
			complain "Modex: $errmsg"
			return 0
		}
		if {[file exists _modex_.drv] == 0} {
			complain "no _modex_.drv found"
			return 0
		}
		$TW_Log insert end "$CPP _modex_.drv >_modex_out\n"
		if [catch { eval exec $CPP _modex_.drv >_modex_out 2>feaver.err} errmsg] {
			common_c _modex_out $TW_Out
			complain "$CPP ($errmsg)"
			return 0
	}	}
	if {$aut_loops && [file exists $aut_file]} {
		$TW_Log insert end "$CPP $aut_file >>_modex_out\n"
		if [catch { eval exec $CPP $aut_file >>_modex_out 2>feaver.err} errmsg] {
			common_c _modex_out $TW_Out
			complain "$CPP ($errmsg)"
			return 0
	}	}

	readinfile $TW_Out  feaver.err

	$TW_Model configure -state normal
	common_c _modex_out $TW_Model 1
	$TW_Model configure -state disabled

	writeoutfile $TW_Model _modex_out	;# no empty lines

#	put_on_top 2 7
	return 1
}

proc be_helpfull {} {
	global TW_Info

	catch { $TW_Info delete prog }

	putnewname "pan.c"
	putnewname "pan.h"
	putnewname "pan.m"
	putnewname "pan.b"
	putnewname "pan.t"
}

proc spin_c {} {
	global loops np_loops exhaustive asserts
	global SPIN Unix memlim aut_loops shortest
	global TW_Out TW_Log PanKilled prx_lnk

	catch { cleanup 0 }
	.top.run configure -fg gray

	progress "Progress:"
	progress "1. Extract model..."
	if {[ax_c] == 0} {
		.top.run configure -fg red
		return 0
	}

	progress "2. Create checker..."
	$TW_Log insert end "$SPIN -a _modex_out\n"
	if [catch { exec $SPIN -a _modex_out >&feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		progress "Done: Spin failed"
		.top.run configure -fg red
		return 0
	}
	readinfile $TW_Out feaver.err

	progress "3. Compile checker..."
	set extra "-DMEMLIM=$memlim"
	if {$exhaustive == 0} {
		set extra "$extra -DBITSTATE"
	} else {
		set extra "$extra -DHC4"
	}
	if {$shortest} {
		set extra "$extra -DREACH"
	}

	if {$loops == 0 \
	&&  $aut_loops == 0 \
	&&  $np_loops  == 0} {
		set extra "$extra -DSAFETY"
	}

	if {$np_loops} {
		if {$loops} {
			complain "cannot search for both accept and non-progress cycles"
			.top.run configure -fg red
			return 0
		}
		if {$aut_loops} {
			complain "cannot search for both Vip-Property violations and non-progress cycles"
			.top.run configure -fg red
			return 0
		}
		set extra "$extra -DNP"
	}

	if {$Unix} {
		$TW_Log insert end "cc $extra -o pan pan.c $prx_lnk\n"
		catch { eval eval exec cc $extra -o pan pan.c $prx_lnk >&feaver.err} errmsg
		if {[string length $errmsg] > 0} {
			readinfile $TW_Out feaver.err
			put_on_top 3 1
			progress "Done: Cc failed"
			.top.run configure -fg red
			be_helpfull
			return 0
		}
	} else {
		$TW_Log insert end "cl $extra -DPC pan.c $prx_lnk\n"
		catch { eval exec cl $extra -DPC pan.c $prx_lnk >&feaver.err } errmsg
		if {[string length $errmsg] > 0} {
			readinfile $TW_Out feaver.err
			put_on_top 3 1
			progress "Done: cl failed"
			.top.run configure -fg red
			be_helpfull
			return 0
		}
	}
	readinfile $TW_Out feaver.err
#	put_on_top 3 1

	progress "4. Checking..."

	set n [pan_c]

	if {$PanKilled} {
		progress "Done: Aborted"
	} else {
		switch $n {
		0	{ progress "Done: No errors" }
		1	{ progress "Done: 1 error"   }
		default	{ progress "Done: $n errors" }
	}	}

	.top.run configure -fg red
	return 1
}

proc common_c {from into {how 0}} {
	global TW_Out

	set r1 [readinfile $into $from $how]
	set r2 [readinfile $TW_Out feaver.err]
	return [expr $r1 && $r2]
}

proc parse_c {} {
	global Fname MODEX TW_Parse TW_Out TW_Log P_Flag z_Flag

	if {$Fname == ""} {
		complain "No filename"
		return 0
	}

	$TW_Log insert end "$MODEX $P_Flag $z_Flag -C $Fname\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -C $Fname >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		complain "Modex -C: $errmsg"
		return 0
	}
	set TW_Parse  [find_path "Parse" ]
	if {$TW_Parse != ""} {
		put_on_top 2 2
		return [common_c feaver.tmp $TW_Parse]
	}
	return 0
}

proc sym_c {} {
	global Fname MODEX TW_Data TW_Out TW_Log P_Flag $z_Flag

	if {$Fname == ""} {
		complain "No filename"
		return 0
	}

	$TW_Log insert end "$MODEX $P_Flag $z_Flag -s $Fname\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -s $Fname >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		complain "Modex -s: $errmsg"
		return 0
	}
	set TW_Data   [find_path "Data" ]
	if {$TW_Data != ""} {
		put_on_top 2 4
		return [common_c feaver.tmp $TW_Data]
	}
	return 0
}

set no_prx 1

proc harness_c {} {
	global fnm TW_Prx no_prx

	if {[file exists ${fnm}prx] == 0} {
		complain "missing ${fnm}prx"
		return 0
	}
	set TW_Prx [find_path "Prx"]
	if {$TW_Prx != ""} {
		put_on_top 2 5
		if {$no_prx} {
			readinfile $TW_Prx ${fnm}prx
			set no_prx 0
	}	}
}

proc gui_addrow {i} {
	global TW_Advanced prx_fn prx_ft prx_lt prx_wt prx_rm gui_changed

	catch {
		destroy $TW_Advanced.x.fn.fn$i
		destroy $TW_Advanced.x.ft.ft$i
		destroy $TW_Advanced.x.lt.lt$i
		destroy $TW_Advanced.x.wt.wt$i
		destroy $TW_Advanced.x.rm.rm$i
	}

	label $TW_Advanced.x.fn.fn$i -textvariable prx_fn($i) -bg black -fg gold
	label $TW_Advanced.x.ft.ft$i -textvariable prx_ft($i) -bg black -fg gold
	label $TW_Advanced.x.lt.lt$i -textvariable prx_lt($i) -bg black -fg gold
	label $TW_Advanced.x.wt.wt$i -textvariable prx_wt($i) -bg black -fg gold

	checkbutton $TW_Advanced.x.rm.rm$i \
		-bg black -fg gold \
		-pady 0 -borderwidth 0 \
		-height 1 \
		-text "mark for removal" \
		-variable prx_rm($i) \
		-command "set gui_changed 1" \
		-relief flat

	pack $TW_Advanced.x.fn.fn$i -side top -pady 1 -anchor w -fill x -expand 1
	pack $TW_Advanced.x.ft.ft$i -side top -pady 1 -anchor w -fill x -expand 1
	pack $TW_Advanced.x.lt.lt$i -side top -pady 1 -anchor w -fill x -expand 1
	pack $TW_Advanced.x.wt.wt$i -side top -pady 1 -anchor w -fill x -expand 1
	pack $TW_Advanced.x.rm.rm$i -side top -pady 0 -anchor w -fill x -expand 1
}

proc gui_editable {} {
	global TW_Advanced prx_nrrows prx_fn prx_ft prx_lt prx_wt prx_rm
	global prx_u1 prx_u2 prx_u3 gui_changed

	set w $TW_Advanced.x

	set j [prx_blank_row]

	set prx_fn($j) "(select)"
	set prx_rm($j) 0

	set prx_u1($j) [tk_optionMenu $w.fn.fn$j prx_fn($j) dummy]
	set prx_u2($j) [tk_optionMenu $w.ft.ft$j prx_ft($j) dummy]
	set prx_u3($j) [tk_optionMenu $w.lt.lt$j prx_lt($j) dummy]

	$w.fn.fn$j configure -bg black -fg gold \
		-activeforeground black -activebackground lightgrey
	$w.ft.ft$j configure -bg black -fg gold \
		-activeforeground black -activebackground lightgrey
	$w.lt.lt$j configure -bg black -fg gold \
		-activeforeground black -activebackground lightgrey

	$prx_u1($j) configure -bg black -fg gold \
		-activeforeground black -activebackground gold
	$prx_u2($j) configure -bg black -fg gold \
		-activeforeground black -activebackground gold
	$prx_u3($j) configure -bg black -fg gold \
		-activeforeground black -activebackground gold

	catch { $prx_u1($j) delete 1 end }
	catch { $prx_u2($j) delete 1 end }
	catch { $prx_u3($j) delete 1 end }

	set ml {}
	catch { set ml [glob *.c] }
	foreach m $ml {
		if {$m == "pan.c"} { continue }
		$prx_u1($j) add command -label $m \
			-command "set prx_ft($j) (all); prx_redo_ft $j $m"
	}
	prx_redo_ft $j $prx_fn($j)	;# handles prx_u2
	prx_redo_lt $j			;# handles prx_u3

	set u "tk_optionMenu $w.wt.wt$j prx_wt($j)"
	foreach m { "active proctype" "extended active proctype" "proctype" "body only" "inline" } {
		set u "$u \"$m\""
	}
	set v [eval $u]

	$v configure -bg black -fg gold \
		-activeforeground black -activebackground gold
	$w.wt.wt$j configure -bg black -fg gold \
		-activeforeground black -activebackground gold

	button $TW_Advanced.x.rm.rm$j \
		-bg SkyBlue4 -fg white \
		-activeforeground SkyBlue4 -activebackground gold \
		-height 1 \
		-relief raised \
		-border 4 \
		-text "click to add..." \
		-anchor w \
		-command "set gui_changed 1; gui_addrow $j; gui_editable"

	pack $w.fn.fn$j -side top -anchor nw -fill x -expand 1
	pack $w.ft.ft$j -side top -anchor nw -fill x -expand 1
	pack $w.lt.lt$j -side top -anchor nw -fill x -expand 1
	pack $w.wt.wt$j -side top -anchor nw -fill x -expand 1
	pack $w.rm.rm$j -side top -anchor nw -padx 5
}

proc gui_columns {} {
	global TW_Advanced prx_nrrows

	frame $TW_Advanced.x -bg black	;# frame with src/fct/lut/wrap columns
	frame $TW_Advanced.x.fn -bg black
	frame $TW_Advanced.x.ft -bg black
	frame $TW_Advanced.x.lt -bg black
	frame $TW_Advanced.x.wt -bg black
	frame $TW_Advanced.x.rm -bg black

	pack $TW_Advanced.x.fn \
		$TW_Advanced.x.ft \
		$TW_Advanced.x.lt \
		$TW_Advanced.x.wt \
		$TW_Advanced.x.rm -side left -anchor n -fill both -expand 1

	label $TW_Advanced.x.fn.lb -fg white -bg SkyBlue4 -text "From Source File"
	label $TW_Advanced.x.ft.lb -fg white -bg SkyBlue4 -text "Extract Function"
	label $TW_Advanced.x.lt.lb -fg white -bg SkyBlue4 -text "Via Lut Filter"
	label $TW_Advanced.x.wt.lb -fg white -bg SkyBlue4 -text "Into Wrapper Type"
	label $TW_Advanced.x.rm.lb -fg white -bg SkyBlue4 -bg SkyBlue4

	pack $TW_Advanced.x.fn.lb -side top -anchor n -fill x -expand 1
	pack $TW_Advanced.x.ft.lb -side top -anchor n -fill x -expand 1
	pack $TW_Advanced.x.lt.lb -side top -anchor n -fill x -expand 1
	pack $TW_Advanced.x.wt.lb -side top -anchor n -fill x -expand 1
	pack $TW_Advanced.x.rm.lb -side top -anchor n -fill x -expand 1

	for {set i 0} {$i < $prx_nrrows} {incr i} {
		prx_decode $i
		gui_addrow $i
	}
	prx_snapshot	;# remember for undo
	set beenthere 1
	gui_editable

	pack $TW_Advanced.x -side bottom -fill x
}

proc gui_middle {} {
	global TW_Advanced

	catch { destroy $TW_Advanced.mid }

	frame $TW_Advanced.mid 
	pack $TW_Advanced.mid -side top -fill both -expand 1

	frame $TW_Advanced.mid.left -bg darkgrey
	pack	$TW_Advanced.mid.left -side top -fill both -expand 1

	set w $TW_Advanced.mid.left

	frame $w.m -bg SkyBlue4
	pack $w.m -side top -fill x -pady 1

	button $w.m.t0 \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground SkyBlue4 -activebackground gold \
		-text "System" -command { system_context }

	button $w.m.e \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground SkyBlue4 -activebackground gold \
		-text "C Context" -command { c_context }

	button $w.m.p \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground SkyBlue4 -activebackground gold \
		-text "Fill Lut" -command { populate_lut }
	button $w.m.u \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground SkyBlue4 -activebackground gold \
		-text "Upgrade Wizard" -command { upgrade_c }

	text $w.t -bg white -fg black -relief flat -border 5

	pack	$w.m.t0 \
		$w.m.e  \
		$w.m.p  \
		$w.m.u -side left -padx 4 -pady 4 -expand 0
	pack $w.t    -side bottom -fill both -expand 1

	gui_stats
}

proc gui_stats {} {
	global TW_Prx TW_Advanced

	set w $TW_Advanced.mid.left.t

	$w delete 1.0 end

	scan [$TW_Prx index end] %d numLines

	set f_cmds 0; set x_cmds 0; set l_cmds 0
	set o_cmds 0; set g_cmds 0; set p_cmds 0
	set h_cmds 0; set d_cmds 0; set c_cmds 0
	set tc_cmds 0; set te_cmds 0;

	for {set i 1} {$i < $numLines} { incr i} {
		$TW_Prx mark set last $i.0
		set line [$TW_Prx get last "last lineend"]
		if {[string first "%F" $line] == 0} { incr f_cmds }
		if {[string first "%X" $line] == 0} { incr x_cmds }
		if {[string first "%L" $line] == 0} { incr l_cmds }

		if {[string first "%O" $line] == 0} { incr o_cmds }

		if {[string first "%G" $line] == 0} { incr g_cmds }

		if {[string first "%P" $line] == 0} { incr p_cmds }

		if {[string first "%H" $line] == 0} { incr h_cmds }
		if {[string first "%D" $line] == 0} { incr d_cmds }
		if {[string first "%C" $line] == 0} { incr c_cmds }

		if {[string first "%TC" $line] == 0} { incr tc_cmds }
		if {[string first "%TE" $line] == 0} { incr te_cmds }
	}

	$w insert end "System Context:\n\t"
	if {$p_cmds == 0} { $w insert end "Not " }
	$w insert end "Defined\n\n"

	$w insert end "Model Extraction:\n"
	$w insert end "	$x_cmds Functions Extracted from\n"
	$w insert end "	$f_cmds Source Files\n"
	$w insert end "	$g_cmds Gui Parameters set\n"
	$w insert end "	$l_cmds Lut Filters\n\n"

	$w insert end "C Context:\n"
	$w insert end "	$o_cmds Linked Objects\n"
	$w insert end "	$h_cmds Typedef and Definitions Section\n"
	$w insert end "	$d_cmds Data Type Declaration\n"
	$w insert end "	$c_cmds C Function Definition\n\n"

	$w insert end "Vip Properties:\n"
	$w insert end "	$te_cmds Events defined\n"
	$w insert end "	$tc_cmds Constraints defined\n"
}

proc gui_prx {} {
	global TW_Advanced prx_nrrows prx_fn prx_ft prx_lt prx_wt prx_rm
	global gui_changed beenthere prx_nluts prx_luts

	catch {
		destroy $TW_Advanced.x
		destroy $TW_Advanced.z
		destroy $TW_Advanced.bl
		destroy $TW_Advanced.br
	}

	set TW_Advanced [find_path "Advanced"]
	set gui_changed 0

	prx_summary			;# extract current info from .prx file

	frame $TW_Advanced.bl -bg SkyBlue4 -width 25
	pack $TW_Advanced.bl -side left -fill y
	frame $TW_Advanced.br -bg SkyBlue4 -width 25
	pack $TW_Advanced.br -side right -fill y

	frame $TW_Advanced.z -bg SkyBlue4	;# room for global buttons

	button $TW_Advanced.z.u \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground black -activebackground gold \
		-text "Undo" -command {prx_revert; gui_prx}

	button $TW_Advanced.z.c \
		-bg SkyBlue4 -fg gold \
		-relief raised \
		-border 4 \
		-activeforeground black -activebackground red \
		-text "Commit" -command { prx_commit 1 }

	label $TW_Advanced.z.l \
		-bg SkyBlue4 -fg gold \
		-font {Helvetica 10 bold} \
		-text "Test Harness Setup"

	pack $TW_Advanced.z.l -side left -anchor w -padx 4 -pady 4 -expand 0
	pack $TW_Advanced.z.c -side right -anchor w -padx 4 -pady 4 -expand 0
	pack $TW_Advanced.z.u -side right -anchor w -pady 4 -expand 0
	pack $TW_Advanced.z -side bottom -fill both -expand 0

	gui_columns			;# create .x frame and contents

	gui_middle
	gui_lut		;# create lut files - putup LUT edit menu
}

proc prx_commit {v} {
	global prx_nrrows gui_changed

	set do_commit 0
	if {$gui_changed} {
		if {$v == 0} {
			switch -- [tk_messageBox \
			-message "Test Harness Setting Modified, Commit?" \
			-type yesno] {
			yes	{ set do_commit 1 }
			default	{}
			}
		} else {
			set do_commit 1
	}	}
	if {$do_commit} {
	#	incr prx_nrrows -1	;# omit the non-added editable row
		prx_snapshot
		prx_write_back
	#	incr prx_nrrows
	}
	set gui_changed 0
	gui_stats
}

proc drv_c {} {
	global TW_Driver

	if {[file exists _modex_.drv] == 0} {
		complain "Run Ax first"
		return 0
	}
	set TW_Driver  [find_path "Driver" ]
	if {$TW_Driver != ""} {
		put_on_top 2 6
		return [readinfile $TW_Driver _modex_.drv]
	}
	return 0
}

proc fcts_c {} {
	global Fname MODEX TW_Fcts TW_Out TW_Log P_Flag z_Flag

	if {$Fname == ""} {
		complain "No filename"
		return 0
	}

	$TW_Log insert end "$MODEX $P_Flag $z_Flag -F $Fname\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -F $Fname >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		complain "Modex -F: $errmsg"
		return 0
	}
	set TW_Fcts   [find_path "Fcts" ]
	if {$TW_Fcts != ""} {
		put_on_top 2 3
		update
		return [common_c feaver.tmp $TW_Fcts]
	}
	return 0
}

proc diff_lut {nm vb} {

	if [catch {set fd [open $nm.nlut r]} errmsg] {	;# old version
		complain "diff_lut: $errmsg"
		return 0
	}
	while {[gets $fd line] > -1} {
		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}
		if {[string length $line] > 0 \
		&&  [string first "#" $line] != 0} {
			lappend Old $line
	}	}
	catch { close $fd }

	if [catch {set fd [open $nm.ulut r]} errmsg] {	;# new version
		complain "diff_lut: $errmsg"
		return 0
	}
	while {[gets $fd line] > -1} {
		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}
		if {[string length $line] > 0 \
		&&  [string first "#" $line] != 0} {
			lappend New $line
	}	}
	catch { close $fd }

	set Old [lsort $Old]
	set New [lsort $New]

	if {$vb} {
		set w .diff$nm
		catch { destroy $w }
		toplevel $w -background black
		wm title $w "LUT upgrade $nm"
		wm iconname $w "Upgrade"
		wm geometry $w
	}
	set cnt 0
	for {set i 0} {$i < [llength $Old]} {incr i} {
		set line [lindex $Old $i]
		if {[lsearch -exact $New $line] < 0} {
			if {$vb} {
				label $w.l$cnt \
					-bg black -fg white \
					-text "Old:	$line"
				pack $w.l$cnt -anchor nw -side top
				incr cnt
			} else {
				extendlut $nm $line 0
	}	}	}
	for {set i 0} {$i < [llength $New]} {incr i} {
		set line [lindex $New $i]
		if {[lsearch -exact $Old $line] < 0} {
			if {$vb} {
				label $w.l$cnt \
					-bg black -fg gold \
					-text "New:	$line"
				pack $w.l$cnt -anchor nw -side top
				incr cnt
			} else {
				extendlut $nm $line 1
	}	}	}

	save_prx 1
	if {$vb} {
		button $w.ex \
			-bg black -fg gold \
			-text "Close" \
			-command "destroy $w"
		pack $w.ex -anchor se -side top
	}
}

proc filesequal {f g} {

	if [catch {set fd1 [open $f r]} errmsg] {
		complain "filesequal: $errmsg"
		return 0
	}
	if [catch {set fd2 [open $g r]} errmsg] {
		complain "filesequal: $errmsg"
		return 0
	}

	set res 1
	while {1} {
		set r1 [gets $fd1 line1]
		set r2 [gets $fd2 line2]

		if {$r1 < 0 && $r2 < 0} {
			break
		}

		if {($r1 >= 0 && $r2 <  0) \
		||  ($r1 <  0 && $r1 >= 0)
		||  [string compare $line1 $line2] != 0} {
			set res 0
			break
		}
	}

	catch { close $fd1 }
	catch { close $fd2 }
	return $res
}

proc start_upgrade {From Into Prx} {
	global MODEX fnm Fname oFname
	global TW_Prx TW_Out TW_Log P_Flag z_Flag

	if {[file exists $Into] == 0 \
	||  [file readable $Into] == 0} {
		complain "Cannot open $Into"
		return
	}
	set pp [string last ".prx" $Prx]
	if {$pp < 0 \
	|| [string length $Prx] != [expr $pp + 4]} {
		complain "Prx filename must end in .prx ([string length $Prx] ${pp})"
		return
	}
	if {[file exists $Prx] != 0} {
		complain "File $Prx exists"
		return
	}

	# -- generate .nlut files for current version
	writeoutfile $TW_Prx _modex_in.prx	;# start_upgrade
	rmsuffs nlut
	$TW_Log insert end "$MODEX $P_Flag $z_Flag -r -M nlut _modex_in.prx\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -r -M nlut "_modex_in.prx" >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		complain "Modex $P_Flag $z_Flag -r -M nlut: $errmsg"
		return
	}
	readinfile $TW_Out feaver.err

	# -- replace all references to From into Into
	replace_fname $From $Into

	set oFname $Fname	;# for revert option
	set Fname $Prx
	set fnm [string range $Fname 0 $pp]

	save_prx 1	;# create new prx file

	# -- generate .ulut files for new version
	rmsuffs ulut
	set nogood 0
	$TW_Log insert end "$MODEX $P_Flag $z_Flag -r -M ulut $Fname\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -r -M ulut $Fname >feaver.tmp 2>feaver.err} errmsg] {
		complain "Modex $P_Flag $z_Flag -r -M ulut: $errmsg"
		return
	}
	readinfile $TW_Out feaver.err

	# -- build a menu of [nu]lut basenames
	catch { destroy .upgrade.ok }

	set f {}
	catch { set f [lsort [glob *.nlut]] }
	set cnt 0
	foreach i $f {
		set j [string range $i 0 [expr [string length $i] - 6]]

		if {[filesequal $j.nlut $j.ulut]} {
			rmfile $j.nlut
			rmfile $j.ulut
		} else {
			if {$cnt == 0} {
				.upgrade.explain configure \
					-text "The following LUTs need updating:"
			}
			diff_lut $j 0
			button .upgrade.buts.but$cnt \
				-bg red -fg white \
				-activeforeground red -activebackground white \
				-relief raised \
				-text "$j" \
				-command "viewlut $j"	;# diff_lut $j 1"

			pack .upgrade.buts.but$cnt -side left

			incr cnt
	}	}
	if {$cnt == 0} {
		.upgrade.explain configure \
			-text "No LUTs need updating"
	} else {
		button .upgrade.backout \
			-text "Revert" \
			-command "backout $cnt $From $Prx"
		pack .upgrade.backout -side right
		rmsuffs nlut
		rmsuffs ulut
	}
}

proc backout {cnt From Prx} {
	global Fname oFname fnm

	rmsuffs ulut
	rmsuffs nlut
	rmfile $Prx

	set Fname $oFname
	set pp [string last ".prx" $Fname]
	set fnm [string range $Fname 0 $pp]

	reopen_c $Fname

	catch { destroy .upgrade.backout }
	for {set i 0} {$i < $cnt} {incr i} {
		catch { destroy .upgrade.buts.but$i }
	}
	.upgrade.explain configure \
		-text "Ok will compute the LUTs that need updating"

	button .upgrade.ok \
		-text "Ok" \
		-command {
			start_upgrade $From [.upgrade.mid.into get] [.upgrade.bot.into get]
		}
	pack .upgrade.ok -side right
}

proc eligible {} {
	global TW_Prx

	set w $TW_Prx

	scan [$w index end] %d numLines
	put_on_top 2 5

	set these ""
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]
		if {[string first "%F " $line] == 0} {
			$w tag add hilite $i.0 $i.end
			$w yview -pickplace [expr $i - 1]
			set these "$these [string range $line 3 end]"
	}	}
	$w tag configure hilite -background ivory -foreground red

	return $these
}

proc whichluts {} {
	global TW_Out TW_Prx TW_Log MODEX fnm P_Flag z_Flag

	writeoutfile $TW_Prx _modex_in.prx	;# whichluts

	$TW_Log insert end "$MODEX $P_Flag $z_Flag -k _modex_in.prx\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -k _modex_in.prx >feaver.tmp 2>feaver.err} errmsg] {
		complain "Modex: $errmsg"
		return
	}
	readinfile $TW_Out feaver.err
	set f {}
	catch { set f [lsort [glob *.nlut]] }

	set these ""
	foreach i $f {
		set j [string range $i 0 [expr [string length $i] - 6]]
		set these "$these $j"
	}

	return "(default) $these"
}

proc pop_lut {nm {v 0}} {
	global MODEX fnm TW_Prx TW_Out TW_Log TW_Errors
	global PrxChanged P_Flag z_Flag

	if {$nm == "(default)"} {
		catch { destroy .newlut }
		return	;# nothing to add
	}

	if {$v} {
		rmsuffs nlut
		writeoutfile $TW_Prx _modex_in.prx	;# pop_lut
		$TW_Log insert end "$MODEX $P_Flag $z_Flag -k _modex_in.prx\n"
		if [catch { eval exec $MODEX $P_Flag $z_Flag -k _modex_in.prx >feaver.tmp 2>feaver.err} errmsg] {
			rmsuffs nlut
			readinfile $TW_Errors feaver.tmp
			readinfile $TW_Out feaver.err
			complain "Modex $P_Flag $z_Flag -k: $errmsg"
			catch { destroy .newlut }
			return
		}
		readinfile $TW_Out feaver.err
	}

	if [catch {set fd [open $nm.nlut r]} errmsg] {
		rmsuffs nlut
		complain "pop_lut: $errmsg"
		catch { destroy .newlut }
		return
	}

	set Old {}
	while {[gets $fd line] > -1} {
		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}
		if {[string length $line] > 0 \
		&&  [string first "#" $line] != 0} {
			lappend Old $line
	}	}
	catch { close $fd }
	rmsuffs nlut

	set Old [lsort $Old]

	for {set i 0} {$i < [llength $Old]} {incr i} {
		set line [lindex $Old $i]
		extendlut $nm $line 0
	}
	set PrxChanged 1

	set w $TW_Prx
	scan [$w index end] %d numLines

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]
		if {[string first "%L" $line] == 0} {
			set hv [string range $line 3 end]
			if {[string compare $nm $hv] == 0 \
			||  ( $hv == "" && $nm == "all" )} {
				$w tag add hilite $i.0 $i.end
				$w yview -pickplace [expr $i - 1]
				break
	}	}	}

	catch { destroy .newlut }
}

proc populate_lut {} {
	global TW_Prx

	set font {Helvetica 12}
	catch { destroy .newlut }
	toplevel .newlut
	wm title .newlut "Populate Lut"
	wm iconname .newlut "PopLut"
	wm geometry .newlut +10+10

	frame .newlut.top

	label .newlut.top.lab \
		-text "Choose:" \
		-font $font \
		-anchor w \
		-background black -foreground white \
		-relief sunken

	eval tk_optionMenu .newlut.top.from From [whichluts]

	button .newlut.ok \
		-text "Ok" \
		-command { pop_lut $From }
	button .newlut.ex \
		-text "Cancel" \
		-command { destroy .newlut }

	pack append .newlut.top \
		.newlut.top.lab { fillx left } \
		.newlut.top.from { fillx expand left }

	pack .newlut.top -fill x -side top
	pack .newlut.ok -side right
	pack .newlut.ex -side right
}

proc upgrade_c {} {
	global TW_Prx From

	set font {Helvetica 12}
	catch { destroy .upgrade }
	toplevel .upgrade
	wm title .upgrade "Upgrade Wizard"
	wm iconname .upgrade "Upgrade"
	wm geometry .upgrade +10+10

	frame .upgrade.top
	frame .upgrade.mid
	frame .upgrade.bot
	frame .upgrade.buts

	label .upgrade.top.lab1 \
		-text "Old:" \
		-font $font \
		-anchor w \
		-background black -foreground white \
		-relief sunken

	eval tk_optionMenu .upgrade.top.from From [eligible]

	label .upgrade.mid.lab2 \
		-text "New:" \
		-font $font \
		-anchor w \
		-background black -foreground white \
		-relief sunken
	entry .upgrade.mid.into \
		-width 20 \
		-font $font \
		-background white \
		-foreground black \
		-relief sunken
	button .upgrade.mid.browse \
		-text "Browse" \
		-command {
			set fileselect "tk_getOpenFile"
			set file [eval $fileselect]
			if {$file != ""} {
				.upgrade.mid.into delete 0 end
				.upgrade.mid.into insert 0 $file
			}
		}
	label .upgrade.bot.lab2 \
		-text "New prx file:" \
		-font $font \
		-anchor w \
		-background black -foreground white \
		-relief sunken
	entry .upgrade.bot.into \
		-width 20 \
		-font $font \
		-background white \
		-foreground black \
		-relief sunken

	button .upgrade.ok \
		-text "Ok" \
		-command {
			start_upgrade $From [.upgrade.mid.into get] [.upgrade.bot.into get]
		}
	button .upgrade.ex \
		-text "Close" \
		-command { 
			rmsuffs nlut
			rmsuffs ulut
			destroy .upgrade
		}

	pack append .upgrade.top \
		.upgrade.top.lab1 { fillx left } \
		.upgrade.top.from { fillx expand left }

	pack append .upgrade.mid \
		.upgrade.mid.lab2   { fillx left } \
		.upgrade.mid.into   { fillx expand left } \
		.upgrade.mid.browse { fillx right }

	pack append .upgrade.bot \
		.upgrade.bot.lab2 { fillx left } \
		.upgrade.bot.into { fillx left }

	label .upgrade.explain \
		-bg red -fg white \
		-text "Ok will compute the LUTs that need updating"

	pack .upgrade.top -fill x -side top
	pack .upgrade.mid -fill x -side top
	pack .upgrade.bot -fill x -side top
	pack .upgrade.explain -fill x -side top
	pack .upgrade.buts -fill x -side top

	pack .upgrade.ok -side right
	pack .upgrade.ex -side right
}

proc rmsuffs {suffix} {
	global CMD Unix

	if {$Unix} {
		catch { set f [glob *.$suffix];  eval exec rm -f $f }
	} else {
		catch {exec $CMD /c del *.$suffix }
	}
}

proc rmfile {f} {
	global CMD Unix

	if {$Unix} {
		catch {exec rm -f $f}
	} else {
		catch {exec $CMD /c del $f }
	}
}

proc gui_lut {} {
	global MODEX TW_Prx TW_Advanced TW_Out TW_Log P_Flag z_Flag

	writeoutfile $TW_Prx _modex_in.prx	;# gui_lut

	rmsuffs lut
	rmsuffs nlut
	$TW_Log insert end "$MODEX $P_Flag $z_Flag -r -k _modex_in.prx\n"
	if [catch { eval exec $MODEX $P_Flag $z_Flag -r -k "_modex_in.prx" >feaver.tmp 2>feaver.err} errmsg] {
		readinfile $TW_Out feaver.err
		complain "Modex $P_Flag $z_Flag -r -k: $errmsg"
		return
	}
	readinfile $TW_Out feaver.err

	catch { destroy $TW_Advanced.mid.left.m.luts }
	set w $TW_Advanced.mid.left.m

	menubutton $w.luts \
		-text "Edit Lut" \
		-bg SkyBlue4 -fg gold \
		-border 4 \
		-activeforeground SkyBlue4 -activebackground gold \
		-relief raised \
		-menu $w.luts.m
	pack	$w.luts -side left -padx 4 -pady 4 -expand 0

	menu $w.luts.m -tearoff 0

	set f {}
	catch { set f [lsort [glob *.lut]] }
	foreach i $f {
		set j [string range $i 0 [expr [string length $i] - 5]]
		$w.luts.m add command \
			-label "$j" \
			-command "show_lut $i $j"
	}
}

## start of Advanced routines

set prx_rt	".prx_w.rt"	;# root for this part of gui

set prx_nrrows	0	;# in summary table
set prx_fn(0) ""	;# source file names
set prx_ft(0) ""	;# fct names
set prx_lt(0) ""	;# lut names
set prx_wt(0) ""	;# wrapper types
set prx_xc(0) ""	;# %X command line syntax
set prx_lnk   ""	;# %O commands
set prx_rm(0) 0		;# removal indication
set prx_luts(0) "(default)"
set prx_nluts 1

proc prx_snapshot {} {
	global prx_fn   prx_ft   prx_lt   prx_wt   prx_nrrows 
	global prx_o_fn prx_o_ft prx_o_lt prx_o_wt prx_o_nrrows

	set prx_o_nrrows $prx_nrrows
	for {set i 0} {$i < $prx_nrrows} {incr i} {
		set prx_o_fn($i) $prx_fn($i)
		set prx_o_ft($i) $prx_ft($i)
		set prx_o_lt($i) $prx_lt($i)
		set prx_o_wt($i) $prx_wt($i)
	}
}

proc prx_revert {} {
	global prx_fn   prx_ft   prx_lt   prx_wt   prx_nrrows   prx_xc
	global prx_o_fn prx_o_ft prx_o_lt prx_o_wt prx_o_nrrows

	set prx_nrrows $prx_o_nrrows
	for {set i 0} {$i < $prx_nrrows} {incr i} {
		set prx_fn($i) $prx_o_fn($i)
		set prx_ft($i) $prx_o_ft($i)
		set prx_lt($i) $prx_o_lt($i)
		set prx_wt($i) $prx_o_wt($i)
	}
	# re-encode, fields may have changed since decoding
	for {set i 0} {$i < $prx_nrrows} {incr i} {
		set prx_xc($i) [prx_encode $i]
	}
}

proc prx_browsefile {j} {

	set fileselect "tk_getOpenFile \
		-filetypes { \
			{ { C Sources }  .c   } \
			{ { Promela models }  .pml } \
			{ { Lut files }  .lut } \
			{ { Prx files }  .prx } \
			{ { Vip files }  .vip } \
			{ { Aut files }  .aut } \
			{ { All Files }   *   } \
			}"
	switch -- [set file [eval $fileselect]] "" return ""
	return $file
}

proc prx_encode {i} {
	global prx_ft prx_fn prx_lt prx_wt

	set ff ""; set ll ""; set aa ""
	if {$prx_lt($i) != "(default)"} {
		set ll "-L $prx_lt($i) "
	}
	if {$prx_ft($i) == "(all)"} {
		set aa "-x"
		switch $prx_wt($i) {
		"proctype"		{ set aa "-xp" }
		"body only"		{ set aa "-xn" }
		"inline"		{ set aa "-xi" }
		default			{ set aa "-x" }
		}
	} else {
		switch $prx_wt($i) {
		"active proctype"	{ set aa "-a" }
		"extended active proctype"	{ set aa "-e" }
		"proctype"		{ set aa "-p" }
		"body only"		{ set aa "-n" }
		"inline"		{ set aa "-i" }
		default			{ set aa "-? $prx_wt($i)" }
		}
		set aa "$aa $prx_ft($i)"
	}
	return "%X ${ff}${ll}$aa"
}

proc prx_decode {j} {
	global prx_xc prx_fn prx_ft prx_lt prx_wt prx_rm

	set prx_ft($j) "(all)"
	set prx_lt($j) "(default)"
	set prx_wt($j) "active proctype"
	set prx_rm($j) 0

	if {[info exists prx_xc($j)] == 0} {
		set prx_xc($j) ""
	}
	if {$prx_xc($j) == ""} { return }

	set p [split $prx_xc($j) "-"]
	for {set i 1} {$i < [llength $p] > 0} {incr i} {	;# 0 is "%X"
		set fld [lindex $p $i]
		switch [string range $fld 0 0] {
		b	{ set prx_fn($j) [string range $fld 2 end]
			  set prx_fn($j) [string trim $prx_fn($j) "\r\n "]
			}
		x	{ set prx_ft($j) "(all)"
			  switch [string range $fld 1 1] {
			  p	  { set prx_wt($j) "proctype" }
			  n	  { set prx_wt($j) "body only" }
			  i	  { set prx_wt($j) "inline" }
			  e	  { set prx_wt($j) "extended active proctype" }
			  default { set prx_wt($j) "active proctype" }
			  }
			}
		a	{ set prx_ft($j) [string range $fld 2 end]
			  set prx_wt($j) "active proctype"
			}
		e	{ set prx_ft($j) [string range $fld 2 end]
			  set prx_wt($j) "extended active proctype"
			}
		p	{ set prx_ft($j) [string range $fld 2 end]
			  set prx_wt($j) "proctype"
			}
		n	{ set prx_ft($j) [string range $fld 2 end]
			  set prx_wt($j) "body only"
			}
		i	{ set prx_ft($j) [string range $fld 2 end]
			  set prx_wt($j) "inline"
			}
		L	{ set prx_lt($j) [string range $fld 2 end] }
		G - r	{ }
		default	{ complain "unrecognized X option -$fld" }
	}	}
}

proc prx_get_fctnames {j} {
	global MODEX prx_fn TW_Out TW_Log

	set nms { "(all)" }

	if {$prx_fn($j) == "" \
	||  $prx_fn($j) == "(select)"} {
		return $nms
	}

	$TW_Log insert end "$MODEX -P -F $prx_fn($j)\n"
	if [catch { exec $MODEX -P -F $prx_fn($j) >&feaver.out } errmsg] {
		readinfile $TW_Out feaver.out
		complain "modex: $errmsg"
	} else {
		readinfile $TW_Out feaver.out
		if [catch {set fd [open "feaver.out" r]} errmsg] {
			complain "readfile: $errmsg"
		} else {
			while {[gets $fd line] > -1} {
				set line [string trim $line "\r\n"]
				set c [string range $line 0 0]
				if {$c == "\t"} { continue }
				set k [split $line "\t"]
				if {[llength $k] == 2} {
					set fctnm [lindex $k 0]
					if {[lsearch -exact $nms $fctnm] == -1} {
						lappend nms $fctnm
			}	}	}
			catch { close $fd }
	}	}

	return $nms
}

proc prx_blank_row {} {
	global prx_nrrows prx_xc prx_fn prx_ft prx_wt prx_lt colwidth
	global prx_rt prx_u1 prx_u2 prx_u3 prx_rm

	set j $prx_nrrows
	incr prx_nrrows

	set prx_xc($j) ""
	set prx_fn($j) ""
	set prx_ft($j) ""
	set prx_lt($j) ""
	set prx_wt($j) ""
	set prx_rm($j) 0

	return $j
}

proc prx_redo_ft {j m} {
	global prx_fn prx_ft prx_u2

	set prx_fn($j) $m
	catch { $prx_u2($j) delete 0 end } msg

	if {$msg != ""} { complain "redo: $msg" }

	foreach m [prx_get_fctnames $j] {
		$prx_u2($j) add command -label $m -command "set prx_ft($j) $m"
	}
}

proc prx_redo_lt {j {m ""}} {
	global prx_nluts prx_luts prx_u3 prx_lt

	if {$m != ""} {
		set prx_lt($j) $m
	}
	catch { $prx_u3($j) delete 0 end }

	$prx_u3($j) add command \
		-label "(New Lut)" \
		-command "prx_add_lut $j"

	for {set i 0} {$i < $prx_nluts} {incr i} {
		set m $prx_luts($i)
		$prx_u3($j) add command \
			-label $m \
			-command "set prx_lt($j) $m"
	}
}

proc prx_write_back {} {	;# update the extraction commands in test harness
	global TW_Prx prx_xc prx_nrrows prx_fn prx_rm
	global prx_nluts prx_luts

	prx_revert	;# pickup last stable values
	set w $TW_Prx
	scan [$w index end] %d numLines

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]
		if {[string first "%F" $line] == 0 \
		||  [string first "%X" $line] == 0} {
			$w delete last [expr $i + 1].0
			incr numLines -1
			incr i -1
	}	}

	set curfile ""
	for {set i 0; set j 1} {$i < $prx_nrrows} {incr i} {
		if {$prx_rm($i) == 1 \
		||  $prx_fn($i) == "" \
		||  $prx_fn($i) == "(select)"} {
			continue
		}
		if {$curfile != $prx_fn($i)} {
			$w insert $j.0 "%F $prx_fn($i)\n"
			set curfile $prx_fn($i)
			incr j
		}
		$w insert $j.0 "$prx_xc($i)\n"
		incr j
	}
	for {set i 0} {$i < $prx_nluts} {incr i} {
		if {$prx_luts($i) == "(default)"} {
			set nm ""
		} else {
			set nm " $prx_luts($i)"
		}
		prx_putfragment "%L$nm" "" 1	;# add if absent
	}
}

proc prx_summary {} {
	global TW_Prx prx_xc prx_fn colwidth prx_nrrows
	global prx_luts prx_nluts prx_lnk

	set prx_nrrows	0
	set prx_nluts   1
	set prx_lnk	""
	set curfile	""
	set colwidth	15

	set w $TW_Prx
	scan [$w index end] %d numLines

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]
		if {[string first "%F" $line] == 0} {
			set hv [string range $line 3 end]
			set curfile $hv
			continue
		}
		if {[string first "%L" $line] == 0} {
			if {[string length $line] > 3} {
				set ln [string range $line 3 end]
				set prx_luts($prx_nluts) $ln
				incr prx_nluts
			}
			continue
		}
		if {[string first "%O" $line] == 0} {
			set prx_lnk "${prx_lnk}[string range $line 3 end] "
			continue
		}
		if {[string first "%X" $line] == 0} {
			set hv [string range $line 3 end]
			set j [prx_blank_row]
			set prx_fn($j) $curfile
			set prx_xc($j) "$hv"
	}	}
}

proc system_context {} {
	global TW_Prx Cfont Ccol

	catch { destroy .prx_sys }
	toplevel .prx_sys

	wm title .prx_sys "System Context"
	.prx_sys configure -bg SkyBlue4

	frame .prx_sys.m -bg SkyBlue4 -height 20
	pack .prx_sys.m -side top -fill x

	label .prx_sys.m.t0 -bg SkyBlue4 -fg white \
		-font {Helvetica 12} \
		-text "Edit System Context"
	pack .prx_sys.m.t0 -side left -padx 5 -pady 5

	button .prx_sys.m.b1 \
		-bg SkyBlue4 -fg gold \
		-relief raised -border 5 \
		-border 4 \
		-text "Dismiss" \
		-command {destroy .prx_sys}

	button .prx_sys.m.b2 \
		-relief raised -border 5 \
		-bg SkyBlue4 -fg gold \
		-border 4 \
		-text "Apply" \
		-command { prx_putfragment "%P" [.prx_sys.t get 1.0 end] }

	pack	.prx_sys.m.b2 \
		.prx_sys.m.b1 -side right -pady 5

	text .prx_sys.t \
		-font $Cfont \
		-bg white \
		-fg $Ccol \
		-relief raised -pady 10
	pack .prx_sys.t -side bottom -fill x -fill both -expand 1

	.prx_sys.t insert end [prx_getfragment "%P"]
}

set prx_save(H) "H"
set prx_save(D) "D"
set prx_save(C) "C"
set prx_o_td	"D"

proc c_context {} {
	global TW_Prx prx_save prx_lnk prx_o_td
	global Cfont Ccol

	catch { destroy .prx_c }
	toplevel .prx_c

	wm title .prx_c "C Context"
	.prx_c configure -bg SkyBlue4
	wm geometry .prx_c +10+185

	frame .prx_c.m -bg SkyBlue4 -height 20
	pack .prx_c.m -side top -fill x

	label .prx_c.m.t0 -bg SkyBlue4 -fg white \
		-font {Helvetica 12} \
		-text "Edit C Context"
	pack .prx_c.m.t0 -side left -padx 5 -pady 5

	button .prx_c.m.b1 -bg SkyBlue4 -fg gold \
		-relief raised -border 5 \
		-text "Dismiss" \
		-command { destroy .prx_c }

	button .prx_c.m.b2 -bg SkyBlue4 -fg gold \
		-relief raised -border 5 \
		-text "Apply" \
		-command { prx_putall }

	pack	.prx_c.m.b2 \
		.prx_c.m.b1 -side right -pady 5

	frame .prx_c.choice -bg grey90
	pack  .prx_c.choice -side top -fill x

	radiobutton .prx_c.choice.b1 \
		-bg grey90 -fg red \
		-command { prx_putfront "H" } \
		-text "Typedefs and Defines" -variable td -value "H"
	radiobutton .prx_c.choice.b2 \
		-bg grey90 -fg red \
		-command { prx_putfront "D" } \
		-text "Data Types" -variable td -value "D"
	radiobutton .prx_c.choice.b3 \
		-bg grey90 -fg red \
		-command { prx_putfront "C" } \
		-text "Functions" -variable td -value "C"

	frame .prx_c.choice.top -bg darkgrey
	label .prx_c.choice.top.lb \
		-bg grey90 -fg red \
		-text "Linked objects:"
	entry .prx_c.choice.top.lnk -font {Helvetica 10}
	pack	.prx_c.choice.top.lb -side left
	pack	.prx_c.choice.top.lnk -side left -fill x -expand 1
	.prx_c.choice.top.lnk insert end $prx_lnk

	pack	.prx_c.choice.top -side top -anchor nw -fill x -expand 1

	pack	.prx_c.choice.b1 \
		.prx_c.choice.b2 \
		.prx_c.choice.b3 -side left

	text .prx_c.child \
		-font $Cfont \
		-bg white \
		-fg $Ccol \
		-height 10 \
		-relief raised -pady 5

	pack .prx_c.child -side top -fill both -expand 1

	set prx_o_td "D"
	.prx_c.choice.b2 select
	prx_c_undo
}

proc prx_c_undo {} {
	global prx_save prx_o_td

	set prx_save(H) [prx_getfragment "%H"]
	set prx_save(D) [prx_getfragment "%D"]
	set prx_save(C) [prx_getfragment "%C"]

	.prx_c.child delete 1.0 end
	.prx_c.child insert end "$prx_save($prx_o_td)"
}

proc prx_putfront { to } {
	global prx_save prx_o_td

	set prx_save($prx_o_td) [.prx_c.child get 1.0 end]
	.prx_c.child delete 1.0 end
	.prx_c.child insert end "$prx_save($to)"
	set prx_o_td $to
}

proc prx_putall {} {
	global prx_save prx_o_td prx_lnk

	set prx_lnk [.prx_c.choice.top.lnk get]

	switch $prx_o_td {
	H	{ prx_putfragment "%H" [.prx_c.child get 1.0 end]
		  prx_putfragment "%D" $prx_save(D)
		  prx_putfragment "%C" $prx_save(C)
		}
	D	{ prx_putfragment "%D" [.prx_c.child get 1.0 end]
		  prx_putfragment "%H" $prx_save(H)
		  prx_putfragment "%C" $prx_save(C)
		}
	C	{ prx_putfragment "%C" [.prx_c.child get 1.0 end]
		  prx_putfragment "%H" $prx_save(H)
		  prx_putfragment "%D" $prx_save(D)
		}
	""	{ prx_putfragment "%H" $prx_save(H)
		  prx_putfragment "%C" $prx_save(C)
		  prx_putfragment "%D" $prx_save(D)
		}
	default	{ complain "this cannot happen <${prx_o_td}>"
		}
	}
	prx_putline "%O" "$prx_lnk"
}

proc prx_getfragment { heading } {
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines

	set j -1; set k -1
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		if {[string first $heading $line] == 0} {
			set j [expr $i + 1]
		}
		if {$j == -1} { continue }
		if {[string first "%%" $line] == 0} {
			set k [expr $i - 1]
			break
	}	}
	if {$j != -1} {
		if {$k == -1} {
			set k [expr $numLines -1]
		}
		if {$k >= $j} {
			return [$w get $j.0 $k.end]
	}	}
	return ""
}

proc prx_add_lut {j} {
	global TW_Prx

	set m [prx_get_fctnames $j]
	set k [lsearch -exact $m "(all)"]
	if {$k != -1} {
		set m [lreplace $m $k $k]
	}

	set w $TW_Prx
	scan [$w index end] %d numLines

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		if {[string first "%L" $line] == 0} {
			if {[string length $line] <= 3} {
				set nm "(all)"
			} else {
				set nm [string range $line 3 end]
			}
			set k [lsearch -exact $m $nm]
			if {$k != -1} {
				set m [lreplace $m $k $k]
	}	}	}

	if {$m == {}} {
		complain "All Luts have already been named (one for each fct)"
		return
	}

	catch { destroy .pick_lut }
	toplevel .pick_lut
	wm minsize .pick_lut 1 1
	wm title .pick_lut "Double-Click a Name"

	frame .pick_lut.l
	scrollbar .pick_lut.l.scroll \
		-command ".pick_lut.l.list yview"
	listbox .pick_lut.l.list \
		-yscroll ".pick_lut.l.scroll set" \
		-relief raised -height 5 -width 20 \
		-bg white

	frame .pick_lut.buts
	button .pick_lut.buts.ok -text "Select" \
		-command " prx_dance $j " -width 5
	button .pick_lut.buts.nok -text "Cancel" \
		-command { destroy .pick_lut } -width 5

	pack	.pick_lut.buts.ok \
		.pick_lut.buts.nok -side left -pady 3

	pack .pick_lut.l.scroll -side right -fill y
	pack .pick_lut.l -side top -pady 8 -fill both -expand yes
	pack .pick_lut.l.list -side left -fill both -expand yes

	pack .pick_lut.buts -side bottom -anchor n

	foreach i $m {
            	.pick_lut.l.list insert end $i
	}
	bind .pick_lut.l.list <Double-Button-1> "
		prx_dance $j
	"
}

proc prx_dance {j} {
	global prx_nluts prx_luts

	set i [.pick_lut.l.list get active]
	if {$i == "(all)"} { return }

	set prx_luts($prx_nluts) $i
	incr prx_nluts
	prx_redo_lt $j $i		;# redo the menu entries

	destroy .pick_lut
}

proc prx_putline { heading suffix } {	;# %O %G only (occurs max 1x)
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines

	set suffix [string trimright $suffix "\n"]

	set j -1
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		if {[string first $heading $line] == 0} {
			set j $i
			break
	}	}

	if {$j != -1} {
		$w delete $j.0 $j.end
		if {$suffix != ""} {
			$w insert $j.0 "$heading ${suffix}\n"
		}
	} else {
		if {$suffix != ""} {
			$w insert end "$heading ${suffix}\n"
	}	}
}

proc prx_putfragment { heading body {ifabsent 0}} {
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines
	set body [string trimright $body "\n"]

	set j -1; set k -1
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		if {[string first $heading $line] == 0 \
		&&  [string length $heading] == [string length $line]} {
			set j [expr $i + 1]
		}
		if {$j == -1} { continue }
		if {[string first "%%" $line] == 0} {
			set k [expr $i - 1]
			break
	}	}
	if {$j != -1} {
		if {$ifabsent} {
			return	;# not absent
		}
		if {$k == -1} {
			set k [expr $numLines -1]
		}
		$w delete $j.0 $k.end
		$w insert $j.0 "${body}\n"
	} else {
		if {$body != "" || $ifabsent} {
			$w insert end "$heading"
			if {$body != ""} {
				$w insert end "\n${body}"
			}
			$w insert end "\n%%\n"
	}	}
}

## end of Advanced support routines

proc setbindings {w li ri lt slt rt c n} {
	$w bind $ri <1> "
		editlut $w \{$li\} \{$ri\} \{$lt\} \{$rt\} $c $n
	"
	$w bind $ri <Any-Enter> "
		$w itemconfigure $ri -fill white
	"
	$w bind $ri <Any-Leave> "
		$w itemconfigure $ri -fill gold
	"
}

proc setaddition {x y w n} {

	set dist 300

	set li [$w create text \
		$x [expr 20*$y] \
		-text "" \
		-anchor nw \
		-fill red]
	set ri [$w create text \
		[expr $x + $dist] [expr 20*$y] \
		-text "<Add Entry>" \
		-font {Helvetica 10} \
		-anchor nw \
		-fill white]

	$w bind $ri <1> "
		$w bind $ri <1> {}
		editlut $w $li $ri {Source} {Target} blue $n
		$w move legend 0 20
		setaddition $x [expr $y+1] $w $n
	"

	$w bind $ri <Any-Enter> "
		$w itemconfigure $ri -fill red
	"
	$w bind $ri <Any-Leave> "
		$w itemconfigure $ri -fill white
	"
}

proc enact {w li ri lt nm} {
	global TW_Prx PrxChanged

	set nlt [.elut.source get]
	set nrt [.elut.target get]

	$w itemconfigure $li -text "$nlt" -fill white
	$w itemconfigure $ri -text "$nrt" -fill gold

	replace_entry $TW_Prx "$lt" "$nlt" "$nrt" $nm
	incr PrxChanged
}

proc editlut {w li ri lt rt c nm} {

	set font {Helvetica 12}
	catch { destroy .elut }
	toplevel .elut
	wm title .elut "Edit LUT entry for $nm"
	wm iconname .elut "ELUT"

	entry .elut.source \
		-width 60 \
		-font $font \
		-background white \
		-foreground black \
		-relief sunken
	entry .elut.target \
		-width 60 \
		-font $font \
		-background white \
		-foreground black \
		-relief sunken
	button .elut.set \
		-text "Save" \
		-command "
			enact $w $li $ri \{$lt\} $nm
			destroy .elut
		"

	button .elut.close \
		-text "Close" \
		-command { destroy .elut }

	.elut.source insert insert $lt
	.elut.target insert insert $rt

	# leaving rhs empty can be used to delete and entry from the lut

	pack .elut.source -fill x -side top
	pack .elut.target -fill x -side top
	pack .elut.close -side right
	pack .elut.set -side right
}

proc show_lut {f n} {
	global MapNr Unix

	if [catch {set fd [open $f r]} errmsg] {
		complain "showlut: $errmsg"
		return 0
	}

	incr MapNr
	set w .map$MapNr

	mkcanvas "$w" "Lut" $n 600 400 ".lut"
	wm title $w "LUT Editor for $n"
	catch { destroy $w.b.b2 }	;# no save as button
#	$w.b.b2 configure -text "Hallo" -command "..."

	viewlut $n

	set dist 300	;# distance between columns
	if {$Unix} {
		set MaxS 50	;# max nr of chars in an entry
	} else {
		set MaxS 60	;# max nr of chars in an entry
	}
	set x 5		;# offset from left marging
	set y 0		;# offset from top
	set visible 0
	while {[gets $fd line] > -1} {

		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}

		if {[string first "Substitute" $line] == 0 \
		||  [string first "Include"    $line] == 0 \
		||  [string first "Global"     $line] == 0 \
		||  [string first "Local"      $line] == 0 \
		||  [string first "NonState"   $line] == 0 \
		||  [string first "Function"   $line] == 0} {
			continue
		}

		set redundant 0
		set tags ""
		if {[string first "Redundant: " $line] == 0} {
			set line [string range $line 11 end]

			while {[string first "_P_E_R_C_E_N_T_" $line] > 0} {
				set k [string first "_P_E_R_C_E_N_T_" $line]
				set m [string range $line 0 [expr $k - 1]]
				incr k [string length "_P_E_R_C_E_N_T_"]
				set line "${m}%[string range $line $k end]"
			}
			set redundant 1
			set tags "redundant"
			set col red
		}

		set bt  [string first "\t" $line]
		incr bt -1
		set lhs [string range $line 0 $bt]

		incr bt 2
		while {[string index $line $bt] == "\t"} {
			incr bt
		}
		set rhs [string range $line $bt end]

		if {$lhs == "" && $rhs != "" \
		&& [string first "# Modex Lookup Table for target " $rhs] == 0} {
			if {[string first $n $line] >= 0} {
				$w.c create text \
					$x [expr 20*$y] \
					-text "$rhs" \
					-font {Helvetica 10} \
					-anchor nw \
					-fill gold
				incr y
				set visible 1
				set tags "$tags header"
			} else {
				set visible 0
		}	}

		if {$visible == 0} {
			continue
		}

		set fx [string first "	/* default-rule */" $rhs]
		if {$fx > 0} {
			incr fx -1
			set rhs [string range $rhs 0 $fx]
			set col white
			set tags "$tags isdefault"
		} else {
			if {$redundant == 0} {
				set col gold
		}	}
		if {$rhs != "" && $lhs != ""} {
			set olhs $lhs
			if {[string length $lhs] > $MaxS} {
				set lhs "[string range $lhs 0 $MaxS].."
			}
			set lht [$w.c create text \
				$x [expr 20*$y] \
				-text "$lhs" \
				-font {Helvetica 10} \
				-anchor nw \
				-fill white]
			set rht [$w.c create text \
				[expr $x + $dist] [expr 20*$y] \
				-text "$rhs" \
				-font {Helvetica 10} \
				-anchor nw \
				-fill $col]

			setbindings $w.c $lht $rht "$olhs" "$lhs" "$rhs" $col $n
			incr y
		}
	}

	setaddition $x $y $w.c $n

	incr y 2
	$w.c create line \
		5 [expr 20*$y] \
		550 [expr 20*$y] \
		-width 2 -fill gray -tags legend
	incr y
	$w.c create text \
		[expr $x + $dist] [expr 20*$y] \
		-text "predefined" \
		-font {Helvetica 10} \
		-anchor nw -fill white -tags legend
	incr y
	$w.c create text \
		[expr $x + $dist] [expr 20*$y] \
		-text "user-defined" \
		-font {Helvetica 10} \
		-anchor nw -fill gold -tags legend
	incr y
	$w.c create text \
		[expr $x + $dist] [expr 20*$y] \
		-text "redundant" \
		-font {Helvetica 10} \
		-anchor nw -fill red -tags legend
	incr y 2
	$w.c create line \
		5 [expr 20*$y] \
		550 [expr 20*$y] \
		-width 2 -fill gray -tags legend
	incr y 2

	catch { close $fd }
	$w.c configure -scrollregion  "0 0 1000 [expr 20*$y]"
	update
}

proc save_c {curr} {
	global Srcname TW_Source

	if {$curr == 1 && $Srcname != ""} {
		return [writeoutfile $TW_Source $Srcname]
	}
	set fileselect "tk_getSaveFile"
	switch -- [set file [eval $fileselect]] "" return

	return [writeoutfile $TW_Source $file]
}

proc refresh_gui {} {
	global hidden io_only loops Depth memlim
	global pseq noend notfixed np_loops quality
	global shortest use_vals exhaustive asserts bounded z_Flag

	set gui_body ""

	if {$pseq     != {}} { set gui_body	"${gui_body}msc:	$pseq\n" }
	if {$hidden   != {}} { set gui_body	"${gui_body}hidden:	$hidden\n" }
	if {$io_only  != 0} { set gui_body	"${gui_body}io_only:	$io_only\n" }
	if {$loops    != 0} { set gui_body	"${gui_body}loops:	$loops\n" }
	if {$asserts  != 1} { set gui_body	"${gui_body}asserts:	$asserts\n" }
	if {$np_loops != 0} { set gui_body	"${gui_body}np_loops:	$np_loops\n" }
	if {$noend    != 1} { set gui_body	"${gui_body}noend:	$noend\n" }
	if {$use_vals != 0} { set gui_body	"${gui_body}use_vals:	$use_vals\n" }
	if {$Depth    != 1000} { set gui_body	"${gui_body}maxdepth:	$Depth\n" }
	if {$memlim   != 350} { set gui_body	"${gui_body}memlim:	$memlim\n" }
	if {$notfixed != 0} { set gui_body	"${gui_body}notfixed:	$notfixed\n" }
	if {$shortest != 0} { set gui_body	"${gui_body}shortest:	$shortest\n" }
	if {$bounded  != 0} { set gui_body	"${gui_body}bounded:	$bounded\n" }
	if {$exhaustive != 0} { set gui_body	"${gui_body}exhaustive:	$exhaustive\n" }
	if {$quality  != 3}  { set gui_body	"${gui_body}quality:	$quality\n" }
	if {$z_Flag   != ""} { set gui_body	"${gui_body}zflag:	1\n" }

	prx_putfragment "%GUI" "$gui_body"
}

proc save_prx {curr} {
	global fnm Fname TW_Prx PrxChanged

	refresh_gui

	set PrxChanged 0

	if {$curr == 1 && $fnm != ""} {
		if {[writeoutfile $TW_Prx ${fnm}prx]} {
			reopen_c ${fnm}prx	;# make sure new settings take hold
			return 1
		} else {
			return 0
	} 	}

	set fileselect "tk_getSaveFile"
	switch -- [set file [eval $fileselect]] "" return

	set Fname $file
	set oFname $file
	set pp [string last ".prx" $file]
	if {$pp > 0} {
		set fnm [string range $Fname 0 $pp]
	} else {
		set fnm "${Fname}.prx"
	}

	return [writeoutfile $TW_Prx $file]	;# no auto-update for a save-as
}

proc readinfile {into from {how 0}} {
	global has_lines

	if [catch {set fd [open $from r]} errmsg] {
		complain "readfile: $errmsg"
		return 0
	}

	catch { $into delete 0.0 end }

	while {[gets $fd line] > -1} {
		while {[string index $line end] == "\\"} {
			set line [string trimright $line "\\"]
			if {[gets $fd line2] > -1} {
				set line2 [string trimleft $line2 " \t"]
				set line "$line $line2"
			} else {
				break
		}	}
		if {$how} {
			if {[string first "# " $line] == 0} {
				continue
			}
			set j  [string length $line]
			for {set i 0} {$i <$j} { incr i } {
				set c [string index $line $i]
				if {$c != "\t" && $c != " "} {
					break
			}	}
			if {$i == $j} {
				continue
			}
		}
		catch { $into insert end $line\n }
	}
	catch { close $fd }

	set k [split $into "_"]
	set n [lindex $k 1]
	set m [lindex $k 2]
	catch	{ if {$has_lines($n,$m)} {
		refresh_lines $n $m
	}	}
	return 1
}

proc file_ok {f} {

	if {[file exists $f]} {
		if {![file isfile $f] || ![file writable $f]} {
			complain "error: file $f is not writable"
			return 0
	}	}
	return 1
}

proc writeoutfile {from to} {

	if ![file_ok $to] { return 0 }

	if [catch {set fd [open $to w]} errmsg] {
		complain "write: $errmsg"
		return 0
	}
	catch { puts $fd [string trimright [$from get 0.0 end] "\n"] } ;# rm redundant newlines at end
	close $fd
	return 1
}

proc help_verification {} {
	global FG BG

	catch {destroy .hv}
	toplevel .hv

	wm title .hv "Help with Verification"
	wm iconname .hv "Verification"

	frame .hv.top

	scrollbar .hv.top.s -command ".hv.top.t yview"

	text .hv.top.t \
		-yscrollcommand ".hv.top.s set" \
		-width 80 \
		-height 40 \
		-background $BG \
		-foreground $FG \
		-font {Helvetica 10 bold}
	pack append .hv.top .hv.top.s { right filly }
	pack append .hv.top .hv.top.t { left expand fill }

	.hv.top.t insert end "
Software Verification with FeaVer
=================================

A comprehensive User Guide is available as part of this
distribution as:

   Documentation/feaver.pdf

Read this User Guide for help on the definition of model
extraction commands, the creation of a test harness file
(a .prx file), setting up mapping (lookup) tables and for
help on deciding where to use model extraction, when to
link to externally defined C modules, or when to include
C code and C declarations into the model that is generated.

   FeaVer can instrument ANSI-C code to check properties of
   process behaviors under adverse circumstances, e.g.,
   with normally unpredictable interleavings of concurrent
   process executions.

   To begin, you must tell FeaVer which aspect of the concurrent
   process behavior has to be examined. If you have a 100,000
   line program, you cannot simply pass all of it to FeaVer
   and wait for the bug reports to roll in. Also, if the program
   executes sequentially, deterministically, and in a purely
   standalone way, then FeaVer is probably not the right tool
   to test it.

   If the program is concurrent, there probably are specific
   portions of the code that you will want to examine in detail
   under a range of circumstances that have to do with its
   robustness, given its interactions with or interference
   from other concurrently executing modules.  This type of
   application is traditionally hard to test, and it is the
   ideal application for FeaVer.

   Begin by identifying which concurrent process behaviors must
   be examined, and under which circumstances. Determine on
   which components the focus of the check will be placed and
   determine if other components can be simplified or can
   perhaps be replaced by test drivers or test stubs.
   Next determine which source code is executed by the processes
   that will be examined, and determine how these processes
   (both real processes and test drivers) communicate.
   All this infrastructure information is then captured in a
   test harness.

The basic sequence of steps in performing system tests is
approximately as follows.  Most of these steps happen
automatically when the test harness is fully defined.
Most of the components of the test harness referred to here
can be defined with support from the graphical user interface.

1. define the test harness (prx file)
	select processes to be tested (%X commands)
	define how they communicate (define chan and proctypes)
2. generate the initial luts (modex -Y -k ...)
	repair modex parser complaints
3. adjust the luts (adding %L to the prx file)
	minimally do syntax conversion for send/recv
	lifting process communications to test harness
4. generate the model (modex ..., cpp result)
	go through each proctype in _modex_out and adjust luts
5. generate the model checker (spin -a)
	adjust variable declarations (Suppres, %D, run parameters)
6. compile the model checker (cc pan.c)
	repair c-compiler complaints
	final adjustments to variable declarations
7. run the check (pan)
	repair error scenarios
	adjust behavior/test harness to get complete coverage

Summary of Prx Commands:

   System:
   %P	promela segment, system infrastructure

   C-context:
   %H  c-header information for generated code
   %C	c-code segment
   %D	c-data declarations segment
   %O  c-linkage options (e.g., external .o files)

   Model Extraction:
   %F	set target source-file for %X commands
   %L	defines mapping tables for %X commands
   %X	model extraction command

   GUI parameters:
   %G	set persistant parameters for gui

   Property related:
   %TC constraint definition for timelines
   %TE event definition for timelines


"
	button .hv.b -text "Ok" -command {destroy .hv}
	pack append .hv .hv.top {top expand fill}
	pack append .hv .hv.b {top}
}

proc help_timeline {} {
	global FG BG

	catch {destroy .ht}
	toplevel .ht

	wm title .ht "Help with Verification"
	wm iconname .ht "Verification"

	frame .ht.top

	scrollbar .ht.top.s -command ".ht.top.t yview"

	text .ht.top.t \
		-yscrollcommand ".ht.top.s set" \
		-width 80 \
		-height 40 \
		-background $BG \
		-foreground $FG \
		-font {Helvetica 10 bold}
	pack append .ht.top .ht.top.s { right filly }
	pack append .ht.top .ht.top.t { left expand fill }

	.ht.top.t insert end "
Use of the TimeLine Editor
==========================

Purpose:
   The timeline editor is a visual tool for expressing properties
   of distributed systems. A property is a formalized requirement on
   the behavior of a distributed system. The property is composed of
   a sequence of system events and the temporal (time) relations between
   these events. A requirement may be sufficient to specify what should
   be implemented, but a property (formalized requirement) is needed
   to thoroughly check the implemented system to ascertain that the
   original requirement is satisfied. Thorough checks of systems can
   only be performed using Model Checking. If Model Checking shows that
   a property is satisfied, it can be relied upon that no execution of
   system, no matter what the particular interleaving of events or the
   speeds of independent processes, can violate the property.
   
   The timeline editor can convert graphical properties to a corresponding 
   Buchi automaton used by the Spin model checker. Spin thoroughly checks
   the property against the system model and reports any violations
   of the property (system executions that match the negated version
   of the property) as an error trace. In the FeaVer system the system
   model is extracted directly from the ANSI C source code of the system.
   Error traces produced by FeaVer/Spin, are execution traces through
   the source code that lead to the error.

Overview:
   The timeline is the thick horizontal bar close to the top of
   the drawing canvas. Time progresses to the right on the timeline.
   To get a blank timeline, select File-New from the dashboard. Along
   with the timeline are vertical bars. These are 'marks', which represent
   system execution steps, not clock ticks -- software model checking
   does not use a system clock.
   Marks are the placed where events are attached. 
 
   There are two types of system events in a property: They are:

   regular events -- denoted by a down arrow with a large,
   	black 'e'. These are non-deterministic events,
   	typically input from users or external entities.
   	Examples, for telephony features: onhooks, offhooks,
   	and incoming calls.

   required events -- denoted by a down arrow with a large,
   	black 'r'. These are events that are required in
   	response to previous events and constraints that
   	have been detected. It is an error if required
   	events are not detected.

   In addition to events, there are also constraints. Contraints are
   things, such as not receiving a particular event, that must
   persist over certain intervals of the property. For instance,
   if there is a requirement that the system must respond to an
   offhook by providing dialtone, there needs to be a constraint:
   'no onhook' defined for the interval between when the offhook
   occurs and when dialtone is provided, otherwise, many executions
   of no interest (mainly all those with onhooks) will be explored
   during the check. A constraint, denoted as a horizontal line,
   starts at one mark, and ends at the same or another mark.
   A constraint may or may not include the mark to which its end point
   is assigned.

   Marks are the blue, vertical lines on which events are placed.
   Each mark can only have one event. Marks are not clock ticks,
   but rather are event ticks. If event e1 is assigned to mark 1,
   and event e2 is assigned to mark 2, we know nothing about the
   interval of time between events e1 and e2. We do know that
   that e1 precedes e2 and that there are no other
   events of interest to our property that occur between e1 and e2.
   There may be other events between e1 and e2 that are not of
   interest to our property, but we do not know how many of these
   events, if any, occur between the occurance of e1 and e2.
	
Adding a new event:
   Determine the type of event you need, then select
   Edit-Event or Edit-Required Event.
   select the mark to which the event is to be assigned,
   label the event, then move the mouse button. There must
   be an empty mark available in order to add a new event.

Adding a constraint:
   Select Edit-Constraint. Using the select button
   of your mouse, select and hold down the button over the
   initial mark. Move the mouse to the end mark and release.
   select the mark to which the constraint is to be assigned,
   Enter a label for the constraint then move the mouse.

Deleting events and constraints:
   Choose the Edit-Select from the dashboard. Select the item
   to be deleted. Click the menu mouse button. Select 'delete'
   from the popup menu then release the menu mouse button.
   Note: there is no undo.

Moving events and constraints using the mouse:
   Select Edit-Select from the dashboard. Select the item
   to be moved. Move the cursor horizontally to the new position.
   Release the select button to complete the move. Events may
   be moved horizontally. Constraints may be moved vertically
   and horizontally.

Editing	event or constraint attributes using the Edit Window:
   Choose Edit-Select from the dashboard. Select the item
   to be modified. With the cursor positioned over the selected
   item, depress the menu mouse button. Select 'edit' from the
   popup menu. The 'Edit' window will appear. Change
   the description by entering new text in the Description field. For events,
   change the type of event by selecting the radio box associated with the
   desired event. For constraints, include or exclude the begin or end
   mark by selecting the appropriate radio box. Save changes by
   selecting the 'OK' button.

Including and Excluding Begin and End marks of
a constraint using the mouse:
   Choose Edit-Select from the dashboard. Select the constraint
   desired. With the cursor positioned over the selected constraint,
   depress the menu mouse button. Select 'include begin mark' to
   include the begin mark of the constraint. This means that the
   constraint specified must hold at the step where any event assigned
   to the begin mark occurs. Select 'exclude begin mark' to exclude
   the begin mark of the constraint. This means that the constraint
   specified does not have to hold at the step where any event assigned
   to the begin mark occurs. However, the constraint must hold at the
   next step after the begin mark of the constraint. Select 'include end
   mark' to include the end mark in the constraint. This means that the
   constraint must hold when any event assigned to the end mark occurs.
   Select 'exlude end mark' to exclude the end mark in the constraint.
   This means that the constraint does not have to hold when any event
   assigned to the end mark ocurs.

Relabeling an Event or Contraint using the mouse:
   Choose Edit-Select from the dashboard. Select the desired label.
   A flashing vertical bar will appear at the end of the label text
   and the label text will appear in red. Use the keyboard navigation
   keys or the mouse to move the insertion point. Modify the text
   then move the mouse to replace the label.

Adding a mark:
   To add a new mark, select Edit-New Mark from the
   dashboard. Position the cursor anywhere along the horizontal
   bar of the timeline where the new mark is desired. Depress the select
   button of the mouse to insert the new mark. Existing marks to the
   right of the inserted mark will be moved to the right to
   accommodate the new mark.

Deleting a mark:
   To delete a mark, position the cursor over the vertical line
   of the mark to be deleted. Depress the mouse menu button and
   select 'delete mark' from the popup menu. Any event assigned
   the mark will be deleted. Conditions assigned to or spanning
   the deleted mark will be adjusted.

Outcome:
   The outcome specifies whether the property as stated
   should pass or should fail and is controlled by the radio buttons
   under 'Outcome'. If the property should 'pass' any executions that
   violate the property will be flagged as errors. If the
   property should 'fail', any executions that satisfy the property
   will be flagged as errors. Select the appropriate radio 
   button under 'Outcome' to.

Printing to file:
   The timeline tool can print a graphical version of the
   timeline property to a file, either in postscript or
   GIF format. To print the graphical version to a printer, you
   could import the .gif version into a graphical editor
   (i.e. PowerPoint or FrameMaker) and use the device printing
   facility of one of those applications, or you could use an
   image editor (e.g., Photoshop, Photo Editor). To print to file,
   select File-Print Postscript or File-Print GIF. If the current
   property has already been saved the .ps or .gif file will
   be in the same directory. The original filename will have a
   .ps or .gif appended to it. If the current property has not been saved,
   the postscript or GIF version will be in default.(gif/ps) in the 
   working directory.

Generating Automata:
   To convert the timeline property to an equivalent never
   claim (i.e. test automata) that can be used by the Spin
   model checker, select either:
   
        Tools-Generate Deterministic Automata
             
             The deterministic version of the test automata will
             not ignore an occurence of the first non-required event.

        Tools-Generate Non-deterministic Automata

             The non-deterministic version of the test automata will
             cause Spin to ignore the occurence of the first non-required
             event, and to wait and begin the check on a subsequent occurence
             first non-required event. The effect of non-determinism is only
             apparent on the first non-required event of the timeline and
             has the effect of broadening the scope of the check to include
             all occurences of the first non-required event.

             For example for a simple property with 'offhook' as the first
             non-required event, and a required event 'dialtone' as a
             required event at the second mark, non-determinism would
             allow the model checker to check that dialtone was provided
             each time the offhook occurs in a system execution.

   The test automata will reflect the current contents of the timeline window,
   not the last saved version of the timeline.	
   
   A graphical version of this automata is presented in a window entitled
   'Graphical Automata'. The graphical depection of the test automata
   is 'view only' (i.e. it can't be printed).

   The corresponding never claim will be saved to the file of the form:
        
        <filename>_<automata-type>.aut

   Where filename is the prefix of the filename (this will be 'default'
   if the timeline hasn't been saved yet), automata-type is 'non', for
   non-deterministic, or 'det' for deterministic.

   The .aut file will be saved in the current working directory.

   To see the 'never claim' version that was saved to the .aut file,
   select the 'never claim' button in the Graphical Automata window.
"
	button .ht.b -text "Ok" -command {destroy .ht}
	pack append .ht .ht.top {top expand fill}
	pack append .ht .ht.b {top}
}

proc about_spin {} {
	global FG BG

	catch {destroy .as}
	toplevel .as

	wm title .as "Help with Verification"
	wm iconname .as "Verification"

	frame .as.top

	scrollbar .as.top.s -command ".as.top.t yview"

	text .as.top.t \
		-yscrollcommand ".as.top.s set" \
		-width 60 \
		-height 7 \
		-background $BG \
		-foreground $FG \
		-font {Helvetica 10 bold}
	pack append .as.top .as.top.s { right filly }
	pack append .as.top .as.top.t { left expand fill }

	.as.top.t insert end "
All information about Spin Version 4, which is used
by FeaVer as a background tool, can be found at the
following website:

	http://spinroot.com/spin/whatispin.html
"
	button .as.b -text "Ok" -command {destroy .as}
	pack append .as .as.top {top expand fill}
	pack append .as .as.b {top}
}

proc about_feaver {} {
	global FG BG xversion

	catch {destroy .af}
	toplevel .af

	wm title .af "Help with Verification"
	wm iconname .af "Verification"

	frame .af.top

	scrollbar .af.top.s -command ".af.top.t yview"

	text .af.top.t \
		-yscrollcommand ".af.top.s set" \
		-width 80 \
		-height 40 \
		-background $BG \
		-foreground $FG \
		-font {Helvetica 10 bold}
	pack append .af.top .af.top.s { right filly }
	pack append .af.top .af.top.t { left expand fill }

	.af.top.t insert end "
FeaVer Version $xversion

Feaver is a user-interface that gives access to tools for the
verification of multi-threaded, concurrent, or distributed systems
code written that is written in ANSI-standard C.

This interface has no functionality itself, but it can
synthesize, execute, and displays the results of commands that
for several background tools:

	MODEX -- a model extractor for generating Spin models
		 from ANSI-C code guided by a test harness),
	SPIN  -- a logic model checker (version 4.0 or later),
	TIMEEDIT -- a timeline editor for property specification.

Also needed are access to general Unix-like tools (grep, mv, cp,
rm), and an ANSI standard C compiler.

There is also a simpler shell script available (feaver_cmd) that
can interpret the test harness files.
Experienced users can bypass this interface and work directly with
the background tools for specialized tasks.

Navigation:
---------------
In text windows use ctl-x, ctl-c, ctl-v to Cut, Copy, and Paste.
(On Unix, use ctl-y instead of ctl-v.)

Hold button-2 on a 3-button mouse down to pan or scroll a window.
Alternatively, use the View Menu to enable scrollbars on all windows.


Disclaimer:
------------
This code is (c) 2000-2003 by Bell Laboratories, Lucent Technologies. 
No guarantee whatsoever is expressed or implied by the distribution
of this code. All rights are reserved. This software is for research
and educational purposes only.
"
	button .af.b -text "Ok" -command {destroy .af}
	pack append .af .af.top {top expand fill}
	pack append .af .af.b {top}
}

proc dohelp {} {
	global FG BG helpfile
	global ind old_ss

	set hex [catch {.help cget -background}]
	if {!$hex} { focus .help; return } ;# help window exists

	set helptabs ""
	set h [toplevel .help]
	wm title $h "Help"
	set t [frame $h.top -height 10 -bg black]

	pack $t -side top -expand 1 -fill both
	label $t.l -text "Search for: " -bg black -fg white
	pack $t.l -side left
	entry $t.e -width 20 -bg white -fg black
	pack $t.e -side left
	button $t.b -text Find -command search_help
	pack $t.b -side left -padx 4
	set f [frame $h.f]
	pack $f -side top -expand 1 -fill both
	text $f.txt -relief raised \
		-font {Helvetica 12} \
		-tabs {2c left} -bd 2 -height 20 -width 60 \
		-wrap word -bg black -fg gold
	pack $f.txt -side top -expand 1
	canvas $f.c -width 1 -height 20
	pack $f.c -side top -expand 1 -fill x
	set b [frame $f.bottom]
	pack $b -side top -expand 1 -fill both
	button $b.b_close -text "Dismiss" -command "destroy $h"
	pack $b.b_close -side top -padx 5 -pady 5

	append errmsg "Couldn't find help file $helpfile"

	#bind $h <Destroy> "mode Help off $wtag"
	if [catch {set hf [open $helpfile r]} errmsg] {
  		complain $errmsg
		catch {destroy $f}
  		return 0
 	}
	
	while {[gets $hf line] >=0} {
		set firstchar [string index $line 0]
		if {$firstchar != "#"} {
			if {[lindex $line 0] == "HELPTYPE"} {
				set curtab [lindex $line 1]
				set text($curtab) ""
				lappend helptabs $curtab
			} else {
				catch {append text($curtab) $line "\n"}
	}	}	}

	set tabw 85
	set tabh 18 
	set nhtabs [llength $helptabs]
	for {set i 0} {$i < $nhtabs} {incr i 1} {
		set tabname [lindex $helptabs $i]
		set tabnumber [expr $i + 1]
		$f.c create polygon [expr ($i * $tabw) - 3] 0 \
				[expr ($i * $tabw) + 3] $tabh \
				[expr ($i * $tabw) + $tabw - 3] $tabh \
				[expr ($i * $tabw) + $tabw + 3] 0 \
				[expr ($i * $tabw) - 3] 0 \
				-tags tab_$tabname -fill white -outline black
		$f.c create text [expr ($i * $tabw) + ($tabw / 2)] [expr $tabh / 2] \
			-text $tabname -anchor center -tags tab_$tabname
		$f.c bind tab_$tabname <1> "
			$f.c raise tab_$tabname
			$f.txt delete 1.0 end
			$f.txt insert end {$text($tabname)}
			set ind 1.0
			set old_ss ''
			"
	}
	#default
	set deftab [lindex $helptabs 0]
	$f.c raise tab_$deftab
	$f.txt insert end "$text($deftab)"
	set ind 1.0
	set old_ss ""
}

proc search_help {} {
	global ind old_ss

	set t ".help.f.txt"
	set ss [.help.top.e get]

	if {$ss == ""} { return }

	if {$old_ss != $ss} {
		set ind 1.0
	}
	set ind [$t search $ss $ind]
	set old_ss $ss
	if {$ind != ""} {
		$t yview -pickplace $ind
		$t tag configure hilite -foreground black -background white
		$t tag delete hilite 
		set split_ind [split $ind "."]
		set char [lindex $split_ind 1]	
		set char [incr char [string length $ss]]
		set indstart $ind
		set indend ""
		append indend [lindex $split_ind 0] "." $char
		$t tag add hilite $indstart $indend
		$t tag configure hilite -foreground white -background black

		#$t tag bind hilite <1> "
		#	complain {ouch - you touched $ss - that hurt!}
		#	"
		#$t tag bind hilite <Enter> "$t config -cursor arrow"
		#$t tag bind hilite <Leave> "$t config -cursor xterm"

		set ind $indend	
	} else {
		complain "no match for $ss"
	}	
}

proc bind_out {} {
	global TW_Out TW_Source Srcname

	set t $TW_Out
	$t tag delete all

	set ind 1.0
	set lastline 0
	set lastchar 0

	set stmnt 0
	set decl 0

	while {1} {
		set ind [$t search -regexp {:[0-9]+:} $ind]

		if {$ind == ""} { break }

		set split_ind [split $ind "."]
		set nextline [lindex $split_ind 0]
		set nextchar [lindex $split_ind 1]

		if {$nextline < $lastline} { break } ;# wrap
		if {$nextline == $lastline \
		&&  $nextchar <= $lastchar} { break }

		set lastline $nextline
		set lastchar $nextchar

		set char   $nextchar	
		set indend $nextline

		scan [$t get $ind $indend.end] ":%d:" lnr

		set indstart "${nextline}.0"
		set indend   "${nextline}.end"

		set decl  [$t search -exact "declaration" $nextline.0 $nextline.end]

		$t tag add hilite$ind $indstart $indend

		if {$decl != "" && $stmnt != ""} {
			$TW_Source tag add path$ind $lnr.0 $stmnt.end
		}

		$t tag bind hilite$ind <Enter> "
			$t tag configure hilite$ind \
				-foreground white -background blue
			$TW_Source tag configure path$ind \
				-foreground red -background white
		"
		$t tag bind hilite$ind <Leave> "
			$t tag configure hilite$ind \
				-foreground blue -background white
			$TW_Source tag configure path$ind \
				-foreground blue -background white
		"

		$t tag bind hilite$ind <1> "
			$TW_Source yview -pickplace $lnr.0
			$TW_Source tag delete show
			$TW_Source tag add show $lnr.0 $lnr.end
			$TW_Source tag configure all \
				-foreground blue -background white
			$TW_Source tag configure show \
				-foreground red -background white
		"
		set ind $indend
		set stmnt [$t search -exact "statement"   $nextline.0 $nextline.end]
		if {$stmnt != ""} { set stmnt $lnr }
	}
}

proc bind_lines {} {
	global TW_Stats TW_Model

	set t $TW_Stats
	$t tag delete all

	set ind 1.0
	set lastline 0
	set lastchar 0
	while {1} {
		set ind [$t search -regexp {line [0-9]+} $ind]

		if {$ind == ""} { break }

		set split_ind [split $ind "."]
		set nextline [lindex $split_ind 0]
		set nextchar [lindex $split_ind 1]

		if {$nextline < $lastline} { break } ;# wrap
		if {$nextline == $lastline \
		&&  $nextchar <= $lastchar} { break }

		set lastline $nextline
		set lastchar $nextchar

		set char   $nextchar	
		set indend $nextline

		scan [$t get $ind $indend.end] "line %d" lnr

		set char [incr char [string length "line"]]
		set indstart $ind
		append indend  "." $char

		$t tag add hilite$ind $indstart $indend

		$t tag bind hilite$ind <1> "
			$TW_Model yview -pickplace $lnr.0
		"
		$t tag bind hilite$ind <Enter> "
			$t tag configure hilite$ind \
				-foreground white -background black
		"
		$t tag bind hilite$ind <Leave> "
			$t tag configure hilite$ind \
				-foreground black -background white
		"
		set ind $indend
	}
}

proc mkcanvas {pn n m W H suff} {
	global FG BG

	catch { destroy $pn }

	toplevel $pn -bg black

	wm title $pn "$n"
	wm iconname $pn $m
	wm minsize $pn 100 100

	set cv [canvas $pn.c  -relief raised -bd 2\
		-scrollregion {-15c -5c 30c 40c} \
		-background $BG \
		-width $W -height $H \
		-xscrollcommand "$pn.hscroll set" \
		-yscrollcommand "$pn.vscroll set"]
	scrollbar $pn.vscroll -relief sunken \
		-background SkyBlue4 \
		-command "$pn.c yview"
	scrollbar $pn.hscroll -relief sunken -orient horiz \
		-background SkyBlue4 \
		-command "$pn.c xview"

	frame $pn.b -bg SkyBlue4

	button $pn.b.b1 \
		-bg SkyBlue4 -fg gold \
		-relief raised -border 4 \
		-text "Dismiss" \
		-command "destroy $pn"
	button $pn.b.b2 \
		-bg SkyBlue4 -fg gold \
		-text "Save in $m$suff" \
		-command "destroy $pn.b.b2; show_ascii $m$suff"

	pack append $pn.b \
		$pn.b.b1 {left} \
		$pn.b.b2 {left}

	pack append $pn \
		$pn.b {bottom padx 5}

	pack append $pn \
		$pn.vscroll {right filly} \
		$pn.hscroll {bottom fillx} \
		$pn.c {top expand fill}

	bind $cv <2> "$cv scan mark %x %y"
	bind $cv <B2-Motion> "$cv scan dragto %x %y"

	tkwait visibility $pn
}

proc mark_unreachedcode {w v} {	;# NEW

	scan [$w index end] %d numLines
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]

		if {[string first "line" $line] >= 0} {
			set nr [scan $line "	line %d, state %d, \"%s\"" lno sno code]
			if {$nr != 3} { continue }
			set a [string first "\"" $line]
			set code [string range $line $a end]
			if {[string first "-end-" $code] == -1} {
				$v insert $lno.end "<<$code>>"
			}
			$v tag add hilite $lno.0 $lno.end
	}	}
	$v tag configure hilite -background white -foreground red
}

set PanPid 0
set PanRunning 0
set PanKilled 0

proc stop_pan {} {
	global Unix PanRunning PanPid PanKilled

	if {$PanRunning && $PanPid > 0 && $PanKilled == 0} {
		if {$Unix} {
			catch { eval exec kill -INT $PanPid }
		} else {
			catch { eval exec kill -s INT $PanPid }
		}
		set PanKilled 1
	}
}

proc has_accept {f} {

	if [catch {set fd [open $f r]} errmsg] {
		complain "has_accept: $errmsg"
		return 0
	}
	set result 0
	while {[gets $fd line] > -1} {
		if {[string first "accept" $line] >= 0} {
			set result 1
			break
	}	}
	catch { close $fd }

	return $result
}

proc pan_c {} {
	global Depth TW_Out TW_Model TW_Info TW_Log loops np_loops noend quality
	global PanRunning PanPid PanKilled LastTxt exhaustive aut_loops shortest
	global bounded asserts

	if {$exhaustive} {
		set bitstate 18	;# local var
	} else {
		switch $quality {
		0	{ set bitstate 18 }
		1	{ set bitstate 19 }
		2	{ set bitstate 21 }
		3	{ set bitstate 24 }
		4	{ set bitstate 27 }
		5	{ set bitstate 30 }
		6	{ set exhaustive 1 }
		}
	}
	progress "Running"

	rmfile core
	for {set curwidth 18} {$curwidth <= $bitstate} {incr curwidth} {

		set extra "-v -Y -e -c10 -m$Depth"	;# report 10 errors max
		if {$bounded} {
			set extra "$extra -b"
		}
		if {$exhaustive == 0} {
			set extra "$extra -w$curwidth"
		}
		if {$loops || $aut_loops} {
			if {[has_accept _modex_out]} {
				set extra "$extra -a"
		}	}
		if {$np_loops}	{set extra "$extra -l"}
		if {$asserts == 0} 	{set extra "$extra -A"}
		if {$noend} 	{set extra "$extra -E"}
		if {$shortest}	{set extra "$extra -i"}
	
		catch { eval exec rm -f _modex_out.trail }

		if {$bitstate} {
			set from [expr $curwidth - 17]
			set upto [expr $bitstate - 17]
			catch { $TW_Info itemconfigure $LastTxt -text "(Level $from of $upto)" }
			update
		}

		$TW_Log insert end "pan $extra\n"
		catch { eval exec pan $extra >&feaver.tmp &} PanPid
	
		set PanRunning 1
		set PanKilled 0
		.top.run configure -text "(Stop)" -command { stop_pan }
		update

		$TW_Out insert 1.0 "Running -- updates will appear here...\n"
		while {1} {
			after 750
			if {[file exists feaver.tmp] \
			&&  [file size feaver.tmp] > 0} {
				readinfile $TW_Out feaver.tmp
				if {[has_string $TW_Out "end of output"] \
				||  [has_string $TW_Out "Valid Options"]} {
					set PanRunning 0
					break
			}	}
			if {[file exists core]} {
				set PanRunning 0
				set PanKilled 1
				readinfile $TW_Out feaver.tmp
				progress "Core Dump Detected"
				break
			}
			update
		}
	
		set f {}
		catch { set f [glob *.trail] }
		catch { destroy .top.trails }
	
		if {[llength $f] > 0} { break }

		if {$PanKilled} { break }
	}
	.top.run configure -text "Check" -command { spin_c }

	catch {
		$TW_Model configure -state normal
		mark_unreachedcode $TW_Out $TW_Model
		$TW_Model configure -state disabled
	}

	if {[llength $f] == 0} { return 0 }

	menubutton .top.trails -bg red -fg white -text "Traces.." \
		-activeforeground red -activebackground white \
		-relief raised -menu .top.trails.m
	pack .top.trails -fill y -side right

	menu .top.trails.m -tearoff 1

	for {set i 0} {$i < [llength $f]} {incr i} {
		set nm [lindex $f $i]
		.top.trails.m add command \
			-label "Error $i" \
			-command "prep_pan_c $nm $i"
	}
	prep_pan_c [lindex $f 0] 0

	return $i
}

set CurNr 0

proc prep_pan_c {nm nr {how 1}} {
	global TW_Stats CMD Unix
	if {$nm != "_modex_.trail"} {
		if {$Unix} {
			catch {eval exec cp $nm "_modex_out.trail"}
		} else {
			catch {exec $CMD /c copy $nm "_modex_out.trail"}
	}	}
	catch {eval exec pan -g >&trail.out} errmsg
	if {[string length $errmsg]>0} {
		complain "prep: $errmsg"
	#	continue
	}
	readinfile $TW_Stats trail.out
	bind_lines
	show_matches $TW_Stats "processes "

	set CurNr $nr
	act_pan_c trail.out $CurNr $how

	show_ascii feaver.non 0

	put_on_top 3 3
}

proc viewlut {nm} {
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]

		if {[string compare "%L $nm" $line] == 0} {
			$w tag add hilite $i.0 $i.end
			$w tag configure hilite -background ivory -foreground red
			$w yview -pickplace [expr $i - 1]
			put_on_top 2 5
			break
	}	}
}

proc sameuptotabs {a b} {

	set n [string first "\t" $a]
	set p [string range $a 0 [expr $n - 1]]
	set q [string range $a $n end]
	set q [string trim $q "\t"]
	set na "$p\t$q"

	set n [string first "\t" $b]
	set p [string range $b 0 [expr $n - 1]]
	set q [string range $b $n end]
	set q [string trim $q "\t"]
	set nb "$p\t$q"

	return [string compare $na $nb]
}

proc extendlut {nm ne isnew} {
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines

	if {$nm == "all" || $nm == "(default)"} {
		set anylut 1
	} else {
		set anylut 0
	}

	set inlut 0
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]

		if {[string length $line] == 0} { continue }

		if {($anylut == 1 && [string match "%L" $line] == 1) \
		||  ($anylut == 0 && [string match "%L $nm" $line] == 1)} {
			$w tag add hilite $i.0 $i.end
			$w tag configure hilite -background white -foreground red
			$w yview -pickplace [expr $i - 1]
			put_on_top 2 5
			set inlut 1
			continue
		}
		if {$inlut == 0} { continue }

		if {[string compare "%%" $line] == 0
		||  [string first "%L" $line]   == 0} {
			if {$isnew} {
				$w insert $i.0 $ne\n
				$w tag add hilite $i.0 $i.end
				$w tag configure hilite -background white -foreground red
				incr numLines
			}
	#		set inlut 0
			break
		}

		if {$isnew == 0} {
			if {[sameuptotabs $ne $line] == 0} {
				set isnew 1
				set ne "## $ne"
				$w delete $i.0 [expr $i+1].0
				incr numLines -1
				incr i -1
		}	}
	}
	if {$inlut == 0} {			;# didn't find the lut
		if {$nm == "all"} {
			set N ""
		} else {
			set N " $nm"
		}
		prx_putfragment "%L$N" "$ne" 1	;# create it
	}
}

proc replace_fname {nm rt} {
	global TW_Prx

	set w $TW_Prx
	scan [$w index end] %d numLines

	set cnt 0
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]

		if {[string compare "%F $nm" $line] == 0} {
			$w delete $i.0 $i.end
			$w insert $i.0 "%F $rt"
			$w tag add hilite $i.0 $i.end
			$w tag configure hilite -background ivory -foreground red
			$w yview -pickplace [expr $i - 1]
			put_on_top 2 5
			incr cnt
	}	}
}

proc has_string {w s} {

	scan [$w index end] %d numLines
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]

		if {[string first "$s" $line] >= 0} {
			return 1
	}	}
	return 0
}

proc replace_entry {w olt lt rt nm} {	;# find entry in w for olt, replace it with lt

	scan [$w index end] %d numLines

	set startat 0
	set startfull 0
	set stopat $numLines
	set stopfull $numLines
	set cnt 0

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]

		if {[string compare "%L $nm" $line] == 0} {
			set startfull [expr $i+1]
		}
		if {[string compare "%L" $line] == 0} {
			set startat [expr $i+1]
		}
		if {[string compare "%%" $line] == 0} {
			if {$startat > 0 && $stopat == $numLines} {
				set stopat $i
			}
			if {$startfull > 0 && $stopfull == $numLines} {
				set stopfull $i
				break
	}	}	}

	if {$startfull > 0} {	;# expected case
		set startat $startfull
		set stopat $stopfull
	} else {
		if {$startat == 0} {
			complain "No LUT for $nm and no default LUT"
			return -1	;# failure
	}	}

	set otherluts ""
	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		set line [$w get last "last lineend"]
		set line [string trimright $line "\n\r"]

		if {[string first "%L" $line] == 0} {
			set thislut $line
		}
		if {[string compare "%%" $line] == 0} {
			set thislut ""
		}
		if {[string first "$olt" $line] >= 0} {
			incr cnt
			if {$i < $startat || $i > $stopat} {
				set otherluts "$otherluts $thislut"
			} else {
				if {[string length "$rt"] > 0} {
					$w delete $i.0 $i.end
					$w insert $i.0 "$lt			$rt"

			#		set a [string first "$olt" $line]
			#		set b [expr $a + [string length "$olt"]]
			#		$w delete $i.$b $i.end
			#		$w insert $i.$b "			$rt"
				} else {
					$w insert $i.0 "## "
			}	}
			$w tag add hilite $i.0 $i.end
			$w yview -pickplace [expr $i - 1]
	}	}
	$w tag configure hilite -background ivory -foreground red

	if {$cnt == 0} {	;# add it
		$w insert $stopat.0 "$lt			${rt}\n"
		return 1
	}

	if {$cnt != 1} {
		complain "$cnt matches for \"$olt\" $otherluts"
		return 2	;# multiple matches
	}
	return 0	;# success
}

set lastpattern ""

proc show_matches {w pattern} {	;# Tcl/Tk book, page 219
	global lno lastpattern

	if {[string equal "$pattern" "$lastpattern"] == 0} {
		set lno 0
	}

	scan [$w index end] %d numLines
	$w tag delete hilite 1.0 $numLines.end

	for {set i 1} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		if {[regexp -indices "$pattern" \
			[$w get last "last lineend"] indices]} {
				$w mark set first \
					"last + [lindex $indices 0] chars"
				$w mark set last "last + 1 chars \
					+ [lindex $indices 1] chars"
			$w tag add hilite $i.0 $i.end
			$w tag configure hilite -background ivory -foreground red
	}	}

	for {set i [expr $lno+1]} {$i < $numLines} { incr i} {
		$w mark set last $i.0
		if {[regexp -indices "$pattern" \
			[$w get last "last lineend"] indices]} {
				$w mark set first \
					"last + [lindex $indices 0] chars"
				$w mark set last "last + 1 chars \
					+ [lindex $indices 1] chars"
			$w yview -pickplace [expr $i - 1]
			set lno $i
			set lastpattern $pattern
			return 1
	}	}
	for {set i 1} {$i <= $lno} { incr i} {
		$w mark set last $i.0
		if {[regexp -indices "$pattern" \
			[$w get last "last lineend"] indices]} {
				$w mark set first \
					"last + [lindex $indices 0] chars"
				$w mark set last "last + 1 chars \
					+ [lindex $indices 1] chars"
			$w yview -pickplace [expr $i - 1]
			set lno $i
			set lastpattern $pattern
			return 1
	}	}
	set lastpattern $pattern
#	complain "No Match of \"$pattern\""
	return 0
}

set minp 0
set maxp 0

proc act_pan_c {f nr how} {
	global Act_as Act_by B_sent
	global FG BG XSZ YSZ CyclePoint
	global Sent_as Sent_at Sent_by
	global Recv_as Recv_at Recv_by
	global N pid pline Matrix verdict
	global pseq io_only xFactor
	global hidden use_vals minp maxp maxN maxW

	set verdict ""
	catch { foreach i [array names Act_as] { unset Act_as($i) } }
	catch { foreach i [array names Act_by] { unset Act_by($i) } }
	catch { foreach i [array names B_sent] { unset B_sent($i) } }
	set maxh [expr [winfo screenheight .] - (350+120)]	;# borders+buttons

	if [catch {set fd [open $f r]} errmsg] {
		complain "act: $errmsg"
		return
	}

	set N 0
	set maxp 0
	set minp 0
	set maxN 0
	set maxW 0
	set lasttype -1
	set CyclePoint -1

	bind . <Configure> ""

	while {[eof $fd] == 0 && [gets $fd line] > -1} {
		if {[string length $line] <= 0} {
			continue
		}
		if {[string first "pan: precondition false" $line] >= 0} {
			set verdict "$line"
			continue
		}
		if {$verdict == "" && [string first "pan: error" $line] >= 0} {
			set verdict "$line"
			continue
		}
		if {[string first "#processes" $line] == 0} {
			break
		}
		if {[string first "START OF CYCLE" $line] >= 0} {
			incr N
			set lasttype -1
			set CyclePoint $N
			continue
		}
		set pln 0
		set ns [scan $line "%d: proc %d (%s line %d " pstp pno pname pln]
		if {$ns == 4} {
			set pname [string trim $pname "()"]
			set pid($pno) $pname

			if {$pno > $maxp} { set maxp $pno }
			if {$pno < $minp} { set minp $pno }
		}

		set x [string first "values: " $line]
		if {$x <= 0} {
			set lasttype -1
			if {$io_only == 0 \
			||  [string first "printf('MSC: " $line] > 0} {
				set x [string first "\[" $line]
				set y [string last  "\]" $line]
				if {$x < 0 || $y < 0} {
					continue
				}
				incr N
				set stmnt [string range $line $x $y]
				set stmnt [string trim $stmnt "\[\]"]

				set Act_as($N) $stmnt
				set Act_by($N) $pno
				set q [string length $stmnt]
				if {$q > $maxW} { set maxW $q }
			}
			continue
		}

		set stmnt [string range $line [expr $x+8] end]
		set x  [string first "!" $stmnt]
		if {$x <= 0} {
			set x  [string first "?" $stmnt]
			set issend 0
		} else {
			set issend 1
		}
		if {$lasttype != 1 \
		||  $issend == 1} {	;# unless recv follows send
			incr N
		}
		set lasttype $issend

		incr x
		set Mcont [string range $stmnt $x end]
		set vals [string trim $stmnt "\[\]"]

		if {$issend} {
			scan $vals "%d!%s" qno args
		} else {
			scan $vals "%d?%s" qno args
		}

		gets $fd line
		set x [string first "\[" $line]
		set y [string last  "\]" $line]
		set stmnt [string range $line $x $y]
		set stmnt [string trim $stmnt "\[\]"]

		if {[string first "D_STEP" $stmnt] >= 0} {
			set stmnt "--"
		}

		scan $line "%d: proc %d (%s line %d " pstp pno pname pln

		set pname [string trim $pname "()"]
		set pid($pno) $pname	;# :$pno"

		if {$pno > $maxp} { set maxp $pno }
		if {$pno < $minp} { set minp $pno }

		if {$issend} {
			if {[info exists B_sent($qno)] == 0} {
				set B_sent($qno) 0
				set B_recv($qno) 0
			}
			if {$use_vals} {
				set xx $args
			} else {
				set xx $stmnt
			}
			set Sent_as($qno,$B_sent($qno)) $xx
			set Sent_by($qno,$B_sent($qno)) $pno
			set Sent_at($qno,$B_sent($qno)) $N
			incr B_sent($qno)
		} else {
			if {[info exists B_recv($qno)] == 0} {
				set B_recv($qno) 0
			}
			if {$use_vals} {
				set xx $args
			} else {
				set xx $stmnt
			}
			set Recv_as($qno,$B_recv($qno)) $xx
			set Recv_by($qno,$B_recv($qno)) $pno
			set Recv_at($qno,$B_recv($qno)) $N
			incr B_recv($qno)
		}

		set q [string length $xx]
		if {$q > $maxW} { set maxW $q }
	}
	catch "close $fd"

	if {[llength pseq] == 0} {
		foreach qno [array names B_sent] {
		#	puts "Queue $qno -- $B_sent($qno) -- $B_recv($qno)"
			for {set i 0} {$i < $B_sent($qno)} {incr i} {
				set from $Sent_by($qno,$i)
				set onto $Recv_by($qno,$i)
				if {$from > $onto} {
					set tmp $from
					set from $onto
					set onto $tmp
				}
				if {[info exists Link($from,$onto)] == 0} {
					set Link($from,$onto) 1
				} else {
					incr Link($from,$onto)
				}
			}
		}
		set maxlink 0
		foreach i [array names Link] {
			if {$Link($i) > $maxlink} {
				set maxlink $Link($i)
			}
			# puts "$Link($i)	$i"
		}

		set pseq [linsert $pseq 1 "XX"]	;# mark possible insertion point
	
		for {set i $maxlink} {$i > 0} {incr i -1} {
			foreach j [array names Link] {
				if {$i == $Link($j)} {
					set k [split $j ","]
					set a [lindex $k 0]
					set b [lindex $k 1]
					set pseq [bestplace $pseq $a $b]
		}	}	}
	
		set x 0	;# take out the XX markers
		while {$x >= 0} {
			set x [lsearch -exact $pseq "XX"]
			if {$x >= 0} {
				set pseq [lreplace $pseq $x $x]
			}
		}
	}
	if {[llength $pseq] == 0} {
		for {set i $minp} {$i <= $maxp} {incr i} {
			set pseq [linsert $pseq end $i]
	}	}

	catch { foreach i [array names pline] { unset pline($i) } }
	catch { foreach i [array names Matrix] { unset Matrix($i) } }

	if {$how} {
		set maxw [expr 2*$XSZ + $xFactor * $maxp]
		mkcanvas ".f0" "Failure Scenario" "error" $maxw $maxh $nr.txt
		.f0.c configure -scrollregion  "0 0 4000 [expr (10+2*$N)*$YSZ]"
	}
	set maxN $N

	# check which processes participate in the scenario:
	if {1} {
		set phits {}
		foreach i [array names Act_as] {
			if {[lsearch -exact $phits $Act_by($i)] < 0} {
				lappend phits $Act_by($i)
		}	}

		foreach qno [array names B_sent] {
			for {set i 0} {$i < $B_sent($qno)} {incr i} {
				if {[lsearch -exact $phits $Sent_by($qno,$i)] < 0} {
					lappend phits $Sent_by($qno,$i)
				}
				catch	{
				if {[lsearch -exact $phits $Recv_by($qno,$i)] < 0} {
					lappend phits $Recv_by($qno,$i)
				}	}
		}	}
		set npseq {}
		for {set i 0} {$i < [llength $pseq]} {incr i} {
			set h [lindex $pseq $i]
			set j [lsearch -exact $phits $h]
			set k [lsearch -exact $hidden $h]
			if {$j >= 0 && $k < 0} {
				lappend npseq $h
		}	}

		set n [llength $pseq]
		for {set i 0} {$i < $n} {incr i} {
			set h [lindex $pseq $i]
			set j [lsearch -exact $npseq $h]
			if {$j < 0} {	;# in pseq, not in npseq
				set pseq  [lreplace $pseq $i $i]
				incr i -1
				incr n -1
		}	}
	}
	# end

	populate_msc $how

	bind . <Configure> {
		check_refresh_layout
	}	
}

proc populate_msc {how} {
	global pseq pid Act_as Act_by B_sent
	global XSZ YSZ xFactor maxN maxW notfixed
	global pline minp maxp verdict CyclePoint

	catch { foreach i [array names pline] { unset pline($i) } }

	if {$notfixed} {
		.f0.c create text 0 0 -text "abcdefABCDEF" -tags testme
		set q [.f0.c bbox testme]
		set ppc [expr ([lindex $q 2] - [lindex $q 0])/[string length "abcdefABCDEF"]]
		.f0.c delete testme
		set need [expr $maxW * $ppc]

		if {$xFactor < $need} {
			set xFactor $need
		}
		if {$XSZ < [expr $need/2]} {
			set XSZ [expr $need/2]
	}	}

	set realmax 0
	for {set i $minp} {$i <= $maxp} {incr i} {
		set pcol [lsearch -exact $pseq $i]
		if {$pcol >= 0} {
			catch { mkline $pcol $pid($i) $i }
			if {$realmax < $pcol} { set realmax $pcol }
	}	}

	filled_places
	
	foreach i [array names Act_as] {
		place_action $i $Act_by($i) $Act_as($i) $how
	}
	foreach qno [array names B_sent] {
		for {set i 0} {$i < $B_sent($qno)} {incr i} {
			placeit $qno $i $how
	}	}

	if {$how} {
		if {$CyclePoint >= 0} {
			set x [expr $XSZ + $xFactor*$realmax + $XSZ/2]
			set x0 [expr $XSZ/2]
			set y  [expr 5*$YSZ + 2*$CyclePoint*$YSZ]
			set y2 [expr 5*$YSZ + 2*$maxN*$YSZ]
		#	.f0.c create line \
		#		$x0 $y \
		#		$x $y \
		#		-width 2 -fill "blue"
		#	.f0.c create line \
		#		$x $y \
		#		$x $y2 \
		#		-width 2 -fill "blue"
		#	.f0.c create line \
		#		$x0 $y2 \
		#		$x $y2 \
		#		-width 2 -fill "blue"
			.f0.c create line \
				$x0 $y \
				$x0 $y2 \
				-width 4 -fill "blue"

			place_step $y $CyclePoint
			wm title .f0 "pan: cycle found"
		} else {
			if {$verdict != ""} {
				wm title .f0 "$verdict"
			} else {
				wm title .f0 "pan: invalid endstate?"
	}	}	}
	update
}

proc mkline {p nm pno} {
	global XSZ YSZ N xFactor pline maxW

	if {[info exists pline($pno)] != 0} {
		return
	}

	set x [expr $XSZ + $xFactor*$p]

	set drag [.f0.c create line \
		$x $YSZ \
		$x [expr 4*$YSZ + (10+2*$N)*$YSZ] \
		-width 2 -fill "gray" \
		-tags col$pno]

	.f0.c create rectangle \
		[expr $x-30] $YSZ \
		[expr $x+30] [expr 2*$YSZ] \
		-outline "black" -fill "gold" \
		-tags col$pno

	.f0.c create text \
		$x [expr $YSZ + $YSZ/2] \
		-text $nm -fill "black" \
		-tags col$pno

	.f0.c create text \
		$x $YSZ \
		-text $pno -fill "ivory" \
		-tags col$pno

	set pline($pno) $drag

	.f0.c bind col$pno <Button-1>  "break "
	.f0.c bind col$pno <B1-Motion> "drag_line $pno %x"
	.f0.c bind col$pno <ButtonRelease-1> "place_line $pno %x"
}

proc drag_line {pno x} {
	global pline

	set delta [expr $x - [lindex [.f0.c coords $pline($pno)] 0] ]
	.f0.c move col$pno $delta 0
}

proc place_line {pno x} {
	global XSZ xFactor pseq CurNr

	set seqno [expr ($x - $XSZ)/$xFactor]

	set curno [lsearch -exact $pseq $pno]

	set pseq [lreplace $pseq $curno $curno]
	set pseq [linsert  $pseq [expr $seqno + 1] $pno]

	catch { .f0.c delete all }
	catch { populate_msc 1 }

#	complain "moved $pno from $curno to [expr $seqno + 1]"
}

proc place_step {y stepnr} {
	.f0.c create text 20 $y -text "$stepnr" -fill "ivory"
}

proc place_action {N pno stmnt how} {
	global XSZ YSZ xFactor
	global pseq pid

	set col "yellow"

	set pref "printf('MSC: "
	if {[string first $pref $stmnt] == 0} {
		set nl [string last "\\n\'" $stmnt]
		if {$nl < 0 } { set nl end } else { incr nl -1 }
		set stmnt [string range $stmnt [string length $pref] $nl]
		set col "gold"
		if {[string first "~R" $stmnt] >= 0} {
			set stmnt [string range $stmnt 2 end]
			set col "red"
		}
		if {[string first "~G" $stmnt] >= 0} {
			set stmnt [string range $stmnt 2 end]
			set col "green"
		}
		if {[string first "~B" $stmnt] >= 0} {
			set stmnt [string range $stmnt 2 end]
			set col "blue"
		}
	}
	if {[string first "D_STEP" $stmnt] >= 0} {
		set stmnt "--"
	}

	set act_col [lsearch -exact $pseq $pno]

	set x [expr $XSZ + $xFactor*$act_col]
	set y [expr 4*$YSZ + $N*$YSZ*2]

	if {$how} { place_step $y $N }

	if {$act_col < 0} { return }

	if {$how} { .f0.c create text $x $y -text "$stmnt" -fill $col -anchor w }

	store_ascii "$stmnt" $act_col $N \
			     $act_col $N \
		    "$stmnt"
}

proc filled_places {} {
	global pseq markspot
	global Act_as Act_by
	global Sent_by Sent_at B_sent
	global Recv_by Recv_at

	catch { foreach i [array names markspot]  { unset markspot($i)  } }

	foreach i [array names Act_as] {
		set act_col [lsearch -exact $pseq $Act_by($i)]
		set markspot($act_col,$i) 1
	}
	foreach qno [array names B_sent] {
		for {set i 0} {$i < $B_sent($qno)} {incr i} {
			set sent_col [lsearch -exact $pseq $Sent_by($qno,$i)]
			set step_s $Sent_at($qno,$i)
			set markspot($sent_col,$step_s) 1

			if {[info exists Recv_by($qno,$i)]} {
				set recv_col [lsearch -exact $pseq $Recv_by($qno,$i)]
				set step_r $Recv_at($qno,$i)
				set markspot($recv_col,$step_r) 1
	}	}	}
}

proc moveupwards {incol fromstep minstep} {
	global markspot

	set i $fromstep
	while {$i > $minstep \
	&&     [info exists markspot($incol,[expr $i - 1])] == 0} {
		incr i -1
	}
	if {$i != $fromstep} {
		unset markspot($incol,$fromstep)
		set markspot($incol,$i) 1
	}
	return $i
}

proc placeit {qno i how} {
	global Sent_as Sent_at Sent_by
	global Recv_as Recv_at Recv_by
	global XSZ YSZ xFactor pid pseq

	set sent_col [lsearch -exact $pseq $Sent_by($qno,$i)]
	set step_s $Sent_at($qno,$i)

	if {[info exists Recv_by($qno,$i)]} {
		set recv_col [lsearch -exact $pseq $Recv_by($qno,$i)]
		set step_r $Recv_at($qno,$i)
		set isrecvd 1

		set step_r [moveupwards $recv_col $step_r $step_s]
	} else {
		set recv_col $sent_col
		set step_r $step_s
		set Recv_as($qno,$i) $Sent_as($qno,$i)
		set isrecvd 0
	}

	set fromx_s [expr $XSZ + $xFactor*$sent_col]
	set fromx_r [expr $XSZ + $xFactor*$recv_col]

	set fromy_s [expr 4*$YSZ + $step_s*$YSZ*2]
	set fromy_r [expr 4*$YSZ + $step_r*$YSZ*2]

	if {$how} {
		place_step $fromy_s $step_s
		place_step $fromy_r $step_r
	}

	if {$sent_col < 0 || $recv_col < 0 } { return }

	if {$how} {
		if {$isrecvd} {
			.f0.c create text \
				$fromx_s [expr $fromy_s - $YSZ] \
				-text "$Sent_as($qno,$i)" \
				-fill "white"
			.f0.c create line \
				$fromx_s $fromy_s \
				$fromx_r $fromy_r \
				-width 3 \
				-fill "red" \
				-arrow last -arrowshape {5 5 5}
		
			.f0.c create text \
				$fromx_r [expr $fromy_r - $YSZ] \
				-text "$Recv_as($qno,$i)" \
				-fill "white"
		} else {
			.f0.c create text \
				$fromx_s [expr $fromy_s - $YSZ] \
				-text "$Sent_as($qno,$i)" \
				-fill "red"
		}
	}
	store_ascii	"$Sent_as($qno,$i)" \
			 $sent_col $step_s \
			 $recv_col $step_r \
			"$Recv_as($qno,$i)"
}

proc store_ascii {sm xs ys xr yr rm} {
	global Matrix

	set e [format "%s@%s@%s@%s@%s@%s" $sm $xs $ys $xr $yr $rm]
	set Matrix($e) 1
}

proc outline {fd s from upto r p how} {

	if {$from > $upto} {
		set mark1 "   <"
		set mark2 "---|"
		set x1 $upto
		set x2 $from
	} else {
		if {$from == $upto} {
			set mark1 "   +"
			set mark2 ""
		} else {
			set mark1 "   |"
			set mark2 "--->"
		}
		set x1 $from
		set x2 $upto
	}
# puts "x1 = $x1 --- x2 = $x2 -- s = $s -- r = $r -- $from -- $upto"
	puts_plus $fd  "  " $how
	for {set i 0} {$i < $x1} {incr i} {
		puts_plus $fd  "   |" $how
	}
	puts_plus $fd "$mark1" $how
	for {set i $x1} {$i < [expr $x2-1]} {incr i} {
		puts_plus $fd "----" $how
	}
	puts_plus $fd "$mark2" $how
	for {set i $x2} {$i < [expr $p-1]} {incr i} {
		puts_plus $fd "   |" $how
	}
	puts_plus $fd "   " $how
	puts_plus $fd "$s\n" $how
}

proc puts_plus {fd line how} {
	global TW_Errors

	if {$how} {
		puts $fd "$line" nonewline
	}
	$TW_Errors insert end $line
}

proc show_ascii {f {how 1}} {
	global Matrix N pid verdict pseq

	if {$how} {
		if [catch {set fd [open $f w]} errmsg] {
			complain "show: $ermsg"
			return
		}
	} else {
		set fd stdout	;# not really used
	}

	set maxp [llength $pseq]
	for {set i 0} {$i <= $maxp} {incr i} {
		if {[info exists pid([lindex $pseq $i])]} {
		puts_plus $fd [format "%2d: %s\n" $i $pid([lindex $pseq $i])] $how
		}
	}
	puts_plus $fd "===============\n" $how
	puts_plus $fd "   " $how

	for {set i 0} {$i <= $maxp} {incr i} {
		puts_plus $fd [format " %2d " $i] $how
	}
	puts_plus $fd "\n" $how

	if {$how == 0 && $N > 250} {	;# too slow for a default
		puts_plus $fd "===============\n" $how
		puts_plus $fd "long trace, see Traces" $how
	} else {
		for {set y 0} {$y <= $N} {incr y} {
		foreach i [array names Matrix] {
						;# 0 1 2   3 4 5
			set j [split $i "@"]	;# S x y   x y R ]
			set a4 [lindex $j 4]

			if {[lindex $j 2] == $y} {
				set a0 [lindex $j 0]
				set a1 [lindex $j 1]
				set a3 [lindex $j 3]
				if {$a4 == $y} {
					set a5 [lindex $j 5]
					outline $fd $a0 $a1 $a3 $a5 \
						$maxp $how
				} else {
					outline $fd $a0 $a1 $a3 "+" \
						$maxp $how
				}
			} else {
				if {$a4 == $y} {
					set a3 [lindex $j 3]
					set a5 [lindex $j 5]
					outline $fd "+" $a3 $a3 $a5 \
						$maxp $how
		}}	}	}
	}

	puts_plus $fd $verdict\n $how
	if {$how} { close $fd }
}

proc bestplace {pseq a b} {

	set has_a [lsearch -exact $pseq $a]
	set has_b [lsearch -exact $pseq $b]

	# puts "consider $a $b"
	if {$has_a >= 0 && $has_b >= 0} {
		# puts "	has both"
		return $pseq
	}

	if {$has_a == -1 && $has_b == -1} {
		set pseq [linsert $pseq 0 $b]
		set pseq [linsert $pseq 0 $a]
		set pseq [linsert $pseq 0 "XX"]
		# puts "	has neither"
		return $pseq
	}

	if {$has_a >= 0} {
		set to_add $b
		set at_add $has_a
	} else {
		set to_add $a
		set at_add $has_b
	}

	set dist1 1000
	for {set x [expr $at_add - 1]} {$x >= 0 && [lindex $pseq $x] != "XX"} {incr x -1} {
	}
	if {$x >= 0} { set dist1 [expr $at_add - $x] }

	set z [llength $pseq]
	set dist2 1000
	for {set y [expr $at_add + 1]} {$y < $z && [lindex $pseq $y] != "XX"} {incr y} {
	}
	if {$y < $z} { set dist2 [expr $y - $at_add] }

	if {$dist1 < $dist2} {
		set pseq [linsert $pseq $x $to_add]
		set pseq [linsert $pseq $x "XX"]
		# puts "searched $dist1 ($dist2) reverse from $at_add add $to_add at $x"
	} else {
		set pseq [linsert $pseq $y $to_add]
		set pseq [linsert $pseq $y "XX"]
		# puts "searched $dist1 ($dist2) forward from $at_add add $to_add at $y"
	}
	return $pseq
}

##begin directory browsing

proc initialize_browse {mode w_tag {new_dir ""}} {
	global work_dir x_over y_down el nel BGCol root_level

	if {($mode == "first") && ($new_dir == "")} {
		set el $work_dir
		set nel ""
	} elseif {($mode == "first") && ($new_dir != "")} {
		set work_dir $new_dir
		set el $work_dir
		set nel ""
	}
	set root_level [find_level $work_dir]
	set x_over 10
	set y_down 10

	catch { .f.$w_tag delete all }

	.f.$w_tag config -bg $BGCol
	display $w_tag $work_dir
	if {($mode == "first") && ($new_dir == "")} {
		populate_volume_list $w_tag
		populate_root_volume $w_tag
	}
}

proc display {w_tag dir} {
	global x_over y_down el work_dir nel Xspace arb_off n_in root_level
	global BGCol BoxCol SymCol LineCol DTextCol FTextCol

# puts "entering display $dir"

	if {$dir == $work_dir} {
		.f.$w_tag create rect [expr $x_over - 3] [expr $y_down - 8] \
			[expr $x_over + 10] [expr $y_down + 5] \
			-fill $BGCol -outline $BGCol -tags "parentdir"
		.f.$w_tag create polygon [expr $x_over - 3] [expr $y_down - 3] \
			[expr $x_over + 4] [expr $y_down - 3] \
			$x_over [expr $y_down - 8] \
			[expr $x_over - 3] [expr $y_down - 3] \
			-fill $LineCol -outline $LineCol \
			-tags "parentdir"
		.f.$w_tag create line $x_over [expr $y_down - 3] $x_over [expr $y_down + 5] \
			[expr $x_over + 10] [expr $y_down + 5] \
			-fill $LineCol -tags "parentdir"
	
		
		incr y_down 15
		.f.$w_tag create text \
			$x_over $y_down \
			-text $work_dir -fill $DTextCol \
			-anchor w -tags "g_$work_dir text_$work_dir"
		}
	set temp [glob -nocomplain -directory $dir -- *]
	set files [lsort -dictionary $temp]		
	set flist ""
	set h 7.5
	set first 0
	set na 0
	set level [expr [find_level $dir] - $root_level]

# puts "level: $level"

	set xinc [expr $level * $Xspace]
	foreach i $files {
		if {([llength [split $i " "]] > 1) || ($i == ".")} {
			continue
		}
    		if {[file isdirectory $i]} {
			set trimmed [string trim $i "/"]
			set split_i [split $trimmed "/"]
			set name [lindex $split_i [expr [llength $split_i] - 1]]
			incr y_down 15
			set level [expr [find_level $i] - $root_level]
			set xinc [expr $level * $Xspace]
			if {$first} {set first 0
			} else {set h 15}
			incr na
			.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - 15] \
				[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
				[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$i"
			.f.$w_tag create text [expr $x_over + $xinc] $y_down -text $name -fill $DTextCol \
				-anchor w -tags "g_$i text_$i"
			
			set expand 0
			foreach j $el {
				if {$i == $j} { ;#i is expanded
					set expand 1
					.f.$w_tag create rect [expr $x_over + $xinc - 20] [expr $y_down - 6] \
						[expr $x_over + $xinc - 8] [expr $y_down + 6] \
						-outline $BoxCol -fill $BoxCol -tags "g_$j"
					.f.$w_tag create line [expr $x_over + $xinc - 17] $y_down \
						[expr $x_over + $xinc - 10] $y_down -fill $SymCol -tags "g_$i"
					.f.$w_tag bind g_$i <ButtonPress-1> "contract $i $w_tag"
					display $w_tag $i
					continue
					}
				}
			if {!$expand} {
				set empty [check_empty $i]
				if {!$empty} {
					.f.$w_tag create rect [expr $x_over + $xinc - 20] [expr $y_down - 6] \
						[expr $x_over + $xinc - 8] [expr $y_down + 6] \
						-outline $BoxCol -fill $BoxCol -tags "g_$i"
					.f.$w_tag create line [expr $x_over + $xinc - 14] [expr $y_down - 3] \
						[expr $x_over + $xinc - 14] [expr $y_down + 4] -fill $SymCol -tags "g_$i"
					.f.$w_tag create line [expr $x_over + $xinc - 17] $y_down \
						[expr $x_over + $xinc - 10] $y_down -fill $SymCol -tags "g_$i"
					.f.$w_tag bind g_$i <ButtonPress-1> "expand $i $w_tag"
					}
					
				}
    		} elseif [file isfile $i] {
			lappend flist $i
		}
	}
	set flist [filter $flist]

	foreach i $flist {
		set trimmed [string trim $i "/"]
		set split_i [split $trimmed "/"]
		set name [lindex $split_i [expr [llength $split_i] - 1]]
		incr y_down 15
		set level [expr [find_level $dir] - $root_level + 1]
		set xinc [expr $level * $Xspace]
		if {$first} {set first 0
			} else {set h 15}
		incr na 1
		.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - 15] \
				[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
				[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$i"
		.f.$w_tag create text [expr $x_over + $xinc] $y_down \
			-text $name -fill $FTextCol -anchor w -tags "g_$i text_$i"
		
		if {[string first ".prx" $name] > 0 \
		||  [string first ".pml" $name] > 0 \
		||  [string first ".c"   $name] > 0} {
			.f.$w_tag bind text_$i <Any-Enter> ".f.$w_tag itemconfigure text_$i -fill yellow"
			.f.$w_tag bind text_$i <Any-Leave> ".f.$w_tag itemconfigure text_$i -fill gold"
			.f.$w_tag bind text_$i <Button-1> "reopen_c $i"
		}
		if {[string first ".vip" $name] > 0} {
			.f.$w_tag bind text_$i <Any-Enter> ".f.$w_tag itemconfigure text_$i -fill yellow"
			.f.$w_tag bind text_$i <Any-Leave> ".f.$w_tag itemconfigure text_$i -fill gold"
			.f.$w_tag bind text_$i <Button-1>  "display_vip $i"
			}
	}
	if {$dir == $work_dir} {
		adjust_scrollregion $w_tag
		refresh_bridges $w_tag ;# will be called only after all recursive calls to display have completed
		.f.$w_tag bind parentdir <1> "
			.f.$w_tag bind parentdir <1> {}
			set work_dir \[get_uponelevel $work_dir]
			.f.$w_tag delete all
			set y_down 10
			set root_level \[find_level \$work_dir]
			set el \$work_dir
			display $w_tag \$work_dir 
			"
		}
}

proc populate_volume_list {bw} {
	global Unix

	if !$Unix {
		set volumes [file volume]
	} else {

 if {1} {
	set volumes "/n"
 } else {
 # this takes forever
		set curd [pwd]
		set split [split $curd "/"]
		set first [lindex $split 0]
		set rt "/${first}"
		set rtfiles [glob -nocomplain -directory $rt -- *]
		set volumes ""
		foreach f $rtfiles {
			if [file isdirectory $f] {
				lappend volumes $f
			}
		}
 }
	}
	foreach v $volumes {
		.f.cb$bw add $v
	}

}

proc populate_root_volume {bw} {
	global Unix
	set curd [pwd]
	if $Unix {
		set curd [string trimleft $curd "/"]
		set path [split $curd "/"]
		set rootv [lindex $path 0]
		set rootv "/${rootv}"
		.f.cb$bw set $rootv
	} else {
		set path [split $curd "/"]
		set rootv [lindex $path 0]
		set rootv "${rootv}/"
		.f.cb$bw set $rootv
	}
}

proc get_uponelevel {dir} {
	if {[string index $dir 0] == "/"} {
		set prefix "/"
	} else {
		set prefix ""
		}
	set trimmed [string trim $dir "/"]
	set splitr [split $trimmed "/"]
	set l [llength $splitr]

	if {$l > 1} {
		set up_one [lrange $splitr 0 [expr $l - 2]]
		if {[llength $up_one] < 2} {lappend up_one ""}
		set aroot [join $up_one "/"]
	} else {
		set aroot $dir
		}
	set new_root ""
	append new_root $prefix $aroot
	debug "from get_uponelevel that was given $dir - about to return $new_root"
	return $new_root
	}

proc display_vip {full_fname} {
        global TW_Vip choice Vip_Fname
        set wex [catch {$TW_Vip cget -background}]
        if {$wex} {
                # Vip tab doesn't exist yet, create it
                place_window new tcsa 2 Vip 1
        }
        set fn $full_fname
        clear open $fn
	set tag [string range $TW_Vip 3 [expr [string length $TW_Vip] - 1]]
	set split [split $tag "_"]
	set tabnumber [lindex $split 2]
	set pos [lindex $split 1]
        put_on_top $pos $tabnumber
        focus_in $tag
}

proc filter {file_list} { ;#returns list of files with extensions matching those in var 'exts'
	global exts
	set new_list ""
	foreach i $file_list {
		if {[llength [split $i " "]] > 1} {
			continue ;# throw out file names with spaces
		}
		foreach j $exts {
			if {[string first $j $i] > 0 \
			&& $j != "_modex_in.prx"} {	;# not temp files
				lappend new_list $i
				break
	}	}	}

	return $new_list
}

proc check_empty {i} {

	set fs [glob -nocomplain -directory $i -types d -- *]	;# has sub-directories

	if {[llength $fs] > 0} {
		return 0
	}

	set fs [glob -nocomplain -directory $i -types f -- *.prx *.vip *.pml]

	if {[llength $fs] > 0} {
		return 0
	}
	return 1
}


proc expand {j w_tag} { ;# adds files in expanded directory -- all below dir j is moved down to make room
	global x_over work_dir el nel Xspace arb_off n_in BoxCol SymCol LineCol DTextCol FTextCol root_level

	lappend el $j
	set y_down [lindex [.f.$w_tag coords text_$j] 1]
	set y_start $y_down
	.f.$w_tag delete g_$j ;#delete text and graphic and recreate
	set ym [lindex [.f.$w_tag cget -scrollregion] 3]
	set items [.f.$w_tag find overlapping 0 [expr $y_down + 15] 800 $ym] ;#find items that have to be moved down later
	set abs_level [find_level $j]
	set level [expr $abs_level - $root_level]
	set xinc [expr $level * $Xspace]
	set trimmed [string trim $j "/"]
	set split_j [split $trimmed "/"]
	set name [lindex $split_j [expr $abs_level - 1]]

	.f.$w_tag xview scroll 1 units	;# by 0.2 of canvas width

	.f.$w_tag create line \
		[expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - 15] \
		[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
		[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$j"
	.f.$w_tag create text \
		[expr $x_over + $xinc] $y_down -text $name -fill $DTextCol \
		-anchor w -tags "g_$j text_$j"
	.f.$w_tag create rect \
		[expr $x_over + $xinc - 20] [expr $y_down - 6] \
		[expr $x_over + $xinc - 8] [expr $y_down + 6] \
		-outline $BoxCol -fill $BoxCol -tags "g_$j"
	.f.$w_tag create line \
		[expr $x_over + $xinc - 17] $y_down \
		[expr $x_over + $xinc - 10] $y_down -fill $SymCol -tags "g_$j"
	.f.$w_tag bind g_$j <ButtonPress-1> "contract $j $w_tag"

	set temp [glob -nocomplain -directory $j -- *]
	set files [lsort -dictionary $temp]
	set flist ""
	set first 1
	set h 7.5
	set na 0
	foreach i $files {
		if {([llength [split $i " "]] > 1) || ($i == ".")} {continue}
    		if {[file isdirectory $i]} { ;# and each directory under parent j
			set trimmed [string trim $i "/"]
			set split_i [split $trimmed "/"]
			set name [lindex $split_i [expr [llength $split_i] - 1]]
			set y_down [expr $y_down + 15]
			set level [expr [find_level $i] - $root_level]
			set xinc [expr $level * $Xspace]
			if {$first} {set first 0
			} else {set h 15}
			incr na 1
			.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - $h] \
				[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
				[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$i"
			.f.$w_tag create text [expr $x_over + $xinc] $y_down -text $name -fill $DTextCol \
				-anchor w -tags "g_$i text_$i"
			set empty [check_empty $i]
			if {!$empty} {
				.f.$w_tag create rect [expr $x_over + $xinc - 20] [expr $y_down - 6] \
						[expr $x_over + $xinc - 8] [expr $y_down + 6] \
						-outline $BoxCol -fill $BoxCol -tags "g_$i"
				.f.$w_tag create line [expr $x_over + $xinc - 14] [expr $y_down - 3] \
					[expr $x_over + $xinc - 14] [expr $y_down + 4] -fill $SymCol -tags "g_$i"
				.f.$w_tag create line [expr $x_over + $xinc - 17] $y_down \
					[expr $x_over + $xinc - 10] $y_down -fill $SymCol -tags "g_$i"
				.f.$w_tag bind g_$i <ButtonPress-1> "expand $i $w_tag"
				}
    		} elseif [file isfile $i] {
			lappend flist $i
			}
		}

	set flist [filter $flist]
	foreach i $flist {
		set trimmed [string trim $i "/"]
		set split_i [split $trimmed "/"]

		set name [lindex $split_i [expr [llength $split_i] - 1]]
		set y_down [expr $y_down + 15]
		set level [expr [find_level $j] - $root_level + 1]
		set xinc [expr $level * $Xspace]
		if {$first} {set first 0 } else {set h 15}
		incr na 1
		.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - $h] \
				[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
				[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$i"
		.f.$w_tag create text [expr $x_over + ($level * $Xspace)] $y_down \
			-text $name -fill $FTextCol -anchor w -tags "g_$i text_$i"

		if {[string first ".prx" $name] > 0 \
		||  [string first ".pml" $name] > 0 \
		||  [string first ".c"   $name] > 0} {
			.f.$w_tag bind text_$i <Any-Enter> ".f.$w_tag itemconfigure text_$i -fill yellow"
			.f.$w_tag bind text_$i <Any-Leave> ".f.$w_tag itemconfigure text_$i -fill gold"
			.f.$w_tag bind text_$i <Button-1> "reopen_c $i"	;# new master
		}
		if {[string first ".vip" $name] > 0} {
			.f.$w_tag bind text_$i <Any-Enter> ".f.$w_tag itemconfigure text_$i -fill yellow"
			.f.$w_tag bind text_$i <Any-Leave> ".f.$w_tag itemconfigure text_$i -fill gold"
			.f.$w_tag bind text_$i <Button-1>  "display_vip $i"
			}
	}

	#move everything else down by the amount of y_down space used
	set y_diff [expr $y_down - $y_start]
	foreach i $items {
		.f.$w_tag move $i 0 $y_diff
	}
	adjust_scrollregion $w_tag
	refresh_bridges $w_tag
	
}

proc refresh_bridges {w_tag} {
	global el x_over Xspace arb_off work_dir BoxCol SymCol LineCol DTextCol FTextCol root_level
	debug "\n\n\n\nENTERING refresh_bridges - el is: $el"
	.f.$w_tag delete bridges
	foreach i $el {
		if {[am_i_last $i]} {
			continue
			}
		set n 0
		#check if there is anything valid in directory i - continue if not
		set temp [glob -nocomplain -directory $i -- *]
		set files [lsort -dictionary $temp]
		set clean_glob ""
		foreach k $files {
			if {([llength [split $k " "]] == 1) || ($k != ".")} {
				lappend clean_glob $k
				}
			}
		if {$clean_glob == ""} {
			continue
			}

		#split clean_glob into a list of files and a list of directories
		set clean_files ""
		set clean_dirs ""
		foreach k $clean_glob {
    			if {[file isdirectory $k]} {
				lappend clean_dirs $k
				}
			if {[file isfile $k]} {
				lappend clean_files $k
				}
			}
		set clean_files [filter $clean_files] ;# filter for filesof interest
		if {$clean_dirs == ""} {
			if {$clean_files == ""} {
				continue
			}
		}
		set first ""
		set last ""
		if {$clean_dirs != ""} {
			set first [lindex $clean_dirs 0]
		} elseif {$clean_files != ""} {
			set first [lindex $clean_files 0]
			}
		if {$clean_files != ""} {
			set last [lindex $clean_files [expr [llength $clean_files] - 1]]
		} elseif {$clean_dirs != ""} {
			set last [lindex $clean_dirs [expr [llength $clean_dirs] - 1]]
			}
		debug "first is first, and last is: $last"

		#since we have some directories -- see if last directory in list is expanded
		#do this recursively until unexpanded last directory is found
		set last_dir $i
		set new_dir [lindex $clean_dirs [expr [llength $clean_dirs] - 1]]
		set keep_looking 1
		set loop_count 0
		while $keep_looking {
			incr loop_count 1
			if {$loop_count == 10} {break}
			set new_dir [lindex $clean_dirs [expr [llength $clean_dirs] - 1]]
			set match 0
			foreach e $el {
				if {$new_dir == $e} {
					set last_dir $new_dir
					set match 1
					break
					}
				}
			if {!$match} {
				set keep_looking 0
				break
				}
			set temp [glob -nocomplain -directory $last_dir -types d -- *]
			set dirs [lsort -dictionary $temp]
			set clean_dirs ""
			foreach k $dirs {
				if {([llength [split $k " "]] == 1) || ($k != ".")} {
					lappend clean_dirs $k
					}
				}
			if {$clean_dirs == ""} {
				set keep_looking 0
				break
			} else {
				set new_dir [lindex $clean_dirs [expr [llength $clean_glob] - 1]]
				}
			}
		set temp [glob -nocomplain -directory $last_dir -types f -- *]
		set files [lsort -dictionary $temp]
		set clean_glob ""
		
		foreach k $files {
			if {([llength [split $k " "]] == 1) || ($k != ".")} {
				lappend clean_glob $k
				}
			}
		set files [filter $clean_glob]
		if {$files == ""} {
			set last $new_dir
		} else {
			set last [lindex $files [expr [llength $files] - 1]]
			}
		set y_start [expr [lindex [.f.$w_tag coords text_$first] 1] - 15]
		set y_end [lindex [.f.$w_tag coords text_$last] 1]
		set level [expr [find_level $i] - $root_level]
		set xinc [expr $level * $Xspace]
		.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] $y_start \
			[expr $x_over + $xinc - $Xspace + $arb_off] $y_end \
			-fill $LineCol -tags "g_$i bridge_$i bridges"
		}

}

proc find_last_path {} {
	global work_dir last_path
	debug "ENTERING find_last_path"
	set cur $work_dir

	#find last path
	set last_path $work_dir
	set go 1
	while $go {
		debug "entering go loop for cur=$cur"
		set temp [glob -nocomplain -directory $cur -- *]
		set files [lsort -dictionary $temp]
		set clean_dirs ""
		foreach k $files {
			if {([llength [split $k " "]] > 1) || ($k == ".")} {continue}
    			if {[file isdirectory $k]} {
				lappend clean_dirs $k
				}
			}
		set last [lindex $clean_dirs [expr [llength $clean_dirs] - 1]]
		if {$last == ""} {
			set go 0; break
		} else {
			set last_path $last
			set cur $last_path
			debug "so far, last_path is $last_path"
			}
		}
	return $last_path
}

proc am_i_last {dir} {
	#determine whether there are files in dir or other directories that are displayed below dir
	debug "ENTERING am_i_last - with dir=$dir"
	if {[string index $dir 0] == "/"} {
		set prefix "/"
	} else {
		set prefix ""
		}
	set path [string trim $dir "/"]
	set splitpath [split $path "/"]
	set trunc [lrange $splitpath 0 [expr [llength $splitpath] - 2]]
	set trunc [join $trunc "/"]
	set trunked ""
	append trunked $prefix $trunc "/"
	set fs [glob -nocomplain -directory $trunked -types f -- *.prx *.vip *.pml]
	debug "fs is: $fs"
	if {[llength $fs] > 0} {
		debug "there are files - so dir is not last"
		return 0 ;#there are files - so dir is not last
		}
	#there are no files, but maybe there are directories
	
	set ds [glob -nocomplain -directory $trunked -types d -- *]
	debug "ds is: $ds"
	if {[llength $ds] == 0} {
		debug "no files and no directories - so dir is last"
		return 1 ;#no files and no directories - so dir is last
	} else {
		if {$dir == [lindex $ds [expr [llength $ds] - 1]]} {
			debug "no files, and dir is last dir in parent directory so $dir is last"
			return 1 ;# no files, and dir is last dir in parent directory - so dir is last
		} else {
			debug "no files, and $dir is not last, so dir is not last"
			return 0 ;# no files, and dir is not last - so dir is not last
			
			}
		}	
}

proc adjust_scrollregion {w_tag} {
	global work_dir el
	set go 1
	set cur $work_dir
	set last $cur
	while $go {
		debug "entering go loop for cur=$cur"
		set temp [glob -nocomplain -directory $cur -- *]
		set files [lsort -dictionary $temp]
		set clean_files ""
		set clean_dirs ""
		foreach k $files {
			if {([llength [split $k " "]] > 1) || ($k == ".")} {continue}
    			if {[file isdirectory $k]} {
				lappend clean_dirs $k
				}
			if {[file isfile $k]} {
				lappend clean_files $k
				}
			}
		set clean_files [filter $clean_files]
		set first [lindex $clean_dirs 0]
		set last [lindex $clean_files [expr [llength $clean_files] - 1]]
		if {$first == ""} {set first [lindex $clean_files 0]}
		if {$last == ""} {set last [lindex $clean_dirs [expr [llength $clean_dirs] - 1]]}
		if {$last == ""} {
			set go 0; return}
		debug "last file/dir in $cur is $last"
		set y_last [lindex [.f.$w_tag coords text_$last] 1]
		debug "y_last - y of $last is: $y_last"
		set in_el 0
		foreach i $el {
			debug "question is $last expanded -- i.e is it in\n\tel=$el"
			if {$last == $i} {
				debug "yes, $last is expanded, setting cur to $last"
				set cur $last
				set in_el 1
				continue
			}
		}
		if {!$in_el} {
			debug "no, $last is not expanded - breaking out"
			set go 0; break
			}
		}
	
	set y2 [expr $y_last + 50]
	.f.$w_tag configure -scrollregion "0 0 500 $y2"
	}

proc contract {j w_tag} { ;# starting with directory j, removes contained directories and file -- recurses on expanded subdirectories
	#all below dir j contents are moved up to make contiguous
	global x_over work_dir el nel y_diff items_to_be_moved Xspace arb_off BoxCol SymCol LineCol DTextCol FTextCol root_level
	for {set i 0} {$i < [llength $el]} {incr i 1} {
		if {$j == [lindex $el $i]} {
			set el [lreplace $el $i [expr $i + 0]]
			}
		}
	set y_down [lindex [.f.$w_tag coords text_$j] 1]
	set y_start $y_down
	set move 0
	if {$items_to_be_moved == ""} {
		set move 1
		set ym [lindex [.f.$w_tag cget -scrollregion] 3]
		set items_to_be_moved [.f.$w_tag find overlapping 0 [expr $y_down + 15] 800 $ym] ;#find items to be moved up later
		}
	.f.$w_tag delete g_$j ;#delete text and graphic and recreate
	set level [expr [find_level $j] - $root_level]
	set xinc [expr $level * $Xspace]
	set trimmed [string trim $j "/"]
	set split_j [split $trimmed "/"]
	set name [lindex $split_j [expr [llength $split_j] - 1]]

	.f.$w_tag xview scroll -1 units	;# by 0.2 of canvas width

	.f.$w_tag create line [expr $x_over + $xinc - $Xspace + $arb_off] [expr $y_down - 15] \
				[expr $x_over + $xinc - $Xspace + $arb_off]	$y_down \
				[expr $x_over + $xinc] $y_down -fill $LineCol -tags "g_$j"
	.f.$w_tag create text [expr $x_over + $xinc] $y_down -text $name -fill $DTextCol \
		-anchor w -tags "g_$j text_$j"
	.f.$w_tag create rect [expr $x_over + $xinc - 20] [expr $y_down - 6] \
		[expr $x_over + $xinc - 8] [expr $y_down + 6] \
		-outline $BoxCol -fill $BoxCol -tags "g_$j"
	.f.$w_tag create line [expr $x_over + $xinc - 17] $y_down \
		[expr $x_over + $xinc - 10] $y_down -fill $SymCol -tags "g_$j"
	.f.$w_tag create line [expr $x_over + $xinc - 14] [expr $y_down - 3] \
		[expr $x_over + $xinc - 14] [expr $y_down + 4] -fill $SymCol -tags "g_$j"
	.f.$w_tag bind g_$j <ButtonPress-1> "expand $j $w_tag"

	set temp [glob -nocomplain -directory $j -- *] ;#glob for contents of contracted directory j
	set files [lsort -dictionary $temp]
	set nd 0
	set flist ""
	foreach i $files {
		if {([llength [split $i " "]] > 1) || ($i == ".")} {continue}
    		if {[file isdirectory $i]} { ;#
			for {set j 0} {$j < [llength $el]} {incr j 1} {
				if {$i == [lindex $el $j]} {
					set el [lreplace $el $j [expr $j + 0]]
					set nsd [contract $i $w_tag] ;#recursive call
					set nd [expr $nd + $nsd]
					break
					}
				}
				incr nd 1
			}	
		if {[file isfile $i]} {
			lappend flist $i
			}
		catch {.f.$w_tag delete g_$i}
		
		}
	set flist [filter $flist]
	incr nd [llength $flist]

	if {$move} { ;# done when all recursive calls to contract have completed
		set y_diff [expr $y_diff - ($nd * 15)]	
		foreach i $items_to_be_moved {
			.f.$w_tag move $i 0 $y_diff
			}
		set items_to_be_moved ""
		set y_diff 0
		set nd 0
		refresh_bridges $w_tag
		adjust_scrollregion $w_tag
		}
	return $nd	
}

proc menu_toggles {} {
	with_asserts;with_asserts;
	all_stmnts; all_stmnts	;# toggle twice to set menu
	with_loops; with_loops	;# ditto
	with_np;    with_np
	with_vals;  with_vals
	with_ends;  with_ends
}

# dynamic global variables

##end directory browsing

wm title . "FeaVer - Modex - Spin"
wm geometry . +100+10

# splash screen
	if {$feaver_logo != ""} {
		set gone 0
		.f.c configure -bg white
		.f.c create image 170 100 -anchor nw \
        		-image $feaver_logo -tags logo
		after 2500 { .f.c delete logo; set gone 1 }
		tkwait variable gone
	}
	.f.c configure -bg grey
# end of splash

measure_text
get_canvas_size
set last_focus ""

set done [static_view]

menu_toggles

set items_to_be_moved "" 	;#dir browsing
set y_diff 0			;#dir browsing

set TW_Info   [find_path "Info"]	;# 1 2

  set TW_Source [find_path "Source"]	;# 2 1
# set TW_Parse  [find_path "Parse" ]	;# 2 2
# set TW_Fcts   [find_path "Fcts" ]	;# 2 3
# set TW_Data   [find_path "Data" ]	;# 2 4
  set TW_Prx    [find_path "Prx"  ]	;# 2 5
# set TW_Driver [find_path "Driver" ]	;# 2 6
  set TW_Model  [find_path "Model" ]	;# 2 7
  set TW_Vip    [find_path "Vip" ]      ;# 2 8
  set TW_Advanced    [find_path "Advanced" ]      ;# 2 9

  set TW_Out    [find_path "Out" ]	;# 3 1
  set TW_Stats  [find_path "Stats" ]	;# 3 2
  set TW_Errors [find_path "Traces"]      ;# 3 3
  set TW_Log	[find_path "Log" ]	;# 3 4

put_on_top 1 1
put_on_top 2 1
put_on_top 3 1

	if [info exists tcl_platform] {
		set sys $tcl_platform(platform)
		if {$argc == 1 && $sys != "windows"} {
			reopen_c "$argv"
	}	}

set old_width ""
set old_height ""

	bind . <Configure> {
		debug "detected configure event"
		check_refresh_layout
	}

check_refresh_layout
