#!nviz -f
# Please log changes in the ChangeLog file in this directory
# (Use "C-x 4 a" from emacs to add an entry)

# These two lines necessary to allow auto-loading
# If you move nviz then be sure to change these two lines
# to reflect the location of the libraries
# Also, don't forget to change the invocation of nvwish above.
# auto_mkindex /data/stimpy/terry/tcl/nviz *.tcl
# exec chmod ugo+rw tclIndex

global src_boot
global env
global BGColor

#If set to 1 output debug statements
global DEBUG
set DEBUG 0

#Initialize ProcessName variable
set env(NV_processname) NVIZ

set BGColor #FFFFFF

source $src_boot/etc/nviz2.2/scripts/config.tcl
#append bwidget for tooltip stuff
lappend auto_path $env(GISBASE)/bwidget
package require BWidget

global Nv_ ScriptState ScriptFile ScriptPlaying NvizLoadState 

set ScriptPlaying 0

#Config Tooltip stuff
DynamicHelp::configure -bg "#FFFFAA"
interp alias {} help {} DynamicHelp::register

##########################################################################
#  Constants
##########################################################################

set Nv_(TOP)  	".middle.draw"
set Nv_(APP)    "."
set Nv_(P_AREA) ".middle.panelarea.panels"
set Nv_(PAREA)   ".middle.panelarea"
set Nv_(AREA) 	".top"
set Nv_(CALLED_SET_FOCUS) no
set Nv_(CurrSurf) 0
set Nv_(CurrVect) 0
set Nv_(CurrSite) 0
set Nv_(CurrSdiff) 0
set Nv_(CurrVol) 0

# Some quick code to initialize the CurrSurf, CurrVect and CurrSite variables
set temp [Nget_surf_list]
if {[llength $temp] == 0} then {
    set Nv_(CurrSurf) 0
} else {
    set Nv_(CurrSurf) [lindex $temp 0]
}

set temp [Nget_vect_list]
if {[llength $temp] == 0} then {
    set Nv_(CurrVect) 0
} else {
    set Nv_(CurrVect) [lindex $temp 0]
}

set temp [Nget_site_list]
if {[llength $temp] == 0} then {
    set Nv_(CurrSite) 0
} else {
    set Nv_(CurrSite) [lindex $temp 0]
}

set temp [Nget_vol_list]
if {[llength $temp] == 0} then {
    set Nv_(CurrVol) 0
} else {
    set Nv_(CurrVol) [lindex $temp 0]
}

##########################################################################
#*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
##########################################################################

# Load this array with the names of the panels that are to be used
#
# 11/1/95 - This array loaded by searching through all the directories
#   in $user_path.  For each directory in this path, the contents of
#   the file panelIndex is added to this array

# note we need a TRACE proc for whenever this list is changed dynamically

#DEBUG
if {$DEBUG} {puts "Adding panels from $user_path"}

set Nv_(panels) [list]
foreach i $user_path {
    set index $i/panelIndex
    if {[file exists $index]} then {
	set panels [exec cat $index]
	set panels [split $panels]
	foreach j $panels {
	    if {[lsearch -exact $Nv_(panels) $j] == -1} then {
		lappend Nv_(panels) $j
	    }
	}
    }
}

# DEBUG
if {$DEBUG} {puts Nv_(panels)}

##########################################################################
#*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
##########################################################################



#########################################################################
# Make sure panel has been loaded
#########################################################################
proc Nv_force_panel { name } {
    global Nv_
    
    set P $Nv_(P_AREA)
    
    # create panel if it doesn't already exist
    set path $P.$name
    if [catch {set Nv_($path)}] {
	set file panel_$name.tcl
	set Nv_($path) [mk$name\Panel $path]
    }
}

#########################################################################
proc set_scrollsize {} {
global Nv_

set wid [winfo width $Nv_(P_AREA)]
set ht [winfo height $Nv_(P_AREA)]

set bbox "0 0 $wid $ht"
$Nv_(PAREA).canvas configure -scrollregion $bbox -width [expr $wid+2]
}


