
set NumFields 0

proc Setglobalcblist { name } {
    set globalcblist ""
    set i [expr [string last #CB# $name]-1]
    set globalcbname [string range $name 0 $i]
    incr i 6
    while 1 {
	set j [string first , [string range $name $i [string length $name]]]
	if { $j == -1 } break
	set j [expr $j+$i-1]
	set globalcblist [concat $globalcblist [string range $name $i $j]]
	set i [expr $j+2]
    }
    set j [string first ) [string range $name $i [string length $name]]]
    set j [expr $j+$i-1]
    set globalcblist [concat $globalcblist [string range $name $i $j]]
    return "$globalcbname $globalcblist"
}

proc CancelVarWindow { inum } {
    global wdataw NameList ValueList
    set rows 1
    while { [winfo exists $wdataw.frame2.c.f.win$inum.f.$rows] } \
	    { incr rows }
    set columns 1
    while { [winfo exists $wdataw.frame2.c.f.win$inum.f.1.e$columns] } \
	    { incr columns}
    incr rows -1 ; incr columns -1
    set fvalue "#N# [expr $rows*$columns]"
    for {set i 1} {$i <= $columns} {incr i} {
	for {set j 1} {$j <= $rows} {incr j} {
	    lappend fvalue [$wdataw.frame2.c.f.win$inum.f.$j.e$i \
		    get]
	}
    }
    set ValueList [lreplace $ValueList [expr $inum-1] \
	    [expr $inum-1] \
	    $fvalue]
    destroy $wdataw.frame2.c.f.win$inum

}

proc OpenVarWindow { i fvalue } {
    global wdataw NameList ValueList

#    if { [winfo exists $wdataw.frame2.c.f.win$i] } { return }
    catch {destroy $wdataw.frame2.c.f.win$i}
    toplevel $wdataw.frame2.c.f.win$i
    set x [expr [winfo x $wdataw]+500]
    set y [expr [winfo y $wdataw]+[winfo y $wdataw.frame2.c.f.label$i]]
   

    wm title $wdataw.frame2.c.f.win$i  [lindex [$wdataw.frame2.c.f.label$i \
	    config -text] 4]
    wm iconname $wdataw.frame2.c.f.win$i [lindex [$wdataw.frame2.c.f.label$i \
	    config -text] 4]
    wm minsize  $wdataw.frame2.c.f.win$i 1 1
    frame $wdataw.frame2.c.f.win$i.f -bd 0
    set titlelist [split [lindex  $NameList [expr $i-1]] (),]
    set titlelist [lrange $titlelist 1 [expr [llength $titlelist]-2]]
    set fvalue [lindex $ValueList [expr $i-1]]
    set numitems [expr [lindex $fvalue 1]/[llength $titlelist]]
    set numnewitems [$wdataw.frame2.c.f.res$i get]
    set fvalue [lrange $fvalue 2 end]
    set num 1
    foreach j $titlelist {
	frame $wdataw.frame2.c.f.win$i.f.$num -bd 0
	label $wdataw.frame2.c.f.win$i.f.$num.l -text $j
	pack $wdataw.frame2.c.f.win$i.f.$num.l -side top -padx 0 -pady 0 -ipadx 0 -ipady 0
	for {set k 1} {$k <= $numnewitems} {incr k} {
	    entry $wdataw.frame2.c.f.win$i.f.$num.e$k -relief sunken -width 12 -bd 1
	    if { $k <= $numitems } {
		set idx [expr ($k-1)*[llength $titlelist]+$num-1]
		$wdataw.frame2.c.f.win$i.f.$num.e$k insert 0 [lindex $fvalue \
		        $idx]
	    }
	    pack $wdataw.frame2.c.f.win$i.f.$num.e$k -side top -padx 0 -pady 0 -ipadx 0 -ipady 0
	}
	pack $wdataw.frame2.c.f.win$i.f.$num -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	incr num
    }
    button $wdataw.frame2.c.f.win$i.cancel -text [_ "Close"] \
	    -command "CancelVarWindow $i " -bd 1

    pack $wdataw.frame2.c.f.win$i.f $wdataw.frame2.c.f.win$i.cancel -side top -padx 0 -pady 0 -ipadx 0 -ipady 0
    WmGidGeom $wdataw.frame2.c.f.win$i +$x+$y
}

proc MakeVarWindow { i fvalue } {
    global wdataw
    set titlelist [split [lindex [$wdataw.frame2.c.f.label$i config -text] 4] (),]
    $wdataw.frame2.c.f.label$i config -text [lindex $titlelist 0]
    set titlelist [lrange $titlelist 1 [expr [llength $titlelist]-2]]
    set numitems [lindex $fvalue 1]
    set fvalue [lrange $fvalue 2 end]
    $wdataw.frame2.c.f.res$i delete 0 end
    $wdataw.frame2.c.f.res$i insert 0 [expr $numitems/[llength $titlelist]]
    $wdataw.frame2.c.f.res$i config -width 5
    if { ![winfo exists $wdataw.frame2.c.f.b$i] } {
	button $wdataw.frame2.c.f.b$i -text [_ "values"] \
		-command " OpenVarWindow $i \"$fvalue\" " -bd 1
	#pack $wdataw.frame2.c.f.b$i -side right -padx 0 -pady 0 -ipadx 0 -ipady 0
	grid $wdataw.frame2.c.f.b$i -row [ expr $i - 1] -column 2 -sticky we \
		-padx 0 -pady 0 -ipadx 0 -ipady 0
    } else { $wdataw.frame2.c.f.b$i conf \
	    -command " OpenVarWindow $i \"$fvalue\" "}

}

proc CalcLongest {} {
    global NumFields NameList ValueList 
    
    set lengthName 0
    set lengthValue 0
 
    for {set i 1} {$i <= $NumFields} {incr i} {
	set fname [lindex $NameList [expr $i-1]]
	set fvalue [lindex $ValueList [expr $i-1]]
	if { [string match *#N#* $fvalue] == 1 } {
	    regexp {^(.*)[(][^()]*[)][ ]*$} $fname trash aa
	    if { [string length $aa]  > $lengthName } { 
		set lengthName [string length $aa]
	    }
	} elseif { [string match *#CB#* $fname] == 0 } {
	    if { [string length $fname] > $lengthName } { 
		set lengthName [string length $fname]
	    }
	} else {
	    set aap [Setglobalcblist $fname]
	    set globalcbname [lindex $aap 0]
	    if { [string length $globalcbname] > $lengthName } { 
		set lengthName [string length $globalcbname]
	    }
	}
	if { [string length $fvalue] > $lengthValue } { 
	    set lengthValue [string length $fvalue]
	}
    }
    return "$lengthName $lengthValue"
}

proc FillInfo {} {
    global NumFields NameList ValueList wdataw

    set aa [CalcLongest]
    set lengthName [expr [lindex $aa 0]+1]
    set lengthValue [expr [lindex $aa 1]+1]
    if { [winfo exists $wdataw.frame2.c.f] } { 
	destroy $wdataw.frame2.c.f
    }
    frame $wdataw.frame2.c.f -bd 0
    for {set i 1} {$i <= $NumFields} {incr i} {
	set fname [lindex $NameList [expr $i-1]]
	if { [string match *#CB#* $fname] == 0 } {
	    regsub -all {_} $fname { } fname
	    regsub -all -- {-} $fname { } fname
	    label $wdataw.frame2.c.f.label$i -text $fname -anchor w
	    #-width $lengthName 
	    #pack $wdataw.frame2.c.f.label$i -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	    grid $wdataw.frame2.c.f.label$i -row [ expr $i - 1] -column 0 -sticky w \
		    -padx 0 -pady 0 -ipadx 0 -ipady 0
	    set globalcblist ""
	} else {
	    set aap [Setglobalcblist $fname]
	    set globalcbname [lindex $aap 0]
	    set globalcblist [lrange $aap 1 end]
	    regsub -all {_} $globalcbname { } globalcbname
	    regsub -all -- {-} $globalcbname { } globalcbname
	    label $wdataw.frame2.c.f.label$i -text $globalcbname -anchor w
		    #-width $lengthName 
	    #pack $wdataw.frame2.c.f.label$i -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	    grid $wdataw.frame2.c.f.label$i -row [ expr $i - 1] -column 0 -sticky w \
		    -padx 0 -pady 0 -ipadx 0 -ipady 0
	}
	set fvalue [lindex $ValueList [expr $i-1]]
	set lengthValue [expr [string length $fvalue]+4]
	if { $lengthValue < 15 } { set lengthValue 15 }
	if { [string compare $globalcblist ""] == 0 } {
	    if { ![winfo exists $wdataw.frame2.c.f.res$i] } {
		entry $wdataw.frame2.c.f.res$i -relief sunken -bd 1 
		#-width $lengthValue 
		#pack $wdataw.frame2.c.f.res$i -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	    }
	    $wdataw.frame2.c.f.res$i delete 0 end
	    $wdataw.frame2.c.f.res$i insert end $fvalue
	    if { [string match #N#* $fvalue] } {
		grid $wdataw.frame2.c.f.res$i -row [ expr $i - 1] -column 1 -sticky we \
		        -padx 0 -pady 0 -ipadx 0 -ipady 0
		MakeVarWindow $i $fvalue
	    } else {
		grid $wdataw.frame2.c.f.res$i -row [ expr $i - 1] -column 1 -columnspan 2 -sticky we \
		        -padx 0 -pady 0 -ipadx 0 -ipady 0
	    }
	} else {
	    if { ![winfo exists $wdataw.frame2.c.f.res$i] } {
		menubutton $wdataw.frame2.c.f.res$i \
		        -menu $wdataw.frame2.c.f.res$i.m -relief raised 
		#-padx 5 
		$wdataw.frame2.c.f.res$i conf -bd 1 -highlightthickness 1
		#pack $wdataw.frame2.c.f.res$i -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
		grid $wdataw.frame2.c.f.res$i -row [ expr $i - 1] -column 1 -columnspan 2 -sticky we \
		        -padx 0 -pady 0 -ipadx 0 -ipady 0
	    }
	    $wdataw.frame2.c.f.res$i conf -text $fvalue 
	    #-width $lengthValue
	    if { [winfo exists $wdataw.frame2.c.f.res$i.m] } { \
		    destroy $wdataw.frame2.c.f.res$i.m }
	    menu $wdataw.frame2.c.f.res$i.m -bd 1 -activeborderwidth 1
	    foreach j $globalcblist {
		$wdataw.frame2.c.f.res$i.m add radio -label $j \
		        -variable selname -value \
		        [concat $i $j] -command {
		    set cnum [lindex $selname 0]
		    $wdataw.frame2.c.f.res$cnum configure -text [lindex $selname 1]
		}
	    }
	}
    }
    $wdataw.frame2.c create window 0 0 -window $wdataw.frame2.c.f -anchor nw 
    # -tag w$i


#     set i [expr $NumFields+1]
#     while { [winfo exists $wdataw.frame2.c.f] } {
#         destroy $wdataw.frame2.c.f
#         $wdataw.frame2.c delete w$i
#         incr i
#     }

#     set maxy [lindex [$wdataw.frame2.c bbox w$NumFields] 3]
#     $wdataw.frame2.c conf -scrollregion "0c 0c 15c [expr $maxy+40]"
#     $wdataw.frame2.c yview moveto 0

     $wdataw.frame2.c conf -scrollregion "0c 0c [ expr $lengthName + $lengthValue]c [expr $NumFields]c"
     $wdataw.frame2.c yview moveto 0
}

proc UpDateVars {} {
    global NumFields NameList ValueList wdataw

    for {set i 1} {$i <= $NumFields} {incr i} {
	if {[winfo exists $wdataw.frame2.c.f.win$i.cancel]} {
	    $wdataw.frame2.c.f.win$i.cancel invoke
	} else {
	    if { [string compare [winfo class $wdataw.frame2.c.f.res$i] \
		    "Entry"] ==0 && ![winfo exists $wdataw.frame2.c.f.b$i] } {
		set tmpchar [$wdataw.frame2.c.f.res$i get]
	    } else { set tmpchar [lindex [$wdataw.frame2.c.f.res$i \
		    config -text] 4]}
	    if { ![winfo exists $wdataw.frame2.c.f.b$i] } {
		set ValueList [lreplace $ValueList [expr $i-1] [expr $i-1] \
		        $tmpchar]
	    }
	}
    }
}

proc UpDateMatsT { name1 name2 op } {
    global GidPriv
    if { $GidPriv(UpDateMatsIdle) == 0 } {
	set GidPriv(UpDateMatsIdle) 1
	after idle UpDateMats
    }
}

proc UpDateMats {} {
    global NumFields NameList ValueList GidPriv 

    set input [.central.s info materials $GidPriv(MaterialName)]
    set NumFields [lindex $input 0]
    set NameList ""
    set ValueList ""
    for { set i 0 } { $i < $NumFields } { incr i 1 } {
	lappend NameList [lindex $input [expr $i*2+1]]
	lappend ValueList [lindex $input [expr $i*2+2]]
    }
    FillInfo
    set GidPriv(UpDateMatsIdle) 0
}

proc UpDateIntv { w intv } {
    .central.s process escape escape escape escape data intervals \
	    ChangeInterval $intv
    UpDate INTVDATA $w
}



proc UpDateAny { w } {

    set typename [wm title $w]
    
    switch $typename {
	"Problem Data" {
	    set type GENDATA
	}
	"Interval Data" {
	    set type INTVDATA
	}
	"Materials" {
	    set type MATERIALS
	}
    }
    UpDate $type $w
}

proc UpDate { type w } {
    global NumMaterials NumIntervals NumFields NameList ValueList probtype
    global NumConditions GidPriv

    set probtype $type
    set input 0
    if { $type == "MATERIALS" } {
	$w.buttonframe2.mb listbox del 0 end
	set inum 0
	foreach i [.central.s info materials] {
	    if { $inum==0 } {
		set GidPriv(MaterialName) $i 
	    }
	    $w.buttonframe2.mb add $i
	    incr inum
	}
	set NumMaterials $inum
	return
    }
    if { $type == "INTVDATA" } {
	$w.buttonframe.mb conf -text [lindex [.central.s info intvdata num] 0]
	set maxintv [lindex [.central.s info intvdata num] 1]
	set input [.central.s info intvdata]
	for { set i 1 } { $i <= $maxintv } { incr i 1 } {
	    if { $i <= $NumIntervals } {
		$w.buttonframe.mb.m entryconfigure [expr $i-1] -label $i \
		        -command "UpDateIntv $w $i"
	    } else {
		$w.buttonframe.mb.m add command -label $i -command \
		        "UpDateIntv $w $i"
	    }
	}
	for { set i [expr $maxintv+1] } { $i <= $NumIntervals } { incr i 1 } {
	    $w.buttonframe.mb.m del [expr $i-1]
	}

	set NumIntervals $maxintv
    }
    if { $type == "GENDATA" } {
	set input [.central.s info gendata]
    }

    set NumFields [lindex $input 0]
    set NameList ""
    set ValueList "" 
    for { set i 0 } { $i < $NumFields } { incr i 1 } {
	lappend NameList [lindex $input [expr $i*2+1]]
	lappend ValueList [lindex $input [expr $i*2+2]]
    }
    FillInfo
}

proc DrawMaterials { w what } {
    global GidPriv wdataw
    switch $what {
	onemat {
	    .central.s process escape escape escape escape data material draw \
		    $GidPriv(MaterialName)
	}
	allmats {
	    .central.s process escape escape escape escape data material draw \
		    -drawall-
	}
    }
    set SmallWinSelecting [.central.s info variable SmallWinSelecting]
    FinishButton $wdataw $wdataw.frame25.b1 [_ "Press 'Finish' when finished\ndrawing"] \
	    ".central.s process escape escape escape" disableall $SmallWinSelecting
}

proc AssignMaterials  { {type Elements} } {
    global wdataw GidPriv

    if { $GidPriv(MaterialName) == ""} {
	WarnWin [_ "Sorry, but first a material must be selected"] $wdataw
	return
    }

    if { $type != "Elements" } {
	.central.s process escape escape escape escape data mat assign \
		$GidPriv(MaterialName) $type
    } else {
	.central.s process escape escape escape escape data mat assign \
		$GidPriv(MaterialName)
    }

    set SmallWinSelecting [.central.s info variable SmallWinSelecting]
    FinishButton $wdataw $wdataw.frame25.b1 \
	[_ "Press 'Finish' to end selection"] \
	".central.s process escape escape escape" disableall $SmallWinSelecting
}

proc SendMaterialsAssign {} {
    global wdataw
    AddEntitiesToMenu $wdataw.frame25.b1.m AssignMaterials \
	    [list [_ "Lines"] [_ "Surfaces"] [_ "Volumes"] ] {Lines Surfaces Volumes} \
	    [list [_ "Elements"] ] {Elements}
}

#
#  Main Program
#


proc Dataw { type { Book "Default" } { w .wdat }  { NFields 0 } {args "" } } {
    global extens wdataw NumFields NameList ValueList GidPriv
    global NumMaterials NumIntervals NumConditions OldNumFields
    # VALENTI ###################
    global DefaultSearchDirectoryP
    # FVALENTI ##################
    set wdataw $w

    if { [InitWindow $w [_ "frames"] DatawWindowGeom] == "close" } {
	return
    }


    frame $wdataw.buttonframe -bd 0

    if { $type == "GENDATA" } { wm title $wdataw [_ "Problem Data"] }
    if { $type == "INTVDATA" } {

	wm title $wdataw [_ "Interval Data"]
	label $wdataw.buttonframe.l -text [_ "Intervals: "]
	menubutton $wdataw.buttonframe.mb -relief raised -menu \
		$wdataw.buttonframe.mb.m -width 10
	$wdataw.buttonframe.mb conf -bd 1 -highlightthickness 1
	menu $wdataw.buttonframe.mb.m -tearoff no -bd 1 -activeborderwidth 1
	set NumIntervals 0
	pack $wdataw.buttonframe.l $wdataw.buttonframe.mb -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
    }
    if { $type == "MATERIALS" } { 
	set GidPriv(UpDateMatsIdle) 0
	frame $wdataw.buttonframe2 -bd 0
	wm title $wdataw [_ "Materials"]
	label $wdataw.buttonframe.l0 -text [_ "New Material: "]
	entry $wdataw.buttonframe.e -relief sunken -width 15 -bd 1
	label $wdataw.buttonframe2.l -text [_ "Materials: "]
	combobox $wdataw.buttonframe2.mb -textvariable GidPriv(MaterialName)
	trace variable GidPriv(MaterialName) w UpDateMatsT
	set NumMaterials 0
	pack $wdataw.buttonframe.l0 $wdataw.buttonframe.e  -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	pack $wdataw.buttonframe2.l $wdataw.buttonframe2.mb -side left -padx 0 -pady 0 -ipadx 0 -ipady 0
	frame $wdataw.frame25 -bd 0
	menubutton $wdataw.frame25.b1 -text [_ "Assign"] -padx 5 \
		-menu $wdataw.frame25.b1.m  -relief raised -bd 1
	$wdataw.frame25.b1 conf -bd 1 -highlightthickness 1
	menu $wdataw.frame25.b1.m -postcommand SendMaterialsAssign -tearoff 0 -bd 1 -activeborderwidth 1

	menubutton $wdataw.frame25.b2 -text [_ "Draw"] -padx 5 -relief raised \
		-menu $wdataw.frame25.b2.m
	$wdataw.frame25.b2 conf -bd 1 -highlightthickness 1

	menu $wdataw.frame25.b2.m -bd 1 -activeborderwidth 1
	$wdataw.frame25.b2.m  add command -label [_ "This material"] -command \
	    "DrawMaterials $wdataw onemat"

	$wdataw.frame25.b2.m  add command -label [_ "All materials"] -command \
	    "DrawMaterials $wdataw allmats"


#         button $wdataw.frame25.b2 -text [_ "Draw"] -padx 5 -command {
#             .central.s process escape escape escape escape data mat draw \
#                     [lindex [$wdataw.buttonframe2.mb conf -text] 4]
#         }
	button $wdataw.frame25.b3 -text [_ "UnAssign"] -padx 5 -command {
	    set aa [mkDialogN $wdataw.modal  \
		    [list -text [_ "Sure, unassign all materials?"] \
		    -aspect 250 -justify left] [list [_ "Cancel"] Cancel]  [list [_ "Ok"] OK]]
	    if { $aa == "OK" } {
		.central.s process escape escape escape escape data mat unassign yes
	    }
	} -bd 1
	# VALENTI ##################
	button $wdataw.frame25.b4 \
		-text [_ "Import/Export"] \
		-bd 1 \
		-command {
	    set filename [tkFDialog \
		    -title [_ "Load Database"] \
		    -initialdir $DefaultSearchDirectoryP \
		    -parent $wdataw -opentype open \
		    -filetypes [_ "{{{Materials} {.mat}}}"]]
	    #passa de si es cancel o open, per aixo hi ha l'if
	    if { [string compare $filename ""] != 0 } {
		set DefaultSearchDirectoryP [file dirname $filename]
		saveMaterialsWindow $filename $Book
	    }
	}
	pack $wdataw.frame25.b1 $wdataw.frame25.b2 $wdataw.frame25.b3 $wdataw.frame25.b4 -side left \
		-anchor nw  -padx 2 -pady 2 -ipadx 0 -ipady 0
		#-padx 5 -pady 5 -anchor nw
	# FVALENTI ################# 
    }
    

    
    frame $wdataw.frame2 -relief raised -bd 1
    frame $wdataw.frame3 -bd 0
    button $wdataw.frame3.ok -text [_ "Accept Data"] -command {
	MakeNoise changesareaccepted
	UpDateVars
	set retval ""
	foreach i $ValueList {
	    append retval "$i "
	}
	if { $probtype == "GENDATA" } {
	    .central.s process escape escape escape escape data problemdata \
		    $retval
	}
	if { $probtype == "INTVDATA" } { 
	    .central.s process escape escape escape escape data Intervaldata \
		    $retval
	}
	if { $probtype == "MATERIALS" } {
	    WarnWin $retval
	    set newmatname [string trim [$wdataw.buttonframe.e get]]
	    if { [regexp { } $newmatname] } {
		tk_dialogRAM $wdataw.tempwinw [_ "Dialog window"] \
		    [_ "Material name not correct"] error 0 [_ "OK"]
		return
	    } 
	    if { $newmatname == "" } {
		set newmatname $GidPriv(MaterialName)
	    } 
	    set last [$wdataw.buttonframe2.mb list index end]
	    set write 1
	    for {set i 0} {$i < $last} {incr i} {
		set mat [$wdataw.buttonframe2.mb list get $i]
		if { $newmatname == $mat } { set write 0 ; break }
	    }
	    if { $write == 0 } {
		set res [tk_dialogRAM $wdataw.tempwinw [_ "Dialog window"] \
		             [_ "Overwrite material: '%s'?" $newmatname] gidquestionhead 1 [_ "OK"] [_ "Cancel"]
		if { $res == 0 } {
		    .central.s process escape escape escape escape data \
		            materials newmaterial $GidPriv(MaterialName) \
		            $newmatname yes $retval
		    set $GidPriv(MaterialName) $newmatname
		}
	    } else {
		.central.s process escape escape escape escape data \
		        materials newmaterial $GidPriv(MaterialName) \
		        $newmatname $retval
		set GidPriv(MaterialName) $newmatname
		$wdataw.buttonframe2.mb add $newmatname 
		tk_dialogRAM $wdataw.tempwinw [_ "Dialog window"] \
		    [_ "Entered new material: '%s'" $newmatname] info 0 [_ "OK"]
	    }
	}
    } -bd 1
    
    button $wdataw.frame3.dismiss -text [_ "Close"] -command "destroy $wdataw" -bd 1
    if { $type != "CONDITIONS" } {
	pack $wdataw.frame3.ok -side left  \
		-padx 0 -pady 0 -ipadx 0 -ipady 0
	#-padx 3 -ipadx 5
    }
    pack $wdataw.frame3.dismiss -side left  \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
    #-padx 3 -ipadx 5
#     pack $wdataw.msg -side top -fill x
    pack $wdataw.buttonframe -fill x  \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
    #-pady 3  -padx 3 -fill x
    if { $type == "CONDITIONS" || $type == "MATERIALS" } {
	pack $wdataw.buttonframe2 -fill x  \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
	#-pady 3  -padx 3 -fill x
    }
    
    pack $wdataw.frame3 -side bottom -anchor center \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
    #-pady 3
	if { [winfo exists $wdataw.frame28] } {  
	pack $wdataw.frame28 -side bottom  -fill x \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
    }
    if { [winfo exists $wdataw.frame25] } { 
	pack $wdataw.frame25 -side bottom -fill x \
		-padx 0 -pady 2 -ipadx 0 -ipady 0
	# -pady 5
    }
    pack $wdataw.frame2 -side top -fill both -expand yes -padx 0 -pady 2 -ipadx 0 -ipady 0

    canvas $wdataw.frame2.c -scrollregion {0c 0c 15c 80c} -width 300 \
	    -height 350 -yscrollcommand "$wdataw.frame2.vscroll set" \
	    -xscrollcommand "$wdataw.frame2.hscroll set"
    scrollbar $wdataw.frame2.vscroll  -relief sunken -command \
	    "$wdataw.frame2.c yview" -bd 1 -elementborderwidth 1
    scrollbar $wdataw.frame2.hscroll  -relief sunken -command \
	    "$wdataw.frame2.c xview" -orient horizontal -bd 1 -elementborderwidth 1
    pack $wdataw.frame2.vscroll -side right -fill y -padx 0 -pady 0 -ipadx 0 -ipady 0
    pack $wdataw.frame2.hscroll -side bottom -fill x -padx 0 -pady 0 -ipadx 0 -ipady 0
    pack $wdataw.frame2.c -in $wdataw.frame2 -expand yes -fill both -padx 0 -pady 0 -ipadx 0 -ipady 0
    lower $wdataw.frame2.c

    set OldNumFields 0
    if { $NFields > 0 } {
	set NumFields $NFields
	set NameList ""
	set ValueList ""
	for { set i 0 } { $i < $NumFields } { incr i 1 } {
	    lappend NameList [lindex $args [expr $i*2]]
	    lappend ValueList [lindex $args [expr $i*2+1]]
	}
	FillInfo
    } else { UpDate $type $w }

}

# KIKE ##################

namespace eval ::ExchangeMaterials {
    variable CurrMaterials
    variable DataMaterials
    variable ModifiedCurrMaterials
    variable ModifiedDataMaterials
}

proc saveMaterialsWindow {filename Book {w .saveMatWin}} {
    
    InitWindow $w [_ "Import/Export materials"] SaveMatWinWindowGeom

    frame $w.top -relief raised -bd 2

    # Show the current database materials  
    frame $w.top.finternal -relief raised -bd 2
    label $w.top.finternal.label -text [_ "Internal materials"]
    set sw1 [ScrolledWindow $w.top.finternal.swinternmat -relief sunken -bd 2 -auto both]
    set tree1 [Tree $sw1.tree -relief flat -borderwidth 0 \
		             -highlightthickness 0 -selectbackground "darkblue" \
		             -highlightbackground yellow -width 30 -redraw 1]
    
    $sw1 setwidget $tree1
    frame $w.top.finternal.fbut -relief raised 
    button $w.top.finternal.fbut.rename -text [_ "Rename"] \
	    -width 10 \
	    -command "::ExchangeMaterials::RenameSelMaterial $tree1 CurrMaterials"
    button $w.top.finternal.fbut.delete -text [_ "Delete"] \
	-width 10 \
	-command "::ExchangeMaterials::RemoveSelNode $tree1 CurrMaterials"
    button $w.top.finternal.fbut.apply -text [_ "Apply"] \
	-width 10 \
	-command [list ::ExchangeMaterials::UpdateGiDMaterials $w]

   
    # Show the external database materials  
    frame $w.top.fexternal -relief raised -bd 2
    label $w.top.fexternal.label -text [_ "External materials"]
    set sw2 [ScrolledWindow $w.top.fexternal.swexternmat -relief sunken -bd 2 -auto both]
    set tree2 [Tree $sw2.tree -relief flat -borderwidth 0 \
		             -highlightthickness 0 -selectbackground "darkblue" \
		             -highlightbackground yellow -width 30 -redraw 1]
    
    $sw2 setwidget $tree2
    frame $w.top.fexternal.fbut
    button $w.top.fexternal.fbut.rename -text [_ "Rename"] \
	-width 10 \
	-command "::ExchangeMaterials::RenameSelMaterial $tree2 DataMaterials"
    button $w.top.fexternal.fbut.delete -text [_ "Delete"] \
	-width 10 \
	-command "::ExchangeMaterials::RemoveSelNode $tree2 DataMaterials"
    button $w.top.fexternal.fbut.save -text [_ "Save"] \
	-width 10 \
	-command [list ::ExchangeMaterials::matSaveButton $filename $w]
    
    # Create the transfer buttons
    frame $w.top.fbut
    button $w.top.fbut.assign -text ">" -width "3"\
	    -command "::ExchangeMaterials::CopySelMaterial $tree1 $tree2 DataMaterials"
    button $w.top.fbut.assignall -text ">>" -width "3" \
	    -command "::ExchangeMaterials::CopyAllMaterials $tree1 $tree2 DataMaterials"
    button $w.top.fbut.deassign -text "<" -width "3" \
	    -command "::ExchangeMaterials::CopySelMaterial $tree2 $tree1 CurrMaterials"
    button $w.top.fbut.deassignall  -text "<<" -width "3" \
	    -command "::ExchangeMaterials::CopyAllMaterials $tree2 $tree1 CurrMaterials"

    
    set def_back [$w cget -background]
    frame $w.frmButtons -bg [CCColorActivo $def_back]
    button $w.frmButtons.btnclose -text [_ "Close"] \
	    -command "destroy $w" \
	    -underline 0 -width 6    


    grid $w.top.fexternal.label -sticky nsew
    grid $sw2 -sticky nsew
    grid $w.top.fexternal.fbut.rename $w.top.fexternal.fbut.delete $w.top.fexternal.fbut.save -pady 5 -padx 5 -sticky ew
    grid $w.top.fexternal.fbut -sticky sew

    
    grid $w.top.fbut.assign -pady 5 -padx 5
    grid $w.top.fbut.assignall -pady 5 -padx 5
    grid $w.top.fbut.deassign -pady 5 -padx 5
    grid $w.top.fbut.deassignall -pady 5 -padx 5

    grid $w.top.finternal.label -sticky nsew
    grid $sw1 -sticky nsew
    grid $w.top.finternal.fbut.rename $w.top.finternal.fbut.delete $w.top.finternal.fbut.apply -pady 5 -padx 5 -sticky ew
    grid $w.top.finternal.fbut -sticky sew

    grid $w.top.finternal $w.top.fbut $w.top.fexternal -pady 5 -padx 6 -sticky nsew
    grid columnconfigure $w.top.finternal "0" -weight 1
    grid rowconfigure $w.top.finternal "1" -weight 1
    grid columnconfigure $w.top.fexternal "0" -weight 1
    grid rowconfigure $w.top.fexternal "1" -weight 1
    grid $w.top -sticky nsew

    grid $w.frmButtons -sticky ews -columnspan 7
    grid $w.frmButtons.btnclose -padx 5 -pady 6
    grid columnconfigure $w.top "0 2" -weight 1
    grid rowconfigure $w.top "0" -weight 1

    grid columnconfigure $w "0" -weight 1
    grid rowconfigure $w "0" -weight 1


    ::ExchangeMaterials::InitMaterials $filename $Book
    #UpdateMaterialsPrim $w.top.fassigned databaseMaterials $Book
    #UpdateMaterialsPrim $w.top.flayers currentMaterials $Book
    
    ::ExchangeMaterials::FillTreeExchangeMaterials $tree1 CurrMaterials
    ::ExchangeMaterials::FillTreeExchangeMaterials $tree2 DataMaterials

    bind $w <Alt-c> "tkButtonInvoke $w.frmButtons.btnclose"
    bind $w <Escape> "tkButtonInvoke $w.frmButtons.btnclose"
   
    #bind $tree2 <Delete> "::ExchangeMaterials::RemoveNode $tree2 DataMaterials"

    focus $w.frmButtons.btnclose
}

proc ::ExchangeMaterials::InitMaterials { filename Book } {
    ::ExchangeMaterials::ReadCurrMaterials $Book
    ::ExchangeMaterials::DWReadMatfile $filename
}

proc ::ExchangeMaterials::DWReadMatfile { filename } {
    variable DataMaterials
    variable ModifiedDataMaterials

    catch { unset DataMaterials }   
    set bookname ""
    set f [open $filename r]
    if { $f == "" } { 
	WarnWin [_ "Error, cannot open file '%s'" $filename]
	return 
    }
    while { ![eof $f] } {
	gets $f aa
	if { $aa == "" || [string index $aa 0] == "#" } { 
	    continue
	} elseif { [regexp -nocase {BOOK:[ ]*([^ ]*)} $aa {} bookname] } {
	    if { ![info exists DataMaterials(MAT,bookslist)] || 
		[lsearch $DataMaterials(MAT,bookslist) $bookname] == -1 } {
		lappend DataMaterials(MAT,bookslist) $bookname
	    }
	} elseif { [regexp -nocase {[NUMBER:[ ]*([0-9]*)[ ]*]?MATERIAL:?[ ]*([^ ]*)} $aa {} matnum matname] } { 
	    lappend DataMaterials(MAT,nameslist) $matname
	    set DataMaterials(MAT,$matname,BOOK) $bookname
	    set inum 0
	    while { ![eof $f] } {
		gets $f aa
		if { $aa == "" || [string index $aa 0] == "#" } { continue }
		if { [regexp {^([^:]*):(.*)$} $aa {} field value] } {
		    set field [string trim $field]
		    set value [string trim $value]
		    if { $field == "QUESTION" } { incr inum }
		    if { $field == "DEPENDENCIES" } {
		        #can exists dependecies written with multiple lines
		        if { [info exists DataMaterials(MAT,$matname,$field,$inum)] } {
		            append DataMaterials(MAT,$matname,$field,$inum) $value
		        } else {
		            set DataMaterials(MAT,$matname,$field,$inum) $value                            
		        }                    
		    } else {
		        set DataMaterials(MAT,$matname,$field,$inum) $value
		    }
		} elseif { [regexp -nocase {^[ ]*END MATERIAL[ ]*$} $aa {}] } {
		    break
		} else {
		    WarnWin [_ "Error reading material, bad line '%s'" $aa]
		    close $f
		    return
		}          
	    }
	} else {
	    WarnWin [_ "Error reading material, bad line '%s'" $aa]
	    break 
	}
    }
    close $f

    foreach i [array names DataMaterials MAT,*,VALUE*] {
	if { [lindex $DataMaterials($i) 0] == "#N#" } {
	    set DataMaterials($i,0) [lindex $DataMaterials($i) 1]
	    for { set j 1 } { $j <= $DataMaterials($i,0) } { incr j } {
		set DataMaterials($i,$j) [lindex $DataMaterials($i) [expr $j+1]]
	    }
	}
    }
    set ModifiedDataMaterials 0
}

proc ::ExchangeMaterials::DWSaveMatfile { filename } {
    variable DataMaterials
    variable ModifiedDataMaterials
    set lastbookname ""
    set f [open $filename w]
    if { $f == "" } { 
	WarnWin [_ "Error, cannot open file '%s'" $filename]
	return 
    }
    set otherfields "HELP STATE IMAGE DEPENDENCIES TKWIDGET TITLE"
    set matnum 1
    foreach matname $DataMaterials(MAT,nameslist) {
	if { [info exists DataMaterials(MAT,$matname,BOOK)] && $DataMaterials(MAT,$matname,BOOK) != "" } {
	    if { $DataMaterials(MAT,$matname,BOOK) != $lastbookname } {
		set lastbookname $DataMaterials(MAT,$matname,BOOK)
		puts $f "BOOK:$DataMaterials(MAT,$matname,BOOK)"
	    }
	}
	puts $f "NUMBER:$matnum MATERIAL:$matname"
	# Write fields
	#can exists title before any question
	set nquest 0
	set i "TITLE"
	if { [info exists CurrMaterials(MAT,$matname,$i,$nquest)] } {
	    puts $f "$i:$DataMaterials(MAT,$matname,$i,$nquest)"
	    set value $CurrMaterials(MAT,$matname,$i,$nquest)
	}
	set nquest 1
	while {[info exists DataMaterials(MAT,$matname,QUESTION,$nquest)]} {
	    puts $f "QUESTION:$DataMaterials(MAT,$matname,QUESTION,$nquest)"
	    puts $f "VALUE:$DataMaterials(MAT,$matname,VALUE,$nquest)"
	    foreach i $otherfields {
		if {[info exists DataMaterials(MAT,$matname,$i,$nquest)]} {
		    puts $f "$i:$DataMaterials(MAT,$matname,$i,$nquest)"
		}                
	    }
	    # Increase question
	    incr nquest
	}       
	puts $f "END MATERIAL"
    
	# Increase material number
	incr matnum
    }
    close $f
    set ModifiedDataMaterials 0
}


proc ::ExchangeMaterials::ReadCurrMaterials { Book } {
    
    variable CurrMaterials   
    variable ModifiedCurrMaterials 
    # Obtain materials from GiD
    catch { unset CurrMaterials }
    
    foreach matname [.central.s info materials] {
	set bookname [.central.s info materials $matname BOOK]
	if { $bookname == "Default" } {
	    set bookname ""
	}
	#if { $bookname != $Book } continue
	if { $bookname != "" && ( ![info exists CurrMaterials(MAT,bookslist)] || 
	    [lsearch $CurrMaterials(MAT,bookslist) $bookname] == -1 ) } { 
	    lappend CurrMaterials(MAT,bookslist) $bookname
	}

	lappend CurrMaterials(MAT,nameslist) $matname
		
	set CurrMaterials(MAT,$matname,BOOK) $bookname

	set matparams [.central.s info materials $matname]
	set matparams [lrange $matparams 1 end]
	set inum  1
	foreach "field value" $matparams {
	    set CurrMaterials(MAT,$matname,QUESTION,$inum) $field            
	    set CurrMaterials(MAT,$matname,VALUE,$inum) $value
	    incr inum
	}
	set otherfields [.central.s info materials $matname OTHERFIELDS]
	if { $otherfields != "" } {
	    set otherfields [lrange $$otherfields 1 end]
	    foreach "field value inum" $otherfields {                
		set CurrMaterials(MAT,$matname,$field,$inum) $value 
	    }
	    
	}        
    }

    foreach i [array names CurrMaterials MAT,*,VALUE*] {
	if { [lindex $CurrMaterials($i) 0] == "#N#" } {
	    set CurrMaterials($i,0) [lindex $CurrMaterials($i) 1]
	    for { set j 1 } { $j <= $CurrMaterials($i,0) } { incr j } {
		set CurrMaterials($i,$j) [lindex $CurrMaterials($i) [expr $j+1]]
	    }
	}
    }
    set ModifiedCurrMaterials 0
}

#dataname must be DataMaterials or CurrMaterials
proc ::ExchangeMaterials::FillTreeExchangeMaterials { tree dataname } {
    upvar #0 ::ExchangeMaterials::$dataname Data
    $tree delete [$tree nodes root]
    #materials without any book
    if { [info exists Data(MAT,nameslist)] } {
	foreach matname $Data(MAT,nameslist) {
	    if { ![info exists Data(MAT,$matname,BOOK)] || 
	    $Data(MAT,$matname,BOOK) == "" } {
		$tree insert end root "->$matname" -text $matname \
		        -image [::Bitmap::get point16x16]            
	    }
	}
    }
    if { [info exists Data(MAT,bookslist) ] } {
	foreach bookname $Data(MAT,bookslist) {
	    $tree insert end root $bookname -text $bookname \
		    -image [::Bitmap::get folder]
	    foreach matname $Data(MAT,nameslist) {
		if { [info exists Data(MAT,$matname,BOOK)] &&
		$Data(MAT,$matname,BOOK) == $bookname } {
		    $tree insert end $bookname "$bookname->$matname" -text $matname \
		            -image [::Bitmap::get point16x16]
		}
	    }
	}
    }
}

proc ::ExchangeMaterials::matSaveButton { filename w } {
    variable ModifiedDataMaterials
    if { $ModifiedDataMaterials == "0" } return    

    if {[file writable $filename]==1} {
	set ret [tk_dialogRAM $w.tempwinw [_ "Dialog window"] \
		[_ "Are you sure to modify external materials file?"] \
		error 0 [_ "OK"] [_ "Cancel"]]
	if { $ret == 0 } {
	    ::ExchangeMaterials::DWSaveMatfile $filename
	}
    } else {
	WarnWin [_ "The selected file is write protected"]
    }
}

proc ::ExchangeMaterials::UpdateGiDMaterials { w } {
    variable CurrMaterials
    variable ModifiedCurrMaterials
    if { $ModifiedCurrMaterials == "0" } return

    set ret [tk_dialogRAM $w.tempwinw [_ "Dialog window"] \
	    [_ "Are you sure to modify the current materials?"] \
	    error 0 [_ "OK"] [_ "Cancel"]]
    if { $ret != 0 } {
	return
    }

    set otherfields "HELP STATE IMAGE DEPENDENCIES TKWIDGET TITLE"

    # Add/Remove materials loaded from database to GiD
    set memMaterials [.central.s info materials]    
    # Add materials
    foreach matname $CurrMaterials(MAT,nameslist) {        
	set found [lsearch $memMaterials $matname] 
	if {$found == -1} {        
	    # Add a new material to GiD
	    set cmd "Data Defaults BaseMaterial $matname"          
	    # Write fields
	    set cmd2 ""
	    if { [info exists CurrMaterials(MAT,$matname,BOOK)] } {
		set Book $CurrMaterials(MAT,$matname,BOOK)
	    }
	    set notherfields 0
	    set cmd3 ""
	    #can exists title before any question
	    set nquest 0
	    set i "TITLE"
	    if { [info exists CurrMaterials(MAT,$matname,$i,$nquest)] } {
		set value $CurrMaterials(MAT,$matname,$i,$nquest)
		set value [string map {{"} {\"}} $value]
		append cmd3 "$i \"$value\" [expr $nquest-1] "
		incr notherfields
	    }
	    set nquest 1
	    while {[info exists CurrMaterials(MAT,$matname,QUESTION,$nquest)]} {                
		set question $CurrMaterials(MAT,$matname,QUESTION,$nquest)
		set value $CurrMaterials(MAT,$matname,VALUE,$nquest)
		set value [string map {{"} {\"}} $value]
		append cmd2 "$question \"$value\" "        
		foreach i $otherfields {
		    if { [info exists CurrMaterials(MAT,$matname,$i,$nquest)] } {
		        set value $CurrMaterials(MAT,$matname,$i,$nquest)
		        set value [string map {{"} {\"}} $value]
		        append cmd3 "$i \"$value\" [expr $nquest-1] "
		        incr notherfields
		    }
		}
		incr nquest                
	    }
	    incr nquest -1
	    if { [info exists CurrMaterials(MAT,$matname,BOOK)] && 
		$CurrMaterials(MAT,$matname,BOOK) != "" } {
		set book $CurrMaterials(MAT,$matname,BOOK)
		if { $notherfields } {
		    set cmd "$cmd $nquest $cmd2 Book $book OtherFields $notherfields $cmd3 escape"
		} else {
		    set cmd "$cmd $nquest $cmd2 Book $book escape"
		}
	    } else {
		if { $notherfields } {
		    set cmd "$cmd $nquest $cmd2 OtherFields $notherfields $cmd3 escape"
		} else {
		    set cmd "$cmd $nquest $cmd2 escape"
		}
	    } 
	    .central.s process escape escape escape escape $cmd      
	}
    }
    # Remove materials
    foreach matname $memMaterials {      
	set found [lsearch $CurrMaterials(MAT,nameslist) $matname]
	if {$found == -1} {
	    #remove material from GiD
	    set cmd "Data Materials DeleteMaterial $matname escape" 
	    .central.s process escape escape escape escape $cmd
	}
    }
}

#dataname must be DataMaterials or CurrMaterials
proc ::ExchangeMaterials::RemoveSelNode { tree dataname } {
    variable Modified$dataname
    upvar #0 ::ExchangeMaterials::$dataname Data

    set node [$tree selection get]
    if { [string equal $node ""] } return
    
    #set bookname [lindex [split $node "->"] 0]
    #set matname [lindex [split $node "->"] 2]
    set bookname ""
    set matname ""
    regexp {(.*)->(.*)} $node dummy bookname matname

    if { $bookname != "" && $matname == "" } {
	#delete all the book
	foreach node [$tree nodes $bookname] {
	    $tree delete $node            
	    #set matname [lindex [split $node "->"] 2]
	    set matname ""
	    regexp {(.*)->(.*)} $node dummy bookname matname
	    set pos [lsearch $Data(MAT,nameslist) $matname]
	    if { $pos != -1 } {
		set Data(MAT,nameslist) [lreplace $Data(MAT,nameslist) $pos $pos]
		array unset Data MAT,$matname,*
	    }            
	}
	$tree delete $bookname
	if { [info exists Data(MAT,bookslist)] } {
	    set pos [lsearch $Data(MAT,bookslist) $bookname]
	    if { $pos != -1 } {
		set Data(MAT,bookslist) [lreplace $Data(MAT,bookslist) $pos $pos]
	    }
	}
    } else {
	set parent [$tree parent $node]
	$tree delete $node
	if { ![llength [$tree nodes $parent]] } {
	    #delete void book
	    $tree delete $parent
	    set bookname $parent
	    if { [info exists Data(MAT,bookslist)] } {
		set pos [lsearch $Data(MAT,bookslist) $bookname]
		if { $pos != -1 } {
		    set Data(MAT,bookslist) [lreplace $Data(MAT,bookslist) $pos $pos]
		}
	    }
	}
	set pos [lsearch $Data(MAT,nameslist) $matname]
	if { $pos != -1 } {
	    set Data(MAT,nameslist) [lreplace $Data(MAT,nameslist) $pos $pos]
	    array unset Data MAT,$matname,*
	}
    }
    set Modified$dataname 1
}

#dataname must be DataMaterials or CurrMaterials
proc ::ExchangeMaterials::CreateBook { tree dataname bookname } {
    variable Modified$dataname
    upvar #0 ::ExchangeMaterials::$dataname Data
    if { ![$tree exists $bookname] } {    
	$tree insert end root $bookname -text $bookname \
	    -image [::Bitmap::get folder]
    }
    if { ![info exists Data(MAT,bookslist)] || \
	    [lsearch $Data(MAT,bookslist) $bookname] == -1 } {
	lappend Data(MAT,bookslist) $bookname
    }
    set Modified$dataname 1
}

#dataname must be DataMaterials or CurrMaterials
proc ::ExchangeMaterials::CreateMaterial { tree dataname bookname matname } {
    variable Modified$dataname
    upvar #0 ::ExchangeMaterials::$dataname Data
    if { $dataname == "DataMaterials" } {
	upvar #0 ::ExchangeMaterials::CurrMaterials SourceData
    } else {
	upvar #0 ::ExchangeMaterials::DataMaterials SourceData
    }


    if { $bookname != "" && ![$tree exists $bookname] } {
	::ExchangeMaterials::CreateBook $tree $dataname $bookname
    }
    if { ![$tree exists "$bookname->$matname"] } {
	if { $bookname != "" } {
	    $tree insert end $bookname "$bookname->$matname" -text $matname \
		-image [::Bitmap::get point16x16]
	} else {
	    $tree insert end root "->$matname" -text $matname \
		-image [::Bitmap::get point16x16]       
	}
    }
    if { [lsearch $Data(MAT,nameslist) $matname] == -1 } {
	lappend Data(MAT,nameslist) $matname
	foreach i [array names SourceData MAT,$matname,*] {
	    set Data($i) $SourceData($i)            
	}
    }
    set Modified$dataname 1
}

proc ::ExchangeMaterials::CopyMaterial { tree dataname bookname matname } {
  if { [$tree exists "$bookname->$matname"] } return
  if { $bookname != "" && ![$tree exists $bookname] } {
    CreateBook $tree $dataname $bookname
  }
  CreateMaterial $tree $dataname $bookname $matname
}

proc ::ExchangeMaterials::CopySelMaterial { treesrc treedst datanamedst } {
    set node [$treesrc selection get]
    if { $node == "" } return
#     set bookname [lindex [split $node "->"] 0]
#     set matname [lindex [split $node "->"] 2]
    set bookname ""
    set matname ""
    regexp {(.*)->(.*)} $node dummy bookname matname
    if { $bookname != "" && $matname == "" } {
	foreach node [$treesrc nodes $bookname] {
#             set matname [lindex [split $node "->"] 2]
	    set matname ""
	    regexp {(.*)->(.*)} $node dummy bookname matname
	    CopyMaterial $treedst $datanamedst $bookname $matname
	}
    } else {
	CopyMaterial $treedst $datanamedst $bookname $matname
    }
}

proc ::ExchangeMaterials::CopyAllMaterials { treesrc treedst datanamedst } {
    foreach bookname [$treesrc nodes root] {
#         set matname [lindex [split $bookname "->"] 2]        
	set matname ""
	regexp {(.*)->(.*)} $bookname dummy b matname
	if { $matname == "" } {
	    foreach node [$treesrc nodes $bookname] {
#                 set matname [lindex [split $node "->"] 2]
		set matname ""
		regexp {(.*)->(.*)} $node dummy b matname
		CopyMaterial $treedst $datanamedst $bookname $matname
	    }
	} else {
	    #matname without book
	    CopyMaterial $treedst $datanamedst "" $matname
	}
    }
}

proc ::ExchangeMaterials::RenameSelMaterial { tree dataname } {
    set node [$tree selection get]
    if { $node == "" } return
    #set bookname [lindex [split $node "->"] 0]
    #set matname [lindex [split $node "->"] 2]
    set matname ""
    regexp {(.*)->(.*)} $node dummy bookname matname
    if { $matname != "" } {
	set newname [tk_dialogEntryRAM .gid.renamemat [_ "Material name"] \
		[_ "Enter the new name of %s" $matname] gidquestionhead any $matname]
	if { $newname == "--CANCEL--" } {
	    return            
	}
	RenameMaterial $tree $dataname $matname $newname
    }    
}

proc ::ExchangeMaterials::RenameMaterial { tree dataname matname newname } {
    variable Modified$dataname
    upvar #0 ::ExchangeMaterials::$dataname Data
       
    set bookname $Data(MAT,$matname,BOOK)
    set node "$bookname->$matname"
    #$tree edit $node $newname 
    set pos [$tree index $node]
    $tree delete $node
    set node "$bookname->$newname"
    if { $bookname != "" } {
	$tree insert $pos $bookname $node -text $newname -image [::Bitmap::get point16x16]
    } else {
	$tree insert $pos root $node -text $newname -image [::Bitmap::get point16x16]
    }

    foreach i [array names Data MAT,$matname,*] {
	# this is bad: regsub ",$matname," $i ",$newname," newi
	set newi [string map [list $matname $newname] $i]
	set Data($newi) $Data($i)     
    }
    array unset Data MAT,$matname,*
    set pos [lsearch $Data(MAT,nameslist) $matname]
    if { $pos != -1 } {
	set Data(MAT,nameslist) [lreplace $Data(MAT,nameslist) $pos $pos $newname]
    }
    set Modified$dataname 1
}
