# 	$Id: tclfileP.tcl,v 1.293 2002/07/16 14:07:44 miguel Exp $	

proc .central.s { args } {
    return [eval [concat .gid.central.s $args]]
}

proc GiveGidDefaultsFile { } {
    global tcl_platform env
    if { $tcl_platform(platform) == "windows" } {
	#return [file join $env(windir) gid.ini]
	return [ gidgetdefaultsfile]
    } else {
	return [file join $env(HOME) .gidDefaults]
    }
}

# Author:       RAMSAN
# Date:         7 Feb 1997
# Function:     ReadDefaultValues
# Description:  Reads in file ~/.gidDefaults or window\gid.init  and finds there
#               some GUI configuration variables
#

proc ReadDefaultValues { file } {
    global GidPriv
    global MainWindowGeom DefaultSearchDirectory DefaultSearchDirectoryP
    global CalcAngleUnits RunProcInfo GidProcWin
    global tcl_platform

    #DebugText ReadDefaultValues file= $file"

    if { [catch { set fileid [open $file r] }] } {
	return
    }

    while { ![eof $fileid] } {
	set aa [gets $fileid]
	if { [regexp {^[*][*][*][*][*]BEGIN} $aa] } {
	    if { [regexp {^[*][*][*][*][*]BEGIN MACROS} $aa] } {
		McrReadMacros $fileid
		continue
	    }
	    set ifound 0
	    while { ![eof $fileid] } {
		set aa [gets $fileid]
		if { [regexp {^[*][*][*][*][*]END} $aa] } {
		    set ifound 1
		    break
		}
	    }
	    if { !$ifound } { 
		break 
	    } else { continue }
	}
	if { [catch { set varname [lindex $aa 0] } ] } { continue }
	 switch -- $varname {
	     MainWindowGeom {
		 if { ![info exists MainWindowGeom] } {
		     set MainWindowGeom [lindex $aa 1]
		 }
	     }
	     BitmapsGeom {
		 if { ![info exists GidPriv(BitmapsWindowGeom)] } {
		     if { [lindex $aa 1] != "NONE" } {
			 set GidPriv(PrePostBitmapsWindowGeom) \
				 "OPEN [lindex $aa 1] CreateBitmaps"
			 after idle CreateBitmaps
		     } else {
			 set GidPriv(PrePostBitmapsWindowGeom) "NONE +0+176 \
				 CreateBitmaps"
		     }
		 }
	     }
	     DefaultSearchDirectory {
		 if { ![info exists DefaultSearchDirectory] } {
		     #set DefaultSearchDirectory [lindex $aa 1]
		     set DefaultSearchDirectory [lrange $aa 1 end]
		 }
	     }
	     DefaultSearchDirectoryP {
		 if { ![info exists DefaultSearchDirectoryP] } {
		     set DefaultSearchDirectoryP [lrange $aa 1 end]
		 }
	     }
	     RightButtonsGeom {
		 if { ![info exists GidPriv(PrePostRightButWindowGeom)] } {
		     if { [lindex $aa 1] != "NONE" } {
			 set GidPriv(PrePostRightButWindowGeom) "OPEN \
				 [lindex $aa 1] RightButtons"
			 after idle RightButtons
		     } else {
			 set GidPriv(PrePostRightButWindowGeom) "INSIDE {} \
				 RightButtons"
		     }
		 }
	     }
	     BottomEntryGeom {
		 if { ![info exists GidPriv(PrePostEntryWindowGeom)] } {
		     if { [lindex $aa 1] != "NONE" } {
			 set GidPriv(PrePostEntryWindowGeom) "OPEN [lindex $aa 1] \
				 BottomEntryFrame"
			 after idle CreateBitmaps
		     } else {
			 set GidPriv(PrePostEntryWindowGeom) "INSIDE {} \
				 BottomEntryFrame"
		     }
		 }
	     }
	     CalcAngleUnits {
		 if { ![info exists CalcAngleUnits] } {
		     set CalcAngleUnits [lindex $aa 1]
		 }
	     }
	     ListEntitiesGeom {
		 if { ![info exists GidPriv(ListEntitiesWindowGeom)] } {
		     if { [lindex $aa 1] != "NONE" } {
			 set GidPriv(ListEntitiesWindowGeom) "OPEN [lindex $aa 1]"
		     } else {
			 set GidPriv(ListEntitiesWindowGeom) "NONE +0+176 "
		     }
		 }
	     }
	     RunProcInfo {
		 set RunProcInfo [lrange $aa 1 end]
		 # 3 seconds to permmit the GiD window to appear
		 after 3000 ActualizeProcInfoBegin
	     }
	     remoteserver {
		 set GidProcWin(remoteserver) [lindex $aa 1]
	     }
	     remoteuser {
		 set GidProcWin(remoteuser) [lindex $aa 1]
	     }
	     remoteauto {
		 set GidProcWin(remoteauto) [lindex $aa 1]
	     }
	     remotetime {
		 set GidProcWin(remotetime) [lindex $aa 1]
	     }
	     remoteport  {
		 set GidProcWin(remoteport) [lindex $aa 1]
	     }
	     remotetimeout {
		 set GidProcWin(remotetimeout) [lindex $aa 1]
	     }
	     NormalFont {
		 foreach "fn family size weight slant" $aa ""
		 font conf $fn -family $family -size $size -weight $weight \
			 -slant $slant
		 font conf BoldFont -family $family -size $size -weight bold \
			 -slant $slant
		 font conf SmallFont -family $family -size [expr $size-2] -weight $weight \
			 -slant $slant
	     }
	     FixedFont -
	     BigFont {
		 foreach "fn family size weight slant" $aa ""
		 font conf $fn -family $family -size $size -weight $weight \
			 -slant $slant
	     }
	     LayersAlsoLower {
		 if { ![info exists GidPriv(LayersAlsoLower)] } {
		     set GidPriv(LayersAlsoLower) [lindex $aa 1]
		 }
	     }
	     LayersBackOpposite {
		 if { ![info exists GidPriv(LayersBackOpposite)] } {
		     set GidPriv(LayersBackOpposite) [lindex $aa 1]
		 }
	     }
	     DuplicateEntities {
		 if { ![info exists GidPriv(DuplicateEntities)] } {
		     set GidPriv(DuplicateEntities) [lindex $aa 1]
		 }
	     }
	     LayersAlphabetic {
		 if { ![info exists GidPriv(LayersAlphabetic)] } {
		     set GidPriv(LayersAlphabetic) [lindex $aa 1]
		 }
	     }
	     SoftwareOpenGL {
		 if { ![info exists GidPriv(SoftwareOpenGL)] } {
		     set GidPriv(SoftwareOpenGL) [lindex $aa 1]
		 }
	     }
	     HaveViewMenu {
		 set pppp [lindex $aa 1]	
		 if { $pppp != $GidPriv(haveviewmenu)} {
		     set GidPriv(haveviewmenu) $pppp
		     SetAllMenusVariables
		     CreateTopMenus
		 }
	     }
	     GUIAppearance {
                 if { ![info exists GidPriv(GUIAppearance)] } {
		     set GidPriv(GUIAppearance) [lindex $aa 1]
                 }
	     }
	     DisplayCoordinates {
                 if { ![info exists GidPriv(Displaycoordinates)] } {
                     set GidPriv(Displaycoordinates) [lindex $aa 1]
                 }
             }
	     default {
		 if { [string match *WindowGeom [lindex $aa 0]] && \
			 ![info exists GidPriv([lindex $aa 0])] } {
		     set name [lindex $aa 0]
		     set GidPriv($name) [lrange $aa 1 end]
		     if { [lindex $GidPriv($name) 2] != "0" && \
			     [lindex $GidPriv($name) 2] != "1" } {
			 set GidPriv($name) [linsert $GidPriv($name) 2 1]
		     }
		 }
	     }
	 }
    }
    close $fileid
}

#
# what can be: PRE or POST
#

proc OpenOutsideWindows { what } {
    global GidPriv
    if { [.gid.central.s disable windows] } { return }

    foreach {name val} [array get GidPriv PrePost*Geom] {
###puts " ·1 $val"
	if { ([lindex $val 0] == "OPEN" || [string match INSIDE* [lindex $val 0]]) \
		|| $name == "PrePostTopMenuWindowGeom" } {
	    catch { eval [lrange $val 3 end] }
	}
    }
    foreach {name val} [array get GidPriv *Geom] {
	regsub {Geom$} $name {} namegeom

###puts " ·2 $val"

	if { [string match *PrePost* $name] } { 
	    continue
	} elseif { $what == "PRE" && ![string match *Post* $name] && \
		([lindex $val 0] == "OPEN" || \
		[string match INSIDE* [lindex $val 0]])} {
	    catch { eval [lrange $val 3 end] }
	} elseif { $what == "PRE" && [string match *Post* $name] } {
	    set aa [lindex $val 0]
	    catch {
		destroy $GidPriv($namegeom)
	    }
	    set GidPriv($name) "$aa [lrange $val 1 end]"
	} elseif { $what == "POST" && [string match *Post* $name] && \
		[lindex $val 0] == "OPEN"  || \
		[string match INSIDE* [lindex $val 0]]} {
	    catch { eval [lrange $val 3 end] }
	} elseif { $what == "POST" && ![string match *Post* $name] } {
	    set aa [lindex $val 0]
	    catch {
		destroy $GidPriv($namegeom)
	    }
	    set GidPriv($name) "$aa [lrange $val 1 end]"
	}
    }
###puts " · fin"
}

proc IsSplashWindowOnInDefaults {} {

    set file [GiveGidDefaultsFile]

    if { [catch { set fileid [open $file r] }] } {
	return 1
    }
    while { ![eof $fileid] } {
	set aa [gets $fileid]
	if { [regexp {SplashWindow[ ]*([01])} $aa {} val] } {
	    close $fileid
	    return $val
	}
    }
    close $fileid
    return 1
}

proc WriteTCLDefaults { } {
    WriteTCLDefaultsInFile [GiveGidDefaultsFile]
}

proc WriteTCLDefaultsInFile { file } {
    global GidPriv CopyMoveInfo GiDPrivToolBar
    global MainWindowGeom DefaultSearchDirectory DefaultSearchDirectoryP
    global CalcAngleUnits RunProcInfo GidProcWin
    global tcl_platform

    #DebugText "WriteTCLDefaultsInFile  file = $file"

    if { $tcl_platform(platform) == "windows" } {
	if { [wm state .gid] == "zoomed" } {
	    if { ![info exists MainWindowGeom] } {
		set MainWindowGeom "600x300+100+100"
	    }
	    set geom $MainWindowGeom
	    if { [regexp {([^x]*)x([^+-]*)([+-]*[0-9]*)([+-]*[0-9]*)} $geom] } {
		set MainWindowGeom "ZOOMED $geom"
	    } elseif { [regexp {([^x]*)x([^+-]*)([+-]*[0-9]*)([+-]*[0-9]*)} \
		    [lindex $geom 1]] } {
		set MainWindowGeom "$geom"
	    } else {
		set MainWindowGeom "ZOOMED 600x300+100+100"
	    }
	} else {
	    set MainWindowGeom [wm geom .gid]
	    regexp {([^x]*)x([^+-]*)([+-]*[0-9]*)([+-]*[0-9]*)} $MainWindowGeom \
		    trash w h x y
	    if { [.gid cget -menu] != "" } {
		set menuheight [.gid.central.s info menuheight]
		incr h $menuheight
	    }
	    set windowcaptionheight [.gid.central.s info windowcaptionheight]
	    if { $x <= 0 } { set x +-4 }
	    if { $y <= 0 } { set y +-4 }
	    if { $w >= [ winfo screenwidth .gid] && \
		    [expr $h+$windowcaptionheight] >= [ winfo screenheight .gid] } {
		set w [ winfo screenwidth .gid]
		set h [ winfo screenheight .gid]
		set x +-4
		set y +-4
	    }
	    set MainWindowGeom ${w}x${h}${x}${y}
	}
    } else {
	set MainWindowGeom [wm geom .gid]
    }

    if { ![info exists CalcAngleUnits] } {
	set CalcAngleUnits "rad"
    }
    set varslist { MainWindowGeom DefaultSearchDirectory \
	    DefaultSearchDirectoryP CalcAngleUnits }

    set fileid [open $file a]
    foreach i $varslist {
	if { [info exists $i] } {
	    set text "puts $fileid \"$i $$i\""
	    eval $text
	}
    }

    if { [info exists GidPriv(LayersAlsoLower)] } {
	puts $fileid "LayersAlsoLower $GidPriv(LayersAlsoLower)"
    }
    if { [info exists GidPriv(LayersBackOpposite)] } {
	puts $fileid "LayersBackOpposite $GidPriv(LayersBackOpposite)"
    }


    if { [info exists GidPriv(DuplicateEntities)] } {
	puts $fileid "DuplicateEntities $GidPriv(DuplicateEntities)"
    }
    if { [info exists GidPriv(LayersAlphabetic)] } {
	puts $fileid "LayersAlphabetic $GidPriv(LayersAlphabetic)"
    }
    if { [info exists GidPriv(SoftwareOpenGL)] } {
	puts $fileid "SoftwareOpenGL $GidPriv(SoftwareOpenGL)"
    }

    puts $fileid "HaveViewMenu $GidPriv(haveviewmenu)"
    
    puts $fileid "GUIAppearance $GidPriv(GUIAppearance)"

    foreach i "NormalFont FixedFont BigFont" {
	set family [font conf $i -family]
	set size [font conf $i -size]
	set weight [font conf $i -weight]
	set slant [font conf $i -slant]
	puts $fileid [list $i $family $size $weight $slant]
    }

    foreach {name val} [array get GidPriv *Geom] {
        regsub {Geom$} $name {} geomwinname
 	if { [info exists GidPriv($geomwinname)] } {
	    set w $GidPriv($geomwinname)
            if { [winfo exists $w] && [winfo class $w] == "Toplevel" } {
		    set InitComm $GidPriv($geomwinname,InitComm)
		    WriteYourGeomToVar $w OPEN $name $InitComm
		    set val $GidPriv($name)
	    } 
	} elseif { [info exists GiDPrivToolBar($name)] } {
	    set w $GiDPrivToolBar($name)
  	    set type [lindex $GidPriv($name) 0]
  	    if { [regexp {(INSIDE[a-zA-Z]+)[0-9]*} $type {} type] } {
  		set vv $GidPriv($name)
  		set par [lindex [pack info $w] 1] 
  		set type $type[lsearch [pack slaves $par] $w]
  		set GidPriv($name) "$type [lrange $vv 1 end]"
		set val $GidPriv($name)
  	    }
	}
	puts $fileid "$name $val"
    }

    if { [info exist RunProcInfo] } {
	set res [catch { PWQuittingGiD } aa]
	if { $res } {
	    #ERROR--$aa
	}
	if { $RunProcInfo != "" } {
	    puts $fileid "RunProcInfo $RunProcInfo"
	}
    }
    foreach i "remoteserver remoteuser remoteauto remotetime remoteport remotetimeout" {
	if { [info exists GidProcWin($i)] } {
	    puts $fileid "$i $GidProcWin($i)"
	}
    }

    McrWriteMacros $fileid
    close $fileid

    #look for it in tk.tcl
    if { [info exists GidPriv(EventFile)] } {
	close $GidPriv(EventFile)
    }

}
proc ToggleTransientWin { w } {
    global GidPriv
    if { $GidPriv(Transient,$w) == 1 } {
	wm transient $w .gid
    } else {
	wm transient $w ""
    }
    AddAlwaysOnTopFlag $w
}

proc AddAlwaysOnTopFlag { w } {
    global GidPriv
    catch { destroy $w._topmenu }
    menu $w._topmenu -tearoff 0
    $w conf -menu $w._topmenu
    menu $w._topmenu.system -tearoff 0
    $w._topmenu add cascade -menu $w._topmenu.system
    $w._topmenu.system add checkbutton -label "Always on top" -var \
	    GidPriv(Transient,$w) -command "ToggleTransientWin $w"
}

proc ConfigureWinIdle { w geomname { InitComm ""} } {
    if { [winfo exists $w] } {
	bind $w <Configure> [list ConfigureWin $w $geomname [ join $InitComm]]
    }
}

proc ConfigureWin { w geomname {InitComm ""}} {
    global GidPriv tcl_platform

    if { [winfo class $w] == "Toplevel" } {
	bind $w <Configure> ""
	
	WriteYourGeomToVar $w OPEN $geomname $InitComm
	after idle ConfigureWinIdle $w $geomname [ list $InitComm]
    }
}

proc DestroyWin { W w geomname {InitComm ""}} {
    global GidPriv tcl_platform


   if { $W == $w } {
	#bind $w <Destroy> ""
	WriteYourGeomToVar $w NONE $geomname $InitComm
    }
}

proc WriteYourGeomToVar { w what geomname {InitComm ""}} {
    global GidPriv tcl_platform
    if { [wm transient $w] != "" } {
	set trans 1
    } else {
	set trans 0
    }
    set geom [wm geom $w]
    if { $tcl_platform(platform) == "windows" } {
	regexp {([^x]*)x([^+-]*)([+-]*[0-9]*)([+-]*[0-9]*)} $geom \
		trash width height x y
	if { $width == "" } { set width 1 }
	if { $height == "" } { set height 1 }
	set menuheight 19
	incr height [expr $menuheight*-1]
	if { $height < 1 } { set height 20 }
	set geom ${width}x${height}${x}${y}
    }
    set GidPriv($geomname) "$what $geom $trans $InitComm"
}

proc InitWindow { w title geomname {InitComm ""} { class ""} { OnlyPos 0 } } {
    global GidPriv
    catch { # to run alone
	if { [.gid.central.s disable windows] } { return close }
    }
    
    if { ![info exists GidPriv(TopLevelsList)] } {
	set GidPriv(TopLevelsList) ""
    }
    if { [lsearch $GidPriv(TopLevelsList) $w] == -1 } {
	lappend GidPriv(TopLevelsList) $w
    }

    catch { destroy $w }
    if { $class == "" } {
	toplevel $w
    } else { toplevel $w -class $class }

    global tcl_platform
    if { $tcl_platform(platform) == "windows" } {
	if { [info exists GidPriv($geomname)] } {
	    set  GidPriv(Transient,$w) [lindex $GidPriv($geomname) 2]
	} else { set  GidPriv(Transient,$w) 1 }
  	ToggleTransientWin $w
    }

    wm title $w $title
    if { [info exists GidPriv($geomname)] } {
	if { $OnlyPos == 0 } {
	    set posgeom [lindex $GidPriv($geomname) 1]
	} else {
	    regexp {[+-].*} [lindex $GidPriv($geomname) 1] posgeom
	}
	WmGidGeom $w $posgeom
    } else { WmGidGeom $w "" }
    bind $w <Destroy> [list DestroyWin %W $w $geomname $InitComm]
    bind $w <Configure> [list ConfigureWin %W $geomname $InitComm]

    regsub {Geom$} $geomname {} geomwinname
    set GidPriv($geomwinname) $w
    set GidPriv($geomwinname,InitComm) $InitComm
}

proc QuadraticMenu { w } {


    set quadratic [lindex [.gid.central.s info Project] 5]
    switch $quadratic {
	0 { set curr Normal }
	1 { set curr Quadratic }
	2 { set curr Quadratic9 }
    }

    set names "Normal Quadratic Quadratic9"
    $w del 0 end

    foreach i $names {
	if { $i == $curr } {
	    $w add check -label $i -var $w
	    global $w
	    set $w 1
	} else {
	    $w add command -label $i -command ".gid.central.s process escape \
		    escape escape escape Meshing quadratic $i escape"
	}
    }
}

#  proc ChangeQuadraticFlag { newval } {

#      set quadratic [lindex [.gid.central.s info Project] 5]

#      switch $newval {
#  	info {
#  	    set word Using
#  	}
#  	quadratic {
#  	    set word "Changing to"
#  	    .gid.central.s process escape escape escape escape Meshing \
#  		    quadratic quadratic escape
#  	    set quadratic 1
#  	}
#  	quadratic9 {
#  	    set word "Changing to"
#  	    .gid.central.s process escape escape escape escape Meshing \
#  		    quadratic quadratic9 escape
#  	    set quadratic 2
#  	}
#  	normal {
#  	    set word "Changing to"
#  	    .gid.central.s process escape escape escape escape Meshing \
#  		    quadratic normal escape
#  	    set quadratic 0
#  	}
#      }
#      if { $quadratic == 0 } {
#  	set text "$word linear degree elements"
#      } elseif { $quadratic == 1 }  { set text "$word quadratic degree elements" 
#      } else { set text "$word quadratic9 degree elements" }
#      tk_dialogRAM .gid.tempwinq {information window} $text questhead 0 OK
    
#  }

proc ChooseElemType { etype { ltype ""} } {

    set MoreWin [.gid.central.s info variables UseMoreWindows]

    set list1 "Linear Triangle Quadrilateral Tetrahedra Hexahedra OnlyPoints"
    set list2 " -     surfaces surfaces      volumes    volumes volumes"

    set todo "escape escape escape escape Meshing \
	    ElemType $etype"

    set inum [lsearch -exact $list1 $etype]
    if { $inum == 0 } {
	set word $ltype
	lappend todo $ltype
    } else { set word [lindex $list2 $inum] }

    .gid.central.s process $todo

    if { $MoreWin > 1 } {
	tk_dialogRAMFull .gid.tempwiniw {information window} \
		"Select $word to assign elem type: $etype" \
		"" "" gidquestionhead 0 OK
    }
    
}

# proc ChangeEntryPlace { {geom NONE}  {ini ""} } {
#     set hhscr [winfo screenheight .]
#     set makeMB 0
#     if { ($ini == "yes" && $geom != "NONE") || ([winfo exists .comm] && \
# 	    [winfo class .comm] != "Toplevel") } {
# 	catch { destroy .comm }
# 	set hh [expr [winfo x .]]
# 	set vv [expr [winfo y .]+[winfo height .]+25]
# 	toplevel .comm 
# 	if { $geom != "NONE" } { wm geometry .comm $geom } else {
# 	    wm geometry .comm [winfo width .]x100+$hh+$vv
# 	}
# 	wm minsize .comm  1 1
# 	set makeMB 1
# 	bind .comm <Destroy> { set BottomEntryGeom [wm geom .comm] }
	
#     } else {
# 	if { [winfo exists .comm] } {
# 	    destroy .comm
# 	    set makeMB 1
# 	}
# 	frame .comm
# 	pack forget .gid.central
# 	pack .comm -fill x -side bottom
# 	catch { pack .gid.central -fill both -expand yes }
#     }
#     entry .comm.e -relief sunken
#     frame .comm.fwarn
#     scrollbar .comm.fwarn.yscroll -relief sunken  -takefocus 0 \
# 	    -command ".comm.fwarn.list yview"
#     listbox .comm.fwarn.list -yscroll ".comm.fwarn.yscroll \
# 	    set"  -relief groove  -borderwidth 4 -takefocus 0
#     if {[winfo class .comm] != "Toplevel" } { 
# 	.comm.fwarn.list conf -width 20 -height 2
#     }
    
#     .comm.fwarn.list conf -selectmode single
#     pack .comm.fwarn.yscroll -side right -fill y
#     pack .comm.fwarn.list -expand yes -fill both 
    
#     pack .comm.e -fill x -side bottom -pady 5 -padx 5
#     pack .comm.fwarn -fill both -side top -pady 5 -expand yes
    

#     if { $makeMB == 1 } { MakeBindings }

# }


proc EnterCommand { w command { entry -1 } } {
    #if entry!=-1 => uses entryconfigure
    
    #if { $command == "" } { return }

    switch -- $entry {
	-1 {
	    set comm "$w conf -command "
	}
	-2 {
	    set comm "$w conf -postcommand "
	}
	default {
	    set comm "$w entryconfigure $entry -command "
	}
    }
    if { $command == "" } { 
	lappend comm ""
	eval $comm
	return
    }

    switch -- [lindex $command 0] {
	"-npw-" {
	    set vareval "$comm {[lrange $command 1 end] $w}"
	}
	"-np-" {
	    set vareval "$comm {[lrange $command 1 end]}"
	}
	"-ne-" {
	    set vareval "$comm {.gid.central.s process [lrange $command 1 end]}"
	}
	default {
	    set vareval "$comm {.gid.central.s process escape escape escape escape \
		    $command}"
	}
    }
    set vareval2 ""
    while 1 {
	if { [string first %W $vareval] == -1 } {
	    append vareval2 $vareval
	    break
	}
	append vareval2 [string range $vareval 0 [expr [string first %W $vareval]-1]]
	append vareval2 $w
	set vareval [string range $vareval [expr [string first %W $vareval]+2] end]
    }

    eval $vareval2

}

proc AddAccelerator { key menu index } {

    regsub -all Control $key Ctrl keyname
    $menu entryconf $index -accelerator $keyname

    if { [llength $key] == 1 } {
	bind .gid <$key> "$menu invoke $index ; break"
    } elseif { [llength $key] == 2 } {
	bind .gid <[lindex $key 0]><[lindex $key 1]> "$menu invoke $index ; break"
    }
}

proc CreateTopMenusUnix { w } {
    global MenuNames MenuNamesP	ViewMenuPriv

    if { ![winfo exists $w] } { return }
    if { [catch { set infoProj [lindex [.gid.central.s info Project] 4] }] } {
	set infoProj "GEOMETRYUSE"
    }

    if { $infoProj != "POSTUSE" } {
	set MenuNamesInto $MenuNames
	set MenuEntriesName MenuEntries
	set MenuCommandsName MenuCommands
	set MenuAccelerName MenuAcceler
    } else {
	set MenuNamesInto $MenuNamesP
	set MenuEntriesName MenuEntriesP
	set MenuCommandsName MenuCommandsP
	set MenuAccelerName MenuAccelerP

	if { [ info exist ViewMenuPriv] } {
	    unset ViewMenuPriv
	}
    }

    set NumMenus [llength $MenuNamesInto]

    set UnderLineList ""

    for {set i $NumMenus } { $i< 15 } { incr i } {
	if { [winfo exists $w.button$i] } {
	    destroy $w.button$i
	}
    }


    for {set i 0 } { $i< $NumMenus } { incr i } {
	set text [lindex $MenuNamesInto $i]

	if { ![winfo exists $w.button$i] } {
	    menubutton $w.button$i -text $text \
		    -menu $w.button$i.m.m 
	    frame $w.button$i.m -class OverlayWindowN
	    wm colormapwindows .gid $w.button$i.m
	    menu $w.button$i.m.m -tearoff no
	} else { 
	    $w.button$i conf -text $text
	    if { [$w.button$i.m.m index end] != "none" } {
		ClearMenu $w.button$i.m.m
		#$w.button$i.m.m del 0 end
	    }
	    $w.button$i.m.m configure -postcommand ""
	}

	upvar \#0 $MenuEntriesName ME
	upvar \#0 $MenuCommandsName MC

	if { $ME($i) == "" } {
	    if { [lindex $MC($i) 0] != "-np-" } {

		WarnWin "Error creating menu '$text'. Needed -np-"
	    }
	    set comm [lrange $MC($i) 1 end]
	    regsub -all %W $comm $w.button$i.m.m comm

	    $w.button$i.m.m conf -postcommand $comm
	}

	for {set under 0 } { $under< [string length $text]} { incr under } {
	    set letter [string tolower [string index $text $under]]
	    if { ![regexp {[a-zA-Z]} $letter] } { continue }
	    if { [lsearch $UnderLineList $letter] == -1 } {
		lappend UnderLineList $letter
		$w.button$i conf -underline $under
		break
	    }
	}

	CreateCascadedMenu $w.button$i.m.m $MenuEntriesName $MenuCommandsName \
		$MenuAccelerName $i
    }

    for {set i 0 } { $i< $NumMenus } { incr i } {
	if { $i < [expr $NumMenus-1] } {
	    pack $w.button$i -side left
	} else { pack $w.button$i -side right}
    }
    GidHelpT $w "Menu with the main commands."
}

proc CreateTopMenusWin { w } {
    global MenuNames MenuNamesP ViewMenuPriv

    if { ![winfo exists $w] } { return }

    set top [winfo toplevel $w]
    if { $top != ".gid" } { 
	set t $top 
	if { [.gid cget -menu] != "" } { 
	    .gid conf -menu "" 
	    destroy .mm1
	}
    } else { 
	set t "" 
    }

    if { [catch { set infoProj [lindex [.gid.central.s info Project] 4] }] } {
	set infoProj "GEOMETRYUSE"
    }

    if { $infoProj != "POSTUSE" } {
	set MenuNamesInto $MenuNames
	set MenuEntriesName MenuEntries
	set MenuCommandsName MenuCommands
	set MenuAccelerName MenuAcceler
    } else {
	set MenuNamesInto $MenuNamesP
	set MenuEntriesName MenuEntriesP
	set MenuCommandsName MenuCommandsP
	set MenuAccelerName MenuAccelerP

	if { [ info exist ViewMenuPriv] } {
	    unset ViewMenuPriv
	}
    }

    set NumMenus [llength $MenuNamesInto]

    set UnderLineList ""

    if { ![winfo exists $t.mm1] } { 
	menu $t.mm1 -type menubar 
#	$top conf -menu $t.mm1
    } else {
	$t.mm1 del 0 end
    }
    $top conf -menu $t.mm1

    foreach i [winfo children $t.mm1] {
        destroy $i
    }

    for {set i 0 } { $i< $NumMenus } { incr i } {

	set text [lindex $MenuNamesInto $i]
	set namemenu $t.mm1.button$i
	if { ![winfo exists $namemenu] } {
	    menu $namemenu
	} else { 
	    ClearMenu $namemenu
	    $namemenu configure -postcommand ""
	    #$namemenu del 0 end
	}
	$t.mm1 add cascade -label $text -menu $namemenu

	
	upvar \#0 $MenuEntriesName ME
	upvar \#0 $MenuCommandsName MC
	if { $ME($i) == "" } {
	    if { [lindex $MC($i) 0] != "-np-" } {
		WarnWin "Error creating menu '$text'. Needed -np-"
	    }
	    set comm [lrange $MC($i) 1 end]
	    regsub -all %W $comm $namemenu comm
	    $namemenu conf -postcommand $comm
	}

	for {set under 0 } { $under< [string length $text]} { incr under } {
	    set letter [string tolower [string index $text $under]]
	    if { ![regexp {[a-zA-Z]} $letter] } { continue }
	    if { [lsearch $UnderLineList $letter] == -1 } {
		lappend UnderLineList $letter
		$t.mm1 entryconf $i -underline $under
		break
	    }
	}

	CreateCascadedMenu $namemenu $MenuEntriesName $MenuCommandsName \
		$MenuAccelerName $i
    }
    # for debugging
    #InstrumentMenu $t.mm1
}

proc CreateTopMenus { { w .gid.menu } } {
    global tcl_platform GidPriv

    if { $tcl_platform(platform) != "windows" } {
  	CreateTopMenusUnix $w
    } else {
	CreateTopMenusWin $w
    }
    set GidPriv(POSTDATA) 1

    McrBindMacros
}