###################################
# Procedure to hide menus
###################################
proc hide_menus {} {
global Nv_ bit_map_path

$Nv_(PAREA).canvas  configure -width 0
$Nv_(PAREA).f1.b1 configure -bitmap @$bit_map_path/right \
        -width 8 -height 12 -command "show_menus"

help $Nv_(PAREA).f1.b1 balloon "Show Panels"

$Nv_(AREA).menu.panel.m entryconfigure 1 -label "Show Panels" -command "show_menus"

}

###################################
# Procedure to reveal menus
###################################
proc show_menus {} {
global Nv_ bit_map_path

$Nv_(PAREA).canvas  configure -width [winfo width $Nv_(P_AREA)]
$Nv_(PAREA).f1.b1 configure -bitmap @$bit_map_path/left \
        -width 8 -height 12 -command "hide_menus"

help $Nv_(PAREA).f1.b1 balloon "Hide Panels"

$Nv_(AREA).menu.panel.m entryconfigure 1 -label "Hide Panels" -command "hide_menus"
}


###########################################################################
# add key bindings so that menu shortcut keys can be used
###########################################################################

###########################################################################
# make toplevel
###########################################################################

proc Nv_makeGUI {{BASE .}} {
    global Nv_ ScriptState src_boot env
    global DEBUG
    global bit_map_path constrained

#DEBUG
if {$DEBUG} {puts "Build toplevel window"}
    
    set Nv_(First) 1
    wm geometry . +10+10
    wm minsize . 10 10
    wm sizefrom . user

    #Use three base frames
    frame .top -relief flat
    frame .middle -relief sunken
    frame .bottom -relief raised

# DEBUG
if {$DEBUG} {puts "toplevel made"}


    ###########################################################################
    # make informational text widget
    ###########################################################################
    
    set Nv_(text) "Start"
    set Nv_(height) 720

    #panel area frame
    frame $Nv_(PAREA) -relief raised -borderwidth 2
    pack $Nv_(PAREA) -side left -fill y -expand 0

    #togl canvas
    frame .middle.draw -relief flat
    pack .middle.draw -side left -fill both -expand 1

    entry .bottom.entry -relief sunken -state disabled \
        -background #FFFFFF -textvariable Nv_(text) 
    pack .bottom.entry -side left -fill both -expand 1

    set cwidth [exec $src_boot/bin/g.gisenv X3D_WIDTH]
    set cheight [exec $src_boot/bin/g.gisenv X3D_HEIGHT]

    if {$cwidth > 0 && $cheight > 0} {
        togl .middle.draw.canvas -rgba true -double true -depth true \
                -width $cwidth -height $cheight
        pack .middle.draw.canvas -side top -expand 0
    } elseif {$cwidth == "" && $cheight > 0} {
        togl .middle.draw.canvas -rgba true -double true -depth true \
                -height $cheight
        pack .middle.draw.canvas -side top -fill x -expand 1
    } elseif {$cheight == "" && $cwidth > 0} {
        togl .middle.draw.canvas -rgba true -double true -depth true \
                -width $cwidth
        pack .middle.draw.canvas -side top -fill y -expand 1
    } else {
	#nothing set
	set constrained 1
        togl .middle.draw.canvas -rgba true -double true -depth true
        pack .middle.draw.canvas -side top -fill both -expand 1
    }

    bind .middle.draw.canvas <Expose> {Nv_expose %W}
    bind .middle.draw.canvas <Configure> {set Nv_(height) %h}
    set tags [bindtags .middle.draw.canvas]

# the Togl widget can't be redrawn until the main panel has been created
#    update

#With widget made reset ProcessName variable
set env(NV_processname) [winfo name .]

#Moved the following packing here to satisfy some TCL versions
#Prevents minimized GUI
    #top frame for menubar
    pack .top -side top -fill x -expand 0
    #middle frame for menus and togl canvas
    pack .middle  -side top -fill both -expand 1
    #botom frame for statusbar
    pack .bottom -side top -fill x -expand 0
   
 
# DEBUG
if {$DEBUG} {puts "info widget made"}
    ###########################################################################
    # make  panel area
    ###########################################################################
    canvas $Nv_(PAREA).canvas -yscrollcommand "$Nv_(PAREA).f1.scrolly set" \
	-borderwidth 2 -relief sunken
    frame $Nv_(PAREA).f1 -borderwidth 0 -relief flat
    scrollbar $Nv_(PAREA).f1.scrolly -command "$Nv_(PAREA).canvas yview"
    button $Nv_(PAREA).f1.b1 -bitmap @$bit_map_path/left \
        -width 8 -height 12 -command "hide_menus"
    help $Nv_(PAREA).f1.b1 balloon "Hide Panels"

    frame $Nv_(P_AREA) -relief raised -borderwidth 3    


# DEBUG
if {$DEBUG} {puts "panel area made"}

    ###########################################################################
    # make  menubar
    ###########################################################################
    frame $Nv_(AREA).menu  -relief raised -borderwidth 1
    pack $Nv_(AREA).menu -side top -fill x -expand 0

    pack $Nv_(PAREA).canvas -side top -fill both -expand yes
    pack $Nv_(PAREA).f1 -side left -before $Nv_(PAREA).canvas -fill y
    pack $Nv_(PAREA).f1.scrolly -side top -fill y -expand 1
    pack $Nv_(PAREA).f1.b1 -side bottom -fill x

    pack $Nv_(P_AREA) -side top -fill y -expand yes

    # Make label with invisible text to hold "Please wait..." message
    label $Nv_(AREA).menu.wait_pls -text "Please Wait..." \
        -fg gray90

    #Bind menu area to canvas and scrollbars
    $Nv_(PAREA).canvas create window 0 0 -window $Nv_(P_AREA) -anchor nw
    bind $Nv_(P_AREA) <Configure> "set_scrollsize"

    pack [Nv_mkMenu $Nv_(AREA).menu.file File \
              {"Load State ..." "Save State ..." \
                "" \
                "Set Canvas Size ..."
                "" \
                "Load 3d Settings ..." "Save 3d Settings ..." \
                "" \
                "Save image as ..." \
                "" \
                "Reset" "Quit" } \
              {0 0 0 0 0 0 0 0 0 0 0 0} \
              { "load_state" "save_state" \
                "Separator" \
                "set_canvas_size" \
                "Separator" \
                "load_3dview" "save_3dview" \
                "Separator" \
                "Cascade img menu2" \
                "Separator" \
                "reset_Nviz" "Nv_close_scripting ; exit ; puts"}]\
        -side left -fill x -expand 0


# DEBUG
if {$DEBUG} {puts "file menu made"}

pack [Nv_mkMenu $Nv_(AREA).menu.help Help \
	{"NVIZ Help" "About NVIZ" "NVIZ - Bugs / ToDo"} \
	{0 0 0} \
	{"nviz_browse nviz_toc.html" "nviz_browse nviz_desc.html" "nviz_browse bugs_todo.html"} ] \
	-side right -fill x -expand 0

# DEBUG
if {$DEBUG} {puts "Help menu made"}

    # Take these out later when these features are more reliable
#    $Nv_(AREA).menu.file.m entryconfigure 3 -state disabled
#    $Nv_(AREA).menu.file.m entryconfigure 4 -state disabled

# DEBUG
if {$DEBUG} {puts "disabled made"}


    pack [Nv_mkPanelMenu $Nv_(AREA).menu.panel] -side left -fill x -expand 0
# DEBUG
if {$DEBUG} {puts "scripting menu 0 made"}


    # Make a menu entry for scripting
    menubutton $Nv_(AREA).menu.scripting -text Scripting \
	-menu $Nv_(AREA).menu.scripting.m -underline 0
    menu $Nv_(AREA).menu.scripting.m

    $Nv_(AREA).menu.scripting.m add checkbutton -label "On" \
	-onvalue 1 -offvalue 0 -variable ScriptState \
	-command "script_handle_on"

    $Nv_(AREA).menu.scripting.m add separator

    $Nv_(AREA).menu.scripting.m add command -label "Create New Scriptfile" \
	-underline 0 -command SetScriptFile

    $Nv_(AREA).menu.scripting.m add command -label "Open and Play Script" \
	-underline 0 -command {set ScriptPlaying 1 ; exec nviz -f $default_panel_path/script_play &}

    $Nv_(AREA).menu.scripting.m add command -label "Close Script" \
	-underline 1 -command Nv_close_scripting

    $Nv_(AREA).menu.scripting.m add separator

    $Nv_(AREA).menu.scripting.m add command -label "Add Script Line" \
	-underline 0 -command AddScriptLine

    $Nv_(AREA).menu.scripting.m add command -label "Add Script Command" \
	-underline 1 -command AddScriptCmd

    $Nv_(AREA).menu.scripting.m add separator

    $Nv_(AREA).menu.scripting.m add command -label "Script Tools" \
	-underline 1 -command {exec nviz -f $default_panel_path/script_tools -q &}

    pack $Nv_(AREA).menu.scripting -side left -fill x -expand 0
    

# DEBUG
if {$DEBUG} {puts "scripting menu made"}

    tk_menuBar $Nv_(AREA).menu $Nv_(AREA).menu.file $Nv_(AREA).menu.panel \
	$Nv_(AREA).menu.scripting
    
    set Nv_(Q) [Q_init 2]
    
    pack $Nv_(AREA).menu.wait_pls -side left -fill x -expand yes 

    # initialize Main panel
    Nv_force_panel main
    Nv_openPanel  main 0
    update

# DEBUG
if {$DEBUG} {puts "menubar made"}

    focus $Nv_(AREA).menu

    return $BASE
}

