#! /usr/local/bin/wish -f
#! /home/petsc/bin/sun4/wish4.1
#! /home/bsmith/bin/sun4/wish4.0 -f
#! /Net/antares/local/sun4/tcl7.4-tk4.0/bin/wish4.0 -f
# $Id: petscview,v 1.44 1998/04/24 20:27:45 bsmith Exp $ 

#
#  You may have to set the correct location of wish on your machine
# in the first line of this file.
#
#
#  tcl/tk keeps on changing. We try to keep PETScView up to date, but that
# would be a full time job. We hope that PETScView will work with an
# wish version larger then 3.6. If you have trouble with it, please send
# email to petsc-maint with the tcl/tk version numbers and the exact code
# that is causing the problem.
#
wm title . "PETScView"
wm iconname . "PETScView"
# wm geometry . 770x865+370+0
set petsc_dir $env(PETSC_DIR)
#tk colormodel . color

#
# tk version 4 has incompatible commands for 
# checkbutton (-selectcolor instead of -selector)
# scrollbar   (-command needs to be different)
# canvas config (-xscrollcommand instead of -xscroll, and command is 
#                different)
# scale         (-activebackground instead of -activeforeground!)
# tk_listboxSingleSelect var(list) replaced with
#   var(list) config -selectmode single.  
# See /home/MPI/mpich/profiling/upshot/bin/upshot.in for an example of
# code that can run with either version of tk
#
#
#  Display time line plot of flops and memory usage
#
set PlotW 730
set PlotH 250
set PlotB 30
proc Create_LinePlot {} {
  global TotalTime TotalFlops
  global PlotW PlotH PlotB

  toplevel .plotcanvas
  wm title .plotcanvas "PETScView Time Plot"
  wm iconname .plotcanvas "PETScView Time Plot"

  set width  [expr $PlotW + 2*$PlotB]
  set height [expr $PlotH + 2*$PlotB + 2*$PlotB]

  canvas .plotcanvas.scrn 
  .plotcanvas.scrn config -height $height -width $width -scrollregion "0 0 600 600"
  pack .plotcanvas.scrn -side left

#
#  bind left button to reset time to indicated on lower axis
#
  bind .plotcanvas.scrn <Button-1> {ResetTime %x %y}

#
# put menu buttons on bottom of LinePlot
#
  for { set i 0} { $i < 4 } { incr i} {

    menubutton .plotcanvas.state($i) -text ""  -menu .plotcanvas.state($i).menu
    .plotcanvas.state($i) configure -pady 0

    menu .plotcanvas.state($i).menu
    .plotcanvas.state($i).menu add cascade -label "Vec" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.vec
      menu .plotcanvas.state($i).menu.vec 
       .plotcanvas.state($i).menu.vec add command -label "Dot" -command "DrawState 40 $i"
       .plotcanvas.state($i).menu.vec add command -label "Norm" -command "DrawState 41 $i"
       .plotcanvas.state($i).menu.vec add command -label "Max" -command "DrawState 42 $i"
       .plotcanvas.state($i).menu.vec add command -label "Min" -command "DrawState 43 $i"
       .plotcanvas.state($i).menu.vec add command -label "TDot" -command "DrawState 44 $i"
       .plotcanvas.state($i).menu.vec add command -label "Scale" -command "DrawState 45 $i"
       .plotcanvas.state($i).menu.vec add command -label "Copy" -command "DrawState 46 $i"
       .plotcanvas.state($i).menu.vec add command -label "Set" -command "DrawState 47 $i"
       .plotcanvas.state($i).menu.vec add command -label "AXPY" -command "DrawState 48 $i"
       .plotcanvas.state($i).menu.vec add command -label "AYPX" -command "DrawState 49 $i"
       .plotcanvas.state($i).menu.vec add command -label "Swap" -command "DrawState 50 $i"
       .plotcanvas.state($i).menu.vec add command -label "WAXPY" -command "DrawState 51 $i"
       .plotcanvas.state($i).menu.vec add command -label "AssemblyBegin" -command "DrawState 52 $i"
       .plotcanvas.state($i).menu.vec add command -label "AssemblyEnd" -command "DrawState 53 $i"
       .plotcanvas.state($i).menu.vec add command -label "MTDot" -command "DrawState 54 $i"
       .plotcanvas.state($i).menu.vec add command -label "MDot" -command "DrawState 55 $i"
       .plotcanvas.state($i).menu.vec add command -label "MAXPY" -command "DrawState 56 $i"
       .plotcanvas.state($i).menu.vec add command -label "PMult" -command "DrawState 57 $i"
       .plotcanvas.state($i).menu.vec add command -label "SetValues" -command "DrawState 58 $i"
       .plotcanvas.state($i).menu.vec add command -label "Load" -command "DrawState 59 $i"
       .plotcanvas.state($i).menu.vec add command -label "View" -command "DrawState 60 $i"
       .plotcanvas.state($i).menu.vec add command -label "ScatterBegin" -command "DrawState 61 $i"
       .plotcanvas.state($i).menu.vec add command -label "ScatterEnd" -command "DrawState 62 $i"
       .plotcanvas.state($i).menu.vec add command -label "SetRandom" -command "DrawState 63 $i"

    .plotcanvas.state($i).menu add cascade -label "Mat" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.mat
      menu .plotcanvas.state($i).menu.mat
       .plotcanvas.state($i).menu.mat add command -label "Mult" -command "DrawState 0 $i"
       .plotcanvas.state($i).menu.mat add command -label "MatrixFreeMult" -command "DrawState 1 $i"
       .plotcanvas.state($i).menu.mat add command -label "AssemblyBegin" -command "DrawState 2 $i"
       .plotcanvas.state($i).menu.mat add command -label "AssemblyEnd" -command "DrawState 3 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetReordering" -command "DrawState 4 $i"
       .plotcanvas.state($i).menu.mat add command -label "MultTrans" -command "DrawState 5 $i"
       .plotcanvas.state($i).menu.mat add command -label "MultAdd" -command "DrawState 6 $i"
       .plotcanvas.state($i).menu.mat add command -label "MultTransAdd" -command "DrawState 7 $i"
       .plotcanvas.state($i).menu.mat add command -label "LUFactor" -command "DrawState 8 $i"
       .plotcanvas.state($i).menu.mat add command -label "CholeskyFactor" -command "DrawState 9 $i"
       .plotcanvas.state($i).menu.mat add command -label "LUFactorSymbolic" -command "DrawState 10 $i"
       .plotcanvas.state($i).menu.mat add command -label "ILUFactorSymbolic" -command "DrawState 11 $i"
       .plotcanvas.state($i).menu.mat add command -label "CholeskyFactorSymbolic" -command "DrawState 12 $i"
       .plotcanvas.state($i).menu.mat add command -label "IncompleteCholeskyFactorSymbolic" -command "DrawState 13 $i"
       .plotcanvas.state($i).menu.mat add command -label "LUFactorNumeric" -command "DrawState 14 $i"
       .plotcanvas.state($i).menu.mat add command -label "CholeskyFactorNumeric" -command "DrawState 15 $i"
       .plotcanvas.state($i).menu.mat add command -label "Relax" -command "DrawState 16 $i"
       .plotcanvas.state($i).menu.mat add command -label "Copy" -command "DrawState 17 $i"
       .plotcanvas.state($i).menu.mat add command -label "Convert" -command "DrawState 18 $i"
       .plotcanvas.state($i).menu.mat add command -label "Scale" -command "DrawState 19 $i"
       .plotcanvas.state($i).menu.mat add command -label "ZeroEntries" -command "DrawState 20 $i"
       .plotcanvas.state($i).menu.mat add command -label "Solve" -command "DrawState 21 $i"
       .plotcanvas.state($i).menu.mat add command -label "SolveAdd" -command "DrawState 22 $i"
       .plotcanvas.state($i).menu.mat add command -label "SolveTran" -command "DrawState 23 $i"
       .plotcanvas.state($i).menu.mat add command -label "SolveTransAdd" -command "DrawState 24 $i"
       .plotcanvas.state($i).menu.mat add command -label "SetValues" -command "DrawState 25 $i"
       .plotcanvas.state($i).menu.mat add command -label "ForwardSolve" -command "DrawState 26 $i"
       .plotcanvas.state($i).menu.mat add command -label "BackwardSolve" -command "DrawState 27 $i"
       .plotcanvas.state($i).menu.mat add command -label "Load" -command "DrawState 28 $i"
       .plotcanvas.state($i).menu.mat add command -label "View" -command "DrawState 29 $i"
       .plotcanvas.state($i).menu.mat add command -label "ILUFactor" -command "DrawState 30 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetColoring" -command "DrawState 31 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetSubMatrices" -command "DrawState 32 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetValues" -command "DrawState 33 $i"
       .plotcanvas.state($i).menu.mat add command -label "IncreaseOverlap" -command "DrawState 34 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetRow" -command "DrawState 35 $i"
       .plotcanvas.state($i).menu.mat add command -label "GetPartitioning" -command "DrawState 36 $i"

    .plotcanvas.state($i).menu add cascade -label "SLES" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.sles
      menu .plotcanvas.state($i).menu.sles
       .plotcanvas.state($i).menu.sles add command -label "Solve" -command "DrawState 70 $i"
       .plotcanvas.state($i).menu.sles add command -label "SetUp" -command "DrawState 71 $i"

    .plotcanvas.state($i).menu add cascade -label "KSP" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.ksp
      menu .plotcanvas.state($i).menu.ksp
       .plotcanvas.state($i).menu.ksp add command -label "GMRESOrthogonalization" -command "DrawState 72 $i"

    .plotcanvas.state($i).menu add cascade -label "PC" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.pc
      menu .plotcanvas.state($i).menu.pc
       .plotcanvas.state($i).menu.pc add command -label "ModifyMatrices" -command "DrawState 74 $i"
       .plotcanvas.state($i).menu.pc add command -label "SetUp" -command "DrawState 75 $i"
       .plotcanvas.state($i).menu.pc add command -label "SetUpOnBlocks" -command "DrawState 76 $i"
       .plotcanvas.state($i).menu.pc add command -label "Apply" -command "DrawState 77 $i"
       .plotcanvas.state($i).menu.pc add command -label "ApplyLeft" -command "DrawState 78 $i"
       .plotcanvas.state($i).menu.pc add command -label "ApplyRight" -command "DrawState 79 $i"

    .plotcanvas.state($i).menu add cascade -label "TS" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.ts
      menu .plotcanvas.state($i).menu.ts
       .plotcanvas.state($i).menu.ts add command -label "Step" -command "DrawState 90 $i"
       .plotcanvas.state($i).menu.ts add command -label "PseudoCmptTS" -command "DrawState 91 $i"

    .plotcanvas.state($i).menu add cascade -label "SNES" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.snes
      menu .plotcanvas.state($i).menu.snes
       .plotcanvas.state($i).menu.snes add command -label "Solve" -command "DrawState 80 $i"
       .plotcanvas.state($i).menu.snes add command -label "LineSearch" -command "DrawState 81 $i"
       .plotcanvas.state($i).menu.snes add command -label "FunctionEvaluation" -command "DrawState 82 $i"
       .plotcanvas.state($i).menu.snes add command -label "JacobianEvaluation" -command "DrawState 83 $i"
       .plotcanvas.state($i).menu.snes add command -label "MinimizationFunctionEvaluation" -command "DrawState 84 $i"
       .plotcanvas.state($i).menu.snes add command -label "GradientEvaluation" -command "DrawState 85 $i"
       .plotcanvas.state($i).menu.snes add command -label "HessianEvaluation" -command "DrawState 86 $i"

    .plotcanvas.state($i).menu add cascade -label "EC" -underline 0 \
	                       -menu .plotcanvas.state($i).menu.ec
      menu .plotcanvas.state($i).menu.ec
       .plotcanvas.state($i).menu.ec add command -label "SetUp" -command "DrawState 105 $i"
       .plotcanvas.state($i).menu.ec add command -label "Solve" -command "DrawState 106 $i"

    set y [expr .79 + .048*$i]
    place .plotcanvas.state($i) -relx .001 -rely $y
  }
}