# for debugging
proc InstrumentCommand { label script } {
    set time [time {uplevel \#0 $script}]
    WarnWinText "$label $script $time"
}
proc InstrumentMenu { menu {label "" } } {

    set comm [$menu cget -postcommand]
    if { $comm != "" } {
	set comm [list InstrumentCommand $label $comm]
	$menu configure -postcommand $comm
    }
    set endidx [$menu index end]
    if { $endidx == "none" } { return }
    for { set i 0 } { $i <= $endidx } { incr i } {
	if { [$menu type $i] == "cascade" } {
	    InstrumentMenu [$menu entrycget $i -menu] [$menu entrycget $i -label] 
	}
    }
}

proc CreateGlobalBinding { keys command } {

    regsub -all {Ctrl} $keys {Control} scbind
    regsub { } $scbind {><} scbind
    set scbind <$scbind>
    bind .gid $scbind $command
}

proc ViewGlobalBinding { keys } {
    regsub -all {Ctrl} $keys {Control} scbind
    regsub { } $scbind {><} scbind
    set scbind <$scbind>
    set oldcomm [bind .gid $scbind]
    return $oldcomm
}

proc ChangeTopMenusAndWindows {} {

    .central.s disable graphics 1
    CreateTopMenus
    if { [lindex [.gid.central.s info Project] 4] != "POSTUSE" } {
	OpenOutsideWindows PRE
	Create3rdButtonMenu .gid.phantom.display3dbutton

	# UpdateDataOptions

    } else {
	OpenOutsideWindows POST
	Create3rdButtonMenu .gid.phantom.display3dbutton POST
    }
    update idletasks
    .central.s disable graphics 0
}

set DelayedConfigureButsVar 0
set DelayedConfigureSize "0 0"

proc DelayedConfigureButsFunc {} {
    global DelayedConfigureButsVar DelayedConfigureSize GidPriv

    incr DelayedConfigureButsVar -1
    if { $DelayedConfigureButsVar > 0 } {  return }
    if { ![winfo exists .gid.buts] } {
	set GidPriv(PrePostRightButWindowGeom) "NONE {} RightButtons"
    } elseif { [winfo class .gid.buts] == "Toplevel" } {
	set GidPriv(PrePostRightButWindowGeom) "OPEN [wm geom .gid.buts] RightButtons"
    } else {
	set GidPriv(PrePostRightButWindowGeom) "INSIDE {} RightButtons"
    }
    if { [winfo exists .gid.buts] } {
	set w [winfo width .gid.buts]
	set h [winfo height .gid.buts]
	if { $w != [lindex $DelayedConfigureSize 0] || \
		$h != [lindex $DelayedConfigureSize 1] } {
	    SetButtons
	    set DelayedConfigureButsVar 0
	    set DelayedConfigureSize "$w $h"
	}
    }
}

proc SetButtons { { first 0 } } {
    global ActionsMenuVar mxbutwidth PostButStack

    set w .gid.buts.f
#    if { [winfo class .gid.buts] == "Toplevel" } { append w .f }
    
    if { $first == 0 } { set PostButStack "" }
    if { $PostButStack != "" } {
###puts " · ·· pack & conf"
	set num [lindex $PostButStack [expr [llength $PostButStack]-1]]
	pack $w.al -side left -padx 0
	$w.al conf -command "set PostButStack \"[lrange $PostButStack \
		0 [expr [llength $PostButStack]-2]]\" ; SetButtons $num"
    } else { pack forget $w.al }
    pack forget $w.ar

###puts " · ·· places"

    set xpos 3 ; set ypos 5
    set butpady 2
###puts " · ·· [winfo width $w] == 1 -> { update idletasks }"
    if { [winfo width $w] == 1 } { update idletasks }
###puts " · ·· sets"
    set tothei [expr [winfo height $w]-20]
    set totwid [winfo width $w]
    set overflow 0
    set last [llength $ActionsMenuVar]
    for {set k 0 } { $k<100 } { incr k } {
	if {$k < $first || $k>=$last || $overflow } {
###puts " · ·· $k forget"
	    place forget $w.b$k
	} else {
###puts " · ·· $k conf & place"
	    set name [lindex $ActionsMenuVar $k]
	    $w.b$k conf -text $name -command ".gid.central.s process $name"
	    place $w.b$k -x $xpos -y $ypos
	    set reqh [ winfo reqheight $w.b$k]
	    set ypos [ expr $ypos + $reqh + $butpady]
	    #incr ypos 31
	    if { $ypos > $tothei && $k < [expr $last-1] } {
		incr xpos 130
		if { [expr $xpos+80] > $totwid } { 
                    pack $w.ar -side right -padx 0
		    $w.ar conf -command \
			    "lappend PostButStack $first ; SetButtons [expr $k+1]"
		    set overflow 1
		}
		set ypos 5
	    }
	}
    }
###puts " · ·· FIN"
}

proc MenuInCommandButton { e x y } {
    global ActionsMenuVar

    set w .gid.menuincommandwindow
    catch { destroy $w }
    menu $w
    set words ""
    foreach i $ActionsMenuVar {
	regsub -all {([a-z])([A-Z])} $i "\\1 \[string tolower \\2]" name
	set name [subst $name]
	set name [string toupper [string index $name 0]][string range $name 1 end]
	if { $i == "Join" || $i == "NoJoin" } { append name " C-a" }
	lappend words [list $name "$e insert end \" $i\""]
    }
    rmenuconf $w $words
    tk_popup $w $x $y 0
}


proc AutoCompleteGiDEntry { e } {
    global ActionsMenuVar

    if { [string trim [$e get]] == "" } {
	if { [winfo exists .gid.wSetCoord.xe] } {
	    focus .gid.wSetCoord.xe
	}
	return
    }
    if { [catch {
	set beginwords [lrange [$e get] 0 end-1]
	set lastword [lindex [$e get] end]
    }] } { return }

    if { $beginwords != "" } {
	$e del 0 end
	$e ins end $beginwords
	uplevel #0 [bind $e <Return>]
	$e ins end $lastword
	after idle AutoCompleteGiDEntry $e
	return
    }

    set idx [lsearch -glob [string tolower $ActionsMenuVar] [string tolower ${lastword}*]]
    set word [lindex $ActionsMenuVar $idx]
    set wordoptions $word
    set isfull 1
    if { $idx != -1 } {
	set idx2 $idx
	while 1 {
	    set idx2new [lsearch -glob [string tolower [lrange $ActionsMenuVar [expr $idx2+1] end]] \
			  [string tolower ${lastword}*]]
	    if { $idx2new == -1 } { break }
	    set idx2 [expr $idx2+1+$idx2new]
	    set newword [lindex $ActionsMenuVar $idx2]
	    lappend wordoptions $newword
	    for { set i [string length $lastword] } { $i < [string length $word] } { incr i } {
		set l1 [string tolower [string index $word $i]]
		set l2 [string tolower [string index $newword $i]]
		if {  $l1 != $l2 } { break }
	    }
	    if { $i < [string length $word] } { set isfull 0 }
	    set word [string range $word 0 [expr $i-1]]
	}
	set text [lrange [$e get] 0 end-1]
	$e del 0 end
	if { $isfull } {
	    $e ins end "$word "
	} else {
	    $e ins end "$word"
	    ChangeWarnLineVar "Options: $wordoptions"
	}
	$e icursor end
	$e xview moveto 1
    }
}


proc SaveNewBitmapsGeom { Nombre bw StartFunc { prefix PrePost } } {
    global GidPriv
    regexp {[0-9]+x[0-9]+(.*)} [winfo geom $bw] trash rest
    bind $bw <Configure> ""
    
    set NumBitmaps 0
    while { [winfo exists $bw.$NumBitmaps] } { 
	incr NumBitmaps 
    }

    set w [winfo width $bw]
    set h [winfo height $bw]


    set w_width 0
    set w_height 0
    set sep_height 0
    set sep_width 0
    
    set term Separadores
    if { $w >= $h} {
	foreach icn $GidPriv($Nombre$term) {
	    $bw.$icn conf -image $GidPriv(image_sep_vert.gif)
	}
	set sep_width $GidPriv(BitmapsSepVWidth)
	set sep_height $GidPriv(BitmapsSepVHeight)

	# buscamos la maxima altura: $h ha de ser >= max_height
	set max_height 0
	set new_width 0
	for { set icn 0} { $icn < $NumBitmaps} { incr icn} {

	    if { ( "$Nombre" != "StdBar") || ( [ expr $icn + 1] != $NumBitmaps)} {
		set b_width [ expr $GidPriv(BitmapsWidth) + 2]
		set b_height [ expr $GidPriv(BitmapsHeight) + 2]
	    } else {
		# ancho y altura del bitmap info_gid en la barra estandard definidos en GrDataMenu.tcl
		# set GidPriv(InfoGiDBitmapWidth) 77
		# set GidPriv(InfoGiDBitmapHeight) 24
		set b_width [ expr $GidPriv(InfoGiDBitmapsWidth) + 2]
		set b_height [ expr $GidPriv(InfoGiDBitmapsHeight) + 2]
	    }
	    set term Separadores
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		## las lineas de los botoncitos
		set b_width [ expr $sep_width + 2]
		set b_height [ expr $sep_height + 2]
	    }
	    set term MenusList
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		set b_width [ expr $b_width + 1]
		set b_height [ expr $b_height + 1]
	    }
	    if { $b_height > $max_height} {
		set max_height $b_height
	    }
	    set new_width [ expr $new_width + $b_width]
	}
	if { $h < $max_height} {
	    set h $max_height
	    set w $new_width
	}

	set row(0) ""
	set width(0) 0
	set height(0) 0
	set nrow 0
	#buscamos que dibujitos van horizontalmente
	for { set icn 0} { $icn < $NumBitmaps} { incr icn} {
	    ## las lineas de los botoncitos
	    if { ( "$Nombre" != "StdBar") || ( [ expr $icn + 1] != $NumBitmaps)} {
		set b_width [ expr $GidPriv(BitmapsWidth) + 2]
		set b_height [ expr $GidPriv(BitmapsHeight) + 2]
	    } else {
		# ancho y altura del bitmap info_gid en la barra estandard definidos en GrDataMenu.tcl
		# set GidPriv(InfoGiDBitmapWidth) 77
		# set GidPriv(InfoGiDBitmapHeight) 24
		set b_width [ expr $GidPriv(InfoGiDBitmapsWidth) + 2]
		set b_height [ expr $GidPriv(InfoGiDBitmapsHeight) + 2]
	    }
	    set term Separadores
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		## las lineas de los botoncitos
		set b_width [ expr $sep_width + 2]
		set b_height [ expr $sep_height + 2]
	    }
	    set term MenusList
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		set b_width [ expr $b_width + 1]
		set b_height [ expr $b_height + 1]
	    }
	    set width($nrow) [ expr $width($nrow) + $b_width]
	    if { $width($nrow) <= $w} {
		lappend row($nrow) $icn
		if { $b_height > $height($nrow)} {
		    set height($nrow) $b_height
		}
	    } else {
		# no lo utilizaremos, pero por si acaso
		set width($nrow) [ expr $width($nrow) - $b_width]
		if { $width($nrow) > $w_width} {
		    set w_width $width($nrow)
		}
		set w_height [ expr $w_height + $height($nrow)]
		incr nrow
		set width($nrow) $b_width
		set row($nrow) $icn
		set height($nrow) $b_height
	    }
	}
	if { $width($nrow) > $w_width} {
	    set w_width $width($nrow)
	}
	set w_height [ expr $w_height + $height($nrow)]
	incr nrow
	
	#enpaquetamos
	eval [concat "grid forget [winfo children $bw]"]

	set ult 1

	for { set ir 0} { $ir < $nrow} { incr ir} {
	    #catch { destroy $bw.f$ir}
	    #frame $bw.f$ir -bd 0
	    set ic 0
	    foreach icn $row($ir) {
		#WarnWinText "$ult = Using $bw.$icn -in $bw.f$ir -sticky w"
		if { ( "$Nombre" != "StdBar") || ( $ult < $NumBitmaps)} {
		    grid $bw.$icn -in $bw.f$ir -row 0 -column $ic -sticky nw
		    grid columnconfig $bw.f$ir $ic -weight 0
		    incr ic
		} else {
		    grid $bw.$icn -in $bw.f$ir -row 0 -column $ic -sticky ne
		    grid columnconfig $bw.f$ir $ic -weight 1
		    incr ic
		}
		incr ult
	    }
	    grid rowconfig $bw.f$ir 0 -weight 1
	    if { ( "$Nombre" != "StdBar") || ( [ expr $ir + 1] != $nrow)} {
		grid $bw.f$ir -sticky nw
	    } else {
		grid $bw.f$ir -sticky new
	    }
	    grid rowconfig $bw $ir -weight 1
	    if { ( "$Nombre" == "StdBar") && ( $ult >= $NumBitmaps)} {
	    }
	}
	grid columnconfig $bw 0 -weight 1


    } else {
	if { "$Nombre" == "StdBar"} {
	    set NumBitmaps [ expr $NumBitmaps - 1]
	}
	# es mas vertical que horizontal ( enpaquetmos de arriba a abajo)
	set term Separadores
	foreach icn $GidPriv($Nombre$term) {
	    $bw.$icn conf -image $GidPriv(image_sep_hori.gif)
	}
	set sep_width $GidPriv(BitmapsSepHWidth)
	set sep_height $GidPriv(BitmapsSepHHeight)

	# buscamos la maxima anchura: $w ha de ser >= max_width
	set max_width 0
	set new_height 0
	for { set icn 0} { $icn < $NumBitmaps} { incr icn} {
	    set b_width [ expr $GidPriv(BitmapsWidth) + 2]
	    set b_height [ expr $GidPriv(BitmapsHeight) + 2]
	    set term Separadores
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		## las lineas de los botoncitos
		set b_width [ expr $sep_width + 2]
		set b_height [ expr $sep_height + 2]
	    }
	    set term MenusList
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		set b_width [ expr $b_width + 1]
		set b_height [ expr $b_height + 1]
	    }
	    if { $b_width > $max_width} {
		set max_width $b_width
	    }
	    set new_height [ expr $new_height + $b_height]
	}
	if { $w < $max_width} {
	    set w $max_width
	    set h $new_height
	}
	
	set col(0) ""
	set width(0) 0
	set height(0) 0
	set ncol 0     
	#buscamos que dibujitos van horizontalmente
	for { set icn 0} { $icn < $NumBitmaps} { incr icn} {
	    ## las lineas de los botoncitos
	    set b_width [ expr $GidPriv(BitmapsWidth) + 2]
	    set b_height [ expr $GidPriv(BitmapsHeight) + 2]
	    set term Separadores
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		## las lineas de los botoncitos
		set b_width [ expr $sep_width + 2]
		set b_height [ expr $sep_height + 2]
	    }
	    set term MenusList
	    if { [ lsearch $GidPriv($Nombre$term) $icn] != -1} {
		set b_width [ expr $b_width + 1]
		set b_height [ expr $b_height + 1]
	    }

	    set height($ncol) [ expr $height($ncol) + $b_height]
	    if { $height($ncol) <= $h} {
		lappend col($ncol) $icn
		if { $b_width > $width($ncol)} {
		    set width($ncol) $b_width
		}
	    } else {
		# no lo utilizaremos, pero por si acaso
		set height($ncol) [ expr $height($ncol) - $b_height]
		if { $height($ncol) > $w_height} {
		    set w_height $height($ncol)
		}
		set w_width [ expr $w_width + $width($ncol)]
		incr ncol
		set height($ncol) $b_height
		set col($ncol) $icn
		set width($ncol) $b_width
	    }
	}
	if { $height($ncol) > $w_height} {
	    set w_height $height($ncol)
	}
	set w_width [ expr $w_width + $width($ncol)]
	if { $ncol <= $NumBitmaps} {
	    incr ncol
	}
	
	#enpaquetamos
	eval [concat "grid forget [winfo children $bw]"]

	for { set ic 0} { $ic < $ncol} { incr ic} {
	    #WarnWinText "ic = $ic / $ncol"
	    #catch { destroy $bw.f$ir}
	    #frame $bw.f$ir -bd 0
	    set ir 0
	    foreach icn $col($ic) {
		#WarnWinText "Using $bw.$icn -in $bw.f$ic -sticky w"
		grid $bw.$icn -in $bw.f$ic -column 0 -row $ir -sticky nw
		incr ir
		grid rowconfig $bw.f$ic $ir -weight 1
	    }
	    grid columnconfig $bw.f$ic 0 -weight 1
	    grid $bw.f$ic -sticky nw -column $ic -row 0
	    grid columnconfig $bw $ic -weight 1
	}

	grid rowconfig $bw 0 -weight 1

    }




    if { [winfo class $bw] == "Toplevel" } {
	wm geom $bw ${w_width}x${w_height}$rest
	update 
	if { [wm transient $bw] != "" } {
	    set trans 1
	} else {
	    set trans 0
	}
	set term WindowGeom
	set GidPriv($prefix$Nombre$term) \
		"OPEN [wm geom $bw] $trans $StartFunc"
    }
    
    bind $bw <Configure> [list SaveNewBitmapsGeom $Nombre $bw $StartFunc]
}

#  proc OldSaveNewBitmapsGeom {} {
#      global GidPriv
#      regexp {[0-9]+x[0-9]+(.*)} [winfo geom .gid.bitmaps] trash rest
#      bind .gid.bitmaps <Configure> ""

#      set NumBitmaps 0
#      while { [winfo exists .gid.bitmaps.$NumBitmaps] } { 
#  	incr NumBitmaps 
#      }

#      #set NumBitmaps [ expr $NumBitmaps - $GidPriv(BitmapsSeparadores)]
#      #set NumBitmaps [ expr $NumBitmaps + $GidPriv(BitmapsSeparadores) / 3.0]

#      set w [winfo width .gid.bitmaps]
#      set h [winfo height .gid.bitmaps]
#      if { $w > $h || [winfo class .gid.bitmaps] == "Toplevel" } {
#  	set rw0 [winfo reqwidth .gid.bitmaps.0]
#  	set ncols [expr int($w/$rw0)]
#      } else {
#  	set rh0 [winfo reqheight .gid.bitmaps.0]
#  	set nrows [expr int($h/double($rh0)+0.1)]
#  	if { $nrows>0 } { 
#  	    set ncols [expr $NumBitmaps/$nrows]
#  	} else { set ncols 1 }
#  	if { [expr $ncols*$nrows<$NumBitmaps] } { incr ncols }
#      }
#      if { $ncols < 1 } { set ncols 1 }
#      if { $NumBitmaps < $ncols } { set ncols $NumBitmaps }
#      set offset [ expr 2 * $GidPriv(BitmapMenus)]
#      if { $GidPriv(BitmapMenus) > $ncols} {
#  	set offset $ncols
#      }
#      set width [expr [winfo reqwidth .gid.bitmaps.0]*$ncols+$offset+2]
#      set nrows [expr $NumBitmaps/$ncols]
#      if { [expr $nrows*$ncols] < $NumBitmaps } { incr nrows }

#      set offset [ expr 2 * $GidPriv(BitmapMenus)]
#      if { $GidPriv(BitmapMenus) > $nrows} {
#  	set offset $nrows
#      }
#      set height [expr [winfo reqheight .gid.bitmaps.0]*$nrows+$offset+2]

#      if { "${width}x${height}$rest" == [winfo geom .gid.bitmaps] && \
#  	    [grid info .gid.bitmaps.0] != "" } {
#  	bind .gid.bitmaps <Configure> "SaveNewBitmapsGeom Bitmaps .gid.bitmaps"
#  	if { [wm transient .gid.bitmaps] != "" } {
#  	    set trans 1
#  	} else {
#  	    set trans 0
#  	}
#  	set GidPriv(PrePostBitmapsWindowGeom) \
#  		"OPEN ${width}x${height}$rest $trans CreateBitmaps"
#  	return
#      }

#      eval [concat "grid forget [winfo children .gid.bitmaps]"]
#      set i 0
#      set row 0
#      while 1 {
#  	for { set j 0 } { $j < $ncols } { incr j } {
#  	    if { ![winfo exist .gid.bitmaps.$i] } { break }
#  	    grid .gid.bitmaps.$i -row $row -col $j -sticky nw
#    	    grid rowconf .gid.bitmaps $row -weight 0
#    	    grid columnconf .gid.bitmaps $j -weight 0
#  	    incr i
#  	}
#  	if { $row == 0 } {
#  	    grid columnconf .gid.bitmaps $j -weight 1
#  	}
#  	if { $j == 0 } { break }
#  	incr row
#  	if { $j < $ncols } { break }
#      }
#      grid rowconf .gid.bitmaps $row -weight 1

#      if { [winfo class .gid.bitmaps] == "Toplevel" } {
#  	wm geom .gid.bitmaps ${width}x${height}$rest
#  	update 
#  	if { [wm transient .gid.bitmaps] != "" } {
#  	    set trans 1
#  	} else {
#  	    set trans 0
#  	}
#  	set GidPriv(PrePostBitmapsWindowGeom) \
#  		"OPEN [wm geom .gid.bitmaps] $trans CreateBitmaps"
#      }
    
    
#      bind .gid.bitmaps <Configure> "SaveNewBitmapsGeom Bitmaps .gid.bitmaps"
#  }

# proc DisplayHelp { text w x y} {
#     set xg [expr [winfo rootx $w]+$x+2]
#     set yg [expr [winfo rooty $w]+$y]
#     set lname [winfo parent $w].help
#     catch { destroy $lname }
#     menu $lname
#     $lname add command -label $text
#     tk_popup $lname $xg $yg 
# }

proc CreateBitmaps { { what "DEFAULT" } } {
    global BitMapsNames BitMapsCommands GIDDEFAULT BitmapsHelp
    global BitMapsNamesP BitMapsCommandsP GIDDEFAULT BitmapsHelpP
    global GidPriv GiDPrivToolBar


    AddNewToolbar "Geometry & View bar" PrePostBitmapsWindowGeom  CreateBitmaps

    set vv $GidPriv(PrePostBitmapsWindowGeom)
    if { $what != "DEFAULT" } {
	set GidPriv(PrePostBitmapsWindowGeom) \
		"$what [lrange $vv 1 end]"
    }
    if { [lindex $GidPriv(PrePostBitmapsWindowGeom) 0] == "NONE" } {
	catch { destroy .gid.bitmaps }
	return
    }

    set separadores ""
    set num_separadores  0
    foreach archivo "sep_hori.gif sep_vert.gif" {
	if { ![info exist GidPriv(image_$archivo)] } {
	    set GidPriv(image_$archivo) [ image create photo -file $GIDDEFAULT/bitmaps/$archivo]
	}
    }

    if { ![string match INSIDE* [lindex $GidPriv(PrePostBitmapsWindowGeom) 0]] } {
	InitWindow .gid.bitmaps "Geom & view operations" \
		PrePostBitmapsWindowGeom \
		CreateBitmaps
	
       

	wm transient .gid.bitmaps .gid
       .gid.bitmaps config -bg $GidPriv(ToolbarBg)

	set bitmap_geom "[ winfo width .gid.bitmaps]x[ winfo height .gid.bitmaps]"
	#puts $bitmap_geom
	if { [ winfo width .gid.bitmaps] > [ winfo height .gid.bitmaps]} {
	    set separadores V
	} else {
	    set separadores H
	}
    } else {
	set vv $GidPriv(PrePostBitmapsWindowGeom)
	if { [winfo exists .gid.bitmaps] } {
	    destroy .gid.bitmaps
	}
	set GidPriv(PrePostBitmapsWindowGeom) $vv
	set GiDPrivToolBar(PrePostBitmapsWindowGeom) .gid.bitmaps

	frame .gid.bitmaps -bd 2 -bg $GidPriv(ToolbarBg)
	bind .gid.bitmaps <Destroy> "+ unset GiDPrivToolBar(PrePostBitmapsWindowGeom)"
	if { [winfo exists .gid.central.wins] } {
	    pack forget .gid.central.wins
	} else {
	    pack forget .gid.central.s
	}

	regexp {([a-zA-Z]*)([0-9]*)} [lindex $GidPriv(PrePostBitmapsWindowGeom) 0] {} \
		where pos
	set widget ""
	if { $pos != "" } {
	    set widget [lindex [pack slaves .gid.central] $pos]
	}
	switch $where {
	    INSIDETOP {
		pack .gid.bitmaps -in .gid.central -side top -anchor nw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side top
		} else {
		    pack .gid.central.s -fill both -expand yes -side top
		}
		set separadores V
	    }
	    INSIDELEFT {
		pack .gid.bitmaps -in .gid.central -side left -anchor nw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side left
		} else {
		    pack .gid.central.s -fill both -expand yes -side left
		}
		set separadores H
	    }
	    INSIDEBOTTOM {
		pack .gid.bitmaps -in .gid.central -side bottom -anchor sw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side bottom
		} else {
		    pack .gid.central.s -fill both -expand yes -side bottom
		}
		pack .gid.central.s -fill both -expand yes -side bottom
		set separadores V
	    }
	    INSIDERIGHT {
		pack .gid.bitmaps -in .gid.central -side right -anchor ne \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side right
		} else {
		    pack .gid.central.s -fill both -expand yes -side right
		}
		set separadores H
	    }
	}
	if { $widget != ""} {
	    pack configure .gid.bitmaps -before $widget
	}
    }

    if { [catch { set infoProj [lindex [.gid.central.s info Project] 4] }] } {
	set infoProj "GEOMETRYUSE"
    }
    
    if { $infoProj != "POSTUSE" } {
	upvar #0 BitMapsNames names
	upvar #0 BitMapsCommands commands
	upvar #0 BitmapsHelp thehelp
    } else {
	upvar #0 BitMapsNamesP names
	upvar #0 BitMapsCommandsP commands
	upvar #0 BitmapsHelpP thehelp
    }

    set i 0
    set GidPriv(BitmapMenus) 0
    set GidPriv(BitmapsSeparadores) ""
    set GidPriv(BitmapsMenusList) ""
    set reqmbw 0
    set reqmbh 0
    set reqmbbw 0
    set reqbw 0
    set reqbh 0
    set lst_botones ""
    foreach j $names(0) {
	# para rehacer los bitmaps con separadores
	frame .gid.bitmaps.f$i -bd 1 -bg $GidPriv(ToolbarBg)

	if { "$j" != "---" } {
	if { ![info exists names(0,$i)] } {
	    if { ![ regexp {.*\.gif$} $j] } {
		button .gid.bitmaps.$i -bitmap @$GIDDEFAULT/bitmaps/$j -bg white \
			-fg black -bd 1 -highlightthickness 0
	    } else {
		if { ![info exist GidPriv(image_$j)] } {
		    set GidPriv(image_$j) [ image create photo -file $GIDDEFAULT/bitmaps/$j]
		}
		button .gid.bitmaps.$i -image $GidPriv(image_$j) -bd 1 -highlightthickness 0\
			-relief flat -bg $GidPriv(ToolbarBg)

	    }
	    global tcl_platform
	    if { $tcl_platform(platform) == "windows" } {
		bind .gid.bitmaps.$i <ButtonRelease-1> "catch \"focus .gid.comm.e\" "
	    }
	    set comm [lindex $commands(0) $i]
	    EnterCommand .gid.bitmaps.$i $comm
	    set reqbw [ winfo reqwidth .gid.bitmaps.$i]
	    set reqbh [ winfo reqheight .gid.bitmaps.$i]
	    lappend lst_botones .gid.bitmaps.$i
	} else {
	    if { ![ regexp {.*\.gif$} $j] } {
		menubutton .gid.bitmaps.$i \
			-bitmap @$GIDDEFAULT/bitmaps/$j \
			-menu .gid.bitmaps.$i.m -relief raised -bg white \
			-fg black -bd 2 \
			-highlightthickness 0 -direction right
	    } else {
		    if { ![info exist GidPriv(image_$j)] } {
			set GidPriv(image_$j) [ image create photo -file $GIDDEFAULT/bitmaps/$j]
		    }
		    menubutton .gid.bitmaps.$i \
			    -image $GidPriv(image_$j) \
			    -menu .gid.bitmaps.$i.m -relief flat -bd 1 \
			    -highlightthickness 0 -direction right -bg $GidPriv(ToolbarBg)
		}
	    menu .gid.bitmaps.$i.m  -tearoff no -bd 1  -bg $GidPriv(ToolbarBg)
	    set comm [lindex $commands(0) $i]
	    if { $comm != "" } { EnterCommand .gid.bitmaps.$i.m $comm -2}
	    set ii 0
	    foreach jj $names(0,$i) {
		if { ![ regexp {.*\.gif$} $jj] } {
		    .gid.bitmaps.$i.m add command -bitmap @$GIDDEFAULT/bitmaps/$jj \
			    -hidemargin 1
		} else {
			if { ![info exist GidPriv(image_$jj)] } {
			    set GidPriv(image_$jj) [ image create photo -file $GIDDEFAULT/bitmaps/$jj]
			}
			.gid.bitmaps.$i.m add command -image $GidPriv(image_$jj) \
				-hidemargin 1
		    }
		    EnterCommand .gid.bitmaps.$i.m [lindex $commands(0,$i) $ii] $i
		    incr ii
		}
		incr GidPriv(BitmapMenus)
		set reqmbw [ winfo reqwidth .gid.bitmaps.$i]
		set reqmbh [ winfo reqheight .gid.bitmaps.$i]
		set reqmbbw [ .gid.bitmaps.$i cget -borderwidth]
	    }
	    lappend GidPriv(BitmapsMenusList) $i

	    set help [lindex $thehelp(0) $i]
	    bind .gid.bitmaps.$i <ButtonPress-1> ".gid.bitmaps.$i conf -relief flat"
	    bind .gid.bitmaps.$i <Enter> [list catch { wm title .gid.bitmaps $help } ]
	    bind .gid.bitmaps.$i <Enter> "catch { wm title .gid.bitmaps \"$help\" } ; \
		    .gid.bitmaps.$i conf -relief raised"
	    bind .gid.bitmaps.$i <Leave> ".gid.bitmaps.$i conf -relief flat"
	    GidHelpT .gid.bitmaps.$i $help

	} else {
	    if { "$separadores" != "" } {
		if { "$separadores" == "H" } {
		    set archivo sep_hori.gif
		} else {
		    set archivo sep_vert.gif
		}
		
		label .gid.bitmaps.$i -image $GidPriv(image_$archivo) -bd 1 -highlightthickness 0\
			-relief flat -bg [ .gid.bitmaps cget -background]
		incr num_separadores
		lappend GidPriv(BitmapsSeparadores) $i
	    } else {
		label .gid.bitmaps.$i -height 0 -width 0 -bd 0 -highlightthickness 0\
			-relief flat -bg [ .gid.bitmaps cget -background] -padx 0 -pady 0
	    }
	}
	#sep# bind .gid.bitmaps.$i <ButtonPress-1> ".gid.bitmaps.$i conf -relief flat"
	#sep# bind .gid.bitmaps.$i <Enter> "catch { wm title .gid.bitmaps $help } ; \
	#sep# 	  .gid.bitmaps.$i conf -relief raised"
	#sep# bind .gid.bitmaps.$i <Leave> ".gid.bitmaps.$i conf -relief flat"

	#set help [lindex $thehelp(0) $i]
	#GidHelp .gid.bitmaps.$i $help
# 	bind .gid.bitmaps.$i <ButtonPress-2> [list DisplayHelp $help %W %x %y]
# 	bind .gid.bitmaps.$i <ButtonPress-3> [list DisplayHelp $help %W %x %y]
	incr i
    }

    #WarnWin "B: ${reqbw}x${reqbh} <-> MB: ${reqmbw}x${reqmbh}"
    # quitamos los bordes
    set reqmbw [ expr $reqmbw - 2 * $reqmbbw]
    set reqmbh [ expr $reqmbh - 2 * $reqmbbw]
    foreach bb $lst_botones {
	$bb conf -width $reqmbw -height $reqmbh
    }

    set GidPriv(BitmapsNumSeparadores) $num_separadores
    bind .gid.bitmaps <Configure> "SaveNewBitmapsGeom Bitmaps .gid.bitmaps CreateBitmaps"
    if { [winfo class .gid.bitmaps] == "Toplevel" } {
	bind .gid.bitmaps <Leave> [list wm title .gid.bitmaps \
		"Geom & view operations"]
	
	foreach i [bind .gid] {
	    bind .gid.bitmaps $i [bind .gid $i]
	}
    }
}