proc menu2 { menu } {

	menu $menu \
	-tearoff 0

	$menu add command \
	-command dump_ppm -underline 0 -label "PPM Image"
	$menu add command \
	-command dump_tif -underline 0 -label "TIFF Image"
        $menu add command \
        -command {set fname [create_file_browser .file_browser 1]
	if {$fname != -1} then {
	appBusy
         set wid [winfo screenwidth .]
	 set ht [winfo screenheight .]
	 Nstart_zoom $fname $wid $ht
	appNotBusy
	}	
	} -underline 0 -label "Maximum Resolution PPM"
    }

proc dump_ppm { } {
    # This routine should use: Nwrite_ppm $fname
    set fname [create_file_browser .file_browser 1]
    # show we are busy
    appBusy

    if {$fname != -1} then {
	if { [string compare [file extension $fname] ".ppm"] != 0 } then {
	    append fname ".ppm"
	}
	Ndraw_all
	Nwrite_ppm $fname
    }
    # show user can proceed
    appNotBusy
}

proc dump_tif { } {
    # This routine should use: Nwrite_tif $fname
    set fname [create_file_browser .file_browser 1]
    # show we are busy
    appBusy

    if {$fname != -1} then {
	if { [string compare [file extension $fname] ".tif"] != 0 } then {
	    append fname ".tif"
	}
	Ndraw_all
	Nwrite_tif $fname
    }
    # show user can proceed
    appNotBusy
}