#
#  Resets the display to indicate a time that was obtained by
# pressing the mouse
#
proc ResetTime {x y} {
  global TotalTime TotalFlops
  global nobjects ndestroyed resolution nevents
  global time event cookie type idI idJ idK objcookie objtype
  global eFlop eMem eMaxMem TotalMem
  global PlotW PlotH PlotB
  global redcircle bluecircle greencircle

  set newtime [expr $TotalTime*($x-$PlotB)/$PlotW]
  Go_To_Time $newtime
}

proc Calc_Coordinates_Plot {} {
  global TotalTime TotalFlops
  global nobjects ndestroyed resolution nevents
  global time event cookie type idI idJ idK objcookie objtype
  global eFlop eMem eMaxMem TotalMem
  global PlotW PlotH PlotB beeninDrawState
  global redcircle bluecircle greencircle player_status

  set player_status "Plotting curve..." ; update

  set eFlop(0)   0
  set eMem(0)    0
  set eMaxMem(0) 0

#
# put in axis
#
  set lastx $PlotB
  set x     [expr $PlotB+$PlotW]
  set y     [expr $PlotB+$PlotH+1]
  .plotcanvas.scrn create line $lastx $y $x $y -arrow last
  .plotcanvas.scrn create line $lastx $y $lastx $PlotB -arrow last
  set y [expr 1.4*$PlotB+$PlotH]
  set x [expr $PlotB + .9*$PlotW]
  set txt "-text {Time}"
  eval ".plotcanvas.scrn create text $x $y $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "


#
# indicate what curves are what 
#
  set lastx [expr 1.1*$PlotB]
  set x [expr 1.9*$PlotB]
  set y [expr .6*$PlotB]
  .plotcanvas.scrn create line $lastx $y $x $y -fill red
 
  set x [expr 2.1*$PlotB]
  set txt "-text {Floating point}"
  eval ".plotcanvas.scrn create text $x $y $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "

  set lastx [expr 5.1*$PlotB]
  set x [expr 5.9*$PlotB]
  .plotcanvas.scrn create line $lastx $y $x $y -fill green
 
  set x [expr 6.1*$PlotB]
  set txt "-text {Memory}"
  eval ".plotcanvas.scrn create text $x $y $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "

  set lastx [expr 8.3*$PlotB]
  set x [expr 9.1*$PlotB]
  .plotcanvas.scrn create line $lastx $y $x $y -fill blue
 
  set x [expr 9.3*$PlotB]
  set txt "-text {Maximum Memory}"
  eval ".plotcanvas.scrn create text $x $y $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "

#
 
  set lastx $PlotB
  set lasty1 [expr $PlotH + $PlotB]
  set lasty2 [expr $PlotH + $PlotB]
  set lasty3 [expr $PlotH + $PlotB]
#
#  plot floating point, max mem, mem 
#
  set shift [expr $PlotB + $PlotH]
  set scale1 [expr  $PlotH/($TotalFlops+.00000001)]
  set TotalMem $eMaxMem($nevents)
  set scale2 [expr  $PlotH/($TotalMem+.00000001)]
	for { set i 1} { $i <= $nevents } { incr i} {
          set x [expr $PlotB + $PlotW*$time($i)/($TotalTime+.0000000001)]
          set y [expr  $shift - $scale1*$eFlop($i)]
          .plotcanvas.scrn create line $lastx $lasty1 $x $y -fill red
          set lasty1 $y
          set y [expr $shift - $scale2*$eMaxMem($i)]
          .plotcanvas.scrn create line $lastx $lasty2 $x $y -fill blue
          set lasty2 $y
          set y [expr $shift - $scale2*$eMem($i)]
          .plotcanvas.scrn create line $lastx $lasty3 $x $y -fill green
          set lasty3 $y
          set lastx $x
	}
#
#  put in initial circles
#
  set xmin [expr $PlotB-4]
  set xmax [expr $PlotB+4]
  set ymin [expr $PlotB+$PlotH+4]
  set ymax [expr $PlotB+$PlotH-4]
  set redcircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill red]
  set bluecircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill blue]
  set greencircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill green]
	set player_status "" ; update

  set beeninDrawState(0) 0
  set beeninDrawState(1) 0
  set beeninDrawState(2) 0
  set beeninDrawState(3) 0

  DrawState 80 0 
  DrawState 70 1 
  DrawState 76 2
  DrawState 0  3
}	 

#
#  Draws when one particular state is active
#
proc DrawState {state level} {
  global TotalTime TotalFlops action
  global nobjects ndestroyed resolution nevents
  global time event cookie type idI idJ idK objcookie objtype
  global eFlop eMem eMaxMem TotalMem
  global PlotW PlotH PlotB
  global redcircle bluecircle greencircle num_segs
  global beeninDrawState


  if { $beeninDrawState($level) == 1} {
    .plotcanvas.scrn delete joe($level)
  }

      
  set y [expr 2*$PlotB + $PlotH - .15*$PlotB + .54*$level*$PlotB]
  set num_segs 0

  set count 0
  set colors(0) blue
  set colors(1) red
  set colors(2) black
  set colors(3) blue
#
# loop over all events looking for requested
#
  for {set i 1} {$i < $nevents} {incr i} {
    if { $event($i) == 2 } {
      if { $type($i) == $state } {
        set lastx [expr round($PlotB + $PlotW*$time($i)/$TotalTime)]
        for {set j [expr $i+1]} {$j < $nevents} {incr j} {
          if { $type($j) == $state } {
            set x [expr round($PlotB + $PlotW*$time($j)/$TotalTime)]
	    if { $x == $lastx } {
              incr x
            }
            break
          }
        }
        .plotcanvas.scrn create line $lastx $y $x $y -fill $colors($level) -width 3 -tag joe($level)
        set beeninDrawState($level) 1
        incr count
      }
    }
  }
  .plotcanvas.state($level) configure -text "$action($state) $count" 
}

#############################################################################
# If continuous is set to be nonzero, then at the beginning and end of 
# running, the viewer automatically reverses direction (useful for demos).
#############################################################################
  set continuous 0
# set continuous 1
##############################################################################
#	Commands to set up menu bar & play bar
##############################################################################

set canvas_height 0
set height 0
set canvas_width 448
set width 448

frame .mbar -relief raised -bd 2
frame .pbar -relief raised -bd 2
frame .vwr
	
scrollbar .vwr.xscroll -orient horizontal -command ".vwr.scrn xview"
scrollbar .vwr.yscroll -orient vertical -command ".vwr.scrn yview"
canvas .vwr.scrn -relief sunken -xscrollcommand ".vwr.xscroll set" \
	-yscrollcommand ".vwr.yscroll set"

set num_log_message 0


message .vwr.scrn.status(0) -width 200 -textvariable log_message(0)

message .vwr.scrn.status(1) -width 200 -textvariable log_message(1)
message .vwr.scrn.status(2) -width 200 -textvariable log_message(2)
message .vwr.scrn.status(3) -width 200 -textvariable log_message(3)
message .vwr.scrn.status(4) -width 200 -textvariable log_message(4)
message .vwr.scrn.status(5) -width 200 -textvariable log_message(5)
message .vwr.scrn.status(6) -width 200 -textvariable log_message(6)
message .vwr.scrn.status(7) -width 200 -textvariable log_message(7)
message .vwr.scrn.status(8) -width 200 -textvariable log_message(8)
message .vwr.scrn.status(9) -width 200 -textvariable log_message(9)
message .vwr.scrn.status(10) -width 200 -textvariable log_message(10)
place .vwr.scrn.status(0) -x 1 -y 1 -anchor nw
place .vwr.scrn.status(1) -x 1 -y 16 -anchor nw
place .vwr.scrn.status(2) -x 1 -y 31 -anchor nw
place .vwr.scrn.status(3) -x 1 -y 46 -anchor nw
place .vwr.scrn.status(4) -x 1 -y 61 -anchor nw
place .vwr.scrn.status(5) -x 1 -y 76 -anchor nw
place .vwr.scrn.status(6) -x 1 -y 91 -anchor nw
place .vwr.scrn.status(7) -x 1 -y 106 -anchor nw
place .vwr.scrn.status(8) -x 1 -y 121 -anchor nw
place .vwr.scrn.status(9) -x 1 -y 136 -anchor nw
place .vwr.scrn.status(10) -x 1 -y 151 -anchor nw

set log_message(0) {}
set log_message(1) {}
set log_message(2) {}
set log_message(3) {}
set log_message(4) {}
set log_message(5) {}
set log_message(6) {}
set log_message(7) {}
set log_message(8) {}
set log_message(9) {}
set log_message(10) {}

message .vwr.scrn.time -width 200 -textvariable simulation_time
pack .vwr.xscroll -side bottom -fill x
pack .vwr.yscroll -side right -fill y
pack .vwr.scrn -expand 1 -fill both

place .vwr.scrn.time -relx 0.005 -rely .995 -anchor sw

##############################################################################
# menubar widgets
##############################################################################
menubutton .mbar.file -text File -underline 0\
	-menu .mbar.file.menu -relief raised
menubutton .mbar.view -text View -underline 0\
	-menu .mbar.view.menu -relief raised
menubutton .mbar.player -text Player -underline 0\
		  -menu .mbar.player.menu -relief raised
menubutton .mbar.options -text Options -underline 0\
	-menu .mbar.options.menu -relief raised
button .mbar.demos -text "About PETScView" -command PV_Introduction
# -underline 0	-menu .mbar.demos.menu
menubutton .mbar.help -text Help -underline 0\
	-menu .mbar.help.menu

#	pack menu commands
pack .mbar.file .mbar.view .mbar.player .mbar.options .mbar.demos -side left
pack .mbar.help -side right

tk_menuBar .mbar .mbar.file .mbar.view .mbar.player .mbar.options .mbar.help
focus .mbar
#focus default .mbar

#
# file menu
##############################################################################
menu .mbar.file.menu
.mbar.file.menu add command -label "Clear" -underline 0 \
	-command {Clear}

.mbar.file.menu add separator
.mbar.file.menu add command -label "Load Log File..." -underline 5 \
	-command {Select_Log_File}
.mbar.file.menu add command -label "Load Definitions..." -underline 5 \
	-command {Select_Definitions_File}
 
.mbar.file.menu add separator
.mbar.file.menu add command -label "Print..." -underline 0 \
	-command {Print}

.mbar.file.menu add separator
.mbar.file.menu add command -label "Exit" -underline 0 \
	-command {Exit}
#
# view menu
##############################################################################
menu .mbar.view.menu
.mbar.view.menu add separator
.mbar.view.menu add checkbutton -label "Show time" -underline 0 \
	-variable time_bin -command {set simulation_time [expr {$time_bin ? "$time($cstep) secs." : ""}]}

.mbar.view.menu add separator
.mbar.view.menu add command -label "View profiling data..." -underline 0 \
	-command {Read_Text $filename .profile "Profiling Data"}
#.mbar.view.menu add separator
#.mbar.view.menu add command -label "Performance Stats..." -underline 0 \
#	-command Performance_Stats