proc CreateOtherBitmaps { Nombre title BitMapsNames BitMapsCommands BitmapsHelp \
	BitmapsPath StartFunc { what "DEFAULT" } { prefix PrePost} } {
    global GidPriv GiDPrivToolBar GIDDEFAULT

    set term WindowGeom

    if { [ info exist GidPriv($prefix$Nombre$term)] } {
	set vv $GidPriv($prefix$Nombre$term)
  	if { [lindex $what 0] != "DEFAULT" } {
  	    set GidPriv($prefix$Nombre$term) \
  		    "$what [lrange $vv 1 end]"
  	}
	if { [lindex $GidPriv($prefix$Nombre$term) 0] == "NONE" } {
	    catch { destroy .gid.bitmaps$Nombre }
	    return ""
	}
    } elseif { [lindex $what 0] == "DEFAULT" && [lindex $what 1] != "" } {
	set GidPriv($prefix$Nombre$term) "[lindex $what 1] {} 1 $StartFunc"
    }


    if { [lindex [.gid.central.s info Project] 4] != "POSTUSE" } {
	set what PRE
    } else { set what POST }
    
    if { $prefix != "PrePost" } {
	if { ($what == "POST" && ![string match *Post* $prefix]) || \
		($what == "PRE" && [string match *Post* $prefix]) } {
	    if { [info exists GidPriv($prefix$Nombre$term)] } {
		set aa [lindex $GidPriv($prefix$Nombre$term) 0]
	    }
	    catch {
		destroy .gid.bitmaps$Nombre
	    }
	    if { [info exists GidPriv($prefix$Nombre$term)] } {
		set GidPriv($prefix$Nombre$term) \
			"$aa [lrange $GidPriv($prefix$Nombre$term) 1 end]"
	    }
	    return
	}
    }


    set separadores ""
    set num_separadores  0
    foreach archivo "sep_hori.gif sep_vert.gif" {
	if { ![info exist GidPriv(image_$archivo)] } {
	    set GidPriv(image_$archivo) [ image create photo -file $BitmapsPath/$archivo]
	}
    }

    if { ![ info exist GidPriv($prefix$Nombre$term)] || \
	    ![string match INSIDE* [lindex $GidPriv($prefix$Nombre$term) 0]] } {
	InitWindow .gid.bitmaps$Nombre "$title" \
		$prefix$Nombre$term \
		$StartFunc
	
	wm transient .gid.bitmaps$Nombre .gid
	.gid.bitmaps$Nombre config -bg $GidPriv(ToolbarBg)
	set bitmap_geom "[ winfo width .gid.bitmaps$Nombre]x[ winfo height .gid.bitmaps$Nombre]"
	#puts $bitmap_geom
	if { [ winfo width .gid.bitmaps$Nombre] > [ winfo height .gid.bitmaps$Nombre]} {
	    set separadores V
	} else {
	    set separadores H
	}
    } else {
	set vv $GidPriv($prefix$Nombre$term)
	if { [winfo exists .gid.bitmaps$Nombre] } {
	    destroy .gid.bitmaps$Nombre
	}
	set GidPriv($prefix$Nombre$term) $vv
	set GiDPrivToolBar($prefix$Nombre$term) .gid.bitmaps$Nombre

	set GidPriv($prefix${Nombre}Window) .gid.bitmaps$Nombre

	frame .gid.bitmaps$Nombre -bd 2 -bg $GidPriv(ToolbarBg)
	bind .gid.bitmaps$Nombre <Destroy> "+ unset GiDPrivToolBar($prefix$Nombre$term)"
	if { [winfo exists .gid.central.wins] } {
	    pack forget .gid.central.wins
	} else {
	    pack forget .gid.central.s
	}

	regexp {([a-zA-Z]*)([0-9]*)} [lindex $GidPriv($prefix$Nombre$term) 0] {} \
		where pos
	set widget ""
	if { $pos != "" } {
	    set widget [lindex [pack slaves .gid.central] $pos]
	}
	switch $where {
	    INSIDETOP {
		pack .gid.bitmaps$Nombre -in .gid.central -side top -anchor nw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side top
		} else {
		    pack .gid.central.s -fill both -expand yes -side top
		}
		set separadores V
	    }
	    INSIDELEFT {
		pack .gid.bitmaps$Nombre -in .gid.central -side left -anchor nw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side left
		} else {
		    pack .gid.central.s -fill both -expand yes -side left
		}
		set separadores H
	    }
	    INSIDEBOTTOM {
		pack .gid.bitmaps$Nombre -in .gid.central -side bottom -anchor sw \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side bottom
		} else {
		    pack .gid.central.s -fill both -expand yes -side bottom
		}
		set separadores V
	    }
	    INSIDERIGHT {
		pack .gid.bitmaps$Nombre -in .gid.central -side right -anchor ne \
			-fill both -expand 0 -padx 0 -pady 0
		if { [winfo exists .gid.central.wins] } {
		    pack .gid.central.wins -expand 1 -fill both -side right
		} else {
		    pack .gid.central.s -fill both -expand yes -side right
		}
		set separadores H
	    }
	}
	if { $widget != ""} {
	    pack configure .gid.bitmaps$Nombre -before $widget
	}
    }

    upvar $BitMapsNames names
    upvar $BitMapsCommands commands
    upvar $BitmapsHelp thehelp

    set i 0
    #set GidPriv(BitmapMenus) 0
    set term_sep Separadores
    set term_ml  MenusList
    set GidPriv($Nombre$term_sep) ""
    set GidPriv($Nombre$term_ml) ""
    foreach j $names(0) {
	# para rehacer los bitmaps con separadores
	frame .gid.bitmaps$Nombre.f$i -bd 0 -bg $GidPriv(ToolbarBg)

	if { "$j" != "---" } {
	if { ![info exists names(0,$i)] } {
	    if { ![ regexp {.*\.gif$} $j] } {
		button .gid.bitmaps$Nombre.$i -bitmap @$BitmapsPath/$j -bg white \
			-fg black -bd 1 -highlightthickness 0
	    } else {
		if { ![info exist GidPriv(image_$j)] } {
		    set GidPriv(image_$j) [ image create photo -file $BitmapsPath/$j]
		}
		button .gid.bitmaps$Nombre.$i -image $GidPriv(image_$j) -bd 1 -highlightthickness 0\
			-relief flat -bg [ .gid.bitmaps$Nombre cget -background]
	    }
	    global tcl_platform
	    if { $tcl_platform(platform) == "windows" } {
		bind .gid.bitmaps$Nombre.$i <ButtonRelease-1> "catch \"focus .gid.comm.e\" "
	    }
	    set comm [lindex $commands(0) $i]
	    EnterCommand .gid.bitmaps$Nombre.$i $comm
	} else {
	    if { ![ regexp {.*\.gif$} $j] } {
		menubutton .gid.bitmaps$Nombre.$i \
			-bitmap @$BitmapsPath/$j \
			-menu .gid.bitmaps$Nombre.$i.m -relief raised -bg white \
			-fg black -bd 2 \
			-highlightthickness 0 -direction right
	    } else {
		    if { ![info exist GidPriv(image_$j)] } {
			set GidPriv(image_$j) [ image create photo -file $BitmapsPath/$j]
		    }
		    menubutton .gid.bitmaps$Nombre.$i \
			    -image $GidPriv(image_$j) \
			    -menu .gid.bitmaps$Nombre.$i.m -relief flat -bd 1 \
			    -highlightthickness 0 -direction right -bg $GidPriv(ToolbarBg)
		}
	    menu .gid.bitmaps$Nombre.$i.m  -tearoff no -bd 1 -bg $GidPriv(ToolbarBg)
	    set comm [lindex $commands(0) $i]
	    if { $comm != "" } { EnterCommand .gid.bitmaps$Nombre.$i.m $comm -2}
	    set ii 0
	    foreach jj $names(0,$i) {
		if { ![ regexp {.*\.gif$} $jj] } {
		    .gid.bitmaps$Nombre.$i.m add command -bitmap @$BitmapsPath/$jj \
			    -hidemargin 1
		} else {
			if { ![info exist GidPriv(image_$jj)] } {
			    set GidPriv(image_$jj) [ image create photo -file $BitmapsPath/$jj]
			}
			.gid.bitmaps$Nombre.$i.m add command -image $GidPriv(image_$jj) \
				-hidemargin 1
		    }
		    EnterCommand .gid.bitmaps$Nombre.$i.m [lindex $commands(0,$i) $ii] $i
		    incr ii
		}
		#incr GidPriv(BitmapMenus)
	    }
	    lappend GidPriv($Nombre$term_ml) $i

	    set help [lindex $thehelp(0) $i]
	    bind .gid.bitmaps$Nombre.$i <ButtonPress-1> ".gid.bitmaps$Nombre.$i conf -relief flat"
	    bind .gid.bitmaps$Nombre.$i <Enter> [list catch { wm title .gid.bitmaps$Nombre $help } ]
	    bind .gid.bitmaps$Nombre.$i <Enter> "catch { wm title .gid.bitmaps$Nombre \"$help\" } ; \
		    .gid.bitmaps$Nombre.$i conf -relief raised"
	    bind .gid.bitmaps$Nombre.$i <Leave> ".gid.bitmaps$Nombre.$i conf -relief flat"
	    GidHelpT .gid.bitmaps$Nombre.$i $help

	} else {
	    if { "$separadores" != "" } {
		if { "$separadores" == "H" } {
		    set archivo sep_hori.gif
		} else {
		    set archivo sep_vert.gif
		}
		
		label .gid.bitmaps$Nombre.$i -image $GidPriv(image_$archivo) -bd 1 -highlightthickness 0\
			-relief flat -bg [ .gid.bitmaps$Nombre cget -background]
		incr num_separadores
		lappend GidPriv($Nombre$term_sep) $i
	    } else {
		label .gid.bitmaps$Nombre.$i -height 0 -width 0 -bd 0 -highlightthickness 0\
			-relief flat -bg [ .gid.bitmaps$Nombre cget -background] -padx 0 -pady 0
	    }
	}
	#sep# bind .gid.bitmaps$Nombre.$i <ButtonPress-1> ".gid.bitmaps$Nombre.$i conf -relief flat"
	#sep# bind .gid.bitmaps$Nombre.$i <Enter> "catch { wm title .gid.bitmaps$Nombre $help } ; \
	#sep# 	  .gid.bitmaps$Nombre.$i conf -relief raised"
	#sep# bind .gid.bitmaps$Nombre.$i <Leave> ".gid.bitmaps$Nombre.$i conf -relief flat"

	#set help [lindex $thehelp(0) $i]
	#GidHelp .gid.bitmaps$Nombre.$i $help
# 	bind .gid.bitmaps$Nombre.$i <ButtonPress-2> [list DisplayHelp $help %W %x %y]
# 	bind .gid.bitmaps$Nombre.$i <ButtonPress-3> [list DisplayHelp $help %W %x %y]
	incr i
    }

    #set GidPriv(BitmapsNumSeparadores) $num_separadores
    bind .gid.bitmaps$Nombre <Configure> [list SaveNewBitmapsGeom $Nombre \
	    .gid.bitmaps$Nombre $StartFunc $prefix]
    if { [winfo class .gid.bitmaps$Nombre] == "Toplevel" } {
	bind .gid.bitmaps$Nombre <Leave> [list wm title .gid.bitmaps$Nombre \
		"$title"]
	
	foreach i [bind .gid] {
	    bind .gid.bitmaps$Nombre $i [bind .gid $i]
	}
    }
    return .gid.bitmaps$Nombre
}

proc SetAllLatersTo { onoff } {

    .gid.central.s process layers 
    if { $onoff == "ON" } {
	foreach i [.gid.central.s info layers -off] {
	    .gid.central.s process on $i
	}
    } else {
	foreach i [.gid.central.s info layers -on] {
	    .gid.central.s process off $i
	}
    }
    .gid.central.s process escape
    FillInfoLayers
}

proc AddLayerOnOff { onoff w basecommand } {
    global GidPriv
    $w del 0 end
    if { $onoff == "ON" } {
	set words [list [list "-All-" "SetAllLatersTo $onoff" ]]
	set LayerNames [.gid.central.s info layers -off]
	if { [info exists GidPriv(LayersAlphabetic)] && $GidPriv(LayersAlphabetic) } {
	    set LayerNames [lsort -dictionary $LayerNames]
	}

	foreach i $LayerNames {
	    lappend words [list $i "$basecommand $i escape ; FillInfoLayers"]
	}
	rmenuconf $w $words
    } elseif { $onoff == "OFF" } {
	set words [list [list "-All-" "SetAllLatersTo $onoff" ]]
	set LayerNames [.gid.central.s info layers -on]
	if { [info exists GidPriv(LayersAlphabetic)] && $GidPriv(LayersAlphabetic) } {
	    set LayerNames [lsort -dictionary $LayerNames]
	}
	foreach i $LayerNames {
	    lappend words [list $i "$basecommand $i escape ; FillInfoLayers"]
	}
	rmenuconf $w $words
    } else {
	set aa [.gid.central.s info Project]
	set layertouse [lindex $aa 3]
	set LayerNames [.gid.central.s info layers]
	if { [info exists GidPriv(LayersAlphabetic)] && $GidPriv(LayersAlphabetic) } {
	    set LayerNames [lsort -dictionary $LayerNames]
	}
	set words ""
	foreach i $LayerNames {
	    if { $i != $layertouse } {
		lappend words [list $i "$basecommand $i escape ; FillInfoLayers"]
	    } else {
		lappend words [list $i "$basecommand $i escape ; FillInfoLayers" check]
	    }
	}
	rmenuconf $w $words
    }
}

proc LayerEntitiesSub { w entity } {
    global GidPriv

    set LayerNames [.gid.central.s info layers]
    if { [info exists GidPriv(LayersAlphabetic)] && $GidPriv(LayersAlphabetic) } {
	set LayerNames [lsort -dictionary $LayerNames]
    }
    set words ""
    if { $GidPriv(LayersAlsoLower) == 0 } {
	foreach i $LayerNames {
	    lappend words [list $i \
		    ".gid.central.s process layers entities $i $entity"]
	}
    } else {
	foreach i $LayerNames {
	    lappend words [list $i \
		    ".gid.central.s process layers entities $i LowerEntities $entity"]
	}
    }
    rmenuconf $w $words
}

proc LayerEntities { w } {
    global GidPriv

    set geomlistNames "Points Lines Surfaces Volumes {All types}" 
    set geomlist "Points Lines Surfaces Volumes All"
    set meshlistNames "Nodes Elements {All types}"
    set meshlist "Nodes Elements  All"


    if { [catch { set whatuse [lindex [.gid.central.s info Project] 4] }] } {
	set whatuse GEOMETRYUSE
    }
    $w del 0 end

    $w add check -label [_ Also lower entities] \
	    -var GidPriv(LayersAlsoLower)
    if { ![info exists GidPriv(LayersAlsoLower)] } {
	set GidPriv(LayersAlsoLower) 0
    }

    switch $whatuse {
	GEOMETRYUSE {
	    foreach i $geomlist j $geomlistNames {
		set menuname [join "$w . [string tolower $i]" ""]
		$w add cascade -label $j -menu $menuname
		if { ![winfo exist $menuname] } {
		    menu $menuname -postcommand "LayerEntitiesSub $menuname $i"
		} else {
		    $menuname conf -postcommand "LayerEntitiesSub $menuname $i"
		}
	    }
	}
	MESHUSE {
	    foreach i $meshlist j $meshlistNames {
		set menuname [join "$w . [string tolower $i]" ""] 
		$w add cascade -label $j -menu $menuname
		if { ![winfo exist $menuname] } {
		    menu $menuname -postcommand "LayerEntitiesSub $menuname $i"
		} else {
		    $menuname conf -postcommand "LayerEntitiesSub $menuname $i"
		}
	    }
	}
    }
}

proc AddChangeToRender { w } {
    $w del 0 end
    set rendertype [lindex [.gid.central.s info Project] 6]

    set whatuse [lindex [.gid.central.s info Project] 4]
    switch $whatuse {
	GEOMETRYUSE {
	    foreach i [list [_ Normal] [_ Filled] [_ Flat lighting] [_ Smooth lighting]] j \
		    { normal filled FlatLighting SmoothLighting } {
		$w add command -label $i -command  ".gid.central.s process render $j"
	    }
	}
	MESHUSE {
	    foreach i [list [_ Normal] [_ Filled] [_ Flat lighting] [_ Smooth lighting]] j \
		    { normal filled FlatLighting SmoothLighting } {
		$w add command -label $i -command  ".gid.central.s process render $j"
	    }
	}
	POSTUSE {
	    foreach i [list [_ Normal] [_ Flat lighting] [_ Smooth lighting]] j \
		    { Normal Flat Smooth } {
		$w add command -label $i -command  ".gid.central.s process escape escape escape escape utilities render $j"
	    }
	}
	default {
	    $w add command -label $whatuse -command  ""
	}
    }

    switch $rendertype {
	normal {
	    $w entryconf 0 -state disabled
	}
	polygons {
	    $w entryconf 2 -state disabled
	}
	render {
	    $w entryconf 3 -state disabled
	}
	postprocess {
	    # miguel 1999-01-21 correctec filled render mode in preprocess ( it uses the postprocess mode)
	    if { ( $whatuse == "GEOMETRYUSE") || ( $whatuse == "MESHUSE") } {
		$w entryconf 1 -state disabled
	    } else {
		set postrender [ .gid.central.s info post get cur_display_render]
		switch $postrender {
		    Normal { 
			$w entryconf 0 -state disabled
		    }
		    Flat { 
			$w entryconf 1 -state disabled
		    }
		    Smooth { 
			$w entryconf 2 -state disabled
		    }
		}
		
	    }
	}
    }

    $w add separator
    if { ( "$whatuse" == "GEOMETRYUSE") || ( "$whatuse" == "MESHUSE") } {
	$w add command -label "Change light dir" -command \
		".gid.central.s process escape escape escape escape changelightvec"
    }
    if { "$whatuse" == "POSTUSE" } {
	$w add command -label "Change light dir" -command \
		".gid.central.s process escape escape escape escape utilities render changelightvec"
    }

}

proc CreateCascadedMenu { menu varname varcommandname acceleratorname \
	currentindex } {
    upvar \#0 $varname var $varcommandname varcomm
    if { $acceleratorname != ""} {
	upvar \#0 $acceleratorname varaccelerator
    }
    global GidPriv
    set UnderLineList ""
    set j 0
    foreach i $var($currentindex) {
	
	set comm [lindex $varcomm($currentindex) $j]
	if { [string match ---* $i] } {
	    $menu add separator
	} elseif { [lindex $i 0] == "-CB-" } {
	    $menu add checkbutton -label [lrange $i 1 end] \
		    -variable GidPriv([lindex $i 1])
	    EnterCommand $menu $comm $j
	    if { [info exists varaccelerator($currentindex)] } {
		AddAccelerator [lindex $varaccelerator($currentindex) $j] \
			$menu $j
	    } else { AddAccelerator "" $menu $j }
	} elseif { ![info exists var($currentindex,$j)] } {
	    $menu add command -label $i
	    EnterCommand $menu $comm $j
	    if { [info exists varaccelerator($currentindex)] } {
		AddAccelerator [lindex $varaccelerator($currentindex) $j] \
			$menu $j
	    } else { AddAccelerator "" $menu $j }
	} else {
	    $menu add cascade -label $i -menu $menu.$j 
	    if { [winfo exists $menu.$j] } { 
		#$menu.$j del 0 end 
		destroy $menu.$j
		menu $menu.$j -tearoff no
	    } else {
		menu $menu.$j -tearoff no
	    }
	    EnterCommand $menu.$j $comm -2
	    CreateCascadedMenu $menu.$j $varname $varcommandname $acceleratorname \
		    "$currentindex,$j"
	}
	for {set under 0 } { $under< [string length $i]} { incr under } {
	    set letter [string tolower [string index $i $under]]
	    if { ![regexp {[a-zA-Z]} $letter] } { continue }
	    if { [lsearch $UnderLineList $letter] == -1 } {
		lappend UnderLineList $letter
		catch {$menu entryconf $j -underline $under}
		break
	    }
	}

	incr j
    }

}

proc Create3rdButtonMenu { w { what PRE } } {
    global 3dButtonNames 3dButtonCommands 3dButtonAcceler
    global 3dButtonDisabled 3dButtonDisabledP

    if { [$w index end] == "none" } {
	CreateCascadedMenu $w 3dButtonNames 3dButtonCommands \
		3dButtonAcceler 0
    }
    set last [$w index end]
    if { $last == "none" } { set last -1}
    if { $what == "PRE" } {
	for { set i 0 } { $i < $last } { incr i} {
	    catch {
		if { [lsearch $3dButtonDisabled [$w entrycget $i -label]] != -1 } {
		    $w entryconf $i -state disabled
		} else { $w entryconf $i -state normal }
	    }
	}
    } else {
	for { set i 0 } { $i < $last } { incr i} {
	    catch {
		if { [lsearch $3dButtonDisabledP [$w entrycget $i -label]] \
			!= -1 } {
		    $w entryconf $i -state disabled
		} else { $w entryconf $i -state normal }
	    }
	}
    }
}

proc TryToFindVector { vec } {

    set num {([+-]?[0-9]*\.?[0-9]*([eE][+-]?[0-9]+)?)}
    set sep [join {[ " " , \n ] +} ""]
    set sepv [join {[ " " , \n 
] *} ""]

    set res [regexp ^$sepv$num$sep$num$sep$num$sepv$ $vec trash v1 trash2 \
	    v2 trash3 v3]

    if { $res && $v1 != "" && $v2 != "" && $v3 != ""} { return $v1,$v2,$v3 }
    return $vec
}


proc MakeBottomEntryBindings {} {
    global uparrow

    focus .gid.comm.e

    bind .gid.comm.e <Shift-Return> {
	set aa [TryToFindVector [.gid.comm.e get]]
	.gid.comm.e delete 0 end 
	.gid.comm.fwarn.list ins end "->$aa"
	set uparrow [.gid.comm.fwarn.list size]
	.gid.comm.fwarn.list yview [expr $uparrow-2]
	.gid.central.s process $aa
	break
    }


    bind .gid.comm.e <Return> {
	set aa [.gid.comm.e get]
	.gid.comm.e delete 0 end 
	.gid.comm.fwarn.list ins end "->$aa"
	set uparrow [.gid.comm.fwarn.list size]
	.gid.comm.fwarn.list yview [expr $uparrow-2]
	
	if { [string match -np-* $aa] } {
	    regsub -- {-np-} $aa {} aa
	    eval $aa
	} else {
	    .gid.central.s process $aa
	}
    }
    bind .gid.comm.e <Escape> {
	.gid.comm.e delete 0 end 
	.gid.central.s process "escape"
    }
    set uparrow 0
    bind .gid.comm.e <Up> {
	.gid.comm.e delete 0 end
	while 1 {
	    incr uparrow -1
	    if { $uparrow < 0 } {
		set uparrow -1
		break
	    } elseif { [regexp {^->.*[^ ]+.*$} [.gid.comm.fwarn.list get $uparrow]] } {
		.gid.comm.e insert 0 [string range [.gid.comm.fwarn.list get $uparrow] \
			2 end]
		break
	    }
	}
    }
    bind .gid.comm.e <Down> {
	.gid.comm.e delete 0 end
	while 1 {
	    incr uparrow 1
	    if { $uparrow >= [.gid.comm.fwarn.list size] } { 
		set uparrow [.gid.comm.fwarn.list size]
		break
	    } elseif { [regexp {^->.*[^ ]+.*$} [.gid.comm.fwarn.list get $uparrow]] } {
		.gid.comm.e insert 0 [string range [.gid.comm.fwarn.list get $uparrow] \
			2 end]
		break
	    }
	}
    }
    bind .gid.comm.e <Alt-KeyPress-3> {
	set x [expr [winfo rootx .gid.comm.e]+%x+2]
	set y [expr [winfo rooty .gid.comm.e]+%y]
	tk_popup .gid.phantom.display3dbutton $x $y 0
    }
    bind .gid.comm.e <Tab> "AutoCompleteGiDEntry .gid.comm.e; break"

    #para dejar el 'pegar' con el boton del medio del raton
    bind .gid.comm.e <ButtonPress-2> ""
    #.gid.comm.e ins insert \"[selection get]\"; break;"
    #bind .gid.comm.e <ButtonRelease-2> ""
}

proc AddEntitiesToMenu { w basecommand args} {

    set geomlist "Points Lines Surfaces Volumes"
    set meshlist "Nodes Elements"
    set graphlist "Nodes"
    if { [llength $args] == 2 } {
	set geomlist [lindex $args 0]
	set meshlist [lindex $args 1]
    }
    if { [catch { set whatuse [lindex [.gid.central.s info Project] 4] }] } {
	set whatuse GEOMETRYUSE
    }
    $w del 0 end
    switch $whatuse {
	GEOMETRYUSE {
	    foreach i $geomlist {
		$w add command -label $i -command "$basecommand $i"
	    }
	}
	MESHUSE {
	    if { [llength $meshlist] == 1 } {
		$w add command -label $meshlist -command $basecommand
	    } else {
		foreach i $meshlist {
		    $w add command -label $i -command "$basecommand $i"
		}
	    }
	}
	POSTUSE {
	    if { [llength $meshlist] == 1 } {
		$w add command -label $meshlist -command $basecommand
	    } else {
		foreach i $meshlist {
		    $w add command -label $i -command "$basecommand $i"
		}
	    }
	}
	GRAFUSE  {
	    foreach i $graphlist {
		$w add command -label $i -command "$basecommand $i"
	    }
	}
    }
}

proc AddEntitiesToMenuAfter { num w basecommand args} {

    set geomlist "Points Lines Surfaces Volumes"
    set meshlist "Nodes Elements"
    if { [llength $args] == 2 } {
	set geomlist [lindex $args 0]
	set meshlist [lindex $args 1]
    }
    if { [catch { set whatuse [lindex [.gid.central.s info Project] 4] }] } {
	set whatuse GEOMETRYUSE
    }
    incr num
    if { [$w index $num] == $num } {
	$w del $num end
    }
    switch $whatuse {
	GEOMETRYUSE {
	    foreach i $geomlist {
		$w add command -label $i -command "$basecommand $i"
	    }
	}
	MESHUSE {
	    foreach i $meshlist {
		$w add command -label $i -command "$basecommand $i"
	    }
	}
	POSTUSE {
	    foreach i $meshlist {
		$w add command -label $i -command "$basecommand $i"
	    }
	}
    }
}

proc AddEntitiesToMenuGeomOrMeshOrGraph { w namesG namesM namesF commandsG commandsM commandsF } {
    set nlist(GEOMETRYUSE) $namesG
    set nlist(MESHUSE) $namesM
    set nlist(GRAFUSE) $namesF 

    set clist(GEOMETRYUSE) $commandsG
    set clist(MESHUSE) $commandsM 
    set clist(GRAFUSE) $commandsF 

    set whatuse ""
    if { [catch { set whatuse [lindex [.gid.central.s info Project] 4] }] } {
	set whatuse GEOMETRYUSE
    }
    if { $whatuse == "POSTUSE" } {
      set whatuse MESHUSE
    }

    $w del 0 end

    foreach i $nlist($whatuse) j $clist($whatuse) {
	$w add command -label $i -command $j
    }
}


proc AddCutsToMenu { w basecommand} {
#     global ViewMenuPriv
    
    #if { ![.central.s info post get changed_geom_list]} { return}

    set cutlist [.central.s info post get all_cuts]
#    set what cuts2

#    if { [ info exist ViewMenuPriv($what)]} {
#	if { ![ string compare $ViewMenuPriv($what) $cutlist ]} {
#	    return
#	}
#    }

#    set ViewMenuPriv($what) $cutlist

    $w del 0 end
    foreach i $cutlist {
	regsub -all {_} $i { } cutlabel
	$w add command -label $cutlabel -command "$basecommand $i"
    }
    if { [ llength $cutlist] > 1} {
	$w add command -label "All Cuts" -command "$basecommand ALL_CUTS"
    }
    if { $cutlist == ""} {
	$w add command -label "There are no Cuts" -state disabled
    }
}

proc AddGraphsToMenu { w basecommand { todos 0}} {
#    global ViewMenuPriv

    set graphlist [.central.s info post get all_graphs]
#    set what graphs

#    if { [ info exist ViewMenuPriv($what)]} {
#	if { ![ string compare $ViewMenuPriv($what) $graphlist ]} {
#	    return
#	}
#    }

#    set ViewMenuPriv($what) $graphlist

    $w del 0 end
    foreach i $graphlist {
	regsub -all {_} $i { } graphlabel
	$w add command -label $graphlabel -command "$basecommand $i"
    }
    if { $todos && ( [ llength $graphlist] > 1) } {
	$w add command -label "All" -command "$basecommand all"
    }
    if { $graphlist == ""} {
	$w add command -label "There are no Graphs" -state disabled
    }
}

proc AddPostGeomToMenu { w basecommand what color_opt} {
    global ViewMenuPriv

    set geomlist [.gid.central.s info post get all_$what]

    if { [ info exist ViewMenuPriv($w,$what)]} {
	if { ![ string compare $ViewMenuPriv($w,$what) $geomlist ]} {
	    return
	}
    }

    $w del 0 end

    if { $geomlist == ""} {
	$w add command -label "There are no $what" -state disabled
	return
    }

    set ViewMenuPriv($w,$what) $geomlist
    
    set id_menu 0
    foreach i $geomlist {
	regsub -all {_} $i { } geomlabel
	if { $color_opt == ""} {
	    $w add command -label $geomlabel -command "$basecommand $i"
	} else {
	    $w add cascade -label "$geomlabel" -menu $w.m$id_menu
	    if { [ winfo exist $w.m$id_menu ]} {
		$w.m$id_menu del 0 end
	    } else {
		menu $w.m$id_menu
	    }

	    foreach j $color_opt {
		$w.m$id_menu add command -label $j -command "$basecommand $i $j"
	    }
	    
	}
	incr id_menu
    }
}


proc AddListEntitiesToMenuExec { i } {
    global GidPriv

    if { !$GidPriv(ListEntitiesMass) } {
	.gid.central.s process escape escape escape \
		escape utilities list $i
    } else {
	.gid.central.s process escape escape escape \
		escape utilities list MassProp $i
    }
}

proc AddListEntitiesToMenu { w } {
    global GidPriv

    set geomlist "Points Lines Surfaces Volumes"
    set meshlist "Nodes Elements"

    if { [catch { set whatuse [lindex [.gid.central.s info Project] 4] }] } {
	set whatuse GEOMETRYUSE
    }
    $w del 0 end
    $w add checkbutton -label Mass -variable GidPriv(ListEntitiesMass)


    switch $whatuse {
	GEOMETRYUSE {
        foreach i $geomlist {
          $w add command -label $i -command "AddListEntitiesToMenuExec $i"
        }
	}
	MESHUSE {
        foreach i $meshlist {
          $w add command -label $i -command "AddListEntitiesToMenuExec $i"
        }
	}
    }


}