###########################################################################
# null proc
###########################################################################
proc null {args} {}

#########################################################################
# open panel P.name  with routine mkP and place in appropriate spot
#########################################################################
proc Nv_openPanel { name {pos -1}} {
    global Nv_
    
    set P $Nv_(P_AREA)
    
    # create panel if it doesn't already exist
    set path $P.$name
    
    # if panel has not yet been created ...
    # or panel is one that needs updating ...
    if {[catch {set panel $Nv_($path)}]} then {
	set panel [mk$name\Panel $path]
	set Nv_($path) $panel
    } elseif {"site" == "$name"} then {
	set panel [mk$name\Panel $path]
	set Nv_($path) $panel
    } elseif {"vect" == "$name"} then {
	set panel [mk$name\Panel $path]
	set Nv_($path) $panel
    } elseif {"sdiff" == "$name"} then {
	set panel [mk$name\Panel $path]
	set Nv_($path) $panel
    }
    
    # if panel is not already mapped ...
    if { [lsearch [place slaves $P] $P.$name] < 0 } {
	if {$pos < 0} { 
	    Q_add $Nv_(Q) $panel 
	} else { 
	    Nv_mapPanel $path $panel $pos
	}
    }
}

proc Nv_mapPanel {name panel pos } {

    #insert update to fix KDE wm problem
    update

    set size [St_get $panel  size]
    if [catch {set height [expr $size * .33]}] { set height 1}
    if [catch {set y [expr $pos * .33]}] { set y 0}
    pack $name -side top -fill x -expand no -anchor n
#    set x [winfo x .top2]
#    set y [winfo y .top2]
#    if {$x && $y} {
#        wm geometry .top2 "+$x+$y"
#    }
}