# player menu
##############################################################################
menu .mbar.player.menu
.mbar.player.menu add command -label "Rewind" -accelerator "ctrl+z"\
		  -command {Rewind 0}
bind .mbar <Control-z> {Rewind 0}
.mbar.player.menu add command -label "Step Backward" -accelerator "ctrl+x"\
		  -command {Step_Backward $stepsize}
bind .mbar <Control-x> {Step_Backward $stepsize}
.mbar.player.menu add command -label "Play Backward" -accelerator "ctrl+c"\
		  -command {Play_Backward}
bind .mbar <Control-c> {Play_Backward}
.mbar.player.menu add command -label "Stop" -accelerator "ctrl+v"\
		  -command {Stop}
bind .mbar <Control-v> {Stop}
.mbar.player.menu add command -label "Play Forward" -accelerator "ctrl+b"\
		  -command {Play_Forward}
bind .mbar <Control-b> {Play_Forward}
.mbar.player.menu add command -label "Step Forward" -accelerator "ctrl+n"\
		  -command {Step_Forward $stepsize}
bind .mbar <Control-n> {Step_Forward $stepsize}
.mbar.player.menu add command -label "Finish" -accelerator "ctrl+m"\
		  -command {Fast_Forward $nevents}
bind .mbar <Control-m> {Fast_Forward $nevents}

.mbar.player.menu add separator
.mbar.player.menu add command -label "Go to step..." -accelerator "ctrl+s" \
	-command "Get_Step"
bind .mbar <Control-s> "Get_Step"
.mbar.player.menu add command -label "Go to time nearest to..." \
	-accelerator "ctrl+t" -command "Get_Time"
bind .mbar <Control-t> "Get_Time"

# options menu
##############################################################################
menu .mbar.options.menu
.mbar.options.menu add separator
.mbar.options.menu add command -label "Step Size..." -underline 1 \
	-command {Get_User_Input .changestepsize "Change Step Size" "Change step size to:" $cstep 0 1000 "Change_Step_Size"}

.mbar.options.menu add cascade -label "Speed" -underline 0 \
	-menu .mbar.options.menu.speed
menu .mbar.options.menu.speed
.mbar.options.menu.speed add radiobutton -label "No delay" -variable delay\
	-value -1 -underline 0
.mbar.options.menu.speed add radiobutton -label "Real time" -variable delay \
	-value 0 -underline 0
.mbar.options.menu.speed add radiobutton -label "Second delay" -variable delay\
	-value 1000 -underline 0
.mbar.options.menu.speed add separator
.mbar.options.menu.speed add command -label "After delay..." -underline 0\
	 -command {Get_User_Input .changedelay "Change Delay"  "Change delay to (ms):" $delay 1 2000 "Change_Delay"}

.mbar.options.menu add separator
.mbar.options.menu add cascade -label "Change Colors" -underline 0 \
	-menu .mbar.options.menu.colors
menu .mbar.options.menu.colors
.mbar.options.menu.colors add command -label "Change idle object color" \
	-underline 7 -command {Change_Color idle "Change Idle Object Color"}
.mbar.options.menu.colors add command -label "Change active object color" \
	-underline 7 -command {Change_Color active "Change Active Object Color"}
.mbar.options.menu.colors add command -label "Change dead object color" \
	-underline 7 -command {Change_Color dead "Change Dead Object Color"}
.mbar.options.menu.colors add command -label "Change log file object color" \
	-underline 7 -command {Change_Color logfile "Change Log File Object Color"}

# demo menu
##############################################################################
menu .mbar.demos.menu
.mbar.demos.menu add command -label "PETScView Demo" -underline 5 \
	-command {PETScView_Demo}
.mbar.demos.menu add command -label "PETScOpts Demo" -underline 5 \
	-command {PETScOpts_Demo}
.mbar.demos.menu add command -label "PETScView Demo Appl Code" -underline 15 \
	-command {PETScView_Demo_Appl}
.mbar.demos.menu add command -label "PETSc Library Hierarchy" -underline 14 \
	-command {PETSc_Picture}

# help menu
##############################################################################
menu .mbar.help.menu
.mbar.help.menu add command -label "About..." -underline 0 -command {About}
.mbar.help.menu add separator
.mbar.help.menu add command -label "Manual" -underline 0 -command {Read_Text \
	$env(PETSC_DIR)/bin/petscview.hlp .help "PETSc Viewer Manual"}
.mbar.help.menu add separator
.mbar.help.menu add command -label "Icon Key" -underline 0 -command minfo
#
# display help window
#
proc minfo {} {
  global minfocalled bitmaps petsc_dir color

  toplevel .minfomsg
  wm title .minfomsg "PETScView Icon Key"
  wm iconname .minfomsg "PETScView Icon Key"

  frame .minfomsg.mbar -relief raised -bd 2
  pack .minfomsg.mbar -side top -fill x -expand 1
  button .minfomsg.mbar.exit -text "Exit" -command {destroy .minfomsg; return}
  pack .minfomsg.mbar.exit -side left

  canvas .minfomsg.scrn -yscrollcommand ".minfomsg.yscroll set" 
  scrollbar .minfomsg.yscroll -command ".minfomsg.scrn yview"
  pack .minfomsg.yscroll -side right -fill y -expand 1
  .minfomsg.scrn config -height 333 -width 355 -scrollregion "0 0 270 1000"
  pack .minfomsg.scrn -side left

  set locx 70
  set locy 30
  set locx2 120
#
# OBJECT INFORMATION
#
  set txt "-text {PETSc Objects}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-bold-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/file.bit"
  set locy [expr $locy + 50]
  eval ".minfomsg.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill white"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- application program}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {SNES}"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create oval [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- nonlinear solver}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text SLES"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- linear solver}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {PC Name}"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create polygon $locx [expr $locy-16] [expr $locx-16] [expr $locy+16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- preconditioner}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {KSP Name}"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create polygon [expr $locx-6] [expr $locy-16] [expr $locx+6] [expr $locy-16] [expr $locx+16] [expr $locy-6] [expr $locx+16] [expr $locy+6] [expr $locx+6] [expr $locy+16] [expr $locx-6] [expr $locy+16] [expr $locx-16] [expr $locy+6] [expr $locx-16] [expr $locy-6] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- Krylov space iterative solver}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text DA"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-24] [expr $locy-16] [expr $locx+24] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel distributed array}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Stride"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-24] [expr $locy-8] [expr $locx+24] [expr $locy+8] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- stride index set}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Index"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-24] [expr $locy-8] [expr $locx+24] [expr $locy+8] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- general index set}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Scatter"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- vector scatter context}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/matrixp.bit"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel sparse matrix}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/matrix.bit"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- sequential sparse matrix}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/matrixsh.bit"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- shell matrix}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/vectorp.bit"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel vector}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/vector.bit"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- sequential vector}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text File"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- file viewer}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Matlab"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- Matlab viewer}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {Draw X}"
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create rectangle [expr $locx-24] [expr $locy-16] [expr $locx+24] [expr $locy+16] -fill $color(active)"
  eval ".minfomsg.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- X-window graphics}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
# COLOR KEY INFORMATION
#
  set txt "-text {Color Key}"
  set locy [expr $locy + 80]
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-bold-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(active)"
  set txt "-text {- active object}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(idle)"
  set txt "-text {- inactive object}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".minfomsg.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(dead)"
  set txt "-text {- destroyed object}"
  eval ".minfomsg.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
}

##############################################################################
# playbar widgets
##############################################################################

scale .pbar.scale -label Step -orient horizontal \
		  -command "Go_To_Step [lindex {[.pbar.scale get]} 2]"

button .pbar.rew -bitmap @$env(PETSC_DIR)/bin/bitmaps/rewind.bit \
	-relief raised -bd 4 -command {Rewind 0}
button .pbar.stepback -bitmap @$env(PETSC_DIR)/bin/bitmaps/stepback.bit \
	-relief raised -bd 4 -command {Step_Backward $stepsize}
button .pbar.playb -bitmap @$env(PETSC_DIR)/bin/bitmaps/playbackward.bit \
	-relief raised -bd 4 -command {Play_Backward}
button .pbar.stop -bitmap @$env(PETSC_DIR)/bin/bitmaps/stop.bit \
	-relief raised -bd 4 -command {Stop}
button .pbar.playf -bitmap @$env(PETSC_DIR)/bin/bitmaps/playforward.bit \
	-relief raised -bd 4 -command {Play_Forward}
button .pbar.stepforward -bitmap @$env(PETSC_DIR)/bin/bitmaps/stepforward.bit\
	 -relief raised -bd 4 -command {Step_Forward $stepsize}
button .pbar.ff -bitmap @$env(PETSC_DIR)/bin/bitmaps/fastforward.bit \
		  -relief raised -bd 4 -command {if {$file_bin == 1} {Fast_Forward $nevents}}

label .pbar.poslbl -text "Step #"
label .pbar.pos -width 4 -relief sunken -textvariable cstep

frame .pbar.status 
label .pbar.status.lbl -width 25 -textvariable player_status
pack .pbar.status.lbl -side left

# pack controls on playbar
pack .pbar.scale -side bottom -fill x
pack .pbar.rew .pbar.stepback .pbar.playb .pbar.stop .pbar.playf \
	.pbar.stepforward .pbar.ff .pbar.poslbl .pbar.pos .pbar.status \
	-side left -fill x

##############################################################################
#
#	Procedures Section
#
##############################################################################

##############################################################################
#	menu bar procedures
##############################################################################

#	file menu procedures
##############################################################################
proc Clear {} {
	global file_bin player_status small_size 
	
	if {$file_bin == 1} {
		pack forget .vwr ; update
		Clear_Variables
		set file_bin 0
		wm title . "PETScView"
		wm iconname . "PETScView"
		set player_status "No File."
		set cstep 0
		.pbar.scale set 0
	}
}
proc Clear_Variables {} {
	global nobjects ndestroyed resolution nevents
	global time event cookie type idI idJ idK objcookie objtype
        global eFlop eMem eMaxMem
	global parent objmessage objname objmem
	global TypeCount TypeFlop TypeTime TypeFlops
	global TotalTime TotalFlops
	global player_status filename
	global coordinates cstep active

#	destroy objects in canvas
	Remove_Object -1
	for {set i 1} {$i <= $cstep} {incr i} {
		if {$event($i) == 0} {
			Remove_Object $idI($i)
		}
	}
	set cstep 0
	.pbar.scale set $cstep

	unset nobjects ndestroyed resolution nevents
	unset time event cookie type idI idJ idK objcookie objtype
        unset eFlop eMem eMaxMem
	unset parent objmessage objname objmem
	unset TypeCount TypeFlop TypeTime TypeFlops
	unset TotalTime TotalFlops
	unset filename
	unset coordinates active
}

proc Select_Log_File {} {
	fileselect Load_Log_File "Open File:" "*.*" .fileSelectWindow fileselect.default.errorHandler  	
}
proc Load_Log_File {file} {
	global filename

	set filename $file
	Read_Data $filename
}

proc Select_Definitions_File {} {
	fileselect Load_Definitions "Load object definitions file:" "*.cfg" .fileSelectWindow fileselect.default.errorHandler
}
proc Load_Definitions {filename} {
	global player_status Name Icon GroupShape GroupDesc color action
	global file_bin obj_color env

	set player_status "Loading Definitions..."
		
	source $filename
	if {$file_bin == 1} {
		set obj_color(-1) color(logfile)
		Update_Objects
	}
	set player_status ""
}