proc HardcopyToPrint { basecommand { prncomm ""} { parent ""}} {
    global tcl_platform GidPriv
    if { $tcl_platform(platform) == "windows" } {
	.gid.central.s process hardcopy print
	return
    } else {
	##WarnWin "hola '$basecommand' '$prncomm' '$parent'"
	if { ! [ info exist GidPriv(PrinterCommand)] } {
	    set GidPriv(PrinterCommand) "lpr"
	}
	if { $prncomm != ""} {
	    set GidPriv(PrinterCommand) $prncomm
	}
	set wname .gid.tempwinw
	if { ( $parent != "" ) && ( $parent != ".") } {
	    set wname $parent.tempwinw
	}
	if { "$prncomm" != ""} {
	    set pepe "ok"
	} else {
	    set pepe [ tk_dialogEntryRAM $wname {Enter value window} \
		    "Which command do you use to print files?" questhead  "any" \
		    $GidPriv(PrinterCommand)]
	}
	# nos devuelve pepe entre comillas si hay mas de una palabra
	if { "$pepe" != "--CANCEL--"} {
	    set tmp_filename [ file join [ lindex [.gid.central.s info Project] 9] \
		    print_[ clock format [clock seconds] -format "%Y-%m-%d-%H:%M:%S"].ps]
	    .gid.central.s process $basecommand $tmp_filename
	    if { [ file exists $tmp_filename] } {
		#para quitar las comillas de pepe si hay mas de una palabra,
                # pues exec toma pepe como nombre de programa ( con espacios y todo)
		set res [ eval [ join "exec $GidPriv(PrinterCommand) $tmp_filename"]]
		if { $res != ""} {
		    WarnWin "$res"
		} else {
		    WarnWin "Job succesfully printed or queued."
		}
		file delete -force $tmp_filename
		#set GidPriv(PrinterCommand) $pepe
	    }
	}
	return 
    }
}


proc AddBitmapsToMenu { w basecommand args } {
    global GIDDEFAULT
    global GidPriv

    #set geomlist "point line surface volume"
    if { $GidPriv(bitmaps_color)} {
	set geomlist "point.gif line.gif surface.gif volume.gif"
	set meshlist "node.gif element.gif"
	set postlist "node.gif element.gif resultonview.gif"
	set graflist "node.gif resultonview.gif"
    } else {
	set geomlist "point line surface volume"
	set meshlist "node element"
	set postlist "node element resultonview"
	set graflist "node resultonview"
    }
    if { [llength $args] == 2 } {
	set geomlist [lindex $args 0]
	set meshlist [lindex $args 1]
    }
    set whatuse [lindex [.gid.central.s info Project] 4]
    $w del 0 end
    switch $whatuse {
	GEOMETRYUSE {
	    foreach i $geomlist {
		if { ![ regexp {(.*)\.gif$} $i dummy command] } {
		    $w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
			    -command "$basecommand $i" -hidemargin 1
		} else {
		    if { ![info exist GidPriv(image_$i)] } {
			set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
		    }
		    $w add command -image $GidPriv(image_$i) \
			    -command "$basecommand $command" -hidemargin 1
		}
	    }
	}
	MESHUSE {
	    foreach i $meshlist {
		if { ![ regexp {(.*)\.gif$} $i dummy command] } {
		    $w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
			    -command "$basecommand $i" -hidemargin 1
		} else {
		    if { ![info exist GidPriv(image_$i)] } {
			set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
		    }
		    $w add command -image $GidPriv(image_$i) \
			    -command "$basecommand $command" -hidemargin 1
		}
	    }
	}
	POSTUSE {
	    if { "$args" == "list"} {
		set postlist $meshlist
	    }
	    foreach i $postlist {
		if { ![ regexp {(.*)\.gif$} $i dummy command] } {
		    $w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
			    -command "$basecommand $i" -hidemargin 1
		} else {
		    if { ![info exist GidPriv(image_$i)] } {
			set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
		    }
		    $w add command -image $GidPriv(image_$i) \
			    -command "$basecommand $command" -hidemargin 1
		}
	    }
	}
	GRAFUSE {
	    #if { [ lindex $basecommand [ expr [ llength $basecommand] - 1]] != "Select"} {
		foreach i $graflist {
		    if { ![ regexp {(.*)\.gif$} $i dummy command] } {
			$w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
				-command "$basecommand $i" -hidemargin 1
		    } else {
			if { ![info exist GidPriv(image_$i)] } {
			    set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
			}
			$w add command -image $GidPriv(image_$i) \
				-command "$basecommand $command" -hidemargin 1
		    }
		}
	    #}
	}
    }
}

proc HazFoto { command} {
    global GidPriv
    
    set GidPriv(TipoFotoActual) $command
    eval $command
}

proc AddBitmapsToCamera { w basecommand args} {
    global GIDDEFAULT
    global GidPriv

    set GidPriv(CameraMenuW) $w
    set GidPriv(CameraMenuBase) "basecommand"
    $w del 0 end
    if { [ info exist GidPriv(TipoFotoActual)] } {

	##set ww [ winfo parent $w]
	##bind $ww <ButtonRelease-1> {
	##    if { "$GidPriv(CameraMenuAfterId)" != ""} {
	##	  after cancel $GidPriv(CameraMenuAfterId)
	##	  eval $GidPriv(TipoFotoActual)
	##    }
	##}
	##
	##bind $ww <B1-Leave> {
	##    if { "$GidPriv(CameraMenuAfterId)" != ""} {
	##	  after cancel $GidPriv(CameraMenuAfterId)
	##    }
	##}
	##
	##set GidPriv(CameraMenuAfterId) [ after 500 { 
	##    set GidPriv(CameraMenuAfterId) ""
	##    unset GidPriv(TipoFotoActual)
	##    AddBitmapsToCamera $GidPriv(CameraMenuW) $GidPriv(CameraMenuBase)
	##    WarnWinText hola
	##}]
	##
	##return

	# set outside 0
	# after 200
	# set ww [ winfo parent $w]
	# set x [ winfo pointerx $ww]
	# set y [ winfo pointery $ww]
	# 
	# set dx [ winfo reqwidth $ww]
	# set dy [ winfo reqheight $ww]
	# set xi [ winfo rootx $ww]
	# set yi [ winfo rooty $ww]
	# set xo [ expr $x - $xi]
	# set yo [ expr $y - $yi]
	# if { ( $xo >= 0) && ( $xo < $dx) && ( $yo >= 0) && ( $yo < $dy) } {
	#     set outside 0
	# } else {
	#     set outside 1
	# }
	# if { $outside} {
	##    eval $GidPriv(TipoFotoActual)
	##    return
	# } else {
	#     unset GidPriv(TipoFotoActual)
	# }
    }
    $w del 0 end

    #set hardcopylist "eps ps tga tiff gif"
    if { $GidPriv(bitmaps_color)} {
	set hardcopylist "eps.gif ps.gif bmp.gif gif.gif jpeg.gif png.gif tga.gif tiff.gif vrml.gif"
    } else {
	set hardcopylist "eps ps bmp gif jpeg png tga tiff vrml"
    }

    #$w del 0 end
    foreach i $hardcopylist {
	if { ![ regexp {(.*)\.gif$} $i dummy command] } {
	    $w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
		    -command "HazFoto \"$basecommand $i\"" -hidemargin 1
		    #-command "$basecommand $i" -hidemargin 1
	} else {
	    if { ![info exist GidPriv(image_$i)] } {
		set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
	    }
	    $w add command -image $GidPriv(image_$i) \
		    -command "HazFoto \"$basecommand $command\"" -hidemargin 1
		    #-command "$basecommand $command" -hidemargin 1
	}
    }
}

proc CambiaBitmap { w toca command} {
    global GIDDEFAULT
    $w conf -bitmap @$GIDDEFAULT/bitmaps/$toca
    eval $command
    #WarnWinText "$w conf -bitmap @$GIDDEFAULT/bitmaps/$toca"
}

proc CambiaImagen { w toca command} {
    global GidPriv
    $w conf -image $GidPriv(image_$toca.gif)
    eval $command
    #WarnWinText "$w conf -bitmap @$GIDDEFAULT/bitmaps/$toca"
}

proc AddBitmapsToDisplayStyle { w basecommand args} {
    global GIDDEFAULT
    global GidPriv

    set idx [ string last "." $w]
    if { $idx != -1 } {
	set GidPriv(PostDisplayStyleBitmap) [ string range $w 0 [ expr $idx - 1]] 
    } else {
	set GidPriv(PostDisplayStyleBitmap) ""
    }

    if { $GidPriv(bitmaps_color)} {
	set displaystylelist "boundaries hiddenbound alllines hiddenlines body bodybound bodylines points"
	set displaystylefiles "boundaries.gif hiddenbound.gif alllines.gif hiddenlines.gif \
		body.gif bodybound.gif bodylines.gif points.gif"
	foreach i $displaystylefiles {
	    if { ![info exist GidPriv(image_$i)] } {
		set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
	    }
	}

	set var [ string tolower [.central.s info post get cur_display_style]]
	regsub {_} $var {} var
	
	$w del 0 end
	foreach i $displaystylelist {
	    if { $i != $var} {
		$w add command -image $GidPriv(image_$i.gif) -command \
			"CambiaImagen $GidPriv(PostDisplayStyleBitmap) $i \"$basecommand $i\""
	    } else {
		$w add command -image $GidPriv(image_$i.gif) -state disabled
		#-command CambiaBitmap $w $i
	    }
	}


    } else {
	set displaystylelist "boundaries hiddenbound alllines hiddenlines body bodybound bodylines points"
	set var [ string tolower [.central.s info post get cur_display_style]]
	regsub {_} $var {} var
	
	$w del 0 end
	foreach i $displaystylelist {
	    if { $i != $var} {
		$w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
			-command "CambiaBitmap $GidPriv(PostDisplayStyleBitmap) $i \"$basecommand $i\""
	    } else {
		$w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
			-state disabled 
		#-command CambiaBitmap $w $i
	    }
	}
    }
}

proc AddBitmapsToCullStyle { w basecommand args} {
    global GIDDEFAULT
    global GidPriv

    set idx [ string last "." $w]
    if { $idx != -1 } {
	set GidPriv(PostDisplayCullBitmap) [ string range $w 0 [ expr $idx - 1]] 
    } else {
	set GidPriv(PostDisplayCullBitmap) ""
    }
    set cullstylelist "none frontfaces backfaces frontback"
    set var [ string tolower [ .central.s info post get cur_display_culling]]

    $w del 0 end
    foreach i $cullstylelist {
	if { $i != $var} {
	    $w add command -bitmap @$GIDDEFAULT/bitmaps/cull$i \
		    -command "CambiaBitmap $GidPriv(PostDisplayCullBitmap) cull$i \"$basecommand $i\""
		    #-command "$basecommand $i"
	} else {
	    $w add command -bitmap @$GIDDEFAULT/bitmaps/cull$i \
		    -state disabled
	}
    }
}

proc AddBitmapsToCutDivide { w basecommand que args} {
    global GIDDEFAULT GidPriv

    if { $GidPriv(bitmaps_color)} {
	set displaystylelist "cut2p.gif cut3p.gif"
	$w del 0 end
	set i cut2p.gif
	if { ![info exist GidPriv(image_$i)] } {
	    set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
	}
	$w add command -image $GidPriv(image_$i) -command "$basecommand $que"

	set i cut3p.gif
	if { ![info exist GidPriv(image_$i)] } {
	    set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
	}
	$w add command -image $GidPriv(image_$i) -command "$basecommand $que ThreePoints"

	if { $que == "CutPlane"} {
	    set i cut_succesion.gif
	    if { ![info exist GidPriv(image_$i)] } {
		set GidPriv(image_$i) [ image create photo -file $GIDDEFAULT/bitmaps/$i]
	    }
	    $w add command -image $GidPriv(image_$i) -command "$basecommand Succesion "
	}
	
    } else {
	set displaystylelist "cut2p cut3p"
	$w del 0 end
	$w add command -bitmap @$GIDDEFAULT/bitmaps/cut2p -command "$basecommand $que "
	$w add command -bitmap @$GIDDEFAULT/bitmaps/cut3p -command "$basecommand $que ThreePoints"

	if { $que == "CutPlane"} {
	    $w add command -bitmap @$GIDDEFAULT/bitmaps/cut_succesion -command "$basecommand Succesion "
	}
    }
#     foreach i $displaystylelist {
# 	$w add command -bitmap @$GIDDEFAULT/bitmaps/$i \
# 		-command "$basecommand $i"
#     }
}

proc AddBitmapsToMeshSetCut { w basecommand que args} {
    global GIDDEFAULT GidPriv

    $w del 0 end
    set all_que [ .central.s info post get all_$que]
    if { $all_que == ""} {
	$w add command -label "There are no $que" -state disabled
	return
    }
    if { [ llength $all_que] < 17 } {
	set all_colors [ .central.s info post get all_$que\_colors]
	set que_on [.central.s info post get cur_$que]
	set jc 0
	foreach j $all_que {
	    regsub {_} $j { } lab
	    set col_set [ lindex $all_colors $jc]
	    # es una lista { ambient diffuse specular shininess}
	    set col_diffuse [ lindex $col_set 1]
	    if { [lsearch $que_on $j] != -1 } {
		$w add command -bitmap @$GIDDEFAULT/bitmaps/$que\_on -background $col_diffuse \
			-command "$basecommand $que $j escape" -label "$lab"
	    } else {
		$w add command -bitmap @$GIDDEFAULT/bitmaps/$que -background $col_diffuse \
			-command "$basecommand $que $j escape" -label "$lab"
	    }
	    set jc [ expr $jc + 1]
	}
	if { [ llength $all_que] > 1} {
	    $w add command -label "All On" -command "$basecommand $que all_$que escape"
	    $w add command -label "All Off" -command "$basecommand $que no_$que escape"
	}
    } else {
	$w add command -label "Style Window" -command " \
	    set GidPriv(WinList_volumes) 0; \
	    set GidPriv(WinList_surfaces) 0; \
	    set GidPriv(WinList_cuts) 0; \
	    set GidPriv(WinList_$que) 1; \
	    PostDisplay"
    }
}

proc AddMeshSetCutMenu { w basecommand que args} {
    global GIDDEFAULT GidPriv

    $w del 0 end
    set all_que [ .central.s info post get all_$que]
    if { $all_que == ""} {
	$w add command -label "There are no $que" -state disabled
	return
    }
    #if { [ llength $all_que] < 17 } {
	set all_colors [ .central.s info post get all_$que\_colors]
	set jc 0
	foreach j $all_que {
	    regsub {_} $j { } lab
	    #$w add command -bitmap @$GIDDEFAULT/bitmaps/$que\_on -background [ lindex $all_colors $jc] \
	    #	     -command "$basecommand $que $j escape" -label "$lab"
	    set col_set [ lindex $all_colors $jc]
	    # es una lista { ambient diffuse specular shininess}
	    set col_diffuse [ lindex $col_set 1]
	    $w add command -background $col_diffuse \
		    -command "$basecommand $que $j" -label "$lab"
	    set jc [ expr $jc + 1]
	}
	if { [ llength $all_que] > 1} {
	    $w add command -label "All" -command "$basecommand $que all_$que"
	}
#    } else {
#	 $w add command -label "Style Window" -command " \
#	     set GidPriv(WinList_meshes) 0; \
#	     set GidPriv(WinList_sets) 0; \
#	     set GidPriv(WinList_cuts) 0; \
#	     set GidPriv(WinList_$que) 1; \
#	     PostDisplay"
#    }
}

proc ToDoWhenChoosingStep { comm } {
    global ViewMenuPriv

    eval [ concat $comm]
    set ViewMenuPriv(DirtyMenus) 1
}

proc AddAnalysisStepsToMenu { w args} {
    global ViewMenuPriv

    set all_anal [.gid.central.s info post get all_analisis]

    if { ![.gid.central.s info post get changed_analysis_step] && \
	    ![.gid.central.s info post get changed_vista_resultados] && \
	    [ info exists ViewMenuPriv(all_anal)] && \
	    ( $ViewMenuPriv(all_anal) == $all_anal) } { 
	return
    }
    set ViewMenuPriv(all_anal) $all_anal

    set cur_anal [.gid.central.s info post get cur_analisis]
    
    $w del 0 end

    set cur_step [.gid.central.s info post get cur_step $cur_anal] 

    set cur_res [.gid.central.s info post get cur_result]
    set cur_res_view  [.gid.central.s info post get cur_results_view]
    set cur_comp [.gid.central.s info post get cur_component]

    regsub -all {_} $cur_res_view {} pp
    set restcommand "$pp $cur_res $cur_comp"
    switch $cur_res_view {
	"Iso_Surfaces" {
	    set values [.gid.central.s info post get iso_cur_result_values]
	    set restcommand "$pp exact $cur_res $cur_comp [lindex $values 0] [lindex $values 1]"
	}
	"Stream_Lines" {
	    set restcommand ""
	}
	"No_Result" {
	    set restcommand ""
	}
	"Display_Vectors" {
	    set value [.gid.central.s info post get cur_vector_factor $cur_res_view \
		    $cur_res $cur_anal $cur_step ]
	    set restcommand "$restcommand $value escape"
	}
	default {
	}
    }

    set basecommand ".gid.central.s process escape escape escape escape results analysissel"

    if { $all_anal == ""} {
	$w add command -label "Please load a MODEL first" -state disabled
	return
    }

    foreach i $all_anal {
	regsub -all {\.} $i {_} menu_name
	$w add cascade -label "$i" -menu $w.m$menu_name
	set all_step [.gid.central.s info post get all_steps $i]
	set cur_step [.gid.central.s info post get cur_step $i] 
	if { [ winfo exist $w.m$menu_name ]} {
	    $w.m$menu_name del 0 end
	} else {
	    menu $w.m$menu_name
	}
# 	foreach j $all_step {
# 	    $w.m$menu_name add command -label $j -command "$basecommand $i $j"
# 	}
	set words ""
	foreach j $all_step {
	    if { ( $cur_anal != $i) || ( $cur_step != $j) } {
		lappend words [list $j "$basecommand $i $j $restcommand"]
	    } else {
		lappend words [list $j "$basecommand $i $j $restcommand" check]
	    }
	}
	rmenuconf $w.m$menu_name $words
    }
}

proc ResultsNoStep { } {
    WarnWin "Please select a Step first"
}

proc AddResultsToMenu { w basecommand que_res { sub 0}} {
    global ViewMenuPriv

    set all_anal [.gid.central.s info post get all_analisis]
    if { $all_anal == ""} {
	set msg "Please load a MODEL first"
    } else {
	set msg "Please select a STEP first"
    }
    set cur_anal [.gid.central.s info post get cur_analisis]
    if { $cur_anal == ""} { 
	$w del 0 end  
	$w add command -label $msg -state disabled
	return
    }

    set cur_step [.gid.central.s info post get cur_step $cur_anal] 
    if { $cur_step == ""} { 
	$w add command -label "Please select a STEP first" -state disabled
	$w del 0 end
	return
    }

    if { $que_res != "Deformation" } {
	set all_res [.gid.central.s info post get cur_results_list $que_res ]
    } else {
	set all_res [.gid.central.s info post get show_geom_all_deform $cur_anal \
	    $cur_step ]
    }
    if { $all_res == ""} { 
	$w del 0 end
	$w add command -label "No useful results found" -state disabled
	return
    }

    ## miramos si el menu que ya tenemos aun es valido
    # para el conyazo de windows, que es mas lento que una tortuga con reuma
    if { ( $cur_anal != "") && ( $cur_step != "") && ( $all_res != "") } {
	if { [ info exist ViewMenuPriv($que_res/$sub/analstep)] && \
		[ info exist ViewMenuPriv($que_res/$sub/allres)] } {
	    if { ![ string compare $ViewMenuPriv($que_res/$sub/analstep) "$cur_anal $cur_step" ] || \
		    ![ string compare $ViewMenuPriv($que_res/$sub/allres) $all_res] } { 
		return
	    }
	}
    }

    set ViewMenuPriv($que_res/$sub/analstep) "$cur_anal $cur_step" 
    set ViewMenuPriv($que_res/$sub/allres) $all_res

    $w del 0 end

    set cur_res [.gid.central.s info post get cur_result]
    set cur_res_view  [.gid.central.s info post get cur_results_view]
    set cur_comp [.gid.central.s info post get cur_component]
    
    set entrada_ventana 0
    if { [ llength $all_res] > 17} {
	set all_res [ lrange $all_res 0 16]
	set entrada_ventana 1
    }

    foreach i $all_res {

	#WarnWinText "components_list '$que_res' '$i' '$cur_anal' '$cur_step'"
	#WarnWinText "+++[encoding system]\n([string length $i]:[string bytelength $i]) '$i'\n---"

	set all_comp [ .gid.central.s info post get components_list $que_res $i $cur_anal $cur_step ]
	regsub -all {_} $i { } txt
	if { ( [ llength $all_comp] > 1) && \
		( $que_res != "Stream_Lines") && ( $que_res != "Deformation") } {
	    
	    # anyadimos el menu de las componentes
	    #WarnWinText "###[encoding system]\n([string length $i]:[string bytelength $i]) '$i'\n***"
	    regsub -all {\.} $i {_} menu_name
	    #set txt $i

	    $w add cascade -label "$txt" -menu $w.m$menu_name
	    if { [ winfo exist $w.m$menu_name ]} {
		$w.m$menu_name del 0 end
	    } else {
		menu $w.m$menu_name
	    }
	    
	    foreach j $all_comp {
		$w.m$menu_name add command -label $j -command "$basecommand $i $j"
	    }
	} else {
	    set postcmd ""
	    #if { $que_res == "Deformation"} {
	    #	 set postcmd "escape"
	    #}
	    # anyadimos el comando
	    if { ( $cur_res != $i) || ( $cur_res_view != $que_res) } {
		$w add command -label "$txt" -command "$basecommand $i $postcmd"
	    } else {
		$w add checkbutton -label "$txt" -onvalue 1 -variable pp -command "$basecommand $i $postcmd" 
		set pp 1
	    }
	}
    }

    if { $entrada_ventana} {
	$w add separator
	$w add command -label " · · ·   More   · · ·" -command PostResults
    }

}