proc Nv_closePanel { name } { 
    pack forget $name 
}

# Simple routine to uniformly close any opened panels
proc Nv_closeAllPanels { } {
    global Nv_

    set children [pack slaves $Nv_(P_AREA)]

    foreach i $children {
	if {[regexp main "$i"] != 1} then {
	    pack forget $i
	}
    }
}

############################################################################
# procedure to make  PANEL pulldown menu
###########################################################################
proc Nv_mkPanelMenu { P { name Panel } } {
    global Nv_ DEBUG
    
    menubutton $P -text $name -menu $P.m -underline 0
    menu $P.m

if {$DEBUG} {puts "Nv_mkPanelMenu 1"}

    set j 0
    $P.m add command -label "Hide Panels" -command hide_menus
    $P.m add separator

    foreach i $Nv_(panels) {
	Nv_force_panel $i
	
	set panel $Nv_($Nv_(P_AREA).$i)
	
	$P.m add command -label [St_get $panel name] \
	    -command "Nv_openPanel $i"
        #Add separators
	if {$i == "vol" || $i == "cutplane" || $i == "kanimator"} {
		$P.m add separator
	}

if {$DEBUG} {puts "Nv_mkPanelMenu 2 $j  [St_get $panel name]"}

	incr j
    }
    
    return $P
}

proc inform {args} {
    global Nv_
    
    set Nv_(text) ""
    foreach S $args {
	set Nv_(text) [concat $Nv_(text) $S]
    }
}

proc Nv_expose { W } {
    global Nv_
    global BGColor

#    if [$W islinked] then {
	if {$Nv_(First)} then {
	    init_graphics
	    set Nv_(First) 0
	} else {
            Nbackground $BGColor
	    Nquick_draw
	}
#    }
}

proc save_3dview { dummy } {
    # Ask the user for a file name to save in
    set file_name [create_map_browser .browse_3dview_file "3d.view" 1]
    
    if {$file_name == -1} then return

    Nsave_3dview $file_name
}

proc load_3dview { dummy } {
    global Nv_
    # Ask the user for a file name to load from
    set file_name [create_map_browser .browse_3dview_file "3d.view" 1]
    
    if {$file_name == -1} then return

    #do a quick draw to make sure display initialized
    Nquick_draw

    Nload_3dview $file_name

    #Reset position GUI
    set ht [lindex [Nget_real_position 1] 2]
	#reset height
	Nv_setEntry $Nv_(main_BASE).midf.height.f.entry  $ht
	Nv_floatscaleCallback $Nv_(main_BASE).midf.height e 2 null $ht
    change_display 2
    change_display 1

    Nquick_draw
}
########################################
# Procedure to manually set canvas size
proc set_canvas_size { dummy } {
global cwidth cheight constrained Nv_ 


set cwidth [lindex [$Nv_(TOP).canvas configure -width] 4]
set cheight [lindex [$Nv_(TOP).canvas configure -height] 4]

#Build size box
toplevel .canvas_size
frame .canvas_size.f1 -borderwidth 2 -relief sunken
frame .canvas_size.f2
frame .canvas_size.f3
pack .canvas_size.f3 .canvas_size.f1 .canvas_size.f2 -side top \
        -fill both -expand 1

label .canvas_size.f3.l1 -text "Set Size of Display Canvas"
pack .canvas_size.f3.l1 -side top -fill both -expand 0

label .canvas_size.f1.l1 -text "Width"
entry .canvas_size.f1.e1 -textvariable cwidth -width 6
label .canvas_size.f1.l2 -text "Height"
entry .canvas_size.f1.e2 -textvariable cheight -width 6
pack .canvas_size.f1.l1 .canvas_size.f1.e1 \
        .canvas_size.f1.l2 .canvas_size.f1.e2 \
        -side left -fill y

checkbutton .canvas_size.f2.c1 -text "Unconstrained" -variable constrained \
        -onvalue 1 -offvalue 0 -command {
        if {$constrained} {
                .canvas_size.f1.e1 configure -state disabled -bg grey
                .canvas_size.f1.e2 configure -state disabled -bg grey
        } else {
                .canvas_size.f1.e1 configure -state normal -bg white
                .canvas_size.f1.e2 configure -state normal -bg white
        }
        }
button .canvas_size.f2.b1 -text "Close" \
        -command {
if {$constrained} {
        pack $Nv_(TOP).canvas -side top -fill both -expand 1
} else {
        $Nv_(TOP).canvas configure -width $cwidth -height $cheight
        pack $Nv_(TOP).canvas -side top -expand 0 -fill none
	#Need Nset_viewport to make sure reshape is called
	Nset_viewport $cwidth $cheight
}
destroy .canvas_size}

if {$constrained} {
	.canvas_size.f1.e1 configure -state disabled -bg grey
        .canvas_size.f1.e2 configure -state disabled -bg grey
}

pack .canvas_size.f2.c1 -side left -fill both
pack .canvas_size.f2.b1 -side right -fill both

}