proc Print {} {
	global PrintOpts

	toplevel .print
	wm title .print "Print Options"
	
	frame .print.topl -relief raised
	frame .print.topr -relief raised
	frame .print.bot -relief sunken -bd 2

	pack .print.bot -side bottom -fill x -expand 1
	pack .print.topl .print.topr -side left -fill x -expand 1

	frame .print.topl.name
	frame .print.topl.com
	frame .print.topl.dest

	pack .print.topl.name .print.topl.com .print.topl.dest -side top -fill both -expand 1 -padx 2m -pady 2m

#	printer name
	label .print.topl.name.lbl -text "Printer Name:"
	entry .print.topl.name.name -relief sunken -textvariable PrintOpts(printer)
	pack .print.topl.name.name -side bottom -fill x
	pack .print.topl.name.lbl -side left

#	print command
	label .print.topl.com.lbl -text "Print Command:"
	entry .print.topl.com.com -relief sunken -textvariable PrintOpts(printcommand)
	pack .print.topl.com.com -side bottom -fill x
	pack .print.topl.com.lbl -side left

#	destination radiobuttons
	radiobutton .print.topl.dest.ptr -relief flat -text "To file" -variable PrintOpts(destination) -value File
	radiobutton .print.topl.dest.file -relief flat -text "To printer" -variable PrintOpts(destination) -value Printer
	pack .print.topl.dest.ptr .print.topl.dest.file -side top -anchor w

	frame .print.topr.or
	frame .print.topr.col

	pack .print.topr.or .print.topr.col -side top -fill both -padx 2m -pady 2m 

#	orientation radiobuttons
	radiobutton .print.topr.or.land -relief flat -text "Landscape" -variable PrintOpts(orientation) -value 1
	radiobutton .print.topr.or.port -relief flat -text "Portrait" -variable PrintOpts(orientation) -value 0
	pack .print.topr.or.land .print.topr.or.port -side top -anchor w

#	color radiobuttons
	radiobutton .print.topr.col.col -relief flat -text "Color" -variable PrintOpts(colormode) -value color
	radiobutton .print.topr.col.gs -relief flat -text "Grayscale" -variable PrintOpts(colormode) -value gray
	radiobutton .print.topr.col.mono -relief flat -text "Monochrome" -variable PrintOpts(colormode) -value mono
	pack .print.topr.col.col .print.topr.col.gs .print.topr.col.mono -side top -anchor w

	button .print.bot.button1 -text Print -command {destroy .print ; Print_To_$PrintOpts(destination)}
	frame .print.bot.default -relief sunken -bd 1
	raise .print.bot.button1
	pack .print.bot.default -side left -expand 1 -padx 3m -pady 2m
	pack .print.bot.button1 -in .print.bot.default -side left -padx 2m -pady 2m -ipadx 2m -ipady 2m
	
	button .print.bot.button2 -text Cancel -command "destroy .print"
	pack .print.bot.button2 -side left -expand 1 -padx 3m -pady 3m -ipadx 2m -ipady 1m

	bind .print <Return> ".print.bot.button1 flash ; .print.bot.button1 invoke"
	bind .print <Control-c> ".print.bot.button2 flash ; .print.bot.button2 invoke"
	bind .print.topl.name.name <Return> ".print.bot.button1 flash ; .print.bot.button1 invoke"
	bind .print.topl.com.com <Return> ".print.bot.button1 flash ; .print.bot.button1 invoke"

	grab set .print	
}
proc Print_To_Printer {} {
	global PrintOpts filename height width file_bin

	if {$file_bin == 1} {
		if {![string compare "" $PrintOpts(printer)} {
			exec $PrintOpts(printcommand) -T$filename << [.vwr.scrn postscript \
				-rotate $PrintOpts(orientation) -width $width -height $height]
		} else {
			exec $PrintOpts(printcommand) -P$PrintOpts(printer) -T$filename  \
				<< [.vwr.scrn postscript -rotate $PrintOpts(orientation) -width \
				$width -height $height]
		}
	}
}
proc Print_To_File {} {
	global file_bin

	if {$file_bin == 1} {
		fileselect Print_Canvas_To_File "Print to File:" "*.ps" \
			.fileSelectWindow fileselect.default.errorHandler
	}
}
proc Print_Canvas_To_File {filename} {
	global PrintOpts height width

	set button 0
	if {[file isfile $filename] == 1} {
		set button [Dialog .fileexists "File Already Exists" "File \"$filename\" already exits.  Are you sure that you want to overwrite it?" warning.bit 1 "Continue" "Cancel"]
	} 
	if {$button == 0} {
			exec cat << [.vwr.scrn postscript -rotate $PrintOpts(orientation) -colormode $PrintOpts(colormode) -width $width -height $height] > $filename
	}
}

proc Exit {} {
	set button [Dialog .quit {Exit} \
		{Do you really want to exit PETScView?} {} 0 {Exit petscview} \
			{Cancel}]
	if {$button == 0} {Write_Defaults ; exit}
}
proc Write_Defaults {} {
	global env color time_bin stepsize delay PrintOpts def_file

	set fd [open $env(HOME)/.petscviewrc w]

	puts $fd "##############################################################################"
	puts $fd "# Default settings used by PETSc View"
	puts $fd "##############################################################################"
	puts $fd ""
	puts $fd "##############################################################################"
	puts $fd "# Colors may be specified symbolically or numerically.  Symbolic names, such" 
	puts $fd "# red, green, or white must be valid and defined in the rgb.txt file"
	puts $fd "# in your systems X library directory.  This file contains their"
	puts $fd "# appropriate mappings for their numeric representation.  Colors may be"
	puts $fd "# defined numerically in terms of their red, green and blue components."
	puts $fd "# The components may be specified in 4-bit, 8-bit, 12-bit, or 16-bit"
	puts $fd "# values.  For example:"
	puts $fd "#	#RGB		4-bit"
	puts $fd "#	#RRGGBB		8-bit"
	puts $fd "#	#RRRGGGBBB	12-bit"
	puts $fd "#	#RRRRGGGGBBBB	16-bit"
	puts $fd "# Here each R, G, or B represents one hexadecimal digit of red, green,"
	puts $fd "# or blue intensity, respectively.  The # is required as the first"
	puts $fd "# character of the specification.   In addition, the same number of"
	puts $fd "# digits must be specified for each component.  A value of all 1's"
	puts $fd "# represents \"full on\" for that color.  (0 represents \"full off\")."
	puts $fd "# For example,"
	puts $fd "#	#000 = black"
	puts $fd "#	#f00 = red"
	puts $fd "#	#ff0 = yellow"
	puts $fd "#	#ff0 = white"
	puts $fd "##############################################################################"
	puts $fd ""
	puts $fd "set color(logfile) \"$color(logfile)\""
	puts $fd "set color(idle) \"$color(idle)\""
	puts $fd "set color(dead) \"$color(dead)\""
	puts $fd "set color(active) \"$color(active)\""
	puts $fd ""
	puts $fd "# change value to 0 causes PETScView to not show the time"
	puts $fd "set time_bin $time_bin"
	puts $fd ""
	puts $fd "# default value for the step size"
	puts $fd "set stepsize $stepsize"
	puts $fd ""
	puts $fd "# default value for the delay in milliseconds (-1 = no delay, 0 = real time , "
	puts $fd "#	1000 = one second)"
	puts $fd "set delay $delay"
	puts $fd ""
	puts $fd "# default settings for printing documents"
	puts $fd "#############################################################################"
	puts $fd ""
	puts $fd "# PrintOpts(destination may either by \"Printer\" or \"File\""
	puts $fd "set PrintOpts(destination) $PrintOpts(destination)"
	puts $fd "# local command for printing postscript documents"
	puts $fd "set PrintOpts(printcommand) \"$PrintOpts(printcommand)\""
	puts $fd "# default printer"
	puts $fd "set PrintOpts(printer) \"$PrintOpts(printer)\""
	puts $fd "# default orientation (1 = landscape, 0 = portrait)"
	puts $fd "set PrintOpts(orientation) $PrintOpts(orientation)"
	puts $fd "# default colormode (can be gray, mono, or color)"
	puts $fd "set PrintOpts(colormode) $PrintOpts(colormode)"
	puts $fd ""
	puts $fd "# default file for the object definitions"
	puts $fd "set def_file $def_file"

	close $fd
}

#	View menu procedures
#############################################################################
proc Performance_Stats {} {
	global filename file_bin
	global action TypeCount TypeFlop TypeTime TypeFlops TotalFlops TotalTime
	if {$file_bin == 0} {return}

	set line "                                                                              \n"
	
  	toplevel .performance
	
	wm title .performance "Performance Stats - $filename"

	frame .performance.mbar -relief raised -bd 2
	text .performance.text -height 24 -width 80 -bd 2 \
		-yscrollcommand ".performance.scroll set"
	scrollbar .performance.scroll -relief raised \
		-command ".performance.text yview"

	pack .performance.mbar -side top -fill x -expand 1
	pack .performance.scroll -side right -fill y -expand 1
	pack .performance.text -side left -fill both -expand 1
	
	button .performance.mbar.exit -text "Exit" -command {destroy .performance ;\
		return}

	pack .performance.mbar.exit -side left

  	for {set i 1} {$i < 7} {incr i} {
		.performance.text insert $i.0 $line
	}

	set dummy [expr $TotalFlops/$TotalTime]

	.performance.text insert 1.0 "Total Flops: $TotalFlops\n"
	.performance.text insert 2.0 "Total Time: $TotalTime\n"
	.performance.text insert 3.0 "Total Flop Rate $dummy\n"

	.performance.text insert 5.1 "Operation"
	.performance.text insert 5.25 "Count"
	.performance.text insert 5.32 "MFlop/Sec"
	.performance.text insert 5.48 "%Time"
	.performance.text insert 5.64 "%Flop\n"

	.performance.text insert 6.0 "--------------------------------------------------------------------------------\n"

  	set y 6

  	for { set i 0} { $i < 65 } {incr i} {
    		if { $TypeCount($i) > 0 } {
				incr y
				.performance.text insert $y.0 $line
				.performance.text insert $y.1 $action($i)
				.performance.text insert $y.25 $TypeCount($i)
				.performance.text insert $y.32 $TypeFlops($i)
				.performance.text insert $y.48 [expr (100.0*$TypeTime($i))/$TotalTime]
				.performance.text insert $y.64 "[expr (100.0*$TypeFlop($i))/($TotalFlops+.000000001)]"
				
    		}
  	}
}

# 	Player menu procedures
##############################################################################
proc Step_Backward {stepsize} {
	global cstep player_status file_bin

	if {$file_bin == 1} {
		set stop 1

		if {[expr $cstep-$stepsize] >= 0} {
		 	set player_status "Stepping Back..." ; update
		  	Rewind [expr $cstep-$stepsize]
		}
	}	
}
proc Play_Backward {} {
	global cstep player_status file_bin continuous stop

	if {$file_bin == 1} {
		if {$cstep > 0} {
			.pbar.playb config -fg green
		 	.pbar.stop config -fg black
		 	set player_status "Playing backward..." ; update
		 	Simulate -1
		 	.pbar.playb config -fg black
		}
                if {$continuous == 1} {
                        if {$stop == 1} return
                        after 3000
                        Play_Forward
                }
	}
}
proc Stop {} {
	global player_status stop file_bin
	
	if {$file_bin == 1} {
		if {$stop == 0} {
			.pbar.stop config -fg green
		 	set stop 1
		 	set player_status Stopped ; update
		}
	}
}
proc Play_Forward {} {
	global cstep nevents player_status file_bin continuous stop

	if {$file_bin == 1} {
		if {$cstep < $nevents} {
			.pbar.playf config -fg green
		 	.pbar.stop config -fg black
		 	set player_status "Playing forward..." ; update
		 	Simulate 1
		 	.pbar.playf config -fg black 
		}
                if {$continuous == 1} {
                        if {$stop == 1} return
                        after 3000
                        Play_Backward
                }
	}
}
proc Step_Forward {stepsize} {
	 global cstep nevents stop player_status file_bin
	
	 if {$file_bin == 1} {
	 	if {[expr $cstep+$stepsize] <= $nevents} {
			set player_status "Stepping forward..." ; update
		  	Fast_Forward [expr $cstep+$stepsize]
		}
	}
}
proc Fast_Forward stop_position {
	global player_status time_secs cstep file_bin stop

	if {$file_bin == 1} {
		set stop 1
		while {$cstep < $stop_position} {
			.pbar.ff config -fg green
		 	incr cstep
		 	Display_Events $cstep
                        Draw_Balls   $cstep
		}
		.pbar.ff config -fg black ; update
		.pbar.scale set $cstep
	}
}
proc Rewind stop_position {
	global event cstep file_bin stop simulation_time log_message
        global num_log_message

	if {$file_bin == 1} {
		set stop 1
		while {$cstep > $stop_position} {
			.pbar.stop config -fg black
			.pbar.rew config -fg green
			Undo_Events $cstep
			incr cstep -1
			if {$cstep == 0} {
				set simulation_time ""
				set log_message(0) "" 
                                Draw_Balls   0
				update
				break
			}
			Undo_Events $cstep
			Display_Events $cstep
                        Draw_Balls   $cstep
		}
		.pbar.rew config -fg black ; update
		.pbar.scale set $cstep
	}
}
proc Get_Step {} {
	global file_bin nevents cstep

	if {$file_bin == 1} {
		Get_User_Input .gotostep "Go to step" "Change step to:" $cstep 0 \
			$nevents Go_To_Step
	}
}
proc Go_To_Step {stop_position} {
	 global player_status cstep nevents file_bin stop

	 if {$file_bin == 1} {
		set stop 1
	 	set player_status "Going to step #$stop_position" ; update

	 	if {$stop_position > $cstep} {
			Fast_Forward $stop_position
	 	} else {
		  	Rewind $stop_position
	 	}
	}
}
proc Get_Time {} {
	global time nevents file_bin cstep

	if {$file_bin == 1} {
		Get_User_Input .gototime "Go to time" "Go to time nearest to (sec):" \
			$time($cstep) 0 $time($nevents) Go_To_Time
	}
}
proc Go_To_Time {selected_time} {
	global time nevents

	set old_diff $time($nevents)

	for {set i 0} {$i < $nevents} {incr i} {
		set new_diff [expr abs([expr $selected_time-$time($i)])]
		if {$new_diff < $old_diff} {
			set step $i
			set old_diff $new_diff
		} 
	}
	Go_To_Step $step
}

#	Options Commmands
##############################################################################
proc Change_Delay {value} {
	global delay

	set delay $value
}
proc Change_Step_Size {value} {
	global stepsize

	set stepsize $value
}
proc Change_Color {type title} {
	global color

	toplevel .c
	wm title .c $title
	
	set old $color($type)

	frame .c.top
	frame .c.mid
	frame .c.bot
	pack .c.top .c.mid .c.bot -side top -fill both

	label .c.top.lbl -text "Current $type color:"
	entry .c.top.entry -textvariable color($type) -width 30
	pack .c.top.lbl -side top -padx 2m -anchor w
	pack .c.top.entry -side bottom -padx 2m -anchor w 

	listbox .c.mid.colors -relief raised -bd 2 -geometry 30x10 \
		-yscrollcommand ".c.mid.scroll set"
	scrollbar .c.mid.scroll -command ".c.mid.colors yview"
	pack .c.mid.colors .c.mid.scroll -side left -fill y -pady 2m

	frame .c.bot.sample -height 1.5c -width 6c
	pack .c.bot.sample -side top -fill x
	button .c.bot.ok -text "OK" -command "Update_Objects ; destroy .c"
	button .c.bot.cancel -text "Cancel" -command "set color($type) $old ; destroy .c"
	pack .c.bot.ok .c.bot.cancel -side left -expand 1 -padx 3m \
		-pady 3m -ipadx 2m -ipady 1m

	set f [open /usr/lib/X11/rgb.txt]
	while {[gets $f line] >= 0} {
		.c.mid.colors insert end [lrange $line 3 end]
	}
	close $f

	if {![string compare "active" $type]} {
		bind .c.mid.colors <Button-1> {
			%W select from [%W nearest %y]
			set color(active) [%W get [%W nearest %y]]
			.c.bot.sample config -bg $color(active)
		}
		bind .c.mid.colors <Double-ButtonPress-1> {
			%W select from [%W nearest %y]
			set color(active) [%W get [%W nearest %y]]	
			.c.bot.ok invoke
		}
	} elseif {![string compare "idle" $type]} {
		bind .c.mid.colors <Button-1> {
			%W select from [%W nearest %y]
			set color(idle) [%W get [%W nearest %y]]
		}
		bind .c.mid.colors <Double-ButtonPress-1> {
			%W select from [%W nearest %y]
			set color(idle) [%W get [%W nearest %y]]	
			.c.bot.ok invoke
		}
	} elseif {![string compare "dead" $type]} {
		bind .c.mid.colors <Button-1> {
			%W select from [%W nearest %y]
			set color(dead) [%W get [%W nearest %y]]
		}
		bind .c.mid.colors <Double-ButtonPress-1> {
			%W select from [%W nearest %y]
			set color(dead) [%W get [%W nearest %y]]	
			.c.bot.ok invoke
		}
	} elseif {![string compare "logfile" $type]} {
		bind .c.mid.colors <Button-1> {
			%W select from [%W nearest %y]
			set color(logfile) [%W get [%W nearest %y]]
		}
		bind .c.mid.colors <Double-ButtonPress-1> {
			%W select from [%W nearest %y]
			set color(logfile) [%W get [%W nearest %y]]	
			.c.bot.ok invoke
		}
	}

	set oldfocus [focus]
	focus .c.top.entry
	grab set .c

	tkwait window .c
	focus $oldfocus
}

#	Help Commands
##############################################################################

proc About {} {
	Dialog .about "About petscview" "PETSc View - 1996\n
Matt Hille\n
Lois Curfman McInnes\n
Barry Smith\n
www.mcs.anl.gov/petsc/petsc.html\n
Argonne National Laboratory" version.bit -1 OK 
}

proc Read_Text {filename w title} {
	toplevel $w
	
	wm title $w $title
	wm iconname $w $title

	frame $w.mbar -bd 2 -relief raised
	text $w.text -relief sunken -bd 2 -yscrollcommand "$w.scroll set"
	$w.text configure -setgrid 1

	scrollbar $w.scroll -command "$w.text yview"
	button $w.mbar.exit -text Exit -command "destroy $w"
	
	pack $w.mbar -side top -fill x
	pack $w.mbar.exit -side left
	pack $w.scroll -side right -fill y
	pack $w.text -side left

	Load_Text $w $filename
}
proc Load_Text {w file} {
	$w.text delete 1.0 end
	set f [open $file]
	while {![eof $f]} {
		$w.text insert end [read $f 1000]
	}
	close $f
}

#
#  Draws balls on the LinePlot
#
proc Draw_Balls {cstep} {
	 global event time nevents
	 global player_status log_message simulation_time
	 global stop delay
         global eFlop eMem eMaxMem TotalTime TotalFlops TotalMem
         global PlotW PlotH PlotB redcircle bluecircle greencircle
         global num_log_message
#
  set x [expr $PlotB + $PlotW*$time($cstep)/($TotalTime+.00000000001)]
  set xmin [expr $x - 4]
  set xmax [expr $x + 4]
  set y [expr $PlotB + $PlotH - $PlotH*$eFlop($cstep)/($TotalFlops+.00000000001)]
  set ymin [expr $y - 4]
  set ymax [expr $y + 4]
  .plotcanvas.scrn delete $redcircle
  set redcircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill red]
  set y [expr $PlotB + $PlotH - $PlotH*$eMem($cstep)/($TotalMem+1)]
  set ymin [expr $y - 4]
  set ymax [expr $y + 4]
  .plotcanvas.scrn delete $greencircle
  set greencircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill green]
  set y [expr $PlotB + $PlotH - $PlotH*$eMaxMem($cstep)/($TotalMem+1)]
  set ymin [expr $y - 4]
  set ymax [expr $y + 4]
  .plotcanvas.scrn delete $bluecircle
  set bluecircle [.plotcanvas.scrn create oval $xmin $ymin $xmax $ymax -fill blue]

}
##############################################################################
#	Simulation procedures
##############################################################################
proc Simulate {dir} {
	 global event time nevents
	 global cstep
	 global player_status log_message simulation_time num_log_message
	 global stop delay

	 set stop 0

	 while {($cstep >= 0) && ($cstep <= $nevents)} { 
		  if {$stop == 1} {.pbar.scale set $cstep ; return}
		  if { $dir == -1 } {
		     Undo_Events $cstep
			  incr cstep $dir
		  	  if {$cstep == 0} {
			     set player_status Ready 
			     .pbar.scale set $cstep
				  set log_status ""
			 	  set simulation_time ""				  
                                  Draw_Balls $cstep
				  return
		          }
			  Undo_Events $cstep
			  Display_Events $cstep
                          Draw_Balls $cstep
		  } else {
			  incr cstep $dir
			  Display_Events $cstep
                          Draw_Balls $cstep

		  	  if {$cstep == $nevents} {
			     set player_status End
				  .pbar.scale set $cstep
			     set log_status ""
			     update ; set stop 0 ;return
		     }
		  }
#
# to make it run as fast as possible 
#
set delay -1
		  if {$delay == 0} {
		  		after [expr int(1000*($time($cstep)-$time([expr $cstep-$dir])))]
		  } elseif {$delay > 0} {
			 	after $delay
		  }
		  update
	 }
}
proc Display_Events cstep {
	 global event type idI idJ idK action parent active
	 global nevents log_message obj_color num_log_message
	 
	 if { $event($cstep) == 0 } {
		   set obj_color($idI($cstep)) color(idle)
	           Place_Object $idI($cstep)
                   Color_Object $idI($cstep)
                   set log_message($num_log_message) "Creating Object # $idI($cstep)..."
	 } elseif { $event($cstep) == 1 } {
		   set obj_color($idI($cstep)) color(dead)
                   Color_Object $idI($cstep)
                   set log_message($num_log_message) "Freeing Object # $idI($cstep)..."
	 } elseif { $event($cstep) == 2 } {
		  	incr active($idI($cstep))
			set obj_color($idI($cstep)) color(active)
			Color_Object $idI($cstep)
		  	if { $idJ($cstep) != -1 } {
				 incr active($idJ($cstep))
				 set obj_color($idJ($cstep)) color(active)
				 Color_Object $idJ($cstep)
		  	}     
		  	if { $idK($cstep) != -1 } {
				incr active($idK($cstep))
				set obj_color($idK($cstep)) color(active)
				Color_Object $idK($cstep)
		  	} 
                        set log_message($num_log_message) $action($type($cstep))
                        incr num_log_message 1
	 	} elseif { $event($cstep) == 3 } {
			incr active($idI($cstep)) -1
			if {$active($idI($cstep)) == 0} {
				set obj_color($idI($cstep)) color(idle)
				Color_Object $idI($cstep)
			}
		  	if { $idJ($cstep) != -1 } {
				incr active($idJ($cstep)) -1
				if {$active($idJ($cstep)) == 0} {
					set obj_color($idJ($cstep)) color(idle)
					Color_Object $idJ($cstep)
				}
		  	}        
		  	if { $idK($cstep) != -1 } {
				incr active($idK($cstep)) -1
				if {$active($idK($cstep)) == 0} {
					set obj_color($idK($cstep)) color(idle)
					Color_Object $idK($cstep)
				}
		  	}
                        incr num_log_message -1
                        set log_message($num_log_message) ""
                }
	 	Display_Time
}
proc Undo_Events cstep {
	global event type idI idJ idK action active
	global obj_color color  num_log_message log_message

	if { $event($cstep) == 0 } {
          Remove_Object $idI($cstep)
          set log_message($num_log_message) ""
	} elseif { $event($cstep) == 1 } {
		 set obj_color($idI($cstep)) color(idle)
		 Color_Object $idI($cstep)
                 set log_message($num_log_message) ""
	 } elseif { $event($cstep) == 2 } {
			incr active($idI($cstep)) -1
			if {$active($idI($cstep)) == 0} {
		  		set obj_color($idI($cstep)) color(idle)
		  		Color_Object $idI($cstep)
			}
		 	if { $idJ($cstep) != -1 } {
				incr active($idJ($cstep)) -1
				if {$active($idJ($cstep)) == 0} {
					set obj_color($idJ($cstep)) color(idle)
					Color_Object $idJ($cstep)
				}
		  }     
		  if { $idK($cstep) != -1 } {
				incr active($idK($cstep)) -1
				if {$active($idK($cstep)) == 0} {
					set obj_color($idK($cstep)) color(idle)
					Color_Object $idK($cstep)
				}
		  }
                        incr num_log_message -1
                        set log_message($num_log_message) ""
	 } elseif { $event($cstep) == 3 } {
		  	incr active($idI($cstep))
			set obj_color($idI($cstep)) color(active)
		  	Color_Object $idI($cstep)
			if { $idJ($cstep) != -1 } {
				incr active($idJ($cstep))
				set obj_color($idJ($cstep)) color(active)
				Color_Object $idJ($cstep)
		  	}        
		  	if { $idK($cstep) != -1 } {
				incr active($idK($cstep))
				set obj_color($idK($cstep)) color(active)
				Color_Object $idK($cstep)
		  	}
                 set log_message($num_log_message) $action($type($cstep))
                 incr num_log_message 1
	 }
	 Display_Time
}  	
proc Display_Time {} {
	global time cstep simulation_time time_bin

	if {$time_bin == 1} {
		set simulation_time "$time($cstep) secs."
	} else {
		set simulation_time ""
	}
}
proc Place_Object objid {
	global coordinates parent objcookie objtype obj_color color
	global GroupShape GroupDesc Icon Name
	global objname objmessage objmem

	set locx [lindex $coordinates($objid) 0]
	set locy [lindex $coordinates($objid) 1]
	set parx [lindex $coordinates($parent($objid)) 0]
	set pary [lindex $coordinates($parent($objid)) 1]

	.vwr.scrn bind object($objid,family) <Button-1> "Display_Info $objid"
	.vwr.scrn bind object($objid,item) <Button-1> "Display_Info $objid"

	$GroupShape($objcookie($objid)) $locx $locy $objid
	eval ".vwr.scrn create [string range [lindex $Icon($objcookie($objid),$objtype($objid)) 0] 1 end] $locx $locy $Icon($objcookie($objid),$objtype($objid)) -tags object($objid,item)"
	

# draw line to parent
	if {$objid != -1} {
		.vwr.scrn create line $locx [expr $locy-20] $parx [expr $pary+20] -tags object($objid,line)
	}

# object information 
	frame .objectinfo($objid) -relief groove -bd 2
	
	set info "id#: $objid
group: $GroupDesc($objcookie($objid))
name: 
$Name($objcookie($objid),$objtype($objid))
other: 
$objname($objid)
$objmessage($objid)
memory: $objmem($objid)"

	message .objectinfo($objid).msg -text $info -width 128
	pack .objectinfo($objid).msg 
}
proc Color_Object objid {
	global obj_color color

	eval ".vwr.scrn itemconfigure object($objid,family) -fill $$obj_color($objid)"
}
proc Display_Info {objid} {
	global coordinates

	set locx [lindex $coordinates($objid) 0]
	set locy [lindex $coordinates($objid) 1]

	place .objectinfo($objid) -x $locx -y $locy -anchor n
	bind .objectinfo($objid) <Button-1> "place forget .objectinfo($objid)"
	bind .objectinfo($objid).msg <Button-1> "place forget .objectinfo($objid)"
}	
proc Remove_Object objid {
	destroy .objectinfo($objid)
	.vwr.scrn delete object($objid,item)
	.vwr.scrn delete object($objid,family)
	.vwr.scrn delete object($objid,line)
}
proc Update_Objects {} {
	global event idI cstep file_bin

	if {$file_bin == 1} {
		Remove_Object -1
		Place_Object -1
		for {set i $cstep} {$i >= 1} {incr i -1} {
			if {$event($i) == 0} {
				Remove_Object $idI($i)
				Place_Object $idI($i)
			}
		}
	}
}
		