proc AddGraphsResultsToMenu { w basecommand que_res args} {
    global ViewMenuPriv

    set all_anal [.gid.central.s info post get all_analisis]
    if { $all_anal == ""} {
	set msg "Please load a MODEL first"
    } else {
	set msg "Please select a STEP first"
    }
    set cur_anal [.gid.central.s info post get cur_analisis]
    if { $cur_anal == "" } {
	$w del 0 end
	$w add command -label $msg -state disabled
	return
    }

    set cur_step [.gid.central.s info post get cur_step $cur_anal] 
    if { $cur_step == ""} { 
	$w del 0 end
	$w add command -label "Please select a STEP first" -state disabled
	return
    }

    set all_res [.gid.central.s info post get cur_results_list $que_res ]
    if { $all_res == ""} { 
	$w del 0 end
	return
    }

    ## miramos si el menu que ya tenemos aun es valido
    # para el conyazo de windows, que es mas lento que una tortuga con reuma
    if { ( $cur_anal != "") && ( $cur_step != "") && ( $all_res != "") } {
	if { [ info exist ViewMenuPriv($que_res//analstep)] && \
		[ info exist ViewMenuPriv($que_res//allres)] } {
	    if { ![ string compare $ViewMenuPriv($que_res//analstep) "$cur_anal $cur_step" ] || \
		    ![ string compare $ViewMenuPriv($que_res//allres) $all_res] } { 
		return
	    }
	}
    }

    set ViewMenuPriv($que_res//analstep) "$cur_anal $cur_step" 
    set ViewMenuPriv($que_res//allres) $all_res

    $w del 0 end

    if { "$all_res" != ""} {
	foreach i $all_res {
	    set all_comp [.gid.central.s info post get cur_components_list $i ]
	    if { [ llength $all_comp] > 1 } {
		# anyadimos el menu de las componentes
		regsub -all {\.} $i {_} menu_name
		$w add cascade -label "$i" -menu $w.m$menu_name
		if { [ winfo exist $w.m$menu_name ]} {
		    $w.m$menu_name del 0 end
		} else {
		    menu $w.m$menu_name
		}
		foreach j $all_comp {
		    $w.m$menu_name add command -label $j -command "$basecommand $i $j"
		}
	    } else {
		# anyadimos el comando
		#if { ( $cur_res != $i) || ( $cur_res_view != $que_res) } {
		    $w add command -label "$i" -command "$basecommand $i"
		    #} else {
			#$w add checkbutton -label "$i" -onvalue 1 -variable pp -command "$basecommand $i" 
			#set pp 1
			#}
		}
	    }
	}
    }

proc PointAnalysisSetAxisTo { que_eje res res_comp} {
    global ViewMenuPriv

    if { [ info exist ViewMenuPriv(point_analysis_ax$que_eje)]} {
	set old_res [ lindex $ViewMenuPriv(point_analysis_ax$que_eje) 0]
	set old_res_comp [ lindex $ViewMenuPriv(point_analysis_ax$que_eje) 1]
	set ViewMenuPriv(point_analysis_ax$que_eje//$old_res//$old_res_comp) 0
    }
    set ViewMenuPriv(point_analysis_ax$que_eje) "$res $res_comp"
    set ViewMenuPriv(point_analysis_ax$que_eje//$res//$res_comp) 1
}

proc PointAnalysisDoIt { basecommand} {
    global ViewMenuPriv
    
    if { ![ info exist ViewMenuPriv(point_analysis_axX)]} {
	WarnWin "Please set X axis first"
	return
    }
    if { ![ info exist ViewMenuPriv(point_analysis_axY)]} { 
	WarnWin "Please set Y axis first"
	return
    }

    set comm "$basecommand $ViewMenuPriv(point_analysis_axX) $ViewMenuPriv(point_analysis_axY)"

    eval [ concat $comm]
}

proc BorderGraphSetAxisTo { que_eje res { res_comp ""}} {
    global ViewMenuPriv

    if { [ info exist ViewMenuPriv(border_graph_ax$que_eje)]} {
	set old_res [ lindex $ViewMenuPriv(border_graph_ax$que_eje) 0]
	set old_res_comp [ lindex $ViewMenuPriv(border_graph_ax$que_eje) 1]
	set ViewMenuPriv(border_graph_ax$que_eje//$old_res//$old_res_comp) 0
    }
    if { $que_eje == "Y"} {
	set ViewMenuPriv(border_graph_ax$que_eje) "$res $res_comp"
	set ViewMenuPriv(border_graph_ax$que_eje//$res//$res_comp) 1
    }			 
    if { $que_eje == "X"} {	 
	set ViewMenuPriv(border_graph_ax$que_eje) "$res"
	foreach i "X_Variation Y_Variation Z_Variation LineVariation" {
	    set ViewMenuPriv(border_graph_ax$que_eje//$i) 0
	}
	set ViewMenuPriv(border_graph_ax$que_eje//$res) 1
    } 
}

proc BorderGraphDoIt { basecommand} {
    global ViewMenuPriv
    
    if { ![ info exist ViewMenuPriv(border_graph_axX)]} { 
	WarnWin "Please set X axis first"
	return
    }
    if { ![ info exist ViewMenuPriv(border_graph_axY)]} { 
	WarnWin "Please set Y axis first"
	return
    }

    set comm "$basecommand $ViewMenuPriv(border_graph_axX) $ViewMenuPriv(border_graph_axY)"

    eval [ concat $comm]
}

proc AddGraphsXYResultsToMenu { w basecommand que_res args} {
    global ViewMenuPriv

    set all_anal [.gid.central.s info post get all_analisis]
    if { $all_anal == ""} {
	set msg "Please load a MODEL first"
    } else {
	set msg "Please select a STEP first"
    }
    set cur_anal [.gid.central.s info post get cur_analisis]
    if { $cur_anal == ""} { 
	$w del 0 end
	foreach eje "X Y" {
	    $w add cascade -label "Set $eje axis" -menu $w.m$eje
	    if { [ winfo exist $w.m$eje ]} {
		$w.m$eje del 0 end
		$w.m$eje add command -label $msg -state disabled
	    } else {
		menu $w.m$eje
		$w.m$eje add command -label $msg -state disabled
	    }    
	} 
	if { $que_res == "Point_Graph"} {
	    $w add command -label "Select Points" -command ResultsNoStep
	}
	if { $que_res == "Border_Graph"} {
	    $w add command -label "Select Border" -command ResultsNoStep 
	}
	return
    }

    set cur_step [.gid.central.s info post get cur_step $cur_anal] 
    if { $cur_step == ""} { 
	$w del 0 end
	foreach eje "X Y" {
	    $w add cascade -label "Set $eje axis" -menu $w.m$eje
	    if { [ winfo exist $w.m$eje ]} {
		$w.m$eje del 0 end
		$w.m$eje add command -label "Please select a STEP first" -state disabled
	    } else {
		menu $w.m$eje
		$w.m$eje add command -label "Please select a STEP first" -state disabled
	    }    
	}
	if { $que_res == "Point_Graph"} {
	    $w add command -label "Select Points"  -command ResultsNoStep
	}
	if { $que_res == "Border_Graph"} {
	    $w add command -label "Select Border"  -command ResultsNoStep
	}
	return
    }

    set all_res [.gid.central.s info post get cur_results_list $que_res ]
    if { $all_res == ""} { 
	$w del 0 end
	foreach eje "X Y" {
	    $w add cascade -label "Set $eje axis" -menu $w.m$eje
	    if { [ winfo exist $w.m$eje ]} {
		$w.m$eje del 0 end
	    } else {
		menu $w.m$eje
	    }    
	}
	if { $que_res == "Point_Graph"} {
	    $w add command -label "Select Points"  -command ResultsNoStep
	}
	if { $que_res == "Border_Graph"} {
	    $w add command -label "Select Border"  -command ResultsNoStep
	}
	return
    }

    ## miramos si el menu que ya tenemos aun es valido
    # para el conyazo de windows, que es mas lento que una tortuga con reuma
    if { ( $cur_anal != "") && ( $cur_step != "") && ( $all_res != "") } {
	if { [ info exist ViewMenuPriv($que_res//analstep)] && \
		[ info exist ViewMenuPriv($que_res//allres)] } {
	    if { ![ string compare $ViewMenuPriv($que_res//analstep) "$cur_anal $cur_step" ] || \
		    ![ string compare $ViewMenuPriv($que_res//allres) $all_res] } { 
		return
	    }
	}
    }

    set ViewMenuPriv($que_res//analstep) "$cur_anal $cur_step" 
    set ViewMenuPriv($que_res//allres) $all_res

    if { ( [ $w type 0] != "cascade") || ( [ $w type 1] != "cascade") } {
	$w del 0 end
	foreach eje "X Y" {
	    $w add cascade -label "Set $eje axis" -menu $w.m$eje
	    if { [ winfo exist $w.m$eje ]} {
		$w.m$eje del 0 end
	    } else {
		menu $w.m$eje
	    }    
	}
	if { $que_res == "Point_Graph"} {
	    $w add command -label "Select Points"  -command ResultsNoStep
	}
	if { $que_res == "Border_Graph"} {
	    $w add command -label "Select Border"  -command ResultsNoStep
	}
    }

    set lista_ejes "X Y"
    if { $que_res == "Border_Graph"} {
	set lista_ejes "Y"
	set eje X
	# construyamos el menu del eje X
	if { [ winfo exist $w.m$eje ]} {
	    $w.m$eje del 0 end
	}

	foreach i "X_Variation Y_Variation Z_Variation LineVariation" {
	    $w.m$eje add checkbutton -label "$i" -command "BorderGraphSetAxisTo $eje $i" \
		    -onvalue 1 -variable ViewMenuPriv(border_graph_ax$eje//$i)
	    set ViewMenuPriv(border_graph_ax$eje//$i) 0
	}
    }

    foreach eje $lista_ejes {
	if { [ winfo exist $w.m$eje ]} {
	    $w.m$eje del 0 end
	}

	foreach i $all_res {
	    set all_comp [.gid.central.s info post get cur_components_list $i ]
	    if { [ llength $all_comp] > 1 } {
		# anyadimos el menu de las componentes
		regsub -all {\.} $i {_} menu_name
		$w.m$eje add cascade -label "$i" -menu $w.m$eje.m$menu_name
		if { [ winfo exist $w.m$eje.m$menu_name ]} {
		    $w.m$eje.m$menu_name del 0 end
		} else {
		    menu $w.m$eje.m$menu_name
		}
		foreach j $all_comp {
		    if { $que_res == "Point_Graph"} {
			$w.m$eje.m$menu_name add checkbutton -label "$j" \
				-command "PointAnalysisSetAxisTo $eje $i $j" \
				-onvalue 1 -variable ViewMenuPriv(point_analysis_ax$eje//$i//$j)
			set ViewMenuPriv(point_analysis_ax$eje//$i//$j) 0
		    }
		    if { $que_res == "Border_Graph"} {
			$w.m$eje.m$menu_name add checkbutton -label "$j" \
				-command "BorderGraphSetAxisTo $eje $i $j" \
				-onvalue 1 -variable ViewMenuPriv(border_graph_ax$eje//$i//$j)
			set ViewMenuPriv(border_graph_ax$eje//$i//$j) 0
		    }
		}
	    } else {
		if { $que_res == "Point_Graph"} {
		    $w.m$eje add checkbutton -label "$i" \
			    -command "PointAnalysisSetAxisTo $eje $i $i" \
			    -onvalue 1 -variable ViewMenuPriv(point_analysis_ax$eje//$i//$i)
		    set ViewMenuPriv(point_analysis_ax$eje//$i//$i) 0
		}
		if { $que_res == "Border_Graph"} {
		    $w.m$eje add checkbutton -label "$i" \
			    -command "BorderGraphSetAxisTo $eje $i $i" \
			    -onvalue 1 -variable ViewMenuPriv(border_graph_ax$eje//$i//$i)
		    set ViewMenuPriv(border_graph_ax$eje//$i//$i) 0
		}
	    }
	}
    }
    
    #$w add command -label "Select Points" -command "PointAnalysisDoIt [list $basecommand]"
    if { $que_res == "Point_Graph"} {
	$w entryconfigure 2 -command "PointAnalysisDoIt [list $basecommand]"
    }
    if { $que_res == "Border_Graph"} {
	$w entryconfigure 2 -command "BorderGraphDoIt [list $basecommand]"
    }
}


# Position a dialog box at a reasonable place on the screen.

proc dpos { w } {
    set hh [expr [winfo screenheight .gid]*.55]		
    set hh [string range $hh 0 [expr [string first . $hh]-1]]
    wm geometry $w -0+400	
}

proc GiveDpos {} {
    return "-0+400"
}

proc AddMoreWelcome {} {
    global GIDDEFAULTTCL tcl_platform
    set base .gid.pepe

    wm geometry .gid.pepe 630x650
    text $base.text \
  	-height 7 -width 1 -yscroll "$base.scrollbar set"

    scrollbar $base.scrollbar \
	-orient v -command "$base.text yview"


    # in moreinfo always the real GiD internal version, not the alternative string
    #if { $GidPriv(TextOfVersion) != "" } {
    #  set GidVersion $GidPriv(TextOfVersion)
    #} else {
      set GidVersion [.gid.central.s info GiDVersion]
    #}

    $base.text ins end "GID internal version:   "
    $base.text ins end "$GidVersion \n"

    $base.text ins end "Last compilation time:\n  "

    if { ![ catch { set fcomp [ open [ file native [ file join $GIDDEFAULTTCL Compiled]]]}]} {
	while { ![ eof $fcomp] } {
	     $base.text ins end [ gets $fcomp]
             $base.text ins end \n
	}
	close $fcomp
    }


    $base.text ins end "tcl_platform: "
    foreach i "machine platform os osVersion" {
	 $base.text ins end " '$tcl_platform($i)'"
    }
    $base.text ins end \n

    catch { $base.text ins end [.gid.central.s info internalstate] }

    if { ![ catch { set fcomp [ open [ file native [ file join $GIDDEFAULTTCL Compiled-more]]]}] } {
	while { ![ eof $fcomp] } {
	     $base.text ins end [ gets $fcomp]
             $base.text ins end \n
	}
	close $fcomp
    }



	grid $base.text -in $base	-row 3 -column 1  \
		-columnspan 3 \
		-sticky nesw
	grid $base.scrollbar -in $base	-row 3 -column 3  \
		-sticky nse

	grid rowconfigure $base 3 -weight 1 

    $base.button_more conf -text Less -command { 
        destroy .gid.pepe.text
	destroy .gid.pepe.scrollbar
	wm geometry .gid.pepe 630x500

	.gid.pepe.button_more conf -text "More" -command "AddMoreWelcome" } 
}



proc CreateWelcomeWin { { overw .gid } } {
    global GIDDEFAULT GidPriv
    global tcl_platform

    set ProgName $GidPriv(ProgName)
    set GenText "Data management system for FEM analysis."

        toplevel .gid.pepe
        wm title .gid.pepe $ProgName
        set base .gid.pepe
	wm minsize $base 630 500
	wm maxsize $base 630 10000



        wm geometry .gid.pepe +[expr [winfo x $overw]+[winfo width $overw]/2-315]+[ \
            expr [winfo y $overw]+[winfo height $overw]/2-315]

        set imatge_about [image create photo -file $GidPriv(AboutWindow)]  
	set imatge_tapa  [image create photo -file [file join $GIDDEFAULT bitmaps about_grey.gif]] 

      if { $GidPriv(TextOfVersion) != "" } {
        set GidVersion $GidPriv(TextOfVersion)
      } else {
        set GidVersion [.gid.central.s info GiDVersion]
      }

   
	label $base.label_img -image $imatge_about 
	label $base.label_tapa -image $imatge_tapa -bd 0 -bg #595959

        place $base.label_tapa -x 428 -y 140 -in $base



	button $base.button_ok \
		-text OK -width 6 -padx 10  -command "destroy .gid.pepe"

	button $base.button_more \
		-text More -width 6 -padx 10  -command "AddMoreWelcome"

global credits_about
set credits_about 0


	button $base.button_credits \
		-text Credits -width 6 -padx 10  -command "start_credits $base 140"		    
		    


	# Geometry management

	grid $base.label_img -in $base	-row 1 -column 1  \
		-columnspan 3
	grid $base.button_ok -in $base	-row 2 -column 1  \
		 -sticky e -padx 8 -pady 8 

	grid $base.button_credits -in $base	-row 2 -column 2  \
		  -padx 8 -pady 8 
	
	grid $base.button_more -in $base	-row 2 -column 3  \
		 -sticky w -padx 8 -pady 8 


        # ponemos el numero de version encima de la imagen
        canvas $base.c -borderwidth 0 -highlightthickness 0 -width 400 -height 35 -bg black

        if { $tcl_platform(platform) == "windows" } {        
	    place $base.c -x 8 -y 422 -in $base
	} else {
	    place $base.c -x 8 -y 422 -in $base
	}

        # frame $base.fv -bd 0
        # label $base.fv.label_version -text $GidVersion -font BigFont -fg #cccccc -bg black
        # grid $base.fv.label_version -sticky we
    
        #set rw [ winfo reqwidth $base.fv.label_version]
        #place $base.label_version -x [ expr [ winfo reqwidth $base.label_img] - $rw - 16] -y 420 -in $base


	# Resize behavior management

	grid rowconfigure $base 1 -weight 0 -minsize 30
	grid rowconfigure $base 2 -weight 0 -minsize 30
        grid rowconfigure $base 3 -weight 1 


	grid columnconfigure $base 1 -weight 1 -minsize 30
	grid columnconfigure $base 2 -weight 1 -minsize 30
	grid columnconfigure $base 3 -weight 1 -minsize 30
  
        bind $base <Return> "destroy .gid.pepe"
        bind $base <Escape> "destroy .gid.pepe"


    tkwait visibility .gid.pepe
    grab  .gid.pepe 


    # a mover las letras
    update idletasks
    if { ![ winfo exist $base.c ]} {
	break
    }
    set txt "Version $GidVersion"
    set len_txt [ string length $txt]
    set dest_x [ expr [ $base.c cget -width] - 36]
    for { set is 0} { $is < $len_txt} { incr is} {
	frame $base.fv$is -bd 0
	label $base.fv$is.l -text [ string index $txt [ expr $len_txt - $is - 1]] \
		-font "Helvetica 14 bold italic" -fg #aaaaaa -bg black -bd 0 -highlightthickness 0
	grid $base.fv$is.l -sticky we -padx 0 -pady 0 
	
	set rw [ winfo reqwidth $base.fv$is.l]
	set dest_x [ expr $dest_x - $rw]
	set ini_x 0
	set c_id [ $base.c create window $ini_x 0 -anchor nw -window $base.fv$is]
	set dif_x [ expr $dest_x - $ini_x]
	update
	update idletasks
	for { set ix $ini_x} { $ix < $dest_x} { set ix [ expr $ix + 5]} {
	    # por si han cerrado la ventana antes de acabar con las letritas
	    if { ![ winfo exist $base.c ]} {
		break
	    }
	    $base.c coords $c_id $ix 0 
	    update
	    update idletasks
	}
	# por si han cerrado la ventana antes de acabar con las letritas
	if { ![ winfo exist $base.c ]} {
	    break
	}
	$base.c coords $c_id $dest_x 0 
	
    }


    # por si han cerrado la ventana antes de acabar con las letritas
    if { [ winfo exist .gid.pepe]} {
	tkwait window .gid.pepe
    }
}


proc start_credits {base i} {
global credits_about

 if {$credits_about==0} {  show_credits $base $i }

}

proc show_credits {w i} {
#credits
global credits_about

set credits_about 1

	    if {[winfo exist $w.label_tapa]} {
	      place $w.label_tapa -x 428 -y $i -in $w
	    } else {set i 9998}
 	    incr i
	    if {$i<260} {after 60 "show_credits $w $i"}

}




proc ChangeWindowTitle { { projectname "" } } {
    global GidPriv

    if { $projectname == "" } {
	set projectname [lindex [.central.s info Project] 1]
    }
    wm title .gid [join [list "$GidPriv(ProgName)                        " \
	    "Project: [file tail $projectname]"]]
    wm iconname .gid [file tail $projectname]
}

proc MakeNoise { name } {
    global GIDDEFAULT
#     catch { exec playaiff $GIDDEFAULT/audio/$name & }
}


proc PrintLayerName {} {
    global WarnLineVar
    set aa [.gid.central.s info Project]
    if { [lindex $aa 3] != "*****" } { 
	ChangeWarnLineVar "Layer in use is '[lindex $aa 3]'"
    } else {
	ChangeWarnLineVar "There is no layer in use"
    }
}

proc CreateIcon {} {
    global GIDDEFAULT tcl_platform

    # is it necessary for windows ?
    if { $tcl_platform(platform) == "windows" } {
#	wm iconbitmap .gid -default $GIDDEFAULT/bitmaps/gid.ico
	wm iconbitmap .gid $GIDDEFAULT/bitmaps/gid.ico
    } else {
	wm iconbitmap .gid @$GIDDEFAULT/bitmaps/GiDicono64.xbm
    }
#    wm iconbitmap . @$GIDDEFAULT/bitmaps/gid_icon.xbm
##    wm iconbitmap . @$GIDDEFAULT/bitmaps/GiDicono.xbm 
#-background yellow -foreground black
#     catch {
# 	set imm [image create bitmap -background black -foreground \
# 		AntiqueWhite3 -file $GIDDEFAULT/bitmaps/gid_icon.xbm]
# 	catch { destroy .iconw }
# 	toplevel .iconw
# 	label .iconw.l -image $imm
# 	pack .iconw.l
# 	wm iconwindow . .iconw
#     }
#     if { $tcl_platform(platform) != "windows" } {
#  	catch {
#        set imm [ image create bitmap -file $GIDDEFAULT/bitmaps/GiDicono.xbm \
#  	       -background yellow -foreground black ]
#  	    set imm [ image create photo -file $GIDDEFAULT/bitmaps/GiDicono64.gif ]
#  	    toplevel .__t__icw
#  	    label .__t__icw.l -image $imm -bd 0
#  	    pack .__t__icw.l
#  	    wm iconwindow . .__t__icw
#  	}
#     }
}

proc OpenTemporaryWindow { text commands {names ""} { help "" } } {

    if { $names == "" } { regsub -all escape $commands Cancel names}

    if {$help == "" } {
	set var [list tk_dialogRAMFull .gid.tempwinw {Dialog window} $text \
		"" "" gidquestionhead 0]
    } else {
	set HelpCommand [list HelpWindow "" $help .gid.tempwinw.helpwin]
	
	set var [list tk_dialogRAMHelp .gid.tempwinw {Dialog window} $text \
		"" "" gidquestionhead $HelpCommand 0]
    }
    append var " $names"
    set retval [eval $var]

    after idle .gid.central.s process [lindex $commands $retval]
}

proc OpenTemporaryEntryWindow { text {default ""} {type any} } {


    set retval [tk_dialogEntryRAM .gid.tempwine {Enter value window} $text questhead \
	    $type $default]

    if { $retval == "--CANCEL--" } { 
	.gid.central.s process escape 
    } else { .gid.central.s process $retval}


}

proc OpenTemporaryComboWindow { text AcceptNew args} {

    if { [llength $args] } {
	set retval [tk_dialogComboRAM .gid.tempwinec {Enter value window} \
		$text questhead $AcceptNew $args]
    } else {
	set retval [tk_dialogComboRAM .gid.tempwinec {Enter value window} $text \
		questhead $AcceptNew ]
    }
    if { $retval == "--CANCEL--" } { 
	.gid.central.s process escape 
    } else { .gid.central.s process $retval}
}

proc AddProblemtypeNamesToVar { prefix dir varname recurse } {
    upvar #0 $varname var
    
    foreach i [glob -nocomplain $dir/*] {
	if { [file ext $i] == ".gid" } {
	    if { $prefix == "" } {
		set name [file tail [file root $i]]
	    } else { set name [file join $prefix [file tail [file root $i]]] }
	    set var($name) ""
	} elseif { $recurse && [file isdir $i] } {
	    if { $prefix == "" } {
		set name [file tail $i]
	    } else { set name [file join $prefix [file tail $i]] }
	    AddProblemtypeNamesToVar $name $i $varname 1
	}
    }
}

proc OpenTemporaryTransformProblemTypeWindow { text } {
    
    global GIDDEFAULT GidPriv TransformPrtypeVar
    
    set current [lindex [.gid.central.s info Project] 0]
    
    catch { unset TransformPrtypeVar }
    AddProblemtypeNamesToVar "" $GIDDEFAULT TransformPrtypeVar 0
    AddProblemtypeNamesToVar "" [file join $GIDDEFAULT problemtypes] \
	    TransformPrtypeVar 1

    set args [lsort [array names TransformPrtypeVar]]
    catch { unset TransformPrtypeVar }
    
    if { [llength $args] } {
	set retval [tk_dialogComboRAM .gid.tempwinetp {Enter name} \
		$text questhead 1 $args]
    } else {
	set retval [tk_dialogComboRAM .gid.tempwinetp {Enter name} $text \
		questhead 1]
    }
    if { $retval == "--CANCEL--" } { 
	.gid.central.s process escape 
    } else { .gid.central.s process $retval}
}

proc OpenPasswordEntryWindow { text {default ""} {type any} } {
    global GidPriv

    if { $default != "MODULO"} {
	set default ""
	set fin 0
	while { !$fin} {
	    set retval [tk_dialogEntryPASS .gid.tempwineps {Enter password window} $text questhead \
		    $type $default]
	    if { $retval == "--CANCEL--" } { 
		.gid.central.s info setpassword "--CANCEL--abcdef" 
		set fin 1
	    } elseif { $retval == "--ACADEMIC--" } { 
		.gid.central.s info setpassword "--ACADEMIC--" 
		set fin 1
	    } else { 
		# longitud password v7 = 24 chars, v6 y anteriores = 16
		if { [ string length $retval] > 20} {
		    .gid.central.s info setpassword $retval
		    set fin 1
		} else {
		    WarnWin "This password is not valid for GiD 7.x.\nPasswords and licences from version 6.x or older \nare incompatible with this version.\nGet a temporal password at $GidPriv(PassWeb)\nPlease, contact your dealer to get a new licence.\n"
		}
	    }
	}

    } else {
	set default ""
	set retval [tk_dialogEntryPASS .gid.tempwineps {Register Module} $text questhead \
		$type $default 1]
	if { $retval != ""} {
	    .gid.central.s info setpassword "$retval"
	}
    }
}

#
# what can be normal or disabled
#

proc EnableOrDisableWindow { w what } {
    catch { $w conf -state $what }
    foreach i [winfo children $w] {
	EnableOrDisableWindow $i $what
    }
}

proc SelectButton { w wplace text disable comm } {

    if { $disable == "disableall" } {
	EnableOrDisableWindow $w disabled
    }

    frame $w.finf -relief ridge -bd 4
    button $w.finf.f -text Finish -command "EndSelectButton $w $comm"
    label $w.finf.l -text $text
    pack $w.finf.f $w.finf.l -side left
    place $w.finf -in $w -x 0 -rely 1 -anchor sw


    delayedop changefunc "$w.finf.f invoke"
}


#
# only called internally
#
proc EndSelectButton { w comm } {

    delayedop -cancel changefunc "$w.finf.f invoke"
    destroy $w.finf
    .gid.central.s process escape escape escape 

    EnableOrDisableWindow $w normal
    eval $comm
}

proc PrintTimeTable { tt } {
    upvar #0 $tt aa
    puts "\n--------------TIME TABLE--------\n"
    foreach {name val} [array get aa] {
	puts "Time for [format %-20s:%lf $name \
		[expr 1e-6*[lindex $val 0]]] seconds"
    }
}

#ChooseType == "project" or "file"
#OpenMode == "read" or "write"
#w == parent
#title == "title of window"
#DefaultFile == "Name of file"
#filetypes == list of names and extensions, e.g: {{"Jpeg Image" ".jpg .jpeg"} {"All files" ".*"} }
#defaultextension == extension to automatically append to name, e.g: ".jpg
#NOTE: if ChooseType == "project" then filetypes and defaultextension are set automatically for GiD
proc Browser-ram { ChooseType OpenMode { w .gid }  { title "Browser" } \
	{ DefaultFile {} }  { filetypes {} } { defaultextension {} } } {
    set ret [Browser-ramR $ChooseType $OpenMode $w $title $DefaultFile $filetypes $defaultextension]

    if { $ret == "" } { 
	.gid.central.s process escape 
    } else { .gid.central.s process \"$ret\"}

}

proc Browser-ramR { ChooseType OpenMode { w .gid }  { title "Browser" } \
	{ DefaultFile {} } { filetypes {} } { defaultextension {} } } {
    global DefaultSearchDirectory DefaultSearchDirectoryP

    if { $ChooseType == "project" } {
	if { ![info exists DefaultSearchDirectoryP] || \
		![file isdirectory $DefaultSearchDirectoryP]} {
	    set DefaultSearchDirectoryP [pwd]
	}
	set deft $DefaultSearchDirectoryP
    } else {
	if { ![info exists DefaultSearchDirectory] || \
		![file isdirectory $DefaultSearchDirectory]} {
	    set DefaultSearchDirectory [pwd]
	}
	set deft $DefaultSearchDirectory
    }

    set comm [list tkFDialog -title $title -initialdir $deft \
	    -parent $w]

    if { $OpenMode == "read" } {
	append comm " -opentype open"
    } else {
	append comm " -opentype save"
    }
    if { $ChooseType == "project" } {
	append comm " -filetypes {{{GID project} {.gid}}}"
	append comm " -dirprojectext .gid -defaultextension .gid"
    } else {
        #filename, not GiD project
        if { $filetypes != "" } {
            append comm " "
 	    append comm [list -filetypes $filetypes]
#WarnWinText "DefaultFile=$DefaultFile filetypes=$filetypes defaultextension=$defaultextension"
        }
        if { $defaultextension != "" } {
            append comm " -defaultextension $defaultextension"
        }
    }

    if { $DefaultFile != "" } {
	append comm " "
	append comm [list -initialfile $DefaultFile]
    }
    set fileName [eval $comm]
    if { $fileName != "" } {
	if { $ChooseType == "project" } {
	    set DefaultSearchDirectoryP [file dirname $fileName]
	} else { set DefaultSearchDirectory [file dirname $fileName] }
    }

    update 

    return $fileName

}

proc TopMenuFrame { {action ""} { w .gid.menu } } {
    global GidPriv tcl_platform

    if { $action == "" } {
	if { [winfo exist $w] } { return }
	if { ![info exists GidPriv(PrePostTopMenuWindowGeom)] } {
	    set action INSIDE
	} else {
	    set action [lindex $GidPriv(PrePostTopMenuWindowGeom) 0]
	}
    }

    if { $action == "INSIDE" } {
	if { [winfo exists $w] } {
	    if { [winfo class $w] != "frame" } {
		destroy $w
	    }  else { return }
	}

	if { $tcl_platform(platform) != "windows" } {
	    frame $w -relief raised -borderwidth 1
	} else { frame $w -borderwidth 0 }

	pack $w -side top -fill x -before .gid.central
	set GidPriv(PrePostTopMenuWindowGeom) "INSIDE {} 1 TopMenuFrame"
    } else {
	if { ![info exists GidPriv(PrePostTopMenuWindowGeom)] || \
		[lindex $GidPriv(PrePostTopMenuWindowGeom) 1] == "" } {
	    set hh [winfo x .gid]
	    set vv [expr [winfo y .gid]+25]
	    set GidPriv(PrePostTopMenuWindowGeom) \
		    "OPEN [winfo width .gid]x25+$hh+$vv 1 TopMenuFrame"
	}
	InitWindow $w GID PrePostTopMenuWindowGeom TopMenuFrame
	update idletasks
	wm transient $w .gid
	wm protocol $w WM_DELETE_WINDOW "wm withdraw $w"

	if { $action == "NONE" } {
	    set GidPriv(PrePostTopMenuWindowGeom) "NONE {} 1 TopMenuFrame"
	    wm withdraw $w
	    .gid conf -menu ""
	}
	update idletasks
    }
    CreateTopMenus
    if { [winfo class $w] == "Toplevel" } {
	foreach i [bind .gid] {
	    bind $w $i [bind .gid $i]
	}
    }

}

proc DefineCoordFrame { { crear 1}} {
    global GidPriv

    set w $GidPriv(CoordFrame) 
    GidHelp "$w label $w.lx label $w.ly label $w.lz" \
	    "Display the current coordinates.\nTo hide, see Utilities->Preferences->General"
    if { $crear} {
	label $w.lx -bg $GidPriv(ToolbarBg) -anchor w
	label $w.ly -bg $GidPriv(ToolbarBg) -anchor w
	label $w.lz -bg $GidPriv(ToolbarBg) -anchor w
	pack $w -side right -fill y
    }
    grid $w.lx -pady 0 -padx 2 -sticky ewn
    grid $w.ly -pady 0 -padx 2 -sticky ew
    grid $w.lz -pady 0 -padx 2 -sticky ew
    grid columnconf $w 0 -weight 1
    grid columnconf $w 0 -minsize 65
}

proc OlvidaCoordFrame {} {
    global GidPriv

    set w $GidPriv(CoordFrame) 
    grid forget $w.lx
    grid forget $w.ly
    grid forget $w.lz
}

proc BottomEntryFrame { {action ""} { w .gid.comm } } {
    global GidPriv tcl_platform GIDDEFAULT

#     if { $action == "" && [winfo exists $w] } { return }

    if { [winfo exists $w.fwarn.list] } {
	set ListboxContents [$w.fwarn.list get 0 end]
    }

    if { $action == "" } {
	if { [winfo exist $w] } { return }
	if { ![info exists GidPriv(PrePostEntryWindowGeom)] } {
	    set action INSIDE
	} else {
	    set action [lindex $GidPriv(PrePostEntryWindowGeom) 0]
	}
    }

    if { $action == "INSIDE" } {
	if { [winfo exists $w] } {
	    if { [winfo class $w] != "frame" } {
		destroy $w
	    } else { return }
	}
	frame $w
	pack forget .gid.central
	pack $w -fill x -side bottom
	catch { pack .gid.central -fill both -expand yes }
	set GidPriv(PrePostEntryWindowGeom) "INSIDE {} 1 BottomEntryFrame"
    } else {
	if { ![info exists GidPriv(PrePostEntryWindowGeom)] || \
		[lindex $GidPriv(PrePostEntryWindowGeom) 1] == "" } {
	    set hh [winfo x .gid]
	    set vv [expr [winfo y .gid]+[winfo height .gid]+25]
	    set GidPriv(PrePostEntryWindowGeom) \
		    "OPEN [winfo width .gid]x100+$hh+$vv 1 BottomEntryFrame"
	}
	InitWindow $w "Enter commands" PrePostEntryWindowGeom BottomEntryFrame
	update idletasks
	wm protocol $w WM_DELETE_WINDOW "wm withdraw $w"

	foreach i [bind .gid] {
	    bind $w $i [bind .gid $i]
	}
	if { $tcl_platform(platform) != "windows" } {
	    bind .gid <FocusIn> "catch \"focus $w.e\" "
	    bind $w <Destroy> "+ bind .gid <FocusIn> {}"
	}

	if { $action == "NONE" } {
	    set GidPriv(PrePostEntryWindowGeom) "NONE {} 1 BottomEntryFrame"
	    wm withdraw $w
	}
    }

    $w conf -background $GidPriv(ToolbarBg)
    frame $w.fle -bg $GidPriv(ToolbarBg) 
    label $w.l -text "Command:" -bg $GidPriv(ToolbarBg) 
    bind $w.l <1> "MenuInCommandButton $w.e %X %Y"
    entry $w.e -relief sunken -background $GidPriv(CommandLineBg)

    #label $w.lcoord -bg $GidPriv(ToolbarBg) -textvariable GidPriv(Coordinates)


    frame $w.fwarn -relief groove -bd 2
    scrollbar $w.fwarn.yscroll  -takefocus 0 \
	    -command "$w.fwarn.list yview" -background $GidPriv(ToolbarBg) \
	    -bd 1 -relief sunken
    listbox $w.fwarn.list -yscroll "$w.fwarn.yscroll \
	    set" -takefocus 0 -background $GidPriv(ToolbarBg) -relief groove -borderwidth 4

    if { [info exists GidPriv(havecontextualbutton)] && $GidPriv(havecontextualbutton)} {
	frame $w.fwarn.buts
	menubutton $w.fwarn.buts.cont -bitmap @$GIDDEFAULT/bitmaps/contextual \
		-bg white -fg black -bd 1 -highlightthickness 0 -relief raised \
		-menu $w.fwarn.buts.cont.m -direction above
	menu $w.fwarn.buts.cont.m 
	
	bind $w.fwarn.buts.cont <1> {
	    ContextualSubMenu %W.m
	    if {$tkPriv(inMenubutton) != ""} { 
		tkMbPost $tkPriv(inMenubutton) %X %Y
	    }
	    break
	}
    
	GidHelpT $w.fwarn.buts.cont "This menu contains all contextual options " \
		"that current command has."
	buttonT $w.fwarn.buts.escape -bitmap @$GIDDEFAULT/bitmaps/escape \
		-bg white -fg black -bd 1 -highlightthickness 0 -relief raised \
		-command ".gid.central.s process escape"
	GidHelpT $w.fwarn.buts.escape "This buttons is the 'Escape' button. Which "\
		"finishes most commands.\nAccelerator: ESC"
	pack $w.fwarn.buts.cont -side top -padx 1 -pady 1
	pack $w.fwarn.buts.escape -side top -padx 1 -pady 1
	pack $w.fwarn.buts -side right
    }

    if { [info exists ListboxContents] } {
	foreach i $ListboxContents {
	    $w.fwarn.list ins end $i
	}
	$w.fwarn.list see end
    }

    if {[winfo class $w] != "Toplevel" } { 
	$w.fwarn.list conf -width 20 -height 2
    }
    
    #coordenadas en posicion vertical
    frame $w.fcoord -bg $GidPriv(ToolbarBg) -relief groove -bd 2
    set GidPriv(CoordFrame) $w.fcoord
    set GidPriv(CoordFrame,uso) coordenadas
    DefineCoordFrame 

    proc UpdateLabelCoordinates { w  } { 
        global GidPriv GIDDEFAULT
	if { "$GidPriv(CoordFrame,uso)" != "coordenadas" || ! [winfo exist $w.fcoord] } { return}
	if { [scan $GidPriv(Coordinates) "x=%g y=%g z=%g" x y z] == 3 } { 
	    $w.fcoord.lx configure -text "x=[CorrectExp [format $GidPriv(RealFormat,Default) $x]]" -state normal
	    $w.fcoord.ly configure -text "y=[CorrectExp [format $GidPriv(RealFormat,Default) $y]]" -state normal
	    $w.fcoord.lz configure -text "z=[CorrectExp [format $GidPriv(RealFormat,Default) $z]]" -state normal
	    $w.fcoord.lz configure -image ""
	} else {
            if { $GidPriv(Coordinates) == "" } {
		$w.fcoord.lx configure -state disabled
		$w.fcoord.ly configure -state disabled
		$w.fcoord.lz configure -state disabled
	    } else {
		$w.fcoord.lx configure -text "Orthogonal" -state disabled
		$w.fcoord.ly configure -text "view to Z" -state disabled
		$w.fcoord.lz configure -image [image create photo  -file \
			$GIDDEFAULT/bitmaps/no_create_point.gif] -state disabled
	    }
	}
    }
    trace var GidPriv(Coordinates) w "UpdateLabelCoordinates $w ;#"
    
    $w.fwarn.list conf -selectmode single
    pack $w.fwarn.yscroll -side right -fill y
    pack $w.fwarn.list -expand yes -fill both -side left
    
    pack $w.fle -fill x -side bottom -expand yes -pady 2 -padx 2
    pack $w.fwarn -fill both -side top -expand yes

   
    grid $w.l $w.e  -in $w.fle -pady 0 -padx 5 -sticky ew
    grid conf $w.l -sticky w
 

    grid columnconf $w.fle 1 -weight 1

    #set same minsize in ChangeVariables.tcl if ChangeVarInfo(Displaycoordinates) is modified
    #after read preferences, if not displaycoordinates hide coord. label
    if { !$GidPriv(Displaycoordinates) } {
	pack forget .gid.comm.fcoord
    }

    


    GidHelpT "$w.fwarn $w.e" "Here are output the process messages. At the same time, it is " \
	    " possible to enter written commands or point coordinates or entities " \
	    "labels. Use <Tab> to expand commands."

    GidHelpT $w.l "Press mouse button 1 over it to get a commands menu."

    MakeBottomEntryBindings

    # para dejar que el boton del medio mueva la barra de scroll
    bind $w.fwarn.yscroll <ButtonPress-2> ""
    bind $w.fcoord <1> "SetCoord"
    bind $w.fcoord.lx <1> "SetCoord"
    bind $w.fcoord.ly <1> "SetCoord"
    bind $w.fcoord.lz <1> "SetCoord"

# check new tab options in entry
#     if { [winfo exists .wSetCoord] } {
# 	bind $w.e <Tab> "focus .wSetCoord.xe ; break"
#     }
}


proc RightButtons { {action ""} { w .gid.buts } } {
    global GidPriv GIDDEFAULT ActionsMenuVar
###puts " · -> '$action' '$w'"
    if { $action == "" && [winfo exists $w] } { return }
    if { $action == "INSIDE" || ($action == "" && \
	    (![info exists GidPriv(PrePostRightButWindowGeom)] || \
	    [lindex $GidPriv(PrePostRightButWindowGeom) 0] == "INSIDE")) } {
	if { [winfo exists $w] } {
	    if { [winfo class $w] != "frame" } {
		destroy $w
	    } else { return }
	}
	frame $w -relief flat  -borderwidth 0
	pack forget .gid.central.s
	pack $w -side right -fill y -in .gid.central
	catch { pack .gid.central.s -fill both -expand yes -side left}
	set GidPriv(PrePostRightButWindowGeom) "INSIDE {} 1 RightButtons"
    } elseif { $action == "OPEN" || \
	    ($action == "" && [lindex $GidPriv(PrePostRightButWindowGeom) 0] \
	    == "OPEN") } {
	if { ![info exists GidPriv(PrePostRightButWindowGeom)] || \
		[lindex $GidPriv(PrePostRightButWindowGeom) 1] == "" } {
	    set GidPriv(PrePostRightButWindowGeom) \
		    "OPEN 130x300+[expr [winfo x .gid]+[winfo width .gid] \
		    +10]+[expr [winfo y .gid]+25] RightButtons"
	}
###puts " · -> InitWindow"
	InitWindow $w "Command buttons" PrePostRightButWindowGeom RightButtons
	wm transient $w .gid
    } else {
	catch { destroy $w }
	set GidPriv(PrePostRightButWindowGeom) "NONE {} 1 RightButtons"
	return
    }
###puts " · -> frames"
    frame .gid.buts.f -width 130 -height 100 -relief flat -bd 2 -background $GidPriv(ToolbarBg)
    pack propagate .gid.buts.f no
    pack .gid.buts.f -side top -fill both -expand yes -padx 0 -pady 0
    bind .gid.buts <Configure> { 
	incr DelayedConfigureButsVar
	after idle DelayedConfigureButsFunc
    }
    for {set i 0 } { $i<100 } { incr i } {
	button $w.f.b$i -anchor w -width 14 -takefocus 0 -bd 1 -background $GidPriv(ToolbarBg) -padx 4 -font SmallFont
    }
    set reqwidth [ winfo reqwidth $w.f.b0]
    .gid.buts.f conf -width [ expr $reqwidth + 8]
    button $w.f.ar -bitmap @$GIDDEFAULT/bitmaps/arrow-r-16 -takefocus 0 -bd 1 -bg $GidPriv(ToolbarBg) -fg blue
    button $w.f.al -bitmap @$GIDDEFAULT/bitmaps/arrow-l-16 -takefocus 0 -bd 1 -bg $GidPriv(ToolbarBg) -fg blue

    foreach i [bind .gid] {
	bind $w $i [bind .gid $i]
    }
###puts " · -> GidHelpT"
    GidHelpT $w "These buttons are a direct access to the GiD commands"
    bind $w <2> { .gid.central.s button 2 %x %y }
    
    bind $w <Right> "if \[winfo ismapped $w.f.ar] \"$w.f.ar invoke\""
    bind $w <Left> "if \[winfo ismapped $w.f.al] \"$w.f.al invoke\""
    
###puts " · -> [info exists ActionsMenuVar] -> { SetButtons }"
    if { [info exists ActionsMenuVar] } { SetButtons }
###puts " · -> FIN"
}

proc UnMapAllWindows { w } {
    global GidPriv
    if { $w != ".gid" || ![info exists GidPriv(TopLevelsList)] } { return }
    foreach i $GidPriv(TopLevelsList) {
	if { [winfo exists $i] && [winfo ismapped $i] } {
	    wm withdraw $i
	}
    }
}

proc MapAllWindows { w } {
    global GidPriv
    if { $w != ".gid"  || ![info exists GidPriv(TopLevelsList)] } { return }
    foreach i $GidPriv(TopLevelsList) {
	if { [winfo exists $i] && ![winfo ismapped $i] } {
	    catch { wm deiconify $i }
	}
    }
}


proc OpenTextFromFile { title FileNamebase offset { offset2 -1} { quit no } } {
    global GidPriv tcl_platform

    if { [winfo exists .gid] } {
	if { [winfo exists .textwin] } { destroy .textwin }
	set w .gid.textwin
    } else { set w .textwin }

    if { $offset2 != -1 } {

	set FileName2 [lindex $FileNamebase 1]
	set FileName [lindex $FileNamebase 0]
    } else {
	set FileName $FileNamebase
    }

    set FileNameGood 1
    if { ![file readable $FileName] } { set FileNameGood  0 }
    if { $offset >= [file size $FileName] } { set FileNameGood  0 }
    if { $FileNameGood == 1 } {
	set f [open $FileName r]
	seek $f $offset
	if { [eof $f] } { close $f ; set FileNameGood  0 }
    }

    if { $offset2 == -1 && $FileNameGood == 0 } { return }

    set FileNameGood2 0
    if { $offset2 != -1 } { 
	set FileNameGood2 1
	if { ![file readable $FileName2] } { set FileNameGood2  0 }
	if { $FileNameGood2 == 1 && $offset2 >= [file size $FileName2] } { 
	    set FileNameGood2 0
	}
	if { $FileNameGood2 == 1 } {
	    set f2 [open $FileName2 r]
	    seek $f2 $offset2
	    if { [eof $f2] } { close $f2 ;set FileNameGood2 0 }
	}
	if { $FileNameGood == 0 && $FileNameGood2 == 0 } { return }
    }

    set CreatingWindow 0
    if { ![winfo exists $w] || $title != [wm title $w] } {

	set CreatingWindow 1

	InitWindow $w $title PrePostTextWindowGeom
	
	frame $w.f
	text $w.f.t -width 50  -yscroll "$w.f.yscroll set" -bd 1
	scrollbar $w.f.yscroll -relief sunken -command "$w.f.t yview" -bd 1 \
	    -elementborderwidth 1
	pack $w.f.yscroll -side right -fill y -pady 5
	pack $w.f.t  -expand yes -fill both -anchor nw -padx 5 -pady 5
	button $w.b -text close -command "destroy $w" -bd 1
	focus $w.b
	pack $w.b -side bottom -pady 2
	pack $w.f -side top -fill both -expand yes -side top
	update
	
	scan [ winfo geometry $w] %dx%d ww hh
	if { ( $ww < 200) || ( $hh < 200)} {
	    wm geometry $w 200x200
	}
    }

    $w.f.t conf -state normal

    if { $FileNameGood == 1 } {
	while { ![eof $f] } {
	    $w.f.t ins end [gets $f]\n
	}
	close $f 
    }
    if { $FileNameGood2 == 1 } {
	while { ![eof $f2] } {
	    $w.f.t ins end [gets $f2]\n
	}
	close $f2
    }
    $w.f.t see [$w.f.t index "end-2l"]

    regsub {\..*} [$w.f.t index end] {} NumLines
    incr NumLines -1
    if { $NumLines > 20 } { set NumLines 20 }

    if { $tcl_platform(platform) != "windows" } {
	$w.f.t conf -state disabled
    }
    
    if { $CreatingWindow == 1 } {
	set hei $NumLines
	if { $hei < 6 } { set hei 6 }
	$w.f.t conf -height $hei
    } 

    if { $quit != "no" } {
	$w.b conf -text Quit
	tkwait visibility $w
	raise $w
	grab $w
	tkwait window $w
    }
}

package require progressbar 1.2

proc ProgressInMeshing { NumSurfs NumVols isurf ivol SurfFactor VolFactor} {
    global GidPriv

    set w .gid.wprogress

    if { ![winfo exists $w] } {

	if { $isurf == $NumSurfs && $ivol == $NumVols } { return }

        toplevel $w -class OverlayWindow

	bind $w <Destroy> "catch { unset GidPriv(StopMeshing) }"

	if { [winfo cells $w] < 6 } {
	    set metercolor white
	} else { set metercolor blue }


	wm title $w "Progress in meshing"
	set pare [winfo parent $w]
	set x [expr [winfo x $pare]+[winfo width $pare ]/2- [winfo reqwidth $w]/2]
	set y [expr [winfo y $pare]+[winfo height $pare ]/2- [winfo reqheight $w]/2]

	WmGidGeom $w +$x+$y

	$w conf -cursor watch

	foreach i "surface volume" {
	    if { $i == "volume" && $NumVols == 0 } { break }
	    frame $w.$i -relief ridge -bd 2
	    label $w.$i.l1 -text "Total number of ${i}s: "
	    if { $i == "surface" } {
		label $w.$i.l2 -text $NumSurfs
	    } else {
		label $w.$i.l2 -text $NumVols
	    }
	    label $w.$i.l3 -text "Meshed $i:"
	    label $w.$i.l4 -text 0 -relief sunken -width 5
#  	    frame $w.$i.f -relief sunken -bd 2 -height 20
#  	    frame $w.$i.f.f -bg $metercolor
	    set wp [::progressbar::progressbar $w.$i.f -variable ::progressbar::var$i -width 200 -background [ $w.$i cget -background]]
	    set ::progressbar::var$i 0
	    
	    grid $w.$i.l1 $w.$i.l2 -sticky w -padx 3
	    grid $w.$i.l3 $w.$i.l4 -sticky w -padx 3 -pady 3
	    grid $wp - -padx 3
#  	    grid $w.$i.f - -sticky ew -padx 3
#  	    place $w.$i.f.f -x 0 -y 0 -relheight 1 -relwidth 0
	    
	    
	    grid $w.$i -sticky ewns -padx 5 -pady 5
	}
	grid columnconf $w 0 -weight 1
	grid rowconf $w 0 -weight 1
	if {$NumVols != 0 } { grid rowconf $w 1 -weight 1 }

	button $w.stop -text Stop -command { 
	    set GidPriv(StopMeshing) 1
	}
	grid $w.stop -pady 2
	focus $w.stop
	grab $w

    }

    if { $isurf != [$w.surface.l4 cget -text] || $SurfFactor>0.05 } {
	$w.surface.l4 conf -text $isurf
	set factor [expr (double($isurf)+$SurfFactor)/$NumSurfs]
#  	place $w.surface.f.f -x 0 -y 0 -relheight 1 \
#  		-relwidth $factor
	set ::progressbar::varsurface [expr int($factor*100)]
    }

    if { $NumVols != 0 && ($ivol != [$w.volume.l4 cget -text] || $VolFactor>0.05) } {
	$w.volume.l4 conf -text $ivol
	set factor [expr (double($ivol)+$VolFactor)/$NumVols]
#  	place $w.volume.f.f -x 0 -y 0 -relheight 1 \
#  		-relwidth $factor
	set ::progressbar::varvolume [expr int($factor*100)]
    }

    update 

    if { $isurf == $NumSurfs && $ivol == $NumVols } {
	after idle destroy $w
    }


}


proc WmGidGeom { w geom } {
    global tcl_platform

    set x 5
    set y 20
    set yeswh 1

    set iszoomed 0
    if { [lindex $geom 0] == "ZOOMED" } {
	set geom [lindex $geom 1]
	set iszoomed 1
    }

    set screenwidth [winfo screenwidth $w]
    set screenheight [winfo screenheight $w]

    if { $geom ==  "" } {
	set x [expr $screenwidth/3]
	set y [expr $screenheight/3]
	set geom +${x}+$y
    }

    if { ![regexp {^([0-9]*)x([0-9]*)([-+]*[0-9]*)([-+]*[0-9]*)$} $geom trash \
	    width height x y] } {
	if { ![regexp {([-+]*[0-9]*)([-+]+[0-9]*)$} $geom trash x y] } {
	    wm geom $w +32+32
	    return
	    error "couldn't compute geometry: $geom"
	}
	set width [winfo reqwidth $w]
	set height [winfo reqheight $w]
	set yeswh 0
    }

    if { ![regsub {[+]-} $x {-} x] } {
	if { $x<0 } { set x [expr $screenwidth+$x-$width] }
    }
    if { ![regsub {[+]-} $y {-} y] } {
	if { $y<0 } { set y [expr $screenheight+$y-$height] }
    }

    if { $x < -15 } { set x 5 }
    if { $y < -15 } { set y 20 }

    if { [expr $x+$width] > [expr $screenwidth+15] } {
	set x [expr $screenwidth-$width]
    }
    if { [expr $y+$height] > [expr $screenheight+15] } {
	set y [expr $screenheight-$height]
    }

    
    if { $x < -15 } { set width [expr $width+$x+5] }
    if { $y < -15 } { set height [expr $height+$y+5] }

    if { ![regexp {[+]} $x] } { set x +$x}
    if { ![regexp {[+]} $y] } { set y +$y}

    if { $yeswh } {
	wm geom $w ${width}x$height$x$y
    } else {
	wm geom $w $x$y
    }

    if { $iszoomed && $tcl_platform(platform) == "windows" } {
	wm state $w zoomed
    }

}

# proc IsWord
#
# w: parent window
# type -        Can be:
#                        word:    word without spaces
#                        any:     anything
#                        real:    real
#                        real+:   positive real
#                        int:     int
#                        int+:    positive int

proc IsWord { type word { w .gid } { PrintError no } } {

    switch $type {
	word {
	    if { ![regexp {^[  ]*[^ \t]+[  ]*$} $word] } {
		set errorRes "A single word must be entered."
	    }
	}
	real {
	    if { ![regexp \
   {^[  ]*([+-]?([0-9]+\.?[0-9]*|[0-9]*\.?[0-9]+)([eE][+-]?[0-9]+)?)[  ]*$} \
		    $word] } {
		set errorRes "One number must be entered."
	    }	   
	}
	real+ {
	    if { ![regexp \
    {^[  ]*([+]?([0-9]+\.?[0-9]*|[0-9]*\.?[0-9]+)([eE][+-]?[0-9]+)?)[  ]*$} \
		    $word] } {
		set errorRes "One positive number must be entered."
	    }	  
	}
	int {
	    if { ![regexp \
		    {^[  ]*[+-]?[0-9]+[  ]*$} \
		    $word] } {
		set errorRes "One integer number must be entered."
	    }	   
	}
	int+ {
	    if { ![regexp \
		    {^[  ]*[+]?[0-9]*[1-9]+[0-9]*[  ]*$} \
		    $word] } {
		set errorRes "One positive integer number must be entered."
	    }	   
	}
    }
    if { [info exists errorRes] } {
	if { $PrintError != "no" } {
	    tk_dialogRAM $w.tempwinerr {Error window} "$errorRes $PrintError" \
		    error 0 OK
	}
	return 0
    } else {
	return 1
    }
}

proc SetProblemTypeChoose { projecttype } {

    set probname [lindex [.gid.central.s info Project] 1]
    set changes [lindex [.gid.central.s info Project] 2]

    set putyes ""

    if { $changes || $probname != "UNNAMED" } {
	set retval [tk_dialogRAMFull .gid.tempwinw {Dialog window} \
			"All data information(materials,conditions,data) will be lost. OK?" \
			"" "" gidquestionhead 0 OK cancel]
	if { $retval == 1 } { return }
	set putyes yes
    }

    .gid.central.s process escape escape escape escape data defaults ProblemType \
	    $putyes \"$projecttype\" escape
}


proc SetProblemTypeMenuForDir { dir menu current path } {
    global GidPriv

    set inum 0

    if { ![info exists GidPriv(dirfiles,$dir)] } {
	set GidPriv(dirfiles,$dir) [glob -nocomplain [file join $dir *]]
	set cacheon 0
    } else { set cacheon 1 }

    set files ""
    foreach i $GidPriv(dirfiles,$dir) {
	lappend files [file tail $i]
    }
    foreach i [lsort -dictionary $files] {
	set ifull [file join $dir $i]
	if { [file extension $i] == ".gid" } {
	    set i [file root $i]
	    if { $i != $current } {
		$menu add command -label $i -command [list SetProblemTypeChoose \
			[file join $path $i]]
	    } else {
		$menu add check -label $i -command [list SetProblemTypeChoose \
			[file join $path $i]] -variable GidPriv(PTMFD) -onvalue 1
		set GidPriv(PTMFD) 1
	    }
	    incr inum
	} elseif { ($cacheon && [info exists GidPriv(dirfiles,$ifull)]) || \
			(!$cacheon && [file isdir $full]) } {
	    #set ishort [file root $i]
	    set ishort $i
	    set newmenu $menu.m$inum
	    $menu add cascade -label $i -menu $newmenu
	    menu $newmenu
	    if { $ishort == [lindex $current 0] } {
		set inumin [SetProblemTypeMenuForDir $ifull $newmenu [lrange $current 1 end] \
			[file join $path $i]]
	    } else {
		set inumin [SetProblemTypeMenuForDir $ifull $newmenu "" \
			[file join $path $i]]
	    }
	    if { $inumin == 0 } {
		$menu delete end
		destroy $newmenu
	    } else { incr inum $inumin }
	}
    }
    return $inum
}


proc SetProblemTypeMenu { menu } {
    global GIDDEFAULT GidPriv

    set maindir [file join $GIDDEFAULT problemtypes]
    if { [$menu entrycget end -label] == "Others..." && \
	     [info exists GidPriv(dirfiles,$maindir)] } { return }
    
    $menu del 0 end
    foreach i [winfo children $menu] { destroy $i }
    
    set current [file split [lindex [.gid.central.s info Project] 0]]

    set inum 0

    if { ![info exists GidPriv(dirfiles,$GIDDEFAULT)] } {
	set GidPriv(dirfiles,$GIDDEFAULT) [glob -nocomplain [file join $GIDDEFAULT *.gid]]
    }

    set files ""
    foreach i $GidPriv(dirfiles,$GIDDEFAULT) {
	lappend files [file tail [file root $i]]
    }
    foreach i [lsort -dictionary $files] {
	if { $i != $current } {
	    $menu add command -label $i -command "SetProblemTypeChoose $i"
	    incr inum
	} else {
	    $menu add check -label $i -command "SetProblemTypeChoose $i" \
		    -variable GidPriv(PTMFD) -onvalue 1
	    set GidPriv(PTMFD) 1
	}
    }
    if { $inum } { $menu add separator }
    SetProblemTypeMenuForDir [file join $GIDDEFAULT problemtypes] \
	$menu $current ""

    $menu add separator

    $menu add command -label "Transform..." -command \
	    ".central.s process escape escape escape escape \
	    data defaults TransfProblem"
    $menu add command -label "Internet Retrieve..." -command \
	RetrievePT::OpenGUI

    $menu add command -label "Others..." -command \
	    ".central.s process escape escape escape escape \
	    data defaults ProblemType"
}

proc ClearCacheFormProblemtypeMenuDir {} {
    global GidPriv
    
    foreach i [array names GidPriv dirfiles,*] {
	unset GidPriv($i)
    }
}

proc FastCacheFromProblemtypeMenuDir { dir } { 
    global GidPriv

    if { ![info exists GidPriv(dirfiles,$dir)] } {
	set GidPriv(dirfiles,$dir) [glob -nocomplain [file join $dir *]]
    }
    set files ""
    foreach i $GidPriv(dirfiles,$dir) {
	lappend files [file tail $i]
    }
    foreach i [lsort -dictionary $files] {
	set ifull [file join $dir $i]
	if { [file extension $i] == ".gid" } {
	    # nothing
	} elseif { [file isdir $ifull] } {
	    FastCacheFromProblemtypeMenuDir $ifull
	}
    }
}

proc FastCacheFromProblemtypeMenu {} {
    global GIDDEFAULT GidPriv

    if { ![info exists GidPriv(dirfiles,$GIDDEFAULT)] } {
	set GidPriv(dirfiles,$GIDDEFAULT) [glob -nocomplain [file join $GIDDEFAULT *.gid]]
    }
    FastCacheFromProblemtypeMenuDir [file join $GIDDEFAULT problemtypes]
}

#  proc SetProblemTypeMenu { menu } {
#      global GIDDEFAULT GidPriv
#      $menu del 0 end
    
#      set current [lindex [.gid.central.s info Project] 0]

#      set probt ""
#      foreach i [glob -nocomplain [file join $GIDDEFAULT *.gid]] {
#  	lappend probt [file tail [file root $i]]
#      }
#      foreach i [glob -nocomplain [file join $GIDDEFAULT problemtypes *.gid]] {
#  	lappend probt [file tail [file root $i]]
#      }
#      set probt [lsort -dictionary $probt]

#      set words ""
#      if { $probt != "" } {
#  	foreach i $probt {
#  	    if { $current != $i } {
#  		lappend words [list $i "SetProblemTypeChoose $i"]
#  	    } else {
#  		lappend words [list $i "SetProblemTypeChoose $i" check]
#  	    }
#  	}
#      }
#      lappend words [list "Others..." ".central.s process escape escape escape escape data defaults problemtype"]
#      rmenuconf $menu $words
#  }

proc GetProblemTypes { } {
    global GIDDEFAULT GidPriv
    
    set current [lindex [.gid.central.s info Project] 0]

    set probt ""
    foreach i [glob -nocomplain [file join $GIDDEFAULT *.gid]] {
	lappend probt [file tail [file root $i]]
    }
    set probt [lsort -dictionary $probt]

    return $probt
}


proc AdvanceBar { numerator divisor  inum { title "" } { maintext ""} { width 0} \
	{ dentro 0} {parent .gid} } {
    global GidPriv tcl_platform

    if { $parent == ".gid" } {
	set w .gid._wadvancebar 
    } else { set w $parent._wadvancebar }

    if { !$dentro && ![winfo exists $w] } {
	if { $numerator != 0 } { return }

	if 1 {
	    
	    toplevel $w -class OverlayWindow
	    
	    if { [winfo cells $w] < 6 } {
		set metercolor white
	    } else { set metercolor blue }
	    
	    
	    wm title $w $title
	    set pare [winfo parent $w]
	    set x [expr [winfo x $pare]+[winfo width $pare ]/2- \
		    [winfo reqwidth $w]/2]
	    set y [expr [winfo y $pare]+[winfo height $pare ]/2- \
		    [winfo reqheight $w]]
	    if { $x < 0 } { set x 0 }
	    if { $y < 0 } { set y 0 }
	    WmGidGeom $w +$x+$y
	    if { $tcl_platform(platform) == "windows" } {
		wm transient $w .gid
	    }
	    $w conf -cursor watch
	} else {
	    frame $w -bd 2 -relief groove
	    place $w -in .gid.comm -x 0 -y 0 -width 100
	    raise $w
	    set metercolor blue
	}

	frame $w.pp -relief ridge -bd 2

	if { [winfo class $w] != "Frame" } {
	    if { $width} {
		label $w.pp.l3 -width $width -text $maintext
	    } else {
		label $w.pp.l3 -text $maintext
	    }
	    label $w.pp.l4 -text 0 -relief sunken -width 8 -bd 1
	}
	set wp [::progressbar::progressbar $w.pp.f -variable ::progressbar::var \
		-width 200 -background [ $w.pp cget -background]]
	set ::progressbar::var 0
#  	frame $w.pp.f -relief sunken -bd 2 -height 20
#  	frame $w.pp.f.f -bg $metercolor
	
	if { [winfo class $w] != "Frame" } {
	    grid $w.pp.l3 $w.pp.l4 -sticky w -padx 3 -pady 3
	}
#  	grid $w.pp.f - -sticky ew -padx 3
#  	place $w.pp.f.f -in $w.pp.f -x 0 -y 0 -relheight 1 -relwidth 0
	grid $wp - -padx 3
	    
	grid $w.pp -sticky ewns -padx 5 -pady 5
	grid columnconf $w 0 -weight 1
	grid rowconf $w 0 -weight 1

	button $w.stop -text Stop -command { 
	    set GidPriv(StopLoading) 1
	} -bd 1
	##if { [winfo class $w] != "Frame" } {
	    grid $w.stop -row 1 -column 0 -pady 4
	##} else {
	##    grid $w.stop -row 0 -column 1
	##}
	#tkwait visibility $w
	#grab $w
	focus $w.stop
	return
    } else {
	# dentro
	if { $dentro && ( "$GidPriv(CoordFrame,uso)" != "progreso")} {
	    set w $GidPriv(CoordFrame)
	    OlvidaCoordFrame
	    set GidPriv(CoordFrame,uso) progreso
	    frame $w.pp -relief ridge -bd 0 -background [ $w cget -background]
	    label $w.pp.l3 -text $maintext -background [ $w cget -background]
	    set ancho 100
	    if { $width} {
		set na [ expr $width * 6]
		if { $na > $ancho} {
		    set ancho $na
		}
	    }
	    set wp [::progressbar::progressbar $w.pp.f -variable ::progressbar::var \
		    -width $ancho -background [ $w cget -background]]
	    set ::progressbar::var 0
	    grid $w.pp.l3 -sticky w
	    grid $wp -padx 2
	    
	    button $w.stop -text Stop -command { 
		set GidPriv(StopLoading) 1
	    }
	    
	    grid $w.pp -sticky ewns -padx 0 -pady 0 -row 0 -column 0
	    grid $w.stop -padx 0 -pady 0 -row 1 -column 0

	    #grid columnconf $w 0 -weight 1
	    #grid rowconf $w 0 -weight 1
	    focus $w.stop
	    return
	}
    }

    set proportion [expr double($numerator)/$divisor]

    if { $dentro} {
	set w $GidPriv(CoordFrame)
    }

    if { [winfo exists $w.pp.l4] } {
	$w.pp.l4 conf -text $inum
    }

    if { [winfo exists $w.pp.l3] && ( $maintext != "") } {
	if { $width} {
	    $w.pp.l3 conf -text $maintext -width $width
	} else {
	    $w.pp.l3 conf -text $maintext
	}
    }

#      place $w.pp.f.f -x 0 -y 0 -relheight 1 \
#  	    -relwidth $proportion

    set ::progressbar::var [expr int($proportion*100)]

    update

    if { $numerator == $divisor} {
	catch { focus .gid.comm.e }
	if { !$dentro} {
	    destroy $w
	} else {
	    set w $GidPriv(CoordFrame)
	    grid forget	$w.pp.f
	    grid forget	$w.pp.l3
	    grid forget	$w.pp
	    grid forget	$w.stop
	    destroy $w.pp.f
	    destroy $w.pp.l3
	    destroy $w.pp
	    destroy $w.stop
	    set GidPriv(CoordFrame,uso) coordenadas
	    DefineCoordFrame 0
	}
    }


}

proc SaveWinConfiguration { } {
    set file [Browser-ramR file write .gid \
		  {write window configuration}]
    if { $file == "" } { return }
    file delete $file
    WriteTCLDefaultsInFile $file
}


proc SetOptions { } {
    global tcl_platform GidPriv

    #aun no se ha pasado por ReadDefaultValues
    #SetGUIAppearanceColor
    
#     option add *Checkbutton*HighlightThickness 0
#     option add *Radiobutton*HighlightThickness 0
#     option add *Checkbutton*TakeFocus 0
#     option add *Radiobutton*TakeFocus 0
    option add *Entry*BorderWidth 1
    if { $tcl_platform(platform) != "windows" } {
	option add *Scrollbar*Width 10
	#option add *Scrollbar*BorderWidth 2
	option add *Scrollbar*BorderWidth 1
	option add *Button*BorderWidth 1
	#option add *Menu*BorderWidth 1
	#option add *Menu*HighlightThickness 1
    }
    option add *Menu*TearOff 0
  
    if { $tcl_platform(platform) != "windows" } {
	# si se cambia esta linea, hay que cambiarla mas abajo: proc SetGUIAppearanceColor ...
	option add *background AntiqueWhite3
	option add *Button*background bisque3
	option add *Menu*background bisque3
	option add *Button*foreground black
	option add *Entry*background thistle
	option add *DisabledForeground grey60
	option add *HighlightBackground AntiqueWhite3
    }


#    tk_setPalette AntiqueWhite3

    SetFontsDefault
}

proc SetFontsDefault {} {
    global tcl_platform
    set disp_height [winfo screenheight .gid]
    if { $disp_height > 1024} {
	set fontsize 12
    } elseif { $disp_height > 768 && $disp_height <= 1024 } {
	set fontsize 12
    } elseif { $disp_height > 600 && $disp_height <= 768 } {
	# for linux (before it was 8)
	set fontsize 10
    } elseif { $disp_height > 480 && $disp_height <= 600 } {
	set fontsize 8
    } else {
	set fontsize 6
    }

    if { $tcl_platform(os) == "IRIX" } {
	font create NormalFont -family helvetica -size 10 -slant roman
	option add *font -*-helvetica-medium-r-*-*-17-*-*-*-*-*-*-*
	font create BoldFont -weight bold -size $fontsize -family helvetica
    } elseif { $tcl_platform(platform) != "windows" } {
	font create NormalFont -family helvetica -size $fontsize
	font create BoldFont -weight bold -size $fontsize -family helvetica
	option add *font NormalFont
    } else {
	set fontsize 8
	catch {
	  #kike, fuente demasiado grande
          #set size [expr [.central.s info menuheight]-4]
          set size [expr [.central.s info menuheight]-6]
	    font create NormalFont -family "MS Sans Serif" -size -$size
	    set fontsize [font actual NormalFont -size]
	    font delete NormalFont
	}
	font create NormalFont -family "MS Sans Serif" -size $fontsize
	font create BoldFont -size $fontsize -family "MS Sans Serif" -weight bold
 	option add *font NormalFont
    }

    set family [font conf NormalFont -family]
    font create FixedFont -size $fontsize -family Courier
    font create BigFont -family $family -size [expr int($fontsize*1.5)]
    font create SmallFont -family $family -size [expr int($fontsize-2)]
}


proc GiveBestGidDefaults {} {
    global GIDDEFAULTTCL
    set realw [winfo screenwidth .gid]
    foreach i [glob [file join $GIDDEFAULTTCL gidDefaults]*] {
	if { [regexp -nocase {gidDefaults([0-9]*)x([0-9]*)} $i trash w h] } {
	    if { $w == $realw } { return $i }
	    if { ![info exists bestf] || [expr abs($realw-$w)]< $bestdist } {
		set bestf $i
		set bestdist [expr abs($realw-$w)]
	    }
	}
    }
    if { [info exists bestf] } { return $bestf }
    return $GIDDEFAULTTCL/gidDefaults
}


proc ContextualSubMenu { w } {
    global ActionsMenuVar ActionsMenuVarType
    
    $w del 0 end
    if { $ActionsMenuVarType == "TMP" } {
	set words ""
	foreach i $ActionsMenuVar {
	    regsub -all {([a-z])([A-Z])} $i "\\1 \[string tolower \\2]" name
	    set name [subst $name]
	    set name [string toupper [string index $name 0]][string range $name 1 end]
	    if { $i == "Join" || $i == "NoJoin" } { append name " C-a" }
	    lappend words [list $name ".gid.central.s process $i"]
	}
	rmenuconf $w $words
    } else {
	rmenuconf $w  { { -NONE- "" } }
	$w entryconf end -state disabled
    }
}


proc SelectJoinOrNoJoin {} {
    global ActionsMenuVar

    if { [lsearch -exact $ActionsMenuVar Join] != -1 } {
	.gid.central.s process Join
    } elseif { [lsearch -exact $ActionsMenuVar NoJoin] != -1 } {
	.gid.central.s process NoJoin
    } 
}

proc UpdateGraphFramesBegin { w HorV x y} {
    global GidPriv
    bind $w <ButtonRelease-1> "UpdateGraphFramesEnd %W $x $y %x %y $HorV"
}

proc UpdateGraphFramesEnd { w xold yold x y HorV } {

    set master [lindex [grid info $w] 1]

    regexp -- {-row[ ]*([0-9]+)} [grid info $w] {} irow
    regexp -- {-column[ ]*([0-9]+)} [grid info $w] {} icol
    
    if { $HorV == "v" || $HorV == "hv"} {
	set newwidth1 [expr [lindex [grid bbox $master 0 0] 2]+$x]
	set newwidth2 [expr [lindex [grid bbox $master 2 0] 2]-$x]
	if { $newwidth1 < 0 } { set newwidth1 0 }
	if { $newwidth2 < 0 } { set newwidth2 0 }
	grid columnconf $master 0 -weight $newwidth1
	grid columnconf $master 2 -weight $newwidth2
    } 
    if { $HorV == "h" || $HorV == "hv"} {
	set newheight1 [expr [lindex [grid bbox $master 0 0] 3]+$y]
	set newheight2 [expr [lindex [grid bbox $master 0 2] 3]-$y]
	if { $newheight1 < 0 } { set newheight1 0 }
	if { $newheight2 < 0 } { set newheight2 0 }
	grid rowconf $master 0 -weight $newheight1
	grid rowconf $master 2 -weight $newheight2
    }
}

proc PackToglSeparator { w row col type } {
    switch $type {
	h {
	    $w conf -cursor sb_v_double_arrow
	    bind $w <1> "UpdateGraphFramesBegin %W h %x %y"
	    grid $w -in .gid.central.wins -row $row -col $col \
		    -sticky nsew
	}
	v {
	    $w conf -cursor sb_h_double_arrow
	    bind $w <1> "UpdateGraphFramesBegin %W v %x %y"
	    grid $w -in .gid.central.wins -row $row -col $col \
		    -sticky nsew
	}
	hv {
	    $w conf -cursor cross
	    bind $w <1> "UpdateGraphFramesBegin %W hv %x %y"
	    grid $w -in .gid.central.wins -row $row -col $col \
		    -sticky nsew
	}
    }
}

proc PackToglWindows { type } {
    
    if { ![winfo exists .gid.central.wins] } {
	PrepareToglForSeveralWindows
    }
    
    set totalnum [string index $type 0]
    set i 2
    while { [winfo exists .gid.central.wins.graphwin$i] } {
	incr i
    }
    incr i -1
    if { $i < $totalnum } { return }

    foreach i [grid slaves .gid.central.wins] { grid forget $i }
    for { set i 1 } { $i <= 5 } { incr i } {
	if { ![winfo exists .gid.central.wins.separator$i] } { 
	    frame .gid.central.wins.separator$i
	}
    }
    
    if { $type == "1" } {
	grid .gid.central.wins.graphwin1 -in .gid.central.wins \
		-row 0 -col 0 \
		-sticky nsew -columnspan 3  -rowspan 3 
	.gid.central.s SetPosition 1
    } elseif { $type == "2LR" || $type == "3L" } {
	grid .gid.central.wins.graphwin1 -rowspan 3 -row 0 -col 0 \
		-sticky nsew
	.gid.central.s SetPosition L
	PackToglSeparator .gid.central.wins.separator1 0 1 v
	if { $type == "2LR" } {
	    PackToglSeparator .gid.central.wins.separator2 1 1 v
	} else {
	    PackToglSeparator .gid.central.wins.separator2 1 1 hv
	}
	PackToglSeparator .gid.central.wins.separator3 2 1 v
    } elseif { $type == "2UD" || $type == "3U" } {
	grid .gid.central.wins.graphwin1 -columnspan 3 -row 0 -col 0 \
		-sticky nsew
	.gid.central.s SetPosition B
	PackToglSeparator .gid.central.wins.separator4 1 0 h
	if { $type == "2UD" } {
	    PackToglSeparator .gid.central.wins.separator2 1 1 v
	} else {
	    PackToglSeparator .gid.central.wins.separator2 1 1 hv
	}
	PackToglSeparator .gid.central.wins.separator5 1 2 h
    } else {
	grid .gid.central.wins.graphwin1 -row 0 -col 0 \
		-sticky nsew
	.gid.central.s SetPosition BL
	PackToglSeparator .gid.central.wins.separator1 0 1 v
	PackToglSeparator .gid.central.wins.separator2 1 1 hv
	PackToglSeparator .gid.central.wins.separator4 1 0 h
    }

    set icurr 2
    if { $type == "2UD" || $type == "3D" } {
	grid .gid.central.wins.graphwin$icurr -in .gid.central.wins \
		-columnspan 3 -row 2 -col 0 \
		-sticky nsew
	.gid.central.wins.graphwin${icurr}.s SetPosition T
	incr icurr
    } elseif { $type == "3R" || $type == "3U" || $type == "4" } {
	grid .gid.central.wins.graphwin$icurr -in .gid.central.wins -row 2 -col 0 \
		-sticky nsew
	.gid.central.wins.graphwin${icurr}.s SetPosition TL
	incr icurr
	PackToglSeparator .gid.central.wins.separator3 2 1 v
    }
    if { $type == "2LR" || $type == "3R" } {
  	grid .gid.central.wins.graphwin$icurr -in .gid.central.wins -rowspan 3 -row 0 -col 2 \
  		-sticky nsew
	.gid.central.wins.graphwin${icurr}.s SetPosition R
  	incr icurr
    } elseif { $type == "3L" || $type == "3D" || $type == "4" } {
	grid .gid.central.wins.graphwin$icurr -in .gid.central.wins \
		-rowspan 1 -row 0 -col 2 \
		-sticky nsew
	.gid.central.wins.graphwin${icurr}.s SetPosition BR
	incr icurr
	PackToglSeparator .gid.central.wins.separator5 1 2 h

    }

    if { $type == "3L" || $type == "3U" || $type == "4" } {
	grid .gid.central.wins.graphwin$icurr -in .gid.central.wins -row 2 -col 2 \
		-sticky nsew
	.gid.central.wins.graphwin${icurr}.s SetPosition TR
	incr icurr
    }

    grid columnconf .gid.central.wins 0 -weight 1
    grid rowconf .gid.central.wins 0 -weight 1

    grid columnconf .gid.central.wins 1 -weight 0 -minsize 1
    grid columnconf .gid.central.wins 2 -weight 1
    
    grid rowconf .gid.central.wins 1 -weight 0 -minsize 1
    grid rowconf .gid.central.wins 2 -weight 1


#      if { $type == 1 } {
#  	set i 5
#  	while { [winfo exists .gid.central.wins.graphwin$i] } { incr i }
#  	incr i -5
#  	if { $i == 0 } {
#  	    .gid.central.wins.wins.graphwin1 conf -bd 0
#  	}
#      }

}

proc GiveNumToglInteriorWins {} {
    set i 2
    while { [winfo exists .gid.central.wins.graphwin$i] } { incr i }
    incr i -1
    return $i
}

proc DestroyRemainingToglWindows { type } {

    if { "[string tolower $type]" == "ext" } { return }
    
    set totalnum [string index $type 0]
    set i [expr $totalnum+1]
    while { [winfo exists .gid.central.wins.graphwin$i] } {
  	destroy .gid.central.wins.graphwin$i
	incr i
    }
}

proc PrepareToglForSeveralWindows {} {

    frame .gid.central.wins
    pack .gid.central.wins -expand 1 -fill both
    frame .gid.central.wins.graphwin1 -bd 2 -relief groove
    raise .gid.central.s
    pack .gid.central.s -in .gid.central.wins.graphwin1 -expand 1 \
	    -fill both

    .gid.central.s conf -width 0 -height 0

    grid .gid.central.wins.graphwin1 -in .gid.central.wins -row 0 \
	    -col 0 -sticky nsew
    grid rowconf .gid.central.wins 0 -weight 1
    grid columnconf .gid.central.wins 0 -weight 1
}

proc CreateNewToglWindow { type } {
    global tcl_platform GidPriv

    if { ![winfo exists .gid.central.wins] } {
	PrepareToglForSeveralWindows
    }

    set type [string toupper $type]

    if { $type == "EXT" } {
	set i 5
    } else {
	set i 2
    }
    while { [winfo exists .gid.central.wins.graphwin$i] } { incr i }
    set w .gid.central.wins.graphwin$i
    
    if { $type == "EXT" } {
	InitWindow $w "View $i" NewWindow${i}WindowGeom 
	bind $w <Escape> ".central.s process escape"
	if { $GidPriv(GiDRuedas)} {
	    bind $w <MouseWheel> { MouseWheelEventToButtonEvent %D }
	}
	bind $w <Control-a> SelectJoinOrNoJoin
	set w $w.f
	frame $w -bd 2 -relief groove
	pack $w -expand 1 -fill both
    } else {
	frame $w -bd 2 -relief groove
	#PackToglWindows $type
    }

    set extra_flags ""
    
    if { $tcl_platform(platform) == "windows" } {
	if { $GidPriv(SoftwareOpenGL)} {
	    set extra_flags "-softrender true"
	}
    }

    if { [catch { \
	     eval [ subst "togl $w.s -rgba true -double true   \
	     -depth true -ident GID -privatecmap false -overlay 1 \
	     -width 100  -height 100 $extra_flags"] }]} {
	 eval [ subst "togl $w.s -rgba true -double true  \
		 -depth true -ident GID -privatecmap false -overlay 0 \
		 -width 100   -height 100 $extra_flags"]
    }
    
    $w.s conf -width 0 -height 0
    pack $w.s -fill both -expand yes

    bind $w.s <1> { 
	set GidPriv(PressingButton1) 1
	%W button 1 %x %y
	after 300 [list catch {  unset GidPriv(PressingButton1) } ]
    }
    bind $w.s <ButtonRelease-1> {
	if { [info exists GidPriv(PressingButton1)] } {
	    %W button -r -f 1 %x %y 
	    break
	}
	%W button -r 1 %x %y 
    }
    bind $w.s <2> { %W button 2 %x %y }
    bind $w.s <Motion> { %W motion %x %y }
    bind $w.s <Leave> { %W leave %x %y }
    bind $w.s <Enter> { %W enter %x %y }

    bind $w <Control-a> SelectJoinOrNoJoin
    
    bind $w.s <3> {
	#%W gidmakecurrent
	set x [expr [winfo rootx %W]+%x+2]
	set y [expr [winfo rooty %W]+%y]
	catch {
	    tk_popup .gid.phantom.display3dbutton $x $y 0
	}
    }
    foreach i [bind .gid] {
	bind $w $i [bind .gid $i]
    }
#     bind $w <FocusIn> "catch { focus .gid.comm.e }"
    #miguel 29.09.1998 porque tkwait?
    #tkwait window $w
    return $w
}



# to initialize
set GidHelp(HelpSystemActive) "" 
set GidHelp(helpcanceller) ""
set GidPriv(JustHelpActived) 0
set GidHelp(HelpLeaveBefore) ""
set GidHelp(JustDeleted) ""
set GidPriv(HelpSystem) .gid.helpsystem
set GidPriv(HelpSystemmenu) 0

proc DisplayGidHelp { w text but x y } {
    global GidPriv GidHelp

    if { $but != "menu" && ($GidHelp(JustDeleted) == $w || $GidHelp(JustDeleted) == "all") } { return }

    if { ![winfo exists $w] } { return }

    if { [winfo exists $GidPriv(HelpSystem)] } {
	if { $w == $GidHelp(HelpSystemActive) } { return }
	destroy $GidPriv(HelpSystem)
    }
    set tag ""
    if { [llength $w] == 2 } {
	set tag [lindex $w 1]
	set w [lindex $w 0]
    }

    set x [winfo pointerx $w]
    set y [winfo pointery $w]

    if { $but != "menu" } {
	if { $x < [winfo rootx $w] || $y < [winfo rooty $w] || \
		$x > [expr [winfo rootx $w]+[winfo width $w]] || \
		$y > [expr [winfo rooty $w]+[winfo height $w]] } {
	    return
	}
    }

    if { $y < [expr [winfo screenheight $w]/2.0] } {
	set y +[expr $y+3]
    } else {
	set y -[expr [winfo screenheight $w]-$y+3]
    }
    if { $x < [expr [winfo screenwidth $w]/2.0] } {
	set x +[expr $x+3]
    } else {
	set x -[expr [winfo screenwidth $w]-$x+3]
    }

    toplevel $GidPriv(HelpSystem)

    set GidHelp(HelpSystemActive) $w
    wm overrideredirect $GidPriv(HelpSystem) 1
    wm geom $GidPriv(HelpSystem) $x$y
    frame $GidPriv(HelpSystem).f -relief ridge -bg white -bd 2
    label $GidPriv(HelpSystem).f.l -bg white -fg black \
	    -justify left -text $text -wraplength 10c
    set link [ToolbarHelp $text]
    if { $link != "" } {
	button $GidPriv(HelpSystem).f.b -image [imagefrom points3.gif] \
		-command "directHelp $link" -bg white -bd 1
	bind $GidPriv(HelpSystem).f.b <1> {
	    uplevel #0 [list %W invoke]
	    destroy $GidPriv(HelpSystem)
	    break
	}
    }
    pack $GidPriv(HelpSystem).f.l -fill both -expand 1
    if { [winfo exists $GidPriv(HelpSystem).f.b] } {
	pack $GidPriv(HelpSystem).f.b -anchor e
    }
    pack $GidPriv(HelpSystem).f -fill both -expand 1

    if { $but == "enter" } {
	bind $GidPriv(HelpSystem) <1> "destroy $GidPriv(HelpSystem)"
	#bind $w <Leave> "catch { destroy $GidPriv(HelpSystem) } ; \
		#    bind $w <Leave> {}"
    } elseif { $but == "menu" } {
	if { [catch { tkwait visibility $GidPriv(HelpSystem) }] } { return }
	set oldfocus [focus]
	focus $GidPriv(HelpSystem)
	grab -global $GidPriv(HelpSystem)
	set GidPriv(HelpSystemmenu) 1
	bind $GidPriv(HelpSystem) <Destroy> "set GidPriv(HelpSystemmenu) 0"
 
	bind $GidPriv(HelpSystem) <1> "destroy $GidPriv(HelpSystem) ; focus $oldfocus"
	bind $GidPriv(HelpSystem) <2> "destroy $GidPriv(HelpSystem) ; focus $oldfocus"
	bind $GidPriv(HelpSystem) <3> "destroy $GidPriv(HelpSystem) ; focus $oldfocus"
	bind $GidPriv(HelpSystem) <Escape> "destroy $GidPriv(HelpSystem) ; focus $oldfocus"
    } else {
	bind $GidPriv(HelpSystem) <1> "destroy $GidPriv(HelpSystem)"
	if { $tag == "" } {
	    bind $w <ButtonRelease-$but> " \
		    catch { destroy $GidPriv(HelpSystem) } ; \
		    bind $w <ButtonRelease-$but> {}"
	} else {
	    $w tag bind $tag <ButtonRelease-$but> " \
		    catch { destroy $GidPriv(HelpSystem) } ; \
		    $w tag bind $tag <ButtonRelease-$but> {}"
	}   
    }
}

proc DisplayGidHelpMenu { w text type xbase ybase } {
    global GidHelp

    after cancel $GidHelp(helpcanceller)
    set GidHelp(helpcanceller) ""

    if { $GidHelp(HelpLeaveBefore) != "" } {
	bind $w <Leave> $GidHelp(HelpLeaveBefore)
    }
    set GidHelp(HelpLeaveBefore) ""

    set x $xbase ; set y $ybase

    catch { destroy .gid.__helpmenu }
    menu .gid.__helpmenu
    .gid.__helpmenu add command -label help -command \
	    "DisplayGidHelp $w [list $text] menu $xbase $ybase"
    if { $type == "helpandtools" } {
	.gid.__helpmenu add command -label "Configure toolbars" -command \
		TOBegin
    }
    tk_popup .gid.__helpmenu $x $y
    
    # si no es "helpandtools" es solo "help"
    # y queda un poco tonto poner un menu de solo una opcion
#      if { $type == "helpandtools" } {
#  	catch { destroy .gid.__helpmenu }
#  	menu .gid.__helpmenu
#  	.gid.__helpmenu add command -label help -command "ToolbarHelp [list $text]"
		
		
		
#  		#"DisplayGidHelp $w [list $text] menu $xbase $ybase"
#  	if { $type == "helpandtools" } {
#  	    .gid.__helpmenu add command -label "Configure toolbars" -command \
#  		    TOBegin
#  	}
#  	tk_popup .gid.__helpmenu $x $y
#      } else {
#  	DisplayGidHelp $w $text menu $xbase $ybase
#      }
}

proc DisplayGidHelpLeave { w x y { force no } } {
    global GidPriv GidHelp

    if ![winfo exists $w] {
	return
    }
    if { $force == "no" && $x >= [winfo rootx $w] && $y >= [winfo rooty $w] && \
	    $x <= [expr [winfo rootx $w]+[winfo width $w]] && \
	    $y <= [expr [winfo rooty $w]+[winfo height $w]] } {
	return
    }

    if { [winfo exists $GidPriv(HelpSystem)] } {
	if { $force == "no" && $x >= [winfo rootx $GidPriv(HelpSystem)] && $y >= \
		[winfo rooty $GidPriv(HelpSystem)] && \
		$x <= [expr [winfo rootx $GidPriv(HelpSystem)]+[winfo width $GidPriv(HelpSystem)]] && \
		$y <= [expr [winfo rooty $GidPriv(HelpSystem)]+[winfo height $GidPriv(HelpSystem)]] } {
	    return
	}
    }
    

    bind all <Motion> ""

    after cancel $GidHelp(helpcanceller)
    set GidHelp(helpcanceller) ""

    if { [winfo exist $GidPriv(HelpSystem)] } {
	set GidPriv(JustHelpActived) 1  
	after 1000 set GidPriv(JustHelpActived) 0  
    }

    if { !$GidPriv(HelpSystemmenu) } {
	catch { destroy $GidPriv(HelpSystem)}  
    }
    if { $GidHelp(HelpLeaveBefore) != "" } {
	bind $w <Leave> $GidHelp(HelpLeaveBefore)
    }
    set GidHelp(HelpLeaveBefore) ""
    after cancel set GidHelp(JustDeleted) ""

    if { $force == "no" } {
	set GidHelp(JustDeleted) $w
    } else {
	set GidHelp(JustDeleted) all
    }
    after 3000 "set GidHelp(JustDeleted) {}"
}

proc DisplayGidHelpLauncher { w x y text } {
    global GidPriv GidHelp

    #if { $GidHelp(JustDeleted) == $w || $GidHelp(JustDeleted) == "all" } { return }

    if { $GidPriv(JustHelpActived) } {
	DisplayGidHelp $w $text enter $x $y
    }

    if { [winfo exist $GidPriv(HelpSystem)] } {
	DisplayGidHelp $w "$text" enter $x $y
    } elseif { $GidHelp(helpcanceller) == "" } {
	set GidHelp(helpcanceller) [after 1500 DisplayGidHelp $w [list $text] enter $x $y]
    }
    #set GidHelp(HelpLeaveBefore) [bind $w <Leave>]

    bind all <Motion> "DisplayGidHelpLeave $w %X %Y"
    #bind $w <Leave> "$GidHelp(HelpLeaveBefore) ; DisplayGidHelpLeave $w"
    bind $w <ButtonPress-1> "+DisplayGidHelpLeave $w %X %Y yes"
}

proc GidHelpL { wlist type args } {
    set text [join $args]

    # use bwidget
    #DynamicHelp::configure -bg white

    foreach w $wlist {
	set tag ""
	if { [llength $w] == 2 } {
	    set tag [lindex $w 1]
	    set w [lindex $w 0]
	}
	if { ![winfo exists $w] } { continue }

	set haveimage 0
	catch {
	    if { [$w cget -image] != "" } { set haveimage 1 }
	}
	catch {
	    if { [$w cget -bitmap] != "" } { set haveimage 1 }
	}

	if { $haveimage } {
	    if { $tag == "" } {
		# using BWidgets
		#DynamicHelp::register $w balloon $text
		bind $w <Enter> "+DisplayGidHelpLauncher $w %X %Y [list $text]"
		foreach i [winfo children $w] {
		    GidHelpL $i $type $text
		}
	    } else {
		$w tag bind $tag <Enter> "+DisplayGidHelpLauncher $w %X %Y [list $text]"
	    }
	}

	if { $tag == "" } {
	    bind $w <ButtonPress-2> \
	    	      "[list DisplayGidHelpMenu $w $text $type %X %Y]; break"
	    bind $w <ButtonPress-3> \
		    "[list DisplayGidHelpMenu $w $text $type %X %Y]; break"
	    foreach i [winfo children $w] {
		GidHelpL $i $type $text
	    }
	} else {
	    $w tag bind $tag <ButtonPress-2> \
	    	      "[list DisplayGidHelpMenu $w $text $type %X %Y]; break"
	    $w tag bind $tag <ButtonPress-3> \
		    "[list DisplayGidHelpMenu $w $text $type %X %Y]; break"
	}
    }
}

proc GidHelp { wlist args } {
    GidHelpL $wlist help [join $args]
}

proc GidHelpT { wlist args } {
    GidHelpL $wlist helpandtools [join $args]
}

proc GidHelpRecursive { w args } {
    GidHelpL $w help [join $args]
    foreach i [winfo children $w] {
	eval GidHelpRecursive $i $args
    }
}

proc NURBSSurfaceMove {} {
    global GidPriv
    set w .gid.nurbsurfmove

    InitWindow $w "NURBS surface movement" NURBSSurfaceMoveWindowGeom


    set GidPriv(NURBSsurfoldmove) 0
    scale $w.s -from -10 -to 10 -resolution 1 -showvalue 0 \
	    -command NURBSSurfaceMoving -orient horizontal

    proc NURBSSurfaceMoving { val } {
	global GidPriv
	set incre [expr $val-$GidPriv(NURBSsurfoldmove)]
	.central.s process normal=$incre
	set GidPriv(NURBSsurfoldmove) $val
    }
	

    button $w.b -text "Reset slide" -command "\
	    set GidPriv(NURBSsurfoldmove) 0 ; $w.s set 0"

    button $w.close -text Close -command "destroy $w"

    grid $w.s -row 1 -col 1 -sticky ew
    grid $w.b -row 2 -col 1
    grid $w.close -row 2 -col 2
    grid columnconf $w 1 -weight 1


}
#NURBSSurfaceMove



proc PostGraphResultsWindow { {w .gid.graph} } {
    global ViewMenuPriv

    InitWindow $w "View graphs" PostGraphResultsWindowGeom PostGraphResultsWindow 
#<- para abrir una ventana sin resultados?

    set cur_anal [.gid.central.s info post get cur_analisis]
    
    tk_optionMenu $w.m1 ViewMenuPriv(border_graph_axX) \
	    LineVariation X_Variation Y_Variation Z_Variation 

    set resnames "tk_optionMenu $w.m2 ViewMenuPriv(border_graph_axY) "
    set res [.gid.central.s info post get cur_results_list Border_Graph ]
    if { "$res" != "" } { 
	append resnames $res
    } else {
	set res "-No results-"
	lappend resnames $res
    }
    eval $resnames

    frame $w.fr -bd 2 -relief ridge -height 100

    proc AddComponentsToMenu { frame } {
	global ViewMenuPriv
	foreach i [winfo children $frame] {
	    catch { destroy $i }
	}
	set irow 1
	foreach i [.gid.central.s info post get cur_components_list \
		$ViewMenuPriv(border_graph_axY)] {
	    set ww [ string tolower $i]$irow
	    regsub -all {\.} $ww · w
	    radiobutton $frame.r$w -text $i -value $i -variable \
		    ViewMenuPriv(border_comp)
	    grid $frame.r$w -sticky nw -row $irow -col 1
	    incr irow
	}
	grid rowconf $frame $irow -weight 1
	grid columnconf $frame 1 -weight 1
    }
    
    if { "$res" != "-No results-" } {
	trace var ViewMenuPriv(border_graph_axY) w "AddComponentsToMenu $w.fr ;#"
	set ViewMenuPriv(border_graph_axY) [lindex $res 0]
    }

    menubutton $w.mopt -text Actions -menu $w.mopt.m -relief raised
    menu $w.mopt.m
    $w.mopt.m add command -label "Draw graphs" -command {
	.central.s process escape escape escape escape Results Graphs \
			OptionsGraph ShowGraphs yes
    }
    $w.mopt.m add command -label "No draw graphs" -command {
	.central.s process escape escape escape escape Results Graphs \
			OptionsGraph ShowGraphs No
    }
    $w.mopt.m add command -label "Clear graphs" -command {
	.central.s process escape escape escape escape Results Graphs \
			OptionsGraph ClearGraphs
    }

    frame $w.buts
    button $w.buts.b -text "Select border" -command {
	.central.s process escape escape escape escape results graphs \
		bordergraph $ViewMenuPriv(border_graph_axX) \
		$ViewMenuPriv(border_graph_axY) $ViewMenuPriv(border_comp)
    }
    focus $w.buts.b

    button $w.buts.close -text "Close" -command "destroy $w"
    grid $w.buts.b $w.buts.close -padx 3 -pady 3
    

    grid $w.m1 -sticky nw -row 1 -col 1
    grid $w.m2 -sticky nw -row 2 -col 1
    grid $w.fr -sticky nsew -row 3 -col 1
    grid $w.mopt -sticky nw -row 4 -col 1
    grid $w.buts -sticky n -row 5 -col 1
    grid rowconf $w 3 -weight 1
    grid columnconf $w 1 -weight 1
}

# rename wm wm_old
# proc wm { args } {
#     set ret [eval [concat wm_old $args]]
#     if { [lindex $args 1] == ".wlay" } {
# 	if { ![winfo exists .tt.text] } {
# 	    toplevel .tt
# 	    pack [text .tt.text]
# 	}
# 	.tt.text ins end "wm args=//$args// return value=$ret\n"
#     }
#     return $ret
# }

proc PostContLimitsIncr { } {
    global GidPriv
    
    set GidPriv(PostContLimitsUserMin) [ format "%g" [ expr $GidPriv(PostContLimitsUserMin) - $GidPriv(PostContLimitsUserDiv)]]
    set GidPriv(PostContLimitsUserMax) [ format "%g" [ expr $GidPriv(PostContLimitsUserMax) + $GidPriv(PostContLimitsUserDiv)]]
}

proc PostContLimitsDecr { } {
    global GidPriv
    
    if { [ expr $GidPriv(PostContLimitsUserMax) - $GidPriv(PostContLimitsUserMin)] > \
	    [ expr 2.0 * $GidPriv(PostContLimitsUserDiv)] } {
	set GidPriv(PostContLimitsUserMin) [ format "%g" [ expr $GidPriv(PostContLimitsUserMin) + $GidPriv(PostContLimitsUserDiv)]]
	set GidPriv(PostContLimitsUserMax) [ format "%g" [ expr $GidPriv(PostContLimitsUserMax) - $GidPriv(PostContLimitsUserDiv)]]
    }
}

proc PostContLimitsReset { } {
    global GidPriv

    set GidPriv(PostContLimitsUserMin) [ format "%g" [ lindex $GidPriv(PostContLimitsOrgLimits) 0]]
    set GidPriv(PostContLimitsUserMax) [ format "%g" [ lindex $GidPriv(PostContLimitsOrgLimits) 1]]
}

proc PostContLimitsInitVariables {} {
    global GidPriv

    if { ![ info exist GidPriv(PostContLimitsApplying)]} {
      set GidPriv(PostContLimitsApplying) 0
    }

    if { !$GidPriv(PostContLimitsApplying)} {
	set GidPriv(PostContLimitsOrgLimits) [ .central.s info post get cur_contour_limits]
	set GidPriv(PostContLimitsUserMin) [ format "%g" [ lindex $GidPriv(PostContLimitsOrgLimits) 0]]
	set GidPriv(PostContLimitsUserMax) [ format "%g" [ lindex $GidPriv(PostContLimitsOrgLimits) 1]]
	set GidPriv(PostContLimitsUserDiv) [ expr ( $GidPriv(PostContLimitsUserMax) - \
		$GidPriv(PostContLimitsUserMin)) * 0.05]

	set pp [ lindex [ .central.s info post get contour_limits] 0]
	set GidPriv(PostContLimitsUseMax) 0
	set GidPriv(PostContLimitsUseMin) 0
	if { "[ lindex $pp 0]" == "USER" } {
	    set GidPriv(PostContLimitsUseMin) 1
	    if { [ info exist GidPriv(PostContLimitsWindow)] && \
		    [ winfo exist $GidPriv(PostContLimitsWindow).f.emin] } {
		$GidPriv(PostContLimitsWindow).f.emin conf -state normal -foreground black
	    }
	}
	if { "[ lindex $pp 2]" == "USER" } {
	    set GidPriv(PostContLimitsUseMax) 1
	    if { [ info exist GidPriv(PostContLimitsWindow)] && \
		    [ winfo exist $GidPriv(PostContLimitsWindow).f.emax] } {
		$GidPriv(PostContLimitsWindow).f.emax conf -state normal -foreground black
	    }
	}
    }
}

proc PostContLimitsApply {} { 
    global GidPriv

    set cur_res [.gid.central.s info post get cur_result]
    set cur_res_view  [.gid.central.s info post get cur_results_view]
    set cur_comp [.gid.central.s info post get cur_component]
    regsub -all {_} $cur_res_view {} tipo_contour
    
    if { ( "$cur_res_view" == "Contour_Fill") || ( "$cur_res_view" == "Contour_Lines") } {
	set GidPriv(PostContLimitsApplying) 1
	.central.s process escape escape escape escape results \
		contoptions
	if { $GidPriv(PostContLimitsUseMin) } { 
	    .central.s process setminoptions setvalue $GidPriv(PostContLimitsUserMin)
	} else { 
	    .central.s process setminoptions resetvalue escape
	}

	if { $GidPriv(PostContLimitsUseMax) } { 
	    .central.s process setmaxoptions setvalue $GidPriv(PostContLimitsUserMax)
	} else {
	    .central.s process setmaxoptions resetvalue escape
	}
	.central.s process escape $tipo_contour $cur_res $cur_comp
	#.central.s process escape escape escape escape results \
	#	 contoptions setminoptions resetvalue escape \
	#	 setmaxoptions resetvalue escape
	set GidPriv(PostContLimitsApplying) 0

	#.gid.central.s process escape escape escape escape Utilities Redisplay
    }
}

proc PostContLimitsCloseWin { w } {

    set GidPriv(PostContLimitsHistoryMin) [ [ $w.f.emin cget list] get 0 end]
    set GidPriv(PostContLimitsHistoryMax) [ [ $w.f.emax cget list] get 0 end]
    destroy $w
}
    
proc PostContLimitsWin { { w .wPostContLim} { solo 1}} {
    global GidPriv

    if { $solo} {
	InitWindow $w "Contour Limits" PostContLimitsWindowGeom PostContLimitsWin
    }

    if { $solo} {
	set GidPriv(PostContLimitsWindow) $w
    }

    #if { [ winfo exists .postContLim] } {
    #	 raise .postContLim
    #	 return
    #}
    #set donde [ wm geometry $w]
    #set nodecor 1
    #if { ![ regexp {([0-9]*)x([0-9]*)[\+,-]([0-9]*)[\+,-]([0-9]*)} $donde dummy w h x y] } {
    #	 set nodecor 0
    #}

    #toplevel $w 
    #wm geometry $w +[expr $x + 50]+[expr $y + 50]

    frame $w.f -relief ridge -bd 2
    #label $w.f.lmax -text Max:
    checkbutton $w.f.lmax -text Max: -variable GidPriv(PostContLimitsUseMax) -command {
	if { $GidPriv(PostContLimitsUseMax)} {
	    $GidPriv(PostContLimitsWindow).f.emax conf -state normal -foreground black
	} else {
	    $GidPriv(PostContLimitsWindow).f.emax conf -state disabled -foreground grey60
	}
    }
    #entry $w.f.emax -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMax)
    if { ![info exist GidPriv(PostContLimitsHistoryMax)] } {
	set GidPriv(PostContLimitsHistoryMax) ""
    }
    combobox $w.f.emax -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMax) \
	    -editable 1 -keephistory 1 -history "$GidPriv(PostContLimitsHistoryMax)"
    #label $w.f.lmin -text Min:
    checkbutton $w.f.lmin -text Min: -variable GidPriv(PostContLimitsUseMin) -command {
	if { $GidPriv(PostContLimitsUseMin)} {
	    $GidPriv(PostContLimitsWindow).f.emin conf -state normal -foreground black
	} else {
	    $GidPriv(PostContLimitsWindow).f.emin conf -state disabled -foreground grey60
	}
    }
    #entry $w.f.emin -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMin)
    if { ![info exist GidPriv(PostContLimitsHistoryMin)] } {
	set GidPriv(PostContLimitsHistoryMin) ""
    }
    combobox $w.f.emin -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMin) \
	    -editable 1 -keephistory 1 -history "$GidPriv(PostContLimitsHistoryMin)"
    
    frame $w.f.fi
    button $w.f.fi.bmas -text "+" -bd 1 -padx 2 -pady 0 -highlightthickness 0 \
	    -command PostContLimitsIncr
    button $w.f.fi.breset -text "o" -bd 1 -padx 2 -pady 0 -highlightthickness 0 \
	    -command PostContLimitsReset 
    button $w.f.fi.bmenos -text "-" -bd 1 -padx 2 -pady 0 -highlightthickness 0 \
	    -command PostContLimitsDecr
    grid $w.f.fi.bmas -row 0 -column 0 -padx 3 -sticky news
    grid $w.f.fi.breset -row 1 -column 0 -padx 3 -sticky news
    grid $w.f.fi.bmenos -row 2 -column 0 -padx 3 -sticky news

    if { $solo} {
	button $w.f.bapply -text Apply -bd 1 -command PostContLimitsApply
	button $w.f.bclose -text Close -bd 1 -command "PostContLimitsCloseWin $w"
    }

    grid $w.f.lmax $w.f.emax 
    grid $w.f.lmin $w.f.emin
    grid $w.f.fi -row 0 -column 2 -rowspan 2

    if { $solo} {
	grid $w.f.bapply -row 0 -column 3 -padx 4 -pady 2
	grid $w.f.bclose -row 1 -column 3 -padx 4 -pady 2
    }

    grid $w.f

    set GidPriv(PostContLimitsApplying) 0
    PostContLimitsInitVariables 
    $w.f.emax conf -state disabled -foreground grey60
    $w.f.emin conf -state disabled -foreground grey60

    if { $solo} {
	bind $w <Return> PostContLimitsApply
    }

}

proc PostContLimitsApplyMinEntry { w } {
    global GidPriv
    set err 0 
    
    if { "$GidPriv(PostContLimitsUserMin)" != "" } {
	set err [ catch { format "%g" $GidPriv(PostContLimitsUserMin) } ]
	if { !$err} {
	    set cur_res [.gid.central.s info post get cur_result]
	    set cur_res_view  [.gid.central.s info post get cur_results_view]
	    set cur_comp [.gid.central.s info post get cur_component]
	    regsub -all {_} $cur_res_view {} tipo_contour
	    
	    if { ( "$cur_res_view" == "Contour_Fill") || ( "$cur_res_view" == "Contour_Lines") } {
		#set GidPriv(PostContLimitsApplying) 1
		.central.s process escape escape escape escape results \
			contoptions setminoptions setvalue $GidPriv(PostContLimitsUserMin) 
		#	escape $tipo_contour $cur_res $cur_comp
		#.central.s process escape escape escape escape results \
		#	 contoptions setminoptions resetvalue escape 
		.gid.central.s process escape escape escape escape Utilities Redisplay \
			escape escape
		#PostContLimitsInitVariables
		#set GidPriv(PostContLimitsApplying) 0
	    }
	} else {
	    WarnWin "A Numerical value must be entered."
	}
    }
    
    #WarnWin "$GidPriv(PostContLimitsUserMin) - $err"	
    if { !$err} {
	set GidPriv(PostContLimitsHistoryMin) [ [ $w.f.emin cget list] get 0 end]
	destroy $w
	#focus .gid
    }
}

proc PostContLimitsMinEntry { w} {
    global GidPriv tcl_platform

    #set donde [ wm geometry $w]
    #set donde [ winfo geometry $w]
    #set nodecor 1
    #if { ![ regexp {([0-9]*)x([0-9]*)[\+,-]([0-9]*)[\+,-]([0-9]*)} $donde dummy w h x y] } {
    #	  set nodecor 0
    #}
    set x [ winfo x $w]
    set y [ winfo y $w]
    set wi [ winfo width $w]
    set w [ winfo parent $w]
    while { "$w" != "" } {
	set xp [ winfo x $w]
	set yp [ winfo y $w]
	set x [ expr $x + $xp]
	set y [ expr $y + $yp + 16]
	if { "[ winfo class $w]" == "Toplevel"} {
	    break
	}
	set w [ winfo parent $w]
    }
    set x [expr $x + $wi]
    set y [expr $y - 16]
    #WarnWin "$w = +$x+$y"

    toplevel .wPostLimMin
    wm geometry .wPostLimMin +$x+$y
    wm title .wPostLimMin Minimum
    wm minsize .wPostLimMin 1 1
    wm overrideredirect .wPostLimMin 1

    frame .wPostLimMin.f -bd 2 -relief ridge
    if { ![info exist GidPriv(PostContLimitsHistoryMin)] } {
	set GidPriv(PostContLimitsHistoryMin) ""
    }
    combobox .wPostLimMin.f.emin -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMin) \
	    -editable 1 -keephistory 1 -history "$GidPriv(PostContLimitsHistoryMin)"

    set limites_org [ .central.s info post get cur_contour_limits]
    set GidPriv(PostContLimitsUserMin) [ format "%g" [ lindex $limites_org 0]]
    .wPostLimMin.f.emin sel to end

    bind .wPostLimMin <Return> "PostContLimitsApplyMinEntry .wPostLimMin"
    bind .wPostLimMin <Escape> "destroy .wPostLimMin"
    bind .wPostLimMin <1> "+PostContLimitsBut1 %W %x %y"

    if { $tcl_platform(platform) == "windows" } {
	button .wPostLimMin.f.b -text X -command "destroy .wPostLimMin" -padx 2 -bd 1 \
		-pady 0 -highlightthickness 0
    } else {
	button .wPostLimMin.f.b -text X -command "destroy .wPostLimMin" -padx 4 -bd 1 -pady 2
    }

    #grid .wPostLimMin.f.emin .wPostLimMin.f.b
    grid .wPostLimMin.f.emin -padx 2 -pady 1
    grid .wPostLimMin.f.b -column 1 -row 0 -padx 1 -pady 1

    grid .wPostLimMin.f
    focus -force .wPostLimMin.f.emin
    #raise .wPostLimMin .gid
    update
    grab .wPostLimMin

}

proc PostContLimitsApplyMaxEntry { w }  {
    global GidPriv
    set err 0

    if { "$GidPriv(PostContLimitsUserMax)" != "" } {
	set err [ catch { format "%g" $GidPriv(PostContLimitsUserMax) } ]
	if { !$err} {
	    set cur_res [.gid.central.s info post get cur_result]
	    set cur_res_view  [.gid.central.s info post get cur_results_view]
	    set cur_comp [.gid.central.s info post get cur_component]
	    regsub -all {_} $cur_res_view {} tipo_contour
	    
	    if { ( "$cur_res_view" == "Contour_Fill") || ( "$cur_res_view" == "Contour_Lines") } {
		#set GidPriv(PostContLimitsApplying) 1
		#WarnWin "Set value"
		.central.s process escape escape escape escape results \
			contoptions setmaxoptions setvalue $GidPriv(PostContLimitsUserMax)
		#	escape $tipo_contour $cur_res $cur_comp
		#.central.s process escape escape escape escape results \
		#	 contoptions setmaxoptions resetvalue escape 
		#WarnWin "Redisplay"
		.gid.central.s process escape escape escape escape Utilities Redisplay \
			escape escape
		#WarnWin "init vars"
		# PostAnimateInitVariables
		# PostContLimitsInitVariables
		# FillPostLegendInfo
		#set GidPriv(PostContLimitsApplying) 0
	    }
	} else {
	    WarnWin "A Numerical value must be entered."
	}
    }

    #WarnWin "$GidPriv(PostContLimitsUserMax) - $err"
    if { !$err} {
	set GidPriv(PostContLimitsHistoryMax) [ [ $w.f.emax cget list] get 0 end]
	destroy $w
    }
    #focus .gid
}


proc PostContLimitsMaxEntry { w} {
    global GidPriv tcl_platform

    #set donde [ wm geometry $w]
    #set donde [ winfo geometry $w]
    #set nodecor 1
    #if { ![ regexp {([0-9]*)x([0-9]*)[\+,-]([0-9]*)[\+,-]([0-9]*)} $donde dummy w h x y] } {
    #	  set nodecor 0
    #}
    set x [ winfo x $w]
    set y [ winfo y $w]
    set wi [ winfo width $w]
    set w [ winfo parent $w]
    while { "$w" != "" } {
	set xp [ winfo x $w]
	set yp [ winfo y $w]
	set x [ expr $x + $xp]
	set y [ expr $y + $yp + 16]
	if { "[ winfo class $w]" == "Toplevel"} {
	    break
	}
	set w [ winfo parent $w]
    }
    set x [expr $x + $wi]
    set y [expr $y - 16]
    #WarnWin "$w = +$x+$y"

    toplevel .wPostLimMax
    wm geometry .wPostLimMax +$x+$y
    wm title .wPostLimMax Maximum
    wm minsize .wPostLimMax 1 1
    wm overrideredirect .wPostLimMax 1

    frame .wPostLimMax.f -bd 2 -relief ridge
    if { ![info exist GidPriv(PostContLimitsHistoryMax)] } {
	set GidPriv(PostContLimitsHistoryMax) ""
    }   
    combobox .wPostLimMax.f.emax -width 11 -bd 1 -textvariable GidPriv(PostContLimitsUserMax) \
	    -editable 1 -keephistory 1 -history "$GidPriv(PostContLimitsHistoryMax)"

    set limites_org [ .central.s info post get cur_contour_limits]
    set GidPriv(PostContLimitsUserMax) [ format "%g" [ lindex $limites_org 1]]
    .wPostLimMax.f.emax sel to end

    bind .wPostLimMax <Return> "PostContLimitsApplyMaxEntry .wPostLimMax"
    bind .wPostLimMax <Escape> "destroy .wPostLimMax"
    bind .wPostLimMax <1> "+PostContLimitsBut1 %W %x %y"

    if { $tcl_platform(platform) == "windows" } {
	button .wPostLimMax.f.b -text X -command "destroy .wPostLimMax" -padx 2 -bd 1 \
		-pady 0 -highlightthickness 0
    } else {
	button .wPostLimMax.f.b -text X -command "destroy .wPostLimMax" -padx 4 -bd 1 -pady 2
    }

    grid .wPostLimMax.f.emax -padx 2 -pady 1
    grid .wPostLimMax.f.b -column 1 -row 0 -padx 1 -pady 1
    grid .wPostLimMax.f
    focus -force .wPostLimMax.f.emax
    #raise .wPostLimMax .gid
    update
    grab .wPostLimMax

}

proc PostContLimitsBut1 { w x y } {

    if { $x < 0 || $y < 0 || $x > [winfo width $w] || $y > [winfo height $w] } {
	destroy $w
    }
}


proc ViewSeveralWindows {} {
    global GidPriv GIDDEFAULT

    set w .gid.viewseveralwindows

    InitWindow $w "Multiple windows" PrePostViewMWindowsWindowGeom ViewSeveralWindows \
	    "" 1
    if { ![info exists GidPriv(ViewSeveralWindowsI)] } {
	set GidPriv(ViewSeveralWindowsI) [image create photo -file \
		$GIDDEFAULT/bitmaps/mwindows.gif]
    }
    label $w.l -text "Select the desired window configuration" \
	    -font BigFont -wraplength [image width $GidPriv(ViewSeveralWindowsI)]
    label $w.i -image $GidPriv(ViewSeveralWindowsI) -relief ridge -bd 2
    frame $w.but -relief ridge -bd 2
    button $w.but.close -text Close -command "destroy $w"
    pack $w.but.close -pady 2

    pack $w.l -side top -padx 3 -pady 3
    pack $w.i -side top -padx 3
    pack $w.but -side top -pady 2 -padx 2 -expand 1 -fill x
    focus $w.but.close

    bind $w.i <1> "ViewSeveralWindowsSelect $w %x %y"
}

proc ViewSeveralWindowsSelect { w x y } {
    set type ""
    if { $x > 16 && $x < 77 } {
	if { $y > 21 && $y < 77 } {
	    set type 1
	} elseif { $y > 102 && $y < 157 } {
	    set type 3L
	} elseif { $y > 185 && $y < 236 } {
	    set type 3D
	}
    } elseif { $x > 109 && $x < 169 } {
	if { $y > 21 && $y < 77 } {
	    set type 2LR
	} elseif { $y > 102 && $y < 157 } {
	    set type 3U
	} elseif { $y > 185 && $y < 236 } {
	    set type 4
	}
    } elseif { $x > 200 && $x < 262 } {
	if { $y > 21 && $y < 77 } {
	    set type 2UD
	} elseif { $y > 102 && $y < 157 } {
	    set type 3R
	} elseif { $y > 185 && $y < 236 } {
	    set type EXT
	}
    }
    if { $type != "" } {
	.central.s process NewWin $type
    }
}

proc CreatePointNewOld {} {
    global GIDDEFAULT GidPriv

    if { ![info exists GidPriv(CreatePointNewOld)] } {
	set GidPriv(CreatePointNewOld) 1
    }
    set w .gid.createpointnewold

    InitWindow $w "Create point procedure" CreatePointNewOldWindowGeom "" \
	    "" 1
    if { ![info exists GidPriv(CreatePointNewOldI)] } {
	set imatge_join [image create photo -file \
		$GIDDEFAULT/bitmaps/join.gif]
	set imatge_nojoin [image create photo -file \
		$GIDDEFAULT/bitmaps/no_join.gif]
    }

    label $w.l -text "  Select the existing point or create a new one?" \
	    -pady 6 
	    #-font BigFont -wraplength [expr 2*[image width $imatge_nojoin]]

    frame $w.note
    label $w.note.note_text -text "  NOTE: Ctrl-a toggles between Join and No join modes."   
    label $w.espai -text "     " 
   
    frame $w.centre 
    frame $w.centre.esq    -relief ridge -bd 2 
    frame $w.centre.dreta   -relief ridge -bd 2


    label $w.centre.esq.imatge_NJ   -image $imatge_nojoin -relief sunken -bd 2
    label $w.centre.dreta.imatge_J -image $imatge_join -relief sunken -bd 2


    button $w.centre.esq.nojoin -text "NO JOIN" -height 2 -width 8 -command "set GidPriv(CreatePointNewOld) 0 
                                                                             CreatePointNewOldExec $w 1"      
    button $w.centre.dreta.join -text JOIN      -height 2 -width 8 -command "set GidPriv(CreatePointNewOld) 1 
                                                                             CreatePointNewOldExec $w 1"

    
    button $w.close -text Cancel -width 6 -height 1\
	    -command "CreatePointNewOldExec $w 0" 


    set manual_link "gid_5.html#SEC9"
    button $w.help -text Help  -width 6 -height 1 -command "\
	    directHelp $manual_link"

    pack $w.centre.esq.imatge_NJ  $w.centre.esq.nojoin -anchor center -expand 1 -side top -padx 6 -pady 6
    pack $w.centre.dreta.imatge_J $w.centre.dreta.join -anchor center -expand 1 -side top -padx 6 -pady 6
   
    pack $w.l -side top -anchor w
    pack $w.centre.esq $w.centre.dreta -anchor center -side left
    
    pack $w.centre -side top -padx 6 -anchor w

    pack $w.note.note_text -side left
    pack $w.note -anchor w
    pack $w.espai 
   
    pack $w.help $w.close -side right -padx 6 -pady 6 -ipady 2
  
    focus $w.centre.dreta.join 
    update idletasks
    #grab $w

}

proc CreatePointNewOldExec { w doit } {
    global GidPriv
    if { !$doit } {
	.central.s process escape
    } elseif { $GidPriv(CreatePointNewOld) } {
	.central.s process old
    } else {
	.central.s process new
    }
    destroy $w
}

proc ToggleGeomMesh {} {
    if { [catch { set infoProj [lindex [.gid.central.s info Project] 4] }] } {
	set infoProj "GEOMETRYUSE"
    }
    if { $infoProj == "GEOMETRYUSE" } {
	.central.s process escape escape escape escape Meshing MeshView
    } else {
	.central.s process escape escape escape escape Geometry escape
    }
}

proc TogglePrePost {} {
    if { [catch { set infoProj [lindex [.gid.central.s info Project] 4] }] } {
	set infoProj "GEOMETRYUSE"
    }

    if { ( $infoProj == "GEOMETRYUSE") || ( $infoProj == "MESHUSE") } {
	.central.s process escape escape escape escape Postprocess
    } else {
	.central.s process escape escape escape escape Preprocess
    }
}


proc imagefrom { name } {
    global GidPriv GIDDEFAULT
    if { ![info exist GidPriv($name)] } {
	set GidPriv($name) [image create photo -file \
		[file join $GIDDEFAULT bitmaps $name]]
    }
    return $GidPriv($name)
}

proc bitmapfrom { name } {
    global GIDDEFAULT
    return @[file join $GIDDEFAULT bitmaps $name]
}

proc ibitmapfrom { name color} {
    global GidPriv GIDDEFAULT
    if { ![info exist GidPriv($name)] } {
	set GidPriv($name) [image create bitmap -file \
		[file join $GIDDEFAULT bitmaps $name] -foreground $color]
    }
    return $GidPriv($name)
}


proc GGCompress {} {
    set w .wcomp

    toplevel $w
    frame $w.f -relief groove -bd 2
    label $w.f.l1 -text Flags:
    entry $w.f.e1
    label $w.f.l2 -text "File In:"
    entry $w.f.e2 
    label $w.f.l3 -text "File Out:"
    entry $w.f.e3 
    grid $w.f.l1 $w.f.e1
    grid $w.f.l2 $w.f.e2
    grid $w.f.l3 $w.f.e3

    proc GGCDoIt { w} {
	set fl [ $w.f.e1 get]
	set fi [ $w.f.e2 get]
	set fo [ $w.f.e3 get]
	if { "$fl" != ""} {
	    gidcompress $fl $fi $fo
	} else {
	    gidcompress $fl $fi $fo
	}
    }
    button $w.f.b1 -text Do -command "GGCDoIt $w"
    button $w.f.b2 -text Close -command "destroy $w"

    grid $w.f.b1 $w.f.b2

    grid $w.f

}

proc framelabel { w text } {
    frame $w -bd 2 -relief groove
    set i 0
    set parent [winfo parent $w]
    if { $parent == "." } { set parent "" }
    set label $parent.__label$i
    while { [winfo exists $label] } {
	incr i
	set label $parent.__label$i
    }
    label $label -text $text -pady 0
    place $label -in $w -x 10 -y -1 -anchor w -bordermode outside
    after idle raise $label
    return $w
}

proc framelabelsep {} {
    set FontHeight [font metric NormalFont -linespace]
    return [expr $FontHeight/2+1]
}

proc AskForNormal { w message } {
    global tkPriv tcl_platform

    toplevel $w
    wm title $w "Enter normal"

    if { $tcl_platform(platform) == "windows" } {
	wm transient $w [winfo toplevel [winfo parent $w]]
    }

    framelabel $w.f "enter normal"
    frame $w.f.f 

    label $w.f.f.l -text $message
    radiobutton $w.f.f.r1 -text "Positive Z" -var tkPriv(afw_check) -value z
    radiobutton $w.f.f.r2 -text "Positive Y" -var tkPriv(afw_check) -value y
    radiobutton $w.f.f.r3 -text "Positive X" -var tkPriv(afw_check) -value x
    radiobutton $w.f.f.r4 -text "Coords:" -var tkPriv(afw_check) -value coords

    entry $w.f.f.e1 -width 5
    entry $w.f.f.e2 -width 5
    entry $w.f.f.e3 -width 5

    $w.f.f.e1 ins end 0.0
    $w.f.f.e2 ins end 0.0
    $w.f.f.e3 ins end 1.0

    proc ChangeCoords { w } {
	global tkPriv
	if { $tkPriv(afw_check) == "coords" } {
	    $w.f.f.e1 conf -state normal -fg [$w.f.f.r1 cget -fg]
	    $w.f.f.e2 conf -state normal -fg [$w.f.f.r1 cget -fg]
	    $w.f.f.e3 conf -state normal -fg [$w.f.f.r1 cget -fg]
	} else { 
	    $w.f.f.e1 conf -state disabled -fg grey60
	    $w.f.f.e2 conf -state disabled -fg grey60
	    $w.f.f.e3 conf -state disabled -fg grey60
	}
    }

    trace var tkPriv(afw_check) w " ChangeCoords $w ;#"

    set tkPriv(afw_check) z

    grid $w.f.f.l -row 1 -col 1 -columnspan 4 -sticky w -padx 2
    grid  $w.f.f.r1 -row 2 -col 1 -columnspan 4 -sticky w -padx 2
    grid  $w.f.f.r2 -row 3 -col 1 -columnspan 4 -sticky w
    grid  $w.f.f.r3 -row 4 -col 1 -columnspan 4 -sticky w
    grid  $w.f.f.r4 -row 5 -col 1
    grid $w.f.f.e1 -row 5 -col 2 -sticky ew
    grid $w.f.f.e2 -row 5 -col 3 -sticky ew
    grid $w.f.f.e3 -row 5 -col 4 -sticky ew
    grid columnconf $w.f.f 2 -weight 1
    grid columnconf $w.f.f 3 -weight 1
    grid columnconf $w.f.f 4 -weight 1
    
    grid $w.f.f -row 1 -col 1 -sticky ewns -pady 6
    grid columnconf $w.f 1 -weight 1
    grid rowconf $w.f 1 -weight 1

    button $w.ok -text OK -width 8 -command "set tkPriv(afw_button) ok" -und 0
    button $w.scr -text "In screen" -width 8 -command "set tkPriv(afw_button) scr" -und 0
    button $w.cancel -text Cancel -width 8 -command "set tkPriv(afw_button) cancel" -und 0

    wm protocol $w WM_DELETE_WINDOW "tkButtonInvoke $w.cancel"
    bind $w.ok <Return> "tkButtonInvoke $w.ok"
    bind $w.f.f.e1 <Return> "tkButtonInvoke $w.ok"
    bind $w.f.f.e2 <Return> "tkButtonInvoke $w.ok"
    bind $w.f.f.e3 <Return> "tkButtonInvoke $w.ok"
    bind $w <Escape> "tkButtonInvoke $w.cancel"
    bind $w <Alt-o> "tkButtonInvoke $w.ok"
    bind $w <Alt-c> "tkButtonInvoke $w.cancel"
    bind $w <Alt-i> "tkButtonInvoke $w.scr"

    grid $w.f -row 1 -col 1 -columnspan 3 -pady 6 -sticky ewns
    grid $w.ok -row 2 -col 1 -padx 2
    grid $w.scr -row 2 -col 2 -padx 2
    grid $w.cancel -row 2 -col 3 -padx 2
    grid columnconf $w 1 -weight 1
    grid rowconf $w 1 -weight 1
    grid columnconf $w 2 -weight 1
    grid columnconf $w 3 -weight 1

    wm withdraw $w
    update idletasks

    set pare [winfo toplevel [winfo parent $w]]
    set x [expr [winfo x $pare]+[winfo width $pare ]/2- [winfo reqwidth $w]/2]
    set y [expr [winfo y $pare]+[winfo height $pare ]/2- [winfo reqheight $w]]
    if { $x < 0 } { set x 0 }
    if { $y < 0 } { set y 0 }
    WmGidGeom $w +$x+$y
    #wm geom $w +$x+$y
    update
    wm deiconify $w

    set oldFocus [focus]
    tkwait visibility $w
    grab $w
    focus $w.ok
    after 100 catch [list "focus -force $w.ok"]

    while 1 {
	tkwait variable tkPriv(afw_button)

	if { $tkPriv(afw_button) != "ok" } { break }
	set value ""
	set isdiffzero 0
	if { $tkPriv(afw_check) == "coords" } {
	    set isbad 0
	    for { set i 1 } { $i <= 3 } { incr i } {
		if { [catch { set val [expr double([$w.f.f.e$i get])] }] } {
		    WarnWin "Coordinate must be a real number"
		    tkTabToWindow $w.f.f.e$i
		    set isbad 1
		    break
		}
		if { $val != 0.0 } { set isdiffzero 1 }
		if { $value == "" } { 
		    append value $val
		} else { append value ",$val" }
	    }
	    if { $isbad } { 
		focus -force $w
		tkTabToWindow $w.f.f.e$i
		continue 
	    }
	    if { !$isdiffzero } {
		WarnWin "Normal must be different from zero"
		focus -force $w
		tkTabToWindow $w.f.f.e1
		continue
	    }
	} elseif { $tkPriv(afw_check) == "z" } {
	    set value "0.0,0.0,1.0"
	} elseif { $tkPriv(afw_check) == "y" } {
	    set value "0.0,1,0,0.0"
	} else {
	    set value "1.0,0.0,0.0"
	}
	break
    }
    set oldGrab [grab current $w]
    if {$oldGrab != ""} {
	set grabStatus [grab status $oldGrab]
    }

    if { $oldFocus == "" || [catch {focus $oldFocus}] } {
	if { [winfo exists .gid] } {
	    focus [focus -lastfor .gid]
	}
    }

    destroy $w
    if {$oldGrab != ""} {
	if {$grabStatus == "global"} {
	    catch { grab -global $oldGrab }
	} else {
	    catch { grab $oldGrab }
	}
    }

    switch $tkPriv(afw_button) {
	ok {
	    .gid.central.s process $value
	}
	cancel {
	    .gid.central.s process escape
	}
    }
}

proc ExecuteFileCommand { comm PREPOST lastaction file } {

    set what [lindex [.central.s info Project] 4]
    if { $what == "GRAFUSE" } { set what POSTUSE }
    if { $PREPOST == "PRE" && $what == "POSTUSE" } {
	if { $lastaction == "goingpre" } { return }
	.central.s process escape escape escape escape Preprocess
	delayedop changefunc [list LoadFileInGid $file goingpre]
	return
    }
    if { $PREPOST == "POST" && $what != "POSTUSE" } {
	.central.s process escape escape escape escape Postprocess
    }
    .central.s process escape escape escape escape Files $comm \"$file\"
}

# last action can be: saving; goingpre;

proc LoadFileInGid { file {lastaction ""} } {

    set file [file native [file attributes $file -longname]]
    if { [file isdir $file] && [string tolower [file ext $file]] == ".gid" } {
	set what [lindex [.central.s info Project] 4]
	if { $what == "GRAFUSE" } { set what POSTUSE }
	if { $what == "POSTUSE" } {
	    if { $lastaction == "goingpre" } { return }
	    .central.s process escape escape escape escape Preprocess
	    delayedop changefunc [list LoadFileInGid $file goingpre]
	    return
	}
	set therearechanges [lindex [.central.s info Project] 2]
	if { $therearechanges } {
	    if { $lastaction == "saving" } { return }
	    .central.s process escape escape escape escape Files New
	    delayedop changefunc [list LoadFileInGid $file saving]
	} else {
	    ExecuteFileCommand Read PRE $lastaction $file
	}
    } elseif { [string match *.flavia.msh $file] || [string match *.flavia.res $file] } {
	ExecuteFileCommand Read POST $lastaction $file
    } else {
	switch [string tolower [file ext $file]] {
	    ".dxf" { ExecuteFileCommand DXFRead PRE $lastaction $file}
	    ".msh" - ".mesh" { ExecuteFileCommand MeshRead PRE $lastaction $file}
	    ".igs" - ".iges" { ExecuteFileCommand IgesRead PRE $lastaction $file}
	    ".nas" { ExecuteFileCommand NASTRANRead PRE $lastaction $file}
	    ".bch" { ExecuteFileCommand BatchFile ANY $lastaction $file}
	    ".x_t" { ExecuteFileCommand ParasolidRead PRE $lastaction $file}
	    ".x_b" { ExecuteFileCommand ParasolidRead PRE $lastaction $file}
	    ".sat" { ExecuteFileCommand AcisRead PRE $lastaction $file}
	    ".vda" { ExecuteFileCommand VDARead PRE $lastaction $file}
	    ".stl" { ExecuteFileCommand STLRead PRE $lastaction $file}
	    default {
		WarnWin "Unknown file type for file '$file'"
		return
	    }
	}
    }
}

proc MsgcatMcInitialize {} {

    set language en
    ::msgcat::mclocale $language
    set file [file join "/gid project/po" $language.po]
    if { [file readable $file] } {
	set fin [open $file r]
	set lastmsgid ""
	while { ![eof $fin] } {
	    gets $fin aa
	    if { [regexp {[ ]*msgid[ ]*"(.*)"} $aa {} char] } {
		set lastmsgid $char
	    } elseif { [regexp {[ ]*msgstr[ ]*"(.*)"} $aa {} char] } {
		if { $lastmsgid != "" && $char != "" } {
		    ::msgcat::mcset $language $lastmsgid $char
		}
	    }
	}
	close $fin
    } 
}


proc SetGUIAppearanceColor { } {
    global tcl_platform GidPriv
    if { ![info exists GidPriv(GUIAppearance)] } {
	set GidPriv(GUIAppearance) 1
    }
    if { $tcl_platform(platform) == "windows" } {
        if { $GidPriv(GUIAppearance) == "0" } {
	    set GidPriv(ToolbarBg) [.gid cget -background]
	} elseif { $GidPriv(GUIAppearance) == "1" } {
	    #clarified color 
	    set GidPriv(ToolbarBg) [CCColorActivo [.gid cget -background] 25] 
	} else {
            #set to a fixed value 
	    set GidPriv(ToolbarBg) #DEDFDE
	}
	set GidPriv(CommandLineBg) #FFFFFF
    } else {
	if { $GidPriv(GUIAppearance) == "0" } {
	    #set GidPriv(ToolbarBg) [.gid cget -background]
	    # este es el otro sitio que hay que cambiar:
	    set GidPriv(ToolbarBg) AntiqueWhite3
	} elseif { $GidPriv(GUIAppearance) == "1" } {
	    #clarified color 
	    #set GidPriv(ToolbarBg) [CCColorActivo [.gid cget -background] 25] 
	    set GidPriv(ToolbarBg) #E9E2D0
	} else {
            #set to a fixed value 
	    #set GidPriv(ToolbarBg) #DEDFDE
	    set GidPriv(ToolbarBg) #E9E2D0
	}
	set GidPriv(CommandLineBg) [CCColorSombra $GidPriv(ToolbarBg) 25]
	#set GidPriv(CommandLineBg) #FFFFFF
    }
}


proc SetTemplatesMenu { menu } {
    global GIDDEFAULT GidPriv

    set dir [file join $GIDDEFAULT templates]
#    if { [$menu entrycget end -label] == "Others..." && \
#	     [info exists GidPriv(dirfiles,$dir)] } { return }
    
    $menu del 0 end
    foreach i [winfo children $menu] { destroy $i }
    set inum 0
    #if { ![info exists GidPriv(dirfiles,$dir)] } {
	set GidPriv(dirfiles,$dir) [glob -nocomplain [file join $dir *.bas]]
    #}

    set files ""
    foreach i $GidPriv(dirfiles,$dir) {
	lappend files [file tail [file root $i]]
    }
    foreach i [lsort -dictionary $files] {
      set basfile \"[file join $dir $i.bas]\"
	$menu add command -label $i -command "processbasfile $basfile"
	incr inum
    }
    proc processbasfile { basfile } {
       .central.s process "escape escape escape escape Files WriteForBAS \"$basfile\""
    }

    if { $inum } { $menu add separator }
    $menu add command -label "Others..." -command \
	    ".central.s process escape escape escape escape \
	    Files WriteForBAS"
}

namespace eval WaitStater {
    variable cursors
}

proc WaitStater::SetWatch { w } {
    SetWatchRecursive $w $w
    update
}

proc WaitStater::UnsetWatch { w } {
    variable cursors

    foreach i [array names cursors $w,*] {
	regexp {[^,]+,(.*)} $i {} win
	$win configure -cursor $cursors($i)
	unset cursors($i)
    }
    update
}

proc WaitStater::SetWatchRecursive { w win } {
    variable cursors

    catch {
	set cursors($w,$win) [$win cget -cursor]
	$win configure -cursor watch
    }
    foreach i [winfo children $win] {
	SetWatchRecursive $w $i
    }
}