# Procedure to load the state of the system, calls a special
# load procedure for each panel in the system.
proc load_state { dummy  } {
    global Nv_

    # First open a file for reading in the state
    set new_file [create_file_browser .state_file 1 0]
    if {$new_file == -1} then return
    
    # show that we are busy
    appBusy

    load_state_aux $new_file
    
    # show that we aren't busy anymore
    appNotBusy
}

#Procedure to load NVIZ HTML pages
proc nviz_browse { URL dummy } {
global env

#OLD: exec  $env(GISBASE)/docs/html/nviz/help_frame.tcl $env(GISBASE)/docs/html/nviz/$URL &
 if {[info exists env(MSYSCON)]} {
	exec -- $env(GRASS_HTML_BROWSER) file://$env(GISBASE)/docs/html/nviz/$URL &;
 } else {
	exec -- $env(GRASS_HTML_BROWSER) file://$env(GISBASE)/docs/html/nviz/$URL >@stdout 2>@stderr &;
 }
}

proc load_state_aux { new_file} {
    global Nv_

    if {[catch {set file_hook [open $new_file r]} error_code] != 0} then {
	display_error "While opening file: $error_code"
	return
    }

    # Close all panels fist
    Nv_closeAllPanels

    # First line before panel data contains the name of the panel which
    # saved the data.  Use this name to build the command which will 
    # read in the data and call the appropriate routine.
    while {[gets $file_hook i] != -1} {
	set cmd_name "Nviz_$i"
	append cmd_name "_load"
	if {[catch {$cmd_name $file_hook} error_code] != 0} then {
	    puts "Diagnostic: $error_code --  Load procedure for panel $i may not be defined"
	}
    }

    # Finally, close the file and exit
    close $file_hook

    # Go through each of the panels one at a time and force them to open
    # This should update them all so they display correctly
    foreach i $Nv_(panels) {
	Nv_openPanel $i
	update
    }

    Nv_closeAllPanels

    return 1
}

# Procedure to completely reset nviz, calls a special reset procedure
# in each panel in the system
proc reset_Nviz { dummy } {
    global Nv_

    # Query user to verify this choice
    if {[tk_dialog .reset_all "Reset" \
	     "Really reset Nviz?" {} 1 "Ok" "Cancel"] == 1} then return

    # Show that we are busy
    appBusy

    # Now call each of the panels one at a time and pass the
    # file hook so that each panel can write out its state
    set tmp_list $Nv_(panels)
    lappend tmp_list main
    foreach i $tmp_list {
	set cmd_name "Nviz_$i"
	append cmd_name "_reset"
	if {[catch {$cmd_name} error_code] != 0} then {
	    puts "Diagnostic: $error_code --  Reset procedure for panel $i may not be defined"
	}
    }

    # Go through each of the panels one at a time and force them to open
    # This should update them all so they display correctly
    foreach i $Nv_(panels) {
	Nv_openPanel $i
	update
    }

    Nv_closeAllPanels

    # Show that user may proceed
    appNotBusy

}