##############################################################################
#  Procedures to create object outlines
##############################################################################
proc Square {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create rectangle [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Thin_RectangleV {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Thin_RectangleH {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create rectangle [expr $locx-24] [expr $locy-8] [expr $locx+24] [expr $locy+8] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Rectangle {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create rectangle [expr $locx-24] [expr $locy-16] [expr $locx+24] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Wide_Rectangle {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Circle {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create oval [expr $locx-32] [expr $locy-32] [expr $locx+32] [expr $locy+32] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Tall_Oval {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create oval [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Wide_Oval {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create oval [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"		
}
proc Up_Triangle {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create polygon $locx [expr $locy-16] [expr $locx-16] [expr $locy+16] [expr $locx+16] [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Down_Triangle {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create polygon [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy-16] $locx [expr $locy+16] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Octagon {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create polygon [expr $locx-6] [expr $locy-16] [expr $locx+6] [expr $locy-16] [expr $locx+16] [expr $locy-6] [expr $locx+16] [expr $locy+6] [expr $locx+6] [expr $locy+16] [expr $locx-6] [expr $locy+16] [expr $locx-16] [expr $locy+6] [expr $locx-16] [expr $locy-6] -fill $$obj_color($objid) -tags object($objid,family)"
}
proc Pentagon {locx locy objid} {
	 global color obj_color
	 eval ".vwr.scrn create polygon $locx [expr $locy-16] [expr $locx+16] [expr $locy+16] [epxr $locx+8] [expr $locy+16] [expr $locx-8] [expr $locy+16] [expr $locx-16] $locy -fill $$obj_color($objid) -tags object($objid,family)"
}

##############################################################################
# procedures to set up simulation
##############################################################################
proc Read_Data {file} {
	global nobjects ndestroyed resolution nevents
	global time event cookie type idI idJ idK objcookie objtype
        global eFlop eMem eMaxMem
	global parent objmessage objname objmem
	global TypeCount TypeFlop TypeTime TypeFlops
	global TotalTime TotalFlops
	global player_status file_bin filename stepsize active

	set player_status "Reading data..." ; update
	if {$file_bin == 1} {Clear_Variables}
		
	set fd [open $file]	
	set filename $file

# get number of events and objects
	gets $fd aline
	scan $aline "Objects created %d Destroyed %d" nobjects ndestroyed
	gets $fd aline
	scan $aline "Clock Resolution %g" resolution
	gets $fd aline
	scan $aline "Events %d" nevents

#  read in all the events
	for { set i 1} { $i <= $nevents } { incr i} {
		gets $fd aline
		scan $aline "%f %d %d %d %d %d %d %f %f %f" time($i)  event($i) \
			cookie($i) type($i) idI($i) idJ($i) idK($i) \
                        eFlop($i) eMem($i) eMaxMem($i)
		if { $event($i) < 2  } {
			set objcookie($idI($i))  $cookie($i)
			set objtype($idI($i))  $type($i)   
  		}
	}

#  read in the objects
	for { set i 0} { $i < $nobjects } { incr i} {
		gets $fd aline
  		scan $aline "%d %d" parent($i) objmem($i) 
  		gets $fd objmessage($i)
  		gets $fd objname($i)
		set active($i) 0
	}

#  read in the times and flops
	for { set i 0} { $i < 200 } { incr i } {
		gets $fd aline
  		scan $aline "%d %d %f %f %f" dummy TypeCount($i) TypeFlop($i) \
			TypeTime($i) TypeFlops($i)
		set TypeFlops($i) [expr $TypeFlops($i)/1000000] 
	}

	gets $fd aline
	scan $aline "Total Flops %e %e" TotalFlops TotalTime

#	set variables for root object	
	set objcookie(-1) -1
	set objtype(-1) 0

	set time(0) 0
	set parent(-1) -1
	set objname(-1) $filename
	set objmessage(-1) "Objects made: $nobjects
Objects freed: $ndestroyed
Clock res.: $resolution
Events: $nevents"
	set objmem(-1) 0
	
        Calc_Coordinates
	Calc_Coordinates_Plot
	Initialize_Player
	if {$file_bin == 0} {pack .vwr -fill both -expand 1}

	if {$stepsize > $nevents} {
		set stepsize $nevents
	}

	set file_bin 1
	set player_status "" 
	wm title . "PETScView - $filename"
	wm iconname . "PETScView - $filename"
}
proc Calc_Coordinates {} {
	global nobjects parent coordinates player_status
	global height width

	set player_status "Calculating coordinates..." ; update
 
	set maxlvl 0 
	set objlvl(-1) 0

# determine object levels, find maximum level
	 for {set i 0} {$i < $nobjects} {incr i} {
		  set objlvl($i) [Get_Gen $i]
		  lappend level($objlvl($i)) $i
		  set maxlvl [expr {$objlvl($i) > $maxlvl ? $objlvl($i) : $maxlvl}]  
	 }
	 
# sort objects in level by parent id
	for {set k 1} {$k <= $maxlvl} {incr k} {
		set length [llength $level($k)]

		for {set i 0} {$i < [expr $length-1]} {incr i} {
			for {set j [expr $length-1]} {$i < $j} {incr j -1} {
				set tmp1 [lindex $level($k) [expr $j-1]]
				set tmp2 [lindex $level($k) $j]
				if {$parent([expr $tmp1]) > $parent([expr $tmp2])} {
					set newlevel "[lrange $level($k) 0 [expr $j-2]] $tmp2 $tmp1 [lrange $level($k) [expr $j+1] [expr $length-1]]"
					set level($k) $newlevel 
				}
			}
			}
	}

	lappend level(0) -1
	set maxobjects 1

# find the maximum number of objects per level
	for {set i 0} {$i <= $maxlvl} {incr i} {
		set length [llength $level($i)]
		set maxobjects [expr {$length > $maxobjects ? $length : $maxobjects}]
	}
	 
	set width [expr $maxobjects*64]
	if {$width < 448} {
		set width 448
	}
	set height [expr ($maxlvl+1)*128]
		
# space objects horizontally & vertically
	 for {set i 0} {$i <= $maxlvl} {incr i} {
		  set n 0
		  foreach object $level($i) {
				incr n
				set length [llength $level($i)]
				set locx [Get_Spacing 0.0 $width $n $length]
#				set locx [Get_Spacing -30.0 $width $n $length]
				set locy [Get_Spacing -80.0 $height [expr $objlvl($object)+1] [expr $maxlvl+1]]
				set coordinates($object) "$locx $locy"
		  }
	 }
	set player_status "" ; update
}	 

proc Get_Gen id {
	global parent

	if {$parent($id) == -1} {
		return [expr 1]
	} else {
		return [expr [Get_Gen $parent($id)]+1]
	}
}

proc Get_Spacing {a b i n} {
	 return [expr ( ($b - $a)/($n+1.7) * $i) + $a]
}


proc Initialize_Player {} {
	global canvas_height canvas_width height width coordinates filename
	global nevents cstep stop log_message simulation_time obj_color
	
	if {$height > 760} {
		set canvas_height 760
	} else {
		set canvas_height $height
	}
	if {$width > 1125} {
		set canvas_width 1125
	} else {
		set canvas_width $width
	}
	.vwr.scrn config -height $canvas_height -width $canvas_width
	.vwr.scrn config -scrollregion "0 0 $width $height"

	set obj_color(-1) color(logfile)
	Place_Object -1
	
	.pbar.scale config -from 0 -to $nevents
	.pbar.scale config -tickinterval [expr int($nevents/4)]

	set log_message(0) ""
	set simulation_time ""
	
	set cstep 0
	set stop 1
	Display_Time
}

##############################################################################
# Utility procedures
##############################################################################
##############################################################################
#	Procedure name: Dialog {w title text bitmap default args}
#	Author: John K. Ousterhout
#	Date:
#	Purpose:
##############################################################################
proc Dialog {w title text bitmap default args} {
	global env button

	toplevel $w -class Dialog
	wm title $w $title
	wm iconname $w Dialog

	frame $w.top -relief raised -bd 1
	pack $w.top -side top -fill both
	frame $w.bot -relief raised -bd 1
	pack $w.bot -side bottom -fill both

	message $w.top.msg -width 3i -text $text \
		-font -Adobe-Times-Medium-R-Normal-*-180-*
	pack $w.top.msg -side right -expand 1 -fill both \
		-padx 3m -pady 3m
	if {$bitmap != ""} {
		label $w.top.bitmap -bitmap @$env(PETSC_DIR)/bin/bitmaps/$bitmap
		pack $w.top.bitmap -side left -padx 3m -pady 3m
	}

	set i 0
	foreach but $args {
		button $w.bot.button$i -text $but -command\
			"set button $i"
		if {$i == $default} {
			frame $w.bot.default -relief sunken -bd 1
			raise $w.bot.button$i
			pack $w.bot.default -side left -expand 1\
				-padx 3m -pady 2m
			pack $w.bot.button$i -in $w.bot.default\
				-side left -padx 2m -pady 2m\
				-ipadx 2m -ipady 2m
		} else {
			pack $w.bot.button$i -side left -expand 1\
				-padx 3m -pady 3m -ipadx 2m -ipady 1m
		}
		incr i
	}
	
	if {$default >= 0} {
		bind $w <Return> "$w.bot.button$default flash; \
			set button $default"
	}
	set oldfocus [focus]
	focus $w
	grab set $w

	tkwait variable button
	destroy $w
	focus $oldfocus
	return $button
}  
#
# fileselect.tcl --
# simple file selector.
#
# Mario Jorge Silva			          msilva@cs.Berkeley.EDU
# University of California Berkeley                 Ph:    +1(510)642-8248
# Computer Science Division, 571 Evans Hall         Fax:   +1(510)642-5775
# Berkeley CA 94720                                 
# 
# Layout:
#
#  file:                  +----+
#  ____________________   | OK |
#                         +----+
#
#  +------------------+    Cancel
#  | ..               |S
#  | file1            |c
#  | file2            |r
#  |                  |b
#  | filen            |a
#  |                  |r
#  +------------------+
#  currrent-directory
#
# Copyright 1993 Regents of the University of California
# Permission to use, copy, modify, and distribute this
# software and its documentation for any purpose and without
# fee is hereby granted, provided that this copyright
# notice appears in all copies.  The University of California
# makes no representations about the suitability of this
# software for any purpose.  It is provided "as is" without
# express or implied warranty.
#


# names starting with "fileselect" are reserved by this module
# no other names used.

# use the "option" command for further configuration

option add *Listbox*font \
    "-*-helvetica-medium-r-normal-*-12-*-*-*-p-*-iso8859-1" startupFile
option add *Entry*font \
    "-*-helvetica-medium-r-normal-*-12-*-*-*-p-*-iso8859-1" startupFile
option add *Label*font \
    "-*-helvetica-medium-r-normal-*-12-*-*-*-p-*-iso8859-1" startupFile


# this is the default proc  called when "OK" is pressed
# to indicate yours, give it as the first arg to "fileselect"

proc fileselect.default.cmd {f} {
  	global filename

	puts stderr "selected file $f"
	return $filename
}


# this is the default proc called when error is detected
# indicate your own pro as an argument to fileselect

proc fileselect.default.errorHandler {errorMessage} {
    puts stdout "error: $errorMessage"
    catch{ cd ~ }
}

# this is the proc that creates the file selector box

proc fileselect {cmd purpose filematch w errorHandler} {

    catch {destroy $w}

    toplevel $w
    grab set $w
    wm title $w "Select File"
    global select_format

    # path independent names for the widgets
    global fileselect

    set fileselect(entry) $w.file.eframe.entry
    set fileselect(list) $w.file.sframe.list
    set fileselect(scroll) $w.file.sframe.scroll
    set fileselect(ok) $w.bframe.okframe.ok
    set fileselect(cancel) $w.bframe.cancel
    set fileselect(dirlabel) $w.file.dirlabel

    # widgets
    frame $w.file -bd 10 
    frame $w.bframe -bd 10
    pack append $w \
        $w.bframe {right frame n} \
        $w.file {left expand fill}

    frame $w.file.eframe
    frame $w.file.sframe
    label $w.file.dirlabel -anchor e -width 24 -text [pwd] 

    pack append $w.file \
        $w.file.eframe {top frame w fillx} \
	$w.file.sframe {top fill expand} \
	$w.file.dirlabel {top frame w fillx}

    label $w.file.eframe.label -anchor w -width 24 -text $purpose
    entry $w.file.eframe.entry -relief sunken

    pack append $w.file.eframe \
		$w.file.eframe.label {top expand frame w} \
                $w.file.eframe.entry {top fillx frame w} 


    scrollbar $w.file.sframe.yscroll -relief sunken \
	 -command "$w.file.sframe.list yview"
    listbox $w.file.sframe.list -relief sunken \
	-yscroll "$w.file.sframe.yscroll set" 

    pack append $w.file.sframe \
        $w.file.sframe.yscroll {right filly} \
 	$w.file.sframe.list {left expand fill} 

    # buttons
    frame $w.bframe.okframe -borderwidth 2 -relief sunken
 
    button $w.bframe.okframe.ok -text OK -relief raised -padx 10 \
        -command "fileselect.ok.cmd $w $cmd $filematch $errorHandler"

    button $w.bframe.cancel -text cancel -relief raised -padx 10 \
        -command "fileselect.cancel.cmd $w"

    pack append $w.bframe.okframe $w.bframe.okframe.ok {padx 10 pady 10}

    pack append $w.bframe $w.bframe.okframe {expand padx 20 pady 20}\
                          $w.bframe.cancel {top}
	
    # Fill the listbox with a list of the files in the directory (run
    # the "/bin/ls" command to get that information).
    # to not display the "." files, remove the -a option and fileselect
    # will still work

    foreach file [lsort [eval glob -nocomplain \
	  $filematch]] {
       $fileselect(list) insert end "$file [file size $file]"
    }

    $fileselect(list) insert end "../"
    foreach directory [lsort [eval glob -nocomplain */]] {
        $fileselect(list) insert end $directory
    }
    
    update
    wm minsize $w \
	  [expr "[winfo reqwidth  $w.bframe] + [winfo reqwidth  $w.file]"] \
	  [winfo reqheight $w.bframe]


   # Set up bindings for the browser.
    bind $fileselect(entry) <Return> {eval $fileselect(ok) invoke}
    bind $fileselect(entry) <Control-c> {eval $fileselect(cancel) invoke}

    bind $w <Control-c> {eval $fileselect(cancel) invoke}
    bind $w <Return> {eval $fileselect(ok) invoke}


#    tk_listboxSingleSelect $fileselect(list)


    bind $fileselect(list) <Button-1> [format {
       # puts stderr "button 1 release"
       %%W select set [%%W nearest %%y]
       $fileselect(entry) delete 0 end
       $fileselect(entry) insert 0 [lindex [%%W get [%%W nearest %%y]] 0]
       set select_format(%s) [$fileselect(entry) get]
    } $w]

    bind $fileselect(list) <Key> {
       %W select from [%W nearest %y]
       $fileselect(entry) delete 0 end
       $fileselect(entry) insert 0 [lindex [%W get [%W nearest %y]] 0]
    }

    bind $fileselect(list) <Double-ButtonPress-1> {
       # puts stderr "double button 1"
       %W select from [%W nearest %y]
       $fileselect(entry) delete 0 end
       $fileselect(entry) insert 0 [lindex [%W get [%W nearest %y]] 0]
       $fileselect(ok) invoke
    }

    bind $fileselect(list) <Return> {
       %W select from [%W nearest %y]
       $fileselect(entry) delete 0 end
       $fileselect(entry) insert 0 [lindex [%W get [%W nearest %y]] 0]
       $fileselect(ok) invoke
    }

    # set kbd focus to entry widget
    focus $fileselect(entry)
	 tkwait window $w
}


# auxiliary button procedures

proc fileselect.cancel.cmd {w} {
   # puts stderr "Cancel"
   destroy $w
}

proc fileselect.ok.cmd {w cmd filematch errorHandler} {
    global fileselect filename

    set selected [$fileselect(entry) get]

    # some nasty file names may cause "file isdirectory" to return an error
    set sts [catch { 
	file isdirectory $selected
    }  errorMessage ]

    if { $sts != 0 } then {
	$errorHandler $errorMessage
	destroy $w
	return

    }

    # clean the text entry and prepare the list
    $fileselect(entry) delete 0 end
    $fileselect(list) delete 0 end


    if {[string length $selected] && [file isdirectory $selected] != 0} {
       cd $selected
       set dir [pwd]
       $fileselect(dirlabel) configure -text $dir

       foreach file [lsort [eval glob -nocomplain $filematch]] {
	  $fileselect(list) insert end "$file [file size $file]"
       }

       $fileselect(list) insert end "../"
       foreach directory [lsort [glob -nocomplain */]] {
	  $fileselect(list) insert end $directory
       }
       return
    }
    destroy $w
	 $cmd $selected
}
#
# PetscView Demo Introduction
#
proc PV_Introduction {} {
  global petsc_dir
  toplevel .txtdemo
  wm title .txtdemo "PETScView Introduction"
#  wm geometry .txtdemo 355x500+0+0

  text .txtdemo.scrn -wrap word -width 45 -height 35 -padx 5m\
     -yscrollcommand ".txtdemo.scroll set"\
     -font *-times-medium-r-normal--*-140-*-*-*-*-*-*
#  text .txtdemo.scrn -wrap word -width 55 -height 63 -padx 5m\
#     -yscrollcommand ".txtdemo.scroll set"\
#     -font *-times-medium-r-normal--*-140-*-*-*-*-*-*
  scrollbar .txtdemo.scroll -command ".txtdemo.scrn yview"
  pack .txtdemo.scroll -side right -fill y
  pack .txtdemo.scrn

  frame .txtdemo.mbar -relief raised -bd 2
  pack .txtdemo.mbar -side top -fill x -expand 1
  button .txtdemo.mbar.exit -text "Exit" -command {destroy .txtdemo; return}
  pack .txtdemo.mbar.exit -side left

  proc loadFile file {
        .txtdemo.scrn delete 1.0 end
        set f [open $file]
        while {![eof $f]} {
                .txtdemo.scrn insert end [read $f 1000]
        }
        close $f
  }
  loadFile $petsc_dir/bin/petscviewinfo.text

  proc forAllMatches {w pattern script} {
     scan [$w index end] %d numLines
     for {set i 1} {$i < $numLines} {incr i} {
         $w mark set last $i.0
         while {[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"
           uplevel $script
         }
     }
  }
        
  forAllMatches .txtdemo.scrn PETSc {
    .txtdemo.scrn tag add big first last
  }
  forAllMatches .txtdemo.scrn PETScView {
    .txtdemo.scrn tag add big first last
  }
  forAllMatches .txtdemo.scrn PETScOpts {
    .txtdemo.scrn tag add big first last
  }
  forAllMatches .txtdemo.scrn http://www.mcs.anl.gov/petsc/petsc.html {
    .txtdemo.scrn tag add big first last
  }
  forAllMatches .txtdemo.scrn Example {
    .txtdemo.scrn tag add big first last
  }
  forAllMatches .txtdemo.scrn {Performance Statistics} {
    .txtdemo.scrn tag add big first last
  }
  .txtdemo.scrn tag configure big \
     -font *-times-bold-r-normal--*-140-*-*-*-*-*-*

  .txtdemo.scrn configure -state disabled
}
#
# PetscView Demo Icon Key.
#    This key is customized for the PETScView demo (unlike the more
#    general icon key) and is intended for use in running automated demos.
#
proc PV_Demo_Icon_Key {} {

  global petsc_dir color
  toplevel .demokey
#  wm geometry .demokey 355x333+0+532
  wm title .demokey "PETScView Demo Icon Key"
  wm iconname .demokey "PETScView Demo Icon Key"

  canvas .demokey.scrn -yscrollcommand ".demokey.yscroll set" 
  scrollbar .demokey.yscroll -relief raised -command ".demokey.scrn yview"
  pack .demokey.yscroll -side right -fill y
  .demokey.scrn config -height 333 -width 355 -scrollregion "0 0 355 880"
  pack .demokey.scrn -side left

  set locx 60
  set locy 30
  set locx2 110

  set txt "-text {PETSc Objects}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-bold-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/file.bit"
  set locy [expr $locy + 50]
  eval ".demokey.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill white"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- application program}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {SNES LS}"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create oval [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- Newton-based nonlinear solver}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text SLES"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-32] [expr $locy-16] [expr $locx+32] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- linear solver}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text BJacobi"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create polygon $locx [expr $locy-16] [expr $locx-16] [expr $locy+16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- Block Jacobi preconditioner}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text SOR"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create polygon $locx [expr $locy-16] [expr $locx-16] [expr $locy+16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- SOR preconditioner}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text GMRES"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create polygon [expr $locx-6] [expr $locy-16] [expr $locx+6] [expr $locy-16] [expr $locx+16] [expr $locy-6] [expr $locx+16] [expr $locy+6] [expr $locx+6] [expr $locy+16] [expr $locx-6] [expr $locy+16] [expr $locx-16] [expr $locy+6] [expr $locx-16] [expr $locy-6] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- GMRES iterative solver}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text BCGS"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create polygon [expr $locx-6] [expr $locy-16] [expr $locx+6] [expr $locy-16] [expr $locx+16] [expr $locy-6] [expr $locx+16] [expr $locy+6] [expr $locx+6] [expr $locy+16] [expr $locx-6] [expr $locy+16] [expr $locx-16] [expr $locy+6] [expr $locx-16] [expr $locy-6] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- BiCGStab iterative solver}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text DA"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-24] [expr $locy-16] [expr $locx+24] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel distributed array}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Stride"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-24] [expr $locy-8] [expr $locx+24] [expr $locy+8] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- stride index set}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Index"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-24] [expr $locy-8] [expr $locx+24] [expr $locy+8] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- general index set}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text Scatter"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- vector scatter context}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/matrixp.bit"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-16] [expr $locy-16] [expr $locx+16] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel sparse matrix}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/vectorp.bit"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- parallel vector}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-bitmap @$petsc_dir/bin/bitmaps/vector.bit"
  set locy [expr $locy + 40]
  eval ".demokey.scrn create rectangle [expr $locx-8] [expr $locy-16] [expr $locx+8] [expr $locy+16] -fill $color(active)"
  eval ".demokey.scrn create [string range [lindex $txt 0] 1 end] $locx $locy $txt"
  set txt "-text {- sequential vector}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set txt "-text {Color Key}"
  set locy [expr $locy + 80]
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-bold-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".demokey.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(active)"
  set txt "-text {- active object}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".demokey.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(idle)"
  set txt "-text {- inactive object}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
#
  set locy [expr $locy + 40]
  eval ".demokey.scrn create  rectangle [expr $locx-10] [expr $locy-10] [expr $locx+10] [expr $locy+10] -fill $color(dead)"
  set txt "-text {- destroyed object}"
  eval ".demokey.scrn create text $locx2 $locy $txt -anchor w -font *-times-medium-r-normal--*-140-*-*-*-*-*-* "
}
#
# Get_User_Input
#############################################################################
proc Get_User_Input {w title text current_value lower_bound upper_bound
	 cmd} {
	
	catch {destroy $w}

	toplevel $w
	
	grab set $w

	wm title $w $title

	frame $w.top -relief raised -bd 1
	pack $w.top -side top -fill both
	frame $w.bot -relief raised -bd 1
	pack $w.bot -side bottom -fill both

	message $w.top.msg -width 3i -text $text
	entry $w.top.entry -relief sunken -textvariable current_value

	pack $w.top.msg $w.top.entry -side left -fill x -expand 1 -padx 3m -pady 3m

	button $w.bot.button1 -text OK -command "OK_Command $w $cmd $lower_bound $upper_bound"
	frame $w.bot.default -relief sunken -bd 1
	raise $w.bot.button1
	pack $w.bot.default -side left -expand 1\
		-padx 3m -pady 2m
	pack $w.bot.button1 -in $w.bot.default\
		-side left -padx 2m -pady 2m -ipadx 2m -ipady 2m

	button $w.bot.button2 -text Cancel -command "destroy $w"
	pack $w.bot.button2 -side left -expand 1\
				-padx 3m -pady 3m -ipadx 2m -ipady 1m
	
	bind $w.top.entry <Return> "$w.bot.button1 flash ; $w.bot.button1 invoke"
	bind $w.top.entry <Control-c> "$w.bot.button2 flash ; $w.bot.button2 invoke"

	focus $w.top.entry
	tkwait window $w
}
proc OK_Command {w cmd lower_bound upper_bound} {
	set value [$w.top.entry get]

	if {($value >= $lower_bound) && ($value <= $upper_bound)} {
		destroy $w
		$cmd $value
	} else {
		return
	}
}

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


# open log file if it is given as a command line argument

if {![file exists $env(HOME)/.petscviewrc]} {
	exec cp $env(PETSC_DIR)/bin/.petscviewrc $env(HOME)/.petscviewrc
}

source ~/.petscviewrc

set file_bin 0
set player_status "No File."

pack .mbar -side top -fill x -expand 1
pack .pbar -side bottom -fill x -expand 1
set def_file $env(PETSC_DIR)/bin/petscview.cfg

if { $argc >= 1 } {
	set first 0
	if {[file isfile [lindex $argv 0]]} {
		set first 1
	}
	for {set i $first} {$i <= $argc} {incr i} {
		if {[string compare "-def_file" [lindex $argv $i]] == 0} {
			incr i
			if {[file isfile [lindex $argv $i]]} {
				set def_file [lindex $argv $i]
			} else {
				set def_file $env(PETSC_DIR)/bin/petscview.cfg
			}
		} elseif {[string compare "-time" [lindex $argv $i]] == 0} {
			set time_bin 1
		} elseif {[string compare "-notime" [lindex $argv $i]] == 0} {
			set time_bin 0
		} elseif {[string compare "-stepsize" [lindex $argv $i]] == 0} {
			incr i
			if {[lindex $argv $i] > 0} {
				set stepsize [lindex $argv $i]
			}
		} elseif {[string compare "-delay" [lindex $argv $i]] == 0} {
			incr i
			if {([lindex $argv $i] >= -1) && ([lindex $argv $i] <= 2000)} {
				set delay [lindex $argv $i]
			}
		} elseif {[string compare "-printer_dest" [lindex $argv $i]] == 0} {
			incr i
			if {([string compare "File" [lindex $argv $i]] == 0) ||
				([string compare "Printer" [lindex $argv $i]] == 0)} {
				set PrintOpts(destination) [lindex $argv $i]
			}
		} elseif {[string compare "-print_command" [lindex $argv $i]] == 0} {
			incr i
			set PrintOpts(printcommand) [lindex $argv $i]
		} elseif {[string compare "-printer" [lindex $argv $i]] == 0} {
			incr i
			set PrintOpts(printer) [lindex $argv $i]
		} elseif {[string compare "-print_orientation" [lindex $argv $i]] == 0} {
			incr i
			if {([lindex $argv $i] == 0) || ([lindex $argv $i] == 1)} {
				set PrintOpts(orientation) [lindex $argv $i]
			}
		} elseif {[string compare "-print_color" [lindex $argv $i]] == 0} {
			incr i
			if {([string compare "gray" [lindex $argv $i]] == 0) || \
				([string compare "color" [lindex $argv $i]] == 0) || \
				([string compare "mono" [lindex $argv $i]] == 0)} {
					set PrintOpts(colormode) [lindex $argv $i]
			} else {
				set PrintOpts(colormode) gray
			}
		}
	}
}
Load_Definitions $def_file
Create_LinePlot

if {[file isfile [lindex $argv 0]]} {
	Read_Data [lindex $argv 0]
}
#########################################################################
#
# PETScView Demo
# Set continuous=1 at top of file for continual playing, forward and then
# reverse.
#
proc PETScView_Demo {} {
  global petsc_dir
#  PV_Demo_Icon_Key  ... Add this for automated demos
  PV_Introduction
  Load_Log_File $petsc_dir/bin/demos/smalllog
  Play_Forward
}

#
# PetscView Demo Application Code
#
proc PETScView_Demo_Appl {} {
  global petsc_dir
  toplevel .appdemo
  wm title .appdemo "Application Code for PETScView Demo"

  frame .appdemo.mbar -relief raised -bd 2
  text .appdemo.scrn -wrap word -width 85 -height 40 -padx 5m -bd 2\
     -yscrollcommand ".appdemo.scroll set"
  scrollbar .appdemo.scroll -relief raised -command ".appdemo.scrn yview"

  pack .appdemo.mbar -side top -fill x -expand 1
  pack .appdemo.scroll -side right -fill y -expand 1
  pack .appdemo.scrn -side left -fill both -expand 1
  button .appdemo.mbar.exit -text "Exit" -command {destroy .appdemo; return}
  pack .appdemo.mbar.exit -side left

  proc loadFile file {
        .appdemo.scrn delete 1.0 end
        set f [open $file]
        while {![eof $f]} {
                .appdemo.scrn insert end [read $f 1000]
        }
        close $f
  }

  loadFile $petsc_dir/src/snes/examples/ex6.c
  .appdemo.scrn configure -state disabled
}
#
# PETScOpts Demo
#
proc PETScOpts_Demo {} {
  global petsc_dir
  exec $petsc_dir/bin/petscopts
}
#
# PETSc Library Hierarchy
#
proc PETSc_Picture {} {
  global petsc_dir
  exec ghostview $petsc_dir/bin/demos/petscwww.eps
}