# This routine is equivalent to the one above except it skips alot of
# the user interface BS
proc reset_nviz_aux { } {
    global Nv_

    # Now call each of the panels one at a time and pass the
    # file hook so that each panel can write out its state
    set tmp_list $Nv_(panels)
    lappend tmp_list main
    foreach i $tmp_list {
	set cmd_name "Nviz_$i"
	append cmd_name "_reset"
	if {[catch {$cmd_name} error_code] != 0} then {
	    puts "Diagnostic: $error_code --  Reset procedure for panel $i may not be defined"
	}
    }

    # Go through each of the panels one at a time and force them to open
    # This should update them all so they display correctly
    foreach i $Nv_(panels) {
	Nv_openPanel $i
	update
    }

    Nv_closeAllPanels

}

# Procedure to save the state of the system, calls a special
# save procedure for each panel in the system. 
proc save_state { dummy } {
    global Nv_

    # First open a file for writing out the state
    set new_file [create_file_browser .state_file 1 0]
    if {$new_file == -1} then return

    # append ".nviz" extension to the filename if it doesn't already have one
    if { [string compare [file extension $new_file] ".nviz"] != 0 } then {
	append new_file ".nviz"
    }

    if {[catch {set file_hook [open $new_file w]} error_code] != 0} then {
	display_error "While opening file: $error_code"
	return
    }

    # Show that we are busy
    appBusy

    # Now call each of the panels one at a time and pass the
    # file hook so that each panel can write out its state
    set tmp_list $Nv_(panels)
    lappend tmp_list main
    foreach i $tmp_list {
	puts $file_hook "$i"
	set cmd_name "Nviz_$i"
	append cmd_name "_save"
	if {[catch {$cmd_name $file_hook} error_code] != 0} then {
	    puts "Diagnostic: $error_code --  Save procedure for panel $i may not be defined"
	}
    }

    # Finally, close the file and exit
    close $file_hook

    # Show that user may proceed
    appNotBusy
}

###################################################
# Routine to display error 
###################################################
proc display_error { err_string } {
    tk_dialog .file_error "File Error" "$err_string" \
	error 0 "Dismiss"
}

# Set the cancel function for drawing
Nset_cancel_func update

# and start the ball rolling...
Nv_makeGUI .top

# Center the view on initialization
look_center

# *********************************************************************
# ************* Additional Keyframe Animator Channels *****************
# *********************************************************************

# Add cutplane 0 to the keyframe animator
# Create the cutplane entry list
global Nv_
set Nv_(CutPlaneFence) OFF
set entry_list [list [list pos_x dynamic] [list pos_y dynamic] [list pos_z dynamic]]
lappend entry_list [list blend_type static]
lappend entry_list [list rot dynamic] [list tilt dynamic]

keyanimAddChannel $Nv_(P_AREA).kanimator "cplane-0" $entry_list \
    cutplane0_get_entries cutplane0_set_entries

# Undo the "Please wait..." message
update
catch {destroy .wait_ok}

# *********************************************************************
# Automatically load state file from command line
# *********************************************************************
if {[catch {set NvizLoadState}] == 0} then {

global Nv_

appBusy
load_state_aux $NvizLoadState

appNotBusy
}

if {$DEBUG} {puts "Finished loading, call draw all"}
Ndraw_all

# *********************************************************************
# Automatics command line script playing functions
# *********************************************************************

# If the -script option was used then we need to immediately start a script
# We kill Nviz after the script has finished playing
if {[catch {set NvizPlayScript}] == 0} then {
    global NvizPlayScript NvizPlayScriptProcess ScriptPlaying
    global NvizScriptKill

    set ScriptPlaying 1
    set NvizPlayScriptProcess [exec nviz -f $default_panel_path/script_play $NvizPlayScript &]

    if {[catch {set NvizScriptKill}] == 0} then {
	after 5000 CheckScriptDone
    }
}

proc CheckScriptDone {} {
    global NvizPlayScriptProcess

    set answer [catch {exec ps -p $NvizPlayScriptProcess | grep $NvizPlayScriptProcess}]
    puts "Done check = $answer"
    if {$answer == 1} then {
	exit 
    }

    after 5000 CheckScriptDone
}







