
# This code creates the ICEM CFD Manager.
#
# Copyright (c) 1993 - 1996 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

# Routines that implement the user-level commands in the manager.

# Config routines. -----------------------------------------------------

proc config_open {new} {
    global confname geoname place partname partfile sheetname
    global icem_fluent icem_powermesh default_geoname
    global tag_meshname tnh_meshname ddn_directory gui_name
    
    if {$confname != ""} release_config_lock
    
    # Figure out the possible configuration names.
    set configs [possible_configurations]
    
    while 1 {
	if {$new || ($configs == "")} {
	    toplevel .select_one
	    set cname [select_one_lc .select_one \
		       "-text \"Enter the name of a new $gui_name(conf).\"" \
			   {} $confname {}]
	} else {
	    toplevel .select_one
	    set cname [select_one_lc .select_one \
		       "-text \"Select a $gui_name(conf) from the list below by\
double-clicking on it with the left mouse button, or type the name of\
a new one and press return.\"" $configs $confname {}]
	}
	if {($cname == "*cancel*") || ($cname == "")} { return 0 }
	
	if ![file exists mulcad/$cname] {cmd_mkdir mulcad/$cname}
	if {[check_path_component $cname $gui_name(Conf)] && \
		[get_config_lock $cname]} break
    }
    
    set confname $cname
    if ![file exists objects/$confname] {cmd_mkdir objects/$confname}
    
    geom_open
    
    return 1
}

# ----------------------------------------------------------------

proc config_copy {} {
    global confname gui_name
    
    set configs [possible_configurations]
    if {$configs == ""} {errormsg "There are no $gui_name(conf)s."; return}
    while 1 {
	if {$confname == ""} {
	    toplevel .select_one
	    set cname [select_one_lc .select_one \
			   "-text \"Select the $gui_name(conf) to copy.\"" \
			   $configs {} {}]
	} else {
	    toplevel .select_one
	    set cname [select_one_lc .select_one \
			   "-text \"Select the $gui_name(conf) to copy, or type return to \
select the current $gui_name(conf).\"" $configs $confname {}]
	}
	if {($cname == "*cancel*") || ($cname == "")} return
	if [check_path_component $cname $gui_name(Conf)] break
    }
    
    if {![file exists mulcad/$cname]} {
	errormsg "No such $gui_name(conf) \"$cname\""
	return
    }
    while 1 {
	set to [query_enter .query "Name of new $gui_name(conf)?" ""]
	if {($to == "*cancel*") || ($to == "")} return
	if [check_path_component $to $gui_name(Conf)] break
    }
    if {$to == $cname} {
	errormsg "Source and destination names are the same"
	return
    }
    if {[file exists mulcad/$to]} {
	errormsg "Cannot overwrite existing $gui_name(conf) $to"
	return
    }
    infomsg "Copying $gui_name(conf)..."
    cmd_cp_r mulcad/$cname mulcad/$to
    if [file exists objects/$cname] {
	infomsg "Copying objects directory..."
	cmd_cp_r objects/$cname objects/$to
    }
    cmd_rm mulcad/$to/config_lock
    infomsg "Done."
}

proc config_delete {} {
    global confname geoname place gui_name
    
    set configs [possible_configurations]
    if {$configs == ""} {errormsg "There are no $gui_name(conf)s."; return}
    if {$confname == ""} {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		   "-text \"Select the $gui_name(conf) to delete.\"" \
		       $configs {} {}]
    } else {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(conf) to delete, or type return to \
select the current $gui_name(conf).\"" $configs $confname {}]
    }
    if {$cname == "*cancel*"} return
    
    if {![file exists mulcad/$cname] || ($cname == "")} {
	errormsg "No such $gui_name(conf) \"$cname\""
	return
    }
    
    if {[query_question .query "Delete $gui_name(conf) $cname?"] == "*cancel*"} return
    
    infomsg "Removing directory mulcad/$cname..."
    if [catch {cmd_rm_r mulcad/$cname} res] {
	errormsg $res
    }
    if [file exists objects/$cname] {
	infomsg "Removing directory objects/$cname..."
	if [catch {cmd_rm_r objects/$cname} res] {
	    errormsg $res
	}
    }
    infomsg "Done."
    
    if [file exists mulcad/$cname] {
	warningmsg "The $gui_name(conf) directory couldn't be removed.\n\
Please check the permissions and/or remove it in a UNIX shell."
    }
    
    if {$cname == $confname} {
	set confname ""
	set geoname ""
	update_partlist - 0
	unset_config_lock
    }
}

proc config_rename {} {
    global confname gui_name
    
    set configs [possible_configurations]
    if {$configs == ""} {errormsg "There are no $gui_name(conf)s."; return}
    if {$confname == ""} {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(conf) to rename.\"" \
		       $configs {} {}]
    } else {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(conf) to rename, or type return to \
select the current $gui_name(conf).\"" $configs $confname {}]
    }
    if {($cname == "*cancel*") || ($cname == "")} return

    if {![file exists mulcad/$cname]} \
	{errormsg "No such $gui_name(conf) \"$cname\""; return}
    
    while 1 {
	set to [query_enter .query "New name of $gui_name(conf)?" ""]
	if {($to == "*cancel*") || ($to == "")} return
	if [check_path_component $to $gui_name(Conf)] break
    }
    
    if {$to == $cname} {
	errormsg "Source and destination names are the same"
	return
    }
    
    if {[file exists mulcad/$to]} {
	errormsg "Cannot overwrite existing $gui_name(conf) $to"
	return
    }
    cmd_rename mulcad/$cname mulcad/$to
    if [file exists objects/$cname] {
	cmd_rename objects/$cname objects/$to
    }
    if {$cname == $confname} {
	# Don't need to update the config lock.
	set confname $to
	update_partlist m 0
    }
}

# ----------------------------------------------------------------

proc geom_open {} {
    global confname geoname place partname partfile sheetname
    global icem_fluent icem_powermesh default_geoname
    global tag_meshname tnh_meshname ddn_directory gui_name
    
    set geos [possible_geometries]
    if {$geos == ""} {set geos $default_geoname}
    if {!$icem_fluent && !$icem_powermesh || ([llength $geos] != 1)} {
	while 1 {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
			   "-text \"Select a $gui_name(geo), or enter the name of a new one.\"" \
			   $geos [lfirst $geos] {}]
	    if {($gname == "*cancel*") || ($gname == "")} { return 0 }
	    if [check_path_component $gname $gui_name(Geo)] break
	}
    } else {
	set gname [lindex $geos 0]
    }
    
    set geoname $gname
    if ![file exists $place] {
	cmd_mkdir $place
	set pmesh mulcad/$confname/$default_geoname/mesh
	if {($geoname != $default_geoname) && \
		([file exists $pmesh/boco] || [file exists $pmesh/clust])} {
	    if {[query_question .query \
		    "Copy clust, boco, and padset from\
		    $default_geoname?"] == "*okay*"} {
		catch {cmd_mkdir $place/mesh}
		catch {cmd_cp $pmesh/boco $place/mesh/boco}
		catch {cmd_cp $pmesh/clust $place/mesh/clust}
		catch {cmd_cp $pmesh/padset $place/mesh/padset}
	    }
	}
    }
    if {!$icem_fluent && !$icem_powermesh} {
	if ![file exists objects/$confname/$geoname] {
	    cmd_mkdir objects/$confname/$geoname 
	}
    }
    
    # Just to be sure.
    if ![file exists parts] {cmd_mkdir parts}
    if ![file exists $place/parts] {cmd_mkdir $place/parts}
    if ![file exists $place/mesh] {cmd_mkdir $place/mesh}
    if ![file exists $place/domains] {cmd_mkdir $place/domains}
    if {!$icem_fluent && !$icem_powermesh} {
	if ![file exists $place/import] {cmd_mkdir $place/import}
    }
    
    if {[file exists $place/padamm_taurus] && \
	    ([glob -nocomplain $place/padamm_taurus/*] == "")} {
	infomsg "Deleting empty \"padamm_taurus\" directory\n"
	cmd_rm_r $place/padamm_taurus
    }
    
    if [file exists $place/padamm_taurus] {
	if [file exists $place/transfer] {
	    warningmsg "Both \"padamm_taurus\" and \"transfer\" directories\
		    exist in this $gui_name(conf) and $gui_name(geo)  \"transfer\"\
		    is the new name for this directory.  If you have files\
		    in \"padamm_taurus\" that you need, you will have to\
		    move them to \"transfer\" manually."
	} else {
	    cmd_rename $place/padamm_taurus $place/transfer
	    warningmsg "Moving \"padamm_taurus\" to \"transfer\"."
	}
    } elseif ![file exists $place/transfer] {
	cmd_mkdir $place/transfer
    }
    
    set partname ""
    set partfile ""
    set sheetname ""
    
    update_partlist - 0
    domain_reset_history
    
    catch {unset tag_meshname}
    catch {unset tnh_meshname}
    
    if {[file exists $place/parts] && \
	    [file exists $place/parts/$ddn_directory]} {
	set ptime [file mtime $place/parts]
	set dtime [file mtime $place/parts/$ddn_directory]
	if {$ptime > $dtime} {
	    infomsg "Updating DDN directory in $place/parts -- it looks\
		like it is out of date..."
	    update_partlist m 1
	}
    }
    global prism_values
    catch {unset prism_values}
}

proc geom_copy {} {
    global confname geoname gui_name
    
    if {$confname == ""} { errormsg "$gui_name(Conf) not set."; return }
    set geos [possible_geometries]
    if {$geos == ""} {errormsg "There are no geometries."; return}
    while 1 {
	if {$geoname == ""} {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(geo) to copy.\"" \
			   $geos {} {}]
	} else {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(geo) to copy, or type return to \
select the current $gui_name(geo).\"" $geos $geoname {}]
	}
	if {($gname == "*cancel*") || ($gname == "")} return
	if [check_path_component $gname $gui_name(Geo)] break
    }
    
    if {![file exists mulcad/$confname/$gname]} {
	errormsg "No such $gui_name(geo) \"$gname\""
	return
    }
    while 1 {
	set to [query_enter .query "Name of new $gui_name(geo)?" ""]
	if {($to == "*cancel*") || ($to == "")} return
	if [check_path_component $to $gui_name(Geo)] break
    }
    if {$to == $gname} {
	errormsg "Source and destination names are the same"
	return
    }
    if {[file exists mulcad/$confname/$to]} {
	errormsg "Cannot overwrite existing $gui_name(geo) $to"
	return
    }
    infomsg "Copying $gui_name(geo)..."
    cmd_cp_r mulcad/$confname/$gname mulcad/$confname/$to
    if [file exists objects/$confname/$gname] {
	infomsg "Copying objects directory..."
	cmd_cp_r objects/$confname/$gname objects/$confname/$to
    }
    infomsg "Done."
}

proc geom_delete {} {
    global confname geoname place gui_name
    
    if {$confname == ""} { errormsg "$gui_name(Conf) not set."; return }
    set geos [possible_geometries]
    if {$geos == ""} {errormsg "There are no geometries."; return}
    while 1 {
	if {$geoname == ""} {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(geo) to delete.\"" \
			   $geos {} {}]
	} else {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(geo) to delete, or type return to \
select the current $gui_name(geo).\"" $geos $geoname {}]
	}
	if {($gname == "*cancel*") || ($gname == "")} return
	if [check_path_component $gname $gui_name(Geo)] break
    }
    
    if {![file exists mulcad/$confname/$gname]} {
	errormsg "No such $gui_name(geo) \"$gname\""
	return
    }
    
    if {[query_question .query "Delete $gui_name(geo) $gname?"] == "*cancel*"} return
    
    infomsg "Removing directory mulcad/$confname/$gname..."
    cmd_rm_r mulcad/$confname/$gname
    if [file exists objects/$confname/$gname] {
	infomsg "Removing directory objects/$confname/$gname..."
	cmd_rm_r objects/$confname/$gname
    }
    infomsg "Done."
    
    if [file exists mulcad/$confname/$gname] {
	warningmsg "The $gui_name(geo) directory couldn't be removed\n\
Please check the permissions and remove it in UNIX"
    }
    
    if {$gname == $geoname} {
	set geoname ""
	update_partlist - 0
    }
}

proc geom_rename {} {
    global confname geoname gui_name
    
    if {$confname == ""} { errormsg "$gui_name(Conf) not set."; return }
    set geos [possible_geometries]
    if {$geos == ""} {errormsg "There are no geometries."; return}
    while 1 {
	if {$geoname == ""} {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(geo) to rename.\"" \
			   $geos {} {}]
	} else {
	    toplevel .select_one
	    set gname [select_one_lc .select_one \
			   "-text \"Select the $gui_name(geo) to rename, or type return to \
select the current $gui_name(geo).\"" $geos $geoname {}]
	}
	if {($gname == "*cancel*") || ($gname == "")} return
	if [check_path_component $gname $gui_name(Geo)] break
    }
    
    if {![file exists mulcad/$confname/$gname]} {
	errormsg "No such $gui_name(geo) \"$gname\""
	return
    }
    while 1 {
	set to [query_enter .query "New name of $gui_name(geo)?" ""]
	if {($to == "*cancel*") || ($to == "")} return
	if [check_path_component $to $gui_name(Geo)] break
    }
    if {$to == $gname} {
	errormsg "Old and new names are the same"
	return
    }
    if {[file exists mulcad/$confname/$to]} {
	errormsg "Cannot overwrite existing $gui_name(geo) $to"
	return
    }
    cmd_rename mulcad/$confname/$gname mulcad/$confname/$to
    if [file exists objects/$confname/$gname] {
	cmd_rename objects/$confname/$gname objects/$confname/$to
    }
    infomsg "Done."
    
    if {$gname == $geoname} {
	set geoname $to
    }

    update_partlist m 1
}

# ----------------------------------------------------------------------

proc config_objgeo {} {
    global confname geoname waiting_for_part partfile gui_name
    
    if {$confname == ""} { errormsg "$gui_name(Conf) not set."; return }
    if {$geoname == ""} { errormsg "$gui_name(Geo) not set."; return }
    set oplace objects/$confname/$geoname
    while 1 {
	set waiting_for_part 1
	set cpart [query_waitvar .query "Select a DDN part to copy to the objects\
		directory (Cancel = done)."]
	if {$cpart == "*cancel*"} break
	
	if [part_is_mulcad] { errormsg "You must select a DDN part."; continue }
	
	infomsg "Copying part file to $oplace ..."
	cmd_cp $partfile $oplace
	infomsg "Done."
    }
}

proc config_chdir {} {
    
    release_config_lock
    
    set olddir [pwd]
    set newdir [query_path .query "New directory?" $olddir]
    if {$newdir == "*cancel*"} return
    if [catch {cd $newdir}] {
	errormsg "Can't change directory"
	return
    }
    if ![check_dirtree] { cd $olddir; return }

    set_title
    reset_label_vars
    config_open 0
}

proc config_cpdir {} {
    global rcp_path env is_win
    
    if $is_win {
	errormsg "This operation is not implemented on windows"
	return
    }
    
    if [info exists env(USER)] {
	set me $env(USER)
    } else {
	set me [exec whoami]
    }
    set machine [query_enter .query "Machine to copy from?" ""]
    if {$machine == "*cancel*"} return
    set user [query_enter .query "User name on $machine?" $me]
    if {$user == "*cancel*"} return
    set remdir [query_enter .query "Directory on $machine\
	    (relative to ~$user)?" ""]
    if {$remdir == "*cancel*"} return
    set locdir [query_enter .query "Directory on local machine?" ../$remdir]
    if {$locdir == "*cancel*"} return
    
    if [file exists $locdir] {
	errormsg "Can't overwrite directory \"$locdir\""
	return
    }
    
    runcom "$rcp_path -r $user@$machine:$remdir $locdir"
}

proc config_archive {} {
    global confname tar_path compress_path uuencode_path gui_name
    
    set configs [possible_configurations]
    if {$configs == ""} {errormsg "There are no $gui_name(conf)s."; return}
    if {$confname == ""} {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(conf) to archive.\"" \
		       $configs {} {}]
    } else {
	toplevel .select_one
	set cname [select_one_lc .select_one \
		       "-text \"Select the $gui_name(conf) to archive, or type return to \
select the current $gui_name(conf).\"" $configs $confname {}]
    }
    if {($cname == "*cancel*") || ($cname == "")} return
    
    if {![file exists mulcad/$cname]} \
	{errormsg "No such $gui_name(conf) \"$cname\""; return}

    set file [query_path .query "Archive file?" "/tmp/config_${cname}.tar.Z.uu"]
    if {$file == "*cancel*"} return
    
    set dir [file dirname $file]
    set tarf $dir/$cname:tar_[pid]
    set ztarf $tarf.gz
    
    infomsg "Tarring ..."
    cmd_tar -cf $tarf mulcad/$cname
    infomsg "Compressing with gzip ..."
    cmd_rm $ztarf
    cmd_gzip $tarf
    infomsg "Uuencoding ..."
    set here [pwd]
    cd $dir
    cmd_uuencode $ztarf $file [file tail $ztarf]
    cmd_rm $ztarf
    cd $here

    infomsg "Done."
    catch {infomsg [exec /bin/ls -l $file]}
}

proc config_unarchive {} {
    global confname tar_path uncompress_path uudecode_path gui_name
        
    set file [query_path .query "Archive file?" "/tmp/"]
    if {$file == "*cancel*"} return
    
    if ![file exists $file] {
	errormsg "File \"$file\" doesn't exist"
	return
    }
    
    if [file isdirectory $file] {
	errormsg "File \"$file\" is a directory"
	return
    }
    
    set fp [open $file r]
    while {![eof $fp]} {
	set line [gets $fp]
	if {([llength $line] == 3) && ([lindex $line 0] == "begin")} {
	    set archname [lindex $line 2]
	    break
	}
    }
    close $fp
    if ![info exists archname] {
	errormsg "This file does not appear to be a uuencoded archive file."
	return
    }
    set cname [lindex [split $archname :] 0]
    if {($cname == "") || ($cname == $archname)} {
	errormsg "This file seems not to have been created by the ICEM CFD Manager"
	return
    }
    if [file exists mulcad/$cname] {
	errormsg "Can't overwrite $gui_name(conf) $cname"
	return
    }
    
    set dir [file dirname $file]
    set here [pwd]
    cd $dir
    infomsg "Uudecoding ..."
    cmd_uudecode $file
    infomsg "Uncompressing ..."
    cmd_rm [file rootname $archname]
    cmd_gzip -d $archname
    set archname [file rootname $archname]
    cd $here
    
    infomsg "Untarring ..."
    cmd_tar -xf $dir/$archname
    cmd_rm $dir/$archname
    
    if {[query_question .query "Remove archive file \"$file\"?"] == "*okay*"} {
	cmd_rm $file
    }
    
    infomsg "Done."
}

proc config_quit {} {
    global icem_fluent icem_powermesh
    
    if $icem_fluent {
	set what "GeoMesh"
    } elseif $icem_powermesh {
	set what "ICEM CFD Powermesh"
    } else {
	set what "ICEM CFD"
    }
    
    if [tk_dialog .really_quit "Quit" \
	    "Confirm exit from the $what Manager" "" -1 Okay Cancel] return
    
    release_config_lock
    
    exit 0
}

proc make_linked_apps {} {
    global env
    
    foreach app {mulcad tetra frontal input prebfc} {
	infomsg "Rebuilding the $app linked application ..."
	if [catch {exec $env(ICEM_ACN)/bin/make_$app} res] {
	    warningmsg $res
	}
    }
    infomsg "All done rebuilding."
}

proc util_edit_vars {} {
    global modal_data icem_fluent icem_powermesh cfdcae

    set mods {}
    foreach mod $modal_data {
        if {[lindex $mod 0] == "solver"} {set mod [util_parse_solvers $mod]}
	if {!$icem_fluent && !$icem_powermesh || [lindex $mod 5]} { lappend mods $mod }
    }

    set res [varchange .modals "$cfdcae Modals" $mods]
    if {$res == "*okay*"} dump_modals
}

proc util_parse_solvers {mod} {
    global env is_aea

#
# Copy all solvers to list that will be returned
#
    set mod_changed {}
    foreach ent $mod { lappend mod_changed $ent }
#
# Only when AEA is current running mode
#
    if {[ info exists is_aea] && ($is_aea == "1")} {
      infomsg "Checking availability of solver interfaces"
#
# Check first if there is a OUTPUT license available
#
      catch {exec $env(ICEM_ACN)/icemcfd/license_check -license_OUTPUT > ./tmp_solver_list}

      set result {}
      set file ./tmp_solver_list
      set fd [open $file r]
      while 1 {
         set line [gets $fd]
         if [eof $fd] break
         lappend result $line
#        puts stdout "$line"
      }
      close $fd
      set a [split $result " "]
      set result $a
#
# Check if License Error appeared
#
      if { [lindex $result 3] != "OUTPUT" } {
         catfile " " ./tmp_solver_list
         eval exec "/bin/rm -f ./tmp_solver_list"
      } else {
        if { [lindex $result 3] == "OUTPUT" && [lindex $result 5] > 0 } {
#
# Use All Solvers if OUTPUT license is available
#
           eval exec "/bin/rm -f ./tmp_solver_list"
        } else {
#
# Use only AEA Solvers if OUTPUT license is not available
#
           set preset_solver Plot3d
           set mod_aea {}
           set mod_changed {}
           lappend mod_aea CFX-4
           lappend mod_aea CFX-5
           lappend mod_aea CFX-TASCflow
           lappend mod_aea Plot3d
           lappend mod_changed [lindex $mod 0] [lindex $mod 1] \
               $mod_aea [lindex $mod 3] $preset_solver [lindex $mod 5] 
           
        }
      }
    }
    return $mod_changed
}


proc util_edit_paths {} {
    global pathname_data icem_fluent icem_powermesh cfdcae

    set paths {}
    foreach path $pathname_data {
	if {!$icem_fluent && !$icem_powermesh || [lindex $path 5]} {
	    lappend paths $path
	}
    }

    if {$icem_fluent} {
	infomsg "This function is not available in GeoMesh."
    } else {
	set res [varchange .pathnames "$cfdcae Pathnames" $paths]
	if {$res == "*okay*"} dump_pathnames
    }
}

proc util_change_icem_acn {} {
    global env

    set oldval $env(ICEM_ACN)
    
    set newval [query_path .query "Enter a new value for the ICEM_ACN variable." \
		$env(ICEM_ACN)]
    if {$newval == "*cancel*"} return
    
    if {![file exists $newval] || ![file isdirectory $newval]} {
	errormsg "That isn't a valid pathname for a directory."
	return
    }
    if {![file exists $newval/bin/icemddn]} {
	warningmsg "That probably isn't an ICEM directory tree, but setting it \
anyway..."
    }

    set env(ICEM_ACN) $newval
    update_pathnames $oldval $newval
    
    update_ld_library_path
}

proc util_mulcad_convert {} {
    global env place partname
    
    set pn $partname; if {$pn == ""} { set pn none }
    
    set cmd "$env(ICEM_ACN)/bin/tclsh $env(ICEM_ACN)/lib/med/mulcad.tcl \
	      $place $pn mulcad.unstruct"
    mess "$cmd\n"
    runxcom MULCAD_HEXA "$cmd" "" 1 0
}

proc util_delete_domains {} {
    global place gui_name
    
    if {$place == ""} {
	errormsg "The $gui_name(conf) or $gui_name(geo) is not set."
	return
    }
    set doms [domain_select $place/domains "Select the domains to delete." \
	    mixed 1]
    if {$doms == ""} return
    set n [llength $doms]
    if {[query_question .query "Delete [llength $doms] domain files?"] \
	    == "*cancel*"} return
    foreach d $doms {
	if [catch {cmd_rm_r $d} res] {
	    errormsg $res
	}
    }
}

proc util_shell {pt} {
    global xterm_params place xterm_prog gui_name is_win
    
    if {$pt != ""} {
	if {$place == ""} {
	    errormsg "No $gui_name(conf) selected"
	    return
	}
	if {![file exists $place/$pt]} {
	    errormsg "Directory $pt does not exist"
	    return
	}
	set here [pwd]
	cd $place/$pt
    }
    if $is_win {
	set err [catch {cmd_xterm} errmsg]
    } else {
	set err [catch {eval cmd_xterm $xterm_params &} errmsg]
    }
    if [info exists here] { cd $here }
    if $err { errormsg $errmsg }
}

proc util_check_lic {} {
    global env xterm_params
    if [file exists $env(ICEM_ACN)/ddn/autlook] {
	set command "$env(ICEM_ACN)/ddn/autlook ; $env(ICEM_ACN)/icemcfd/license_check"
    } else {
	set command $env(ICEM_ACN)/icemcfd/license_check
    }
    set xterm_params_backup $xterm_params
    set xterm_params "-geometry =90x24+0+0\
             -fn 9x15bold -fg black -cr black -bg wheat -sb -sl 10000"
    runxcom LICENSE_CHECK "$command" "" 1 0
    set xterm_params $xterm_params_backup
}

proc util_editor {} {
    set file [query_path .query "Filename?" [pwd]/]
    if {$file == "*cancel*"} return
    run_editor $file
}

proc util_toggle_run {} {
    global runcoms
    if $runcoms then \
	{infomsg {Not running commands}; set runcoms 0} else \
	{infomsg {Running commands again}; set runcoms 1}
}

proc util_cleanup {} {
    global place gui_name
    if {$place == ""} {
	errormsg "$gui_name(Conf) or $gui_name(geo) is undefined"
	return
    }
    eval cmd_rm [glob -nocomplain $place/transfer/{tape*,I*,G*,T*}]
}

proc util_tcl {} {
    global prev_command
    
    set com [query_enter .query "Enter Tcl command:" ""]
    if {$com == "*cancel*"} return
    
    if {($com == "") && [info exists prev_command]} {set com $prev_command}
    if {$com == "^^"} {set com [selection get]}
    set prev_command $com
    
    catch {uplevel #0 eval \{$com\}} result
    infomsg "Result: $result"
}

proc util_gplot {} {
    global gplot_path place printer_name no_exec_errors
    
    set file "plots/"
    set output PostScript
    
    if {![dialog .gplot Gplot \
	  "Please edit the following options for Gplot." \
	  {
	      {file -type path -title "CGM file" -help "This should be a \
CGM plot file that was produced by DDN."}
	      
	      {use_printer -title "Send to printer" -group print -help \
		      "This option determines whether the PostScript\
		      output file will be sent to the printer."}
	      
	      {printer_name -type string -title "Printer name" -group print \
		  -active {$use_printer} \
		  -help "This is the name of the printer that the output will \
		  be sent to.  It must be a PostScript printer."}
	      
	      {output -type string -title "Output file" -group print \
		  -help "This is the output file to which the PostScript \
		  plot will be written."}
	  }]} return
    
    if ![file exists $file] {
	warningmsg "CGM file $file doesn't exist!"
	return
    }
    
    infomsg "Gplot (C) 1987, Pittsburgh Supercomputing Center."
    infomsg "Please contact ICEM CFD Engineering for more information."
    
    runcom "$gplot_path -C -dPS $file $output 2>&1" "" 1
    
    if $use_printer {
	print_file $output
    }
}

proc util_autoplot {} {
    global autoplot_path place printer_name
    
    if 0 {
	set ddn_plots [glob -nocomplain "plots/pl*"]
	if {$place != ""} {
	    set padamm_plots [glob -nocomplain "$place/transfer/pl*"]
	} else {
	    set padamm_plots {}
	}
    }

    set file "plots/"
    set output PostScript
    
    if {![dialog .autoplot Autoplot \
	  "Please edit the following options for Autoplot." \
	  {
	      {file -type path -title "Tape9 file" -help "This should be a \
tape9 plot file that was produced by DDN."}
	      
	      {units -opt {{Inches INCH} {Centimeters CM}} -title "Units" \
		  -help "This option determines whether units in the tape9 \
file are interpreted as inches or centimeters."}
	      
	      {banner -title "Include banner" -help "This option determines \
whether a banner is included in the output."}
	      
	      {use_printer -title "Send to printer" -group print -help "This option \
determines whether the PostScript output file will be sent to the printer."}
	      
	      {printer_name -type string -title "Printer name" -group print \
		  -active {$use_printer} \
		  -help "This is the name of the printer that the output will \
be sent to.  It must be a PostScript printer."}
	      
	      {output -type string -title "Output file" -group print \
		  -active {!$use_printer} \
		  -help "This is the output file to which the PostScript \
plot will be written."}
	  }]} return
    
    if {![file exists $file]} {
	warningmsg "Tape9 file doesn't exist!"
	return
    }
    
    if $use_printer {
	set command "$autoplot_path -tape9 $file -m $units -laser $printer_name"
    } else {
	set command "$autoplot_path -tape9 $file -m $units -file $output"
    }
    if {!$banner} {set command "$command -nobanner"}
    
    runxcom Autoplot $command "" 1 0
}

proc util_clear_lock {} {
    global is_win
    
    if $is_win return
    
    infomsg "Clearing all lock bits ..."
    if [catch {exec find . -exec chmod a-lst \{\} \;} res] {
	warningmsg $res
    }
}

# App routines. -------------------------------------------------------

proc app_compose_remote {dlrem} {
    global env
    
    if {$dlrem != "y"} { return ""; }
    
    set host1 [split $env(DISPLAY) :]
    if {$host1 == ""} {
	set host1 [cmd_uname_n]
	set ret " -host $host1"
    } else {
	set ret " -host [lindex $host1 0]"
    }    
    return $ret
}

proc app_ddn {} {
    global partfile partname sheetname ddn_path icem_fluent env icem_powermesh
    global gui_name
    
    if {($partname == "") && ![pick_part $gui_name(geopart)]} return
    
    if { !$icem_fluent && !$icem_powermesh } {
	if {($partfile != "") && [part_is_mulcad] && \
	    [query_question .query \
	     "The current part is in the $gui_name(meshpart) directory: really run DDN?"] \
		== "*cancel*"} return
    }
    
    if {$partfile == ""} then \
	{set db parts} else \
	{set db [file dirname $partfile]}
    set command "$ddn_path db=$db pn=[ddn_partname $partname] sn=$sheetname \
dbms=no [get_ddn_defaults] lf=yes hd=y pi=yes bb=n"
    runxcom DDN $command "" 1 0
    update_partlist d 0
}

proc app_comak {} { app_mulcad "" COMAK comak }

proc app_mulcad {{extras ""} {appname MULCAD} {tfile mulcad}} {
    global partfile place confname geoname partname sheetname ddn_path env
    global editor solver padamm_terse remotehost gui_name
    
    if {$place == ""} {
	errormsg "$gui_name(Conf) or $gui_name(geo) is undefined"
	return
    }
    if {($partname == "") && ![pick_part $gui_name(meshpart)]} return
    
    if {($partfile != "") && ![part_is_mulcad] && [query_question .query \
	    "The current part is not in the $gui_name(meshpart) directory:\
	    really run $appname?"] == "*cancel*"} return
    
    if {![file exists $place/domains]} { cmd_mkdir $place/domains }
    
    # First write out the modals that are interesting.
    
    set ed [file tail $editor]
    if {$remotehost == ""} {
	set rh localhost
    } else {
	set rh $remotehost
    }
    if {$padamm_terse == "true"} {
	set pt YES
    } else {
	set pt NO
    }
    
    set modal_line(10085) " 10085 'EDITOR' = '$ed'"
    set modal_line(10141) " 10141 'QUIET EXECUTION' = '$pt'"
    set modal_line(10140) " 10140 'REMOTE HOST' = '$rh'"
    #set modal_line(10135) " 10135 'USE COMAK' = 'YES'"

    set modal_system(10085) "SYSTEM/ 'BASIC MULCAD MODALS'"
    set modal_system(10141) "SYSTEM/ 'PADAMM - GEN. MODALS'"
    set modal_system(10140) "SYSTEM/ 'MESH GEN. MODALS'"
    #set modal_system(10135) "SYSTEM/ 'BASIC MULCAD MODALS'"    
    
    if [file exists .mulcad_modals] {
	set mf [open .mulcad_modals r]
	set lines ""
	while {![eof $mf]} { lappend lines [gets $mf] }
	close $mf
	cmd_rm .mulcad_modals
	set mf [open .mulcad_modals w]
	foreach line $lines {
	    set m [lindex $line 0]
	    if [info exists modal_line($m)] {
		puts $mf $modal_line($m)
		unset modal_line($m)
	    } else {
		puts $mf $line
	    }
	}
	foreach m [array names modal_line] {
	    puts $mf "*"
	    puts $mf $modal_system($m)
	    puts $mf $modal_line($m)
	}
	close $mf
    } else {
	set mf [open .mulcad_modals w]
	puts $mf "ICEM MULCAD - VERSION 3.1.2 - MODALS FILE"
	foreach m [array names modal_line] {
	    puts $mf "*"
	    puts $mf $modal_system($m)
	    puts $mf $modal_line($m)
	}
	close $mf
    }
    
    set restart_name [tmpname]
    catch {cmd_rm $restart_name}
    set restart [open $restart_name w]
    puts $restart "y"
    puts $restart "F.1.16.4"
    puts $restart "$env(ICEM_ACN)/common/tfile_$tfile]"
    puts $restart "3.LOWER"
    puts $restart F.5.13.5.6
    puts $restart $env(ICEM_ACN)/common/gpl
    puts $restart "F"
    puts $restart "F.5.13.7.$appname"
    puts $restart $confname
    puts $restart $geoname
    if {$extras != ""} {
	foreach ex $extras { puts $restart $ex }
    }
    close $restart
    if {$partfile == ""} then \
	{set db $place/parts} else \
	{set db [file dirname $partfile]}
    set command "$ddn_path db=$db pn=[ddn_partname $partname] sn=$sheetname \
i=$restart_name dbms=no [get_ddn_defaults] lf=yes pi=yes bb=n"
    runxcom $appname $command "" 1 0
    
    # Now see if the modals are changed...
    if ![catch {open .mulcad_modals r} mf] {
	while {![eof $mf]} {
	    set line [gets $mf]
	    set ll [llength $line]; incr ll -1
	    set val [string trim [lindex $line $ll] ']
	    case [lindex $line 0] in {
		10085 {
		    # 10085 'EDITOR' = 'ed'
		    set editor $ed
		}
		10086_unused {
		    # 10086 'ANALYSIS CODE' = 'sol'
		    case $val in {
			{DYNA3D Dyna3d}      {set solver Dyna3d}
			{FIDAP Fidap}        {set solver Fidap}
			{FLUENT Fluent}      {set solver Fluent}
			{NASTRAN Nastran}    {set solver Nastran}
			{CFD_ACE CFD-ACE}    {set solver CFD-ACE}
			{AIRFLOW3D Airflo3d} {set solver Airflo3d}
			{STAR_CD Star-CD}    {set solver Star-CD}
			default {
			    warningmsg "Didn't understand solver \"$val\" from Mulcad"
			}
		    }
		}
		10141 {
		    # 10141 'QUIET EXECUTION' = 'pt'
		    case $val in {
			YES {set padamm_terse true}
			NO  {set padamm_terse false}
		    }
		}
		10140 {
		    # 10140 'REMOTE HOST' = 'rh'
		    if {$val == "localhost" || $val == "LOCALHOST"} {
			set remotehost ""
		    } else {
			set remotehost $val
		    }
		}
	    }
	}
	close $mf
    }
    
    update_partlist m 0
}

proc app_auto_comak {} {
    app_mulcad {
	1.1.12.].]
	16
	5.2.].]
	].]
	y
	10.3
	y
	y
	y
	].9.6.y
    }
}

# This script automatically runs comak and updates the topology.  The
# answers argument is needed in case the comak script asks some questions.

proc auto_comak {pname {answers ""}} {
    global partname sheetname confname geoname
    
    unselect_part
    set ff mulcad/$confname/$geoname/parts/[string tolower $pname]
    catch {cmd_rm [glob $ff*]}
    update_partlist m 1
    set partname $pname
    set sheetname 1
    
    set extras [concat {
	1.1.12.].]
	16
	5.2.].]
    } $answers {
	].]
	y
	10.3
	y
	y
	y
	].9.6.y
    }
    app_mulcad $extras
}

proc auto_padamm {pname} {
    global partname sheetname confname geoname padamm_terse
    
    set padamm_terse true
    
    set partname $pname
    set sheetname 1
    set extras {
	1.1.14.2.].]
	11.2.1.1.2.]
	5.3
	].].]
	9.6.y
    }
    app_mulcad $extras
    
    update_partlist m 1
    set_part_partfile mulcad/$confname/$geoname/parts/iparta.1
    app_padamm
}

proc app_ddn_tetra {} {
    global place ddn_mesher_license gui_name
    
    if {$place == ""} {
	errormsg "Can't run DDN Mesher Interface -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    set dir $place/mesh
    
    switch $ddn_mesher_license {
	Hexa   { set ddnml 1 }
	Tetra  { set ddnml 2 }
	Global { set ddnml 3 }
    }
    
    run_ddn_linked DDN_Mesher m tetra "$dir\n$ddnml"
    #run_ddn_linked DDN_Mesher m tetra "$dir"
}

proc app_tetra {} {
    global place partname tetra_path gui_name n_processors max_binary_tetin
    
    puts "in app_tetra"
    if {$place == ""} {
	errormsg "Can't run Tetra -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }

    check_tetin1
    
    set input [ get_tetin_file $place ]
    if { $input == "" } return
    
    set ifile $place/mesh/$input
    
    if {![file exists $ifile]} {
	errormsg "File $input does not exist in mesh directory"
	return
    }
    
    scan $input "tetin%d" number
    
    set ofile $place/domains/uncut_domain.$number
    
    cmd_rm tetra_params
    build_tetra_param_file tetra_params $ifile $ofile
    if {[query_question .query "Write output also to log file?"] == "*okay*"} {
	for {set i 1} {[file exists $place/mesh/tetra_log.$i]} {incr i} {}
	set command "$tetra_path tetra_params |& tee $place/mesh/tetra_log.$i"
    } else {
	set command "$tetra_path tetra_params"
    }
    if { $n_processors > 1 } {
	append command " -nproc $n_processors"
    }
    if { $max_binary_tetin >= 0 } {
	append command " -max_binary $max_binary_tetin"
    }
    runxcom_remote TETRA $command "" 1 1
}

proc app_cutter {} {
    global place cutter_path ddnterm gui_name dlrem
    
    set remote [app_compose_remote $dlrem]
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    if {$place == ""} {
	errormsg "Can't run Cutter -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    set input [ get_tetin_file $place ]
    
    if { $input == "" } return
    
    scan $input "tetin%d" number
        
    set sfile $place/mesh/$input
    set ifile $place/domains/uncut_domain.$number
    set ofile $place/domains/cut_domain.$number

    # Don't ask about closegaps -- this is not wanted.
    # set command "$cutter_path $ifile $sfile $ofile closegaps"
    
    set command "$cutter_path $ifile $sfile $ofile $x $remote"
    
    runxcom CUTTER $command "" 1 1
}

proc app_tetra_editor {} {
    global place env ddnterm black_and_white gui_name is_win
    
    switch $ddnterm {
        x11     { set x " -x" }
        OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    if $black_and_white { set bw " -bw" } else { set bw "" }

    if {$place == ""} {
        errormsg "Can't run the Tetra GUI -- the $gui_name(conf) or \
$gui_name(geo) is not set."
        return
    }

    check_tetin1
    
    foreach v {
        {TETRA tetra}
        {TETRA_LEO leo}
        {COARSE tri_coarse}
        {CUTTER cutter}
        {IMPROVER tetra_smoother}
    } {
        global [lindex $v 1]_path
        set env([lindex $v 0]_BIN) [set [lindex $v 1]_path]
    }
    catch {unset env(LEO_TETRA)}
    set env(LEO_TETRA_HACK) 1
    
    set prog "$env(ICEM_ACN)/bin/leo"
    set command "$prog -tetra $x $bw $place"
    if { $n_processors } {
	append command " -nproc $n_processors"
    }
    if { $max_binary_tetin >= 0 } {
	append command " -max_binary $max_binary_tetin"
    }

    runxcom TETRA_GUI $command "" 1 1
}

proc app_tetra_smoother {{triang 0}} {
    global place smoother tetra_smoother_path tri_smoother_path
    global n_processors max_binary_tetin
    
    check_tetin1
    
#
# select the domain file
#
    set domain [domain_select $place/domains "Select an unstructured domains." unstruct 0]
    if {$domain == {}} return
    
    set domain_file $domain
#
# select the tetin file
#
    set tetin_file [ get_tetin_file $place ]
    
# don't really need a tetin ile
#    if {$tetin_file == ""} return

    set tetin_path $place/mesh/$tetin_file
    
#
# run the smoother 
#
    if $triang {
	set command "$tri_smoother_path $domain_file $tetin_path"
    } else {
	set command "$tetra_smoother_path $domain_file $tetin_path"
	if { $n_processors > 0  } {
		append command " -nproc $n_processors"
	}
        if { $max_binary_tetin >= 0 } {
	    append command " -max_binary $max_binary_tetin"
        }
    }

    runxcom SMOOTHER $command "" 1 1
}

proc app_coarsener {} {
    global place tri_coarse_path coarse_output coarse_dev coarse_asp
    global coarse_done
    
    set domain [domain_select $place/domains \
	    "Select an unstructured triangular surface domain." unstruct 0]
    if {$domain == {}} return
    set coarse_output [file tail $domain.coarse]
    
    set num 0
    if ![file exists $place/mesh/boco] {
	warningmsg "No boco file."
    } else {
	set fams [exec grep {^*} $place/mesh/boco]
	foreach fam [split $fams \n] {
	    incr num
	    set fam_name($num) [string range $fam 1 end]
	}
	if !$num {
	    warningmsg "No families found in boco file."
	}
    }
    toplevel .coarse
    
    frame .coarse.out
    label .coarse.out.l -text "Output file:"
    entry .coarse.out.e -relief sunken -background white -borderwidth 2 \
	    -textvariable coarse_output
    pack .coarse.out.l -side left -fill both
    pack .coarse.out.e -side left -fill both -expand 1
    
    set swin [scroller_simple .coarse.params]
    
    label $swin.faml -text Family
    label $swin.devl -text "Max deviation"
    label $swin.aspl -text "Aspect ratio"
    blt_table $swin $swin.faml 0,0
    blt_table $swin $swin.devl 0,1
    blt_table $swin $swin.aspl 0,2
    
    if ![info exists coarse_dev(def)] { set coarse_dev(def) "" }
    if ![info exists coarse_asp(def)] { set coarse_asp(def) 0.1 }
    label $swin.famdef -text Default
    entry $swin.devdef -relief sunken -background white -borderwidth 2 \
	    -textvariable coarse_dev(def)
    entry $swin.aspdef -relief sunken -background white -borderwidth 2 \
	    -textvariable coarse_asp(def)
    blt_table $swin $swin.famdef 1,0
    blt_table $swin $swin.devdef 1,1
    blt_table $swin $swin.aspdef 1,2
    
    foreach e "$swin.devdef $swin.aspdef" {
	bind $e <2> {catch {%W insert insert [selection get]}}
    }
    
    for {set i 1} {$i <= $num} {incr i} {
	if ![info exists coarse_dev($i)] { set coarse_dev($i) "" }
	if ![info exists coarse_asp($i)] { set coarse_asp($i) "" }
	label $swin.fam$i -text $fam_name($i)
	entry $swin.dev$i -relief sunken -background white -borderwidth 2 \
		-textvariable coarse_dev($i)
	entry $swin.asp$i -relief sunken -background white -borderwidth 2 \
		-textvariable coarse_asp($i)
	set c [expr {$i + 1}]
	blt_table $swin $swin.fam$i $c,0
	blt_table $swin $swin.dev$i $c,1
	blt_table $swin $swin.asp$i $c,2
	
	foreach e "$swin.dev$i $swin.asp$i" {
	    bind $e <2> {catch {%W insert insert [selection get]}}
	}
    }

    frame .coarse.buts
    button .coarse.buts.done -text Done -command "set coarse_done 1" \
	    -width 1
    button .coarse.buts.cancel -text Cancel -command "set coarse_done 0" \
	    -width 1
    pack .coarse.buts.done .coarse.buts.cancel \
	    -side left -fill both -expand 1 -padx 5 -pady 5
    
    pack .coarse.out .coarse.params .coarse.buts -side top -fill both -expand 1
    
    wm geometry .coarse +200+200
    wm title .coarse "Triangle coarsener parameters"
    tkwait variable coarse_done
    destroy .coarse
    if !$coarse_done return
    
    cmd_rm coarse_params
    set fp [open coarse_params w]
    for {set i 1} {$i <= $num} {incr i} {
	set line "define_family $i"
	if {($coarse_dev($i) != "") && $coarse_dev($i)} {
	    append line " max_deviation $coarse_dev($i)"
	}
	if {($coarse_asp($i) != "") && $coarse_asp($i)} {
	    append line " min_aspect $coarse_asp($i)"
	}
	puts $fp $line
    }
    puts $fp return
    close $fp
    
    set command "$tri_coarse_path $domain $place/domains/$coarse_output \
	    -t $coarse_dev(def) -a $coarse_asp(def) -p coarse_params"

    runxcom COARSENER $command "" 1 1
}

proc app_stamp {what} {
    global place stamp_path partfile ddn_path place icem_stamp
    global confname geoname env partname sheetname gui_name
    
    if {$place == ""} {
	errormsg "Can't run stamp -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    if {$what == "ddn"} {
	if {$partfile == ""} {
	    errormsg "Can't run the DDN stamp interface -- no project part is selected"
	    return
	}
	
	set quest "The current part is not in the $gui_name(meshpart) directory:\
                   really run Stamp DDN?"
	if {($partfile != "") && ![part_is_mulcad] && \
	    ([query_question .query $quest] == "*cancel*")} return
	
	set fmts [glob -nocomplain $place/transfer/*.fmt]
	if {$fmts == ""} {
	    errormsg "Can't run stamp -- there are no .fmt files available."
	    return
	}
	
	set rfmts {}
	foreach f $fmts { lappend rfmts [file rootname [file tail $f]] }
	toplevel .fmt
	set fmtname [select_one .fmt {-text "Select a .fmt file for input to the\
                                      DDN stamping interface."} $rfmts "" {}]
	if {$fmtname == "*cancel*"} return
	
	set restart_name [tmpname]
	set restart [open $restart_name w]
	puts $restart "y"
	puts $restart "F"
	puts $restart "F.5.13.5.3.!gpl/gpllib_stamp"
	puts $restart "F.5.13.3.STAMP"
	puts $restart $confname
	puts $restart $geoname
	puts $restart $fmtname.fmt
	close $restart
	
	if {$partfile == ""} then \
	    {set db $place/parts} else \
	    {set db [file dirname $partfile]}
	set command "$ddn_path db=$db pn=[ddn_partname $partname] sn=$sheetname \
i=$restart_name dbms=no [get_ddn_defaults] lf=yes pi=yes bb=n"
	runxcom STAMP $command "" 1 0
	cmd_rm $restart_name
	
	update_partlist m 0
	return
    }

    if {![file exists $place/stamping]} {
	errormsg "Can't run stamp -- no $place/stamping directory."
	return
    }
    set files [glob -nocomplain $place/stamping/*.dkr]
    set choices {}
    foreach file $files {
	regsub .dkr [file tail $file] "" choice
	lappend choices $choice
    }
    if {$choices == {}} {
	errormsg "No stamp input files available."
	return
    }
    toplevel .select_one
    set input [select_one_lc .select_one \
	       "-text {Pick a Stamp input file.}" \
		   $choices [lindex $choices 0] {}]
    if {$input == "*cancel*"} return
    
    set command "$stamp_path -$what . $input"
    set back [pwd]
    cd $place/stamping
    runxcom STAMPING $command "" 1 1
    cd $back
}


# ----------------------------------------------------------------------

proc app_blockmod {} {
    global env confname partname partfile sheetname geoname
    global icem_fluent icem_powermesh pcube_path is_win

    if {$partname == ""} {
	errormsg "You must first select a project part."
	return
    }

    if {($partfile != "") && ![part_is_mulcad]} {
	errormsg "Can't run P-cube on a part in the DDN directory -- you must\
select one in the Projects directory or move a DDN part."
	return
    }
    
    set db mulcad/$confname/$geoname/parts

if !$is_win {    
   if { !$icem_fluent && !$icem_powermesh } {
       set my_workstation [exec /bin/uname]
       if {[string match "IRIX*" $my_workstation]} {
	 set tcl_level tcl7.0
	 set tk_level  tk3.3
       } else {
	 set tcl_level tcl7.0
	 set tk_level  tk3.3
       }

# make sure that topology directory exists - 22.4.94 - GWH

    if {![file exists mulcad/$confname/topology]} {
	 exec /bin/mkdir mulcad/$confname/topology
    }

# provide vendor name for P-Cube startup - 8.5.94 - GWH
    set env(ICEM_CDC) 1 

# changed to work in same way as geomesh - 18.4.94 - GWH

    set command "/bin/echo ; \
 setenv TCL_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tcl_level/library; \
 setenv TK_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tk_level/library; \
 $pcube_path db=$db pn=[ddn_partname $partname] sn=$sheetname dbms=no \
 [get_pcube_defaults] lf=yes"


  } else {
     set tcl_level tcl7.0
     set tk_level  tk3.3
    set command "/bin/echo ; \
    setenv TCL_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tcl_level/library; \
    setenv TK_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tk_level/library; \
    $pcube_path db=$db pn=[ddn_partname $partname] sn=$sheetname dbms=no \
    [get_pcube_defaults] lf=yes"
  }

}

if $is_win {
   set tcl_level tcl7.5
   set tk_level tk4.1
   set p1 [pwd]
  
   infomsg "TCL_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tcl_level"
   infomsg "TK_LIBRARY $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tk_level"

   set env(TCL_LIBRARY) $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tcl_level
   set env(TK_LIBRARY) $env(ICEM_ACN)/ddn/fbd/tcl/tcl/$tk_level

   if {![file exists $p1/mulcad/$confname/topology ]} {
	 exec mkdir $p1/mulcad/$confname/topology
    }

   set command "$env(ICEM_ACN)/bin/pcube.exe "
   set pwd [pwd]
   catch {exec del out.pcube}

   if ![info exists env(WIN95)] {
# Windows NT
     set old_path "$env(Path)"
     set env(Path) " "
     set env(Path) "$env(ICEM_ACN)/ddn/fbd/tcl/lib;/Netscape/Navigator/Program"
     catch {exec $command db=$pwd/$db pn=$partname sn=$sheetname dbms=no  [get_pcube_defaults] > out.pcube} res
     set env(Path) "$old_path"
   } else {
# Windows 95
     set old_path "$env(PATH)"
     set env(PATH) " "
     set env(PATH) "$env(ICEM_ACN)/ddn/fbd/tcl/lib;/Netscape/Navigator/Program"
     catch {exec $command db=$pwd/$db pn=$partname sn=$sheetname dbms=no  [get_pcube_defaults] > out.pcube} res
     set env(PATH) "$old_path"
   }

   if [file exists out.pcube] {
         set res [exec cat.exe out.pcube]
         infomsg "$res" 
   }
   infomsg "DONE"
   
} else {
    runxcom P-Cube $command "" 1 1
}
    update_partlist - 1

}


proc app_input {} {run_ddn_linked ICEM_Input d inputg ""}

proc app_frontal {} {run_ddn_linked Frontal d frontg ""}

proc app_ddn_global {} {
    global place xterm_prog gui_name
    
    if {$place == ""} {
	errormsg "Can't run Global -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    
    set cart_file $place/mesh/cart_file
    set epilog_file $place/mesh/epilog
    set domain_file $place/domains/global_domain
    set config_dir $place

    set epi [open $epilog_file w]
    puts $epi "print 0 \"enter return to create global file\\n\""
    puts $epi interactive
    puts $epi fix_missing_intercepts
    puts $epi "print 0 \"saving to $domain_file\\n\""
    puts $epi "save $domain_file"
    puts $epi "print 0 \"save to $domain_file complete\\n\""
    puts $epi interactive
    puts $epi quit
    close $epi

    run_ddn_linked Global_Grid m global "$config_dir\n$xterm_prog\n$cart_file"
}

proc get_tetin_file { place } {
    set tetin ""
    set files [glob -nocomplain "$place/mesh/tetin*"]
    set files2 [glob -nocomplain "$place/mesh/*.tin"]
    set files "$files $files2"
    set inputs {}
    foreach file $files {
	set ft [file tail $file]
	lappend inputs $ft
    }
    if {$inputs == ""} {
	errormsg "No tetin files available!"
	return ""
    }
    
    if {[llength $inputs] > 1} {
	toplevel .select_one
	set tetin [select_one_lc .select_one "-text {Pick a Tetin file.}" \
		$inputs [lindex $inputs 0] {}]
	if {$tetin == "*cancel*"} return ""
    } else {
	set tetin [lindex $inputs 0]
    }
    return $tetin
}

proc app_hex {{extra ""}} {
    global place partname hex_path black_and_white ddnterm gui_name env is_win
    global batch dlrem displayhost
    
    set remote [app_compose_remote $dlrem]
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
	
    if {$place == ""} {
	errormsg "Can't run Hex -- the $gui_name(conf) or\
$gui_name(geo) is not set."
	return
    }

    check_tetin1
    
    set tetin [ get_tetin_file $place ]
    if { $tetin == "" } {
	return
    }

    if $batch {
	runcom "$hex_path $place -tetin $tetin < "
    } else {
	set env(HEXA_BIN) $hex_path
    
	if $black_and_white { set bw -bw } else { set bw "" }
	
	set prog $env(ICEM_ACN)/icemcfd/hex_gui
	if $is_win {
	    set prog "$hex_path -f $env(ICEM_ACN)/lib/hexa/guibase/guibase.tcl \
		-tool $env(ICEM_ACN)/lib/hexa/hexa.tcl"
	}
	set command "$prog $bw $x $place -tetin $tetin $extra"
	if { [ info exists displayhost ] } {
	    if { $displayhost != "" } {
		append command " -host $displayhost"
	    }
	}
	runxcom HEX $command "" 1 [expr {$extra == ""}]
    }
}

proc app_unput {} {
    global place env unput_path ddnterm black_and_white gui_name
    global ddn_mesher_license is_win dlrem
       
    check_tetin1
    
    set remote [app_compose_remote $dlrem]
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    if $black_and_white { set bw " -bw" } else { set bw "" }
    
    if {$place == ""} {
	errormsg "Can't run Unput -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    
    set env(UNPUT_BIN) $unput_path

    set prog $env(ICEM_ACN)/icemcfd/unput_gui
    if $is_win { set prog "$unput_path -f \
       $env(ICEM_ACN)/lib/unput/guibase/guibase.tcl -tool \
       $env(ICEM_ACN)/lib/unput/unput.tcl" }
    set command "$prog $x $bw \
	-domdir $place/import -descdir $place/mesh -ddnml $ddn_mesher_license"

    runxcom UNPUT $command "" 1 1
}

proc app_thex {} {
    global confname place thex_path gui_name

    check_tetin1
    
    if {$place == ""} {
        errormsg "The $gui_name(conf) or $gui_name(geo) is not set."
        return
    }

    set domain [domain_select $place/domains "Pick a triangle domain." unstruct 0]
    if {$domain == {}} return

# get name for quadratic elements domain
    set outfile [query_path .query "Quad output file?" \
		     "$place/domains/tri_quad"]
    if {$outfile == "*cancel*"} return
    
    set input [ get_tetin_file $place ]
    if { $input == "" } return

    set sfile $place/mesh/$input
    
    set command "$thex_path $domain $sfile $outfile"
    
    runxcom THEX $command "" 1 1
}

proc app_global_gui {} {
    global place global_path black_and_white ddnterm gui_name env is_win
    global batch dlrem
    
    check_tetin1
    
    set remote [app_compose_remote $dlrem]
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    if $black_and_white { set bw " -bw" } else { set bw "" }
    
    if {$place == ""} {
	errormsg "Can't run the Global GUI -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    
    if $batch {
	runcom "$global_path $place/mesh/cart_file < "
    } else {
	
	set env(GLOBAL_BIN) $global_path
    
	if $is_win {
	    set guibase $env(ICEM_ACN)/lib/global/guibase/guibase.tcl
	    set tool $env(ICEM_ACN)/lib/global/global.tcl
	    set prog "$global_path -f $guibase -tool $tool"
	} else {
	    set prog $env(ICEM_ACN)/icemcfd/global_gui
	}
	set cart_file $place/mesh/cart_file
	set command "$prog $bw $x $remote $cart_file"
	runxcom GLOBAL $command "" 1 1
    }
}

proc app_tetra_gui {} {
    global place env ddnterm black_and_white gui_name is_win dlrem
    global displayhost n_processors max_binary_tetin
    
    check_tetin1
    
    set remote [app_compose_remote $dlrem]
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    if $black_and_white { set bw " -bw" } else { set bw "" }

    if {$place == ""} {
	errormsg "Can't run the Tetra GUI -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }

    check_tetin1
    
    foreach v {
	{TETRA tetra}
	{TETRA_LEO leo}
	{COARSE tri_coarse}
	{CUTTER cutter}
	{IMPROVER tetra_smoother}
    } {
	global [lindex $v 1]_path
	set env([lindex $v 0]_BIN) [set [lindex $v 1]_path]
    }
    
    set prog $env(ICEM_ACN)/icemcfd/tetra_gui

    if $is_win { set prog "$env(ICEM_ACN)/icemcfd/cutter -f $env(ICEM_ACN)/lib/tetra/guibase/guibase.tcl -tool $env(ICEM_ACN)/lib/tetra/tetra.tcl" }
    set command "$prog $x $bw $place"
    if { [ info exists displayhost ] } {
	if { $displayhost != "" } {
		append command " -host $displayhost"
	}
    }
    if { [ info exists n_processors ] } {
	if { $n_processors > 1 } {
		append command " -nproc $n_processors"
	}
    }
    if { [ info exists max_binary_tetin ] } {
	if { $max_binary_tetin >= 0 }  {
		append command " -max_binary $max_binary_tetin"
	}
    }

    runxcom TETRA_GUI $command "" 1 1
}

proc check_tetin1 {} {
    global place is_win

    if !$is_win return

    set tin [lindex [glob -nocomplain $place/mesh/*.tin] 0]
    if {$tin == ""} return

    cmd_rm $place/mesh/tetin1
    cmd_cp $tin $place/mesh/tetin1
    mess "Note: copied [file tail $tin] to tetin1\n"
}

proc app_autohex {} {
    global place env ddnterm black_and_white global_path confname gui_name
    
    switch $ddnterm {
	x11     { set x " -x" }
	default { set x "" }
    }
    
    if {$place == ""} {
	errormsg "Can't run AutoHex -- the $gui_name(conf) or \
$gui_name(geo) is not set."
	return
    }
    
    set env(AUTOHEX_ROOT) $env(ICEM_ACN)
    
    set command "$env(ICEM_ACN)/bin/autohex $x $confname"
    
    runxcom AUTOHEX $command "" 1 1
}

proc app_med {} {
    global env ddnterm place
    
    if ![info exists env(MED_ROOT)] {
	set env(MED_ROOT) $env(ICEM_ACN)
    }
    
    if [info exists env(MED_BIN)] {
	set prog $env(MED_BIN)
    } else {
	set prog $env(MED_ROOT)/bin/med
    }
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    set command "$prog $x $place"
    
    runxcom MED $command "" 1 1
}

proc app_visual3 {} {
    global env ddnterm
    
    if ![info exists env(VISUAL3_DIR)] {
	set env(VISUAL3_DIR) $env(ICEM_ACN)
    }
    
    if [info exists env(VISUAL3_BIN)] {
	set prog $env(VISUAL3_BIN)
    } else {
	set prog $env(VISUAL3_DIR)/bin/visual3
    }
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    set command "$prog $x"
    
    runxcom VISUAL3 $command "" 1 1
}

proc app_mom3d {} {
    global env place
    
    if ![info exists env(MOM3D_DIR)] {
	set env(MOM3D_DIR) $env(ICEM_ACN)
    }
    
    set command "$env(ICEM_ACN)/icemcfd/mom3d_gui -dir $place"
    
    runxcom MOM3D $command "" 1 1
}


proc get_famnames {{surface_file ""}} {
	global fam_visible place
	set family_boco ""

	if { $surface_file != "" && \
		[ file exists $place/mesh/$surface_file ] } {
		if { [ catch { exec grep read_family_boco \
			$place/mesh/$surface_file } line ] == 0 } {
			set family_boco [ lindex $line 1 ]
			set family_boco "$place/mesh/$family_boco"
		}
	}
	if {$family_boco == "" } {
	    set famnames [ array names fam_visible ] 
	    if { $famnames != "" } {
# if there are names on the screen use them
		set famnames [lsort $famnames]
		return $famnames
	    }
	}
	if { $family_boco == "" } {
		set family_boco "$place/mesh/family_boco"
	}
	if [ file exists $family_boco ] {
		set fp [open $family_boco r]
		set famnames ""
		while {![eof $fp]} {
			set line [gets $fp]
			set fam [ lindex $line 0 ]
			if { ![ info exists in_list($fam) ] } {
				set in_list($fam) 1
				lappend famnames $fam
			}
		}
		close $fp
		mess "$famnames\n"
		return $famnames
	}

	set bocos ""
	foreach b [lsort [glob -nocomplain $place/mesh/boco*]] {
		lappend bocos $b
	}
	if {$bocos == ""} {
		errormsg "Can't run Prism 2 -- no boco file was found."
		return ""
	}

	set boco ""
	if { [ llength $bocos ] != 1 } {
		set boco [file_select  "Pick a boco file" \
                	  [lindex $bocos 0] ]
		if {$boco == ""} return ""
	} else {
		set boco $bocos
	}

	if { $boco == "" } {
		errormsg "Can't run Prism -- no boco file was found."
		return ""
	}
	if { [file exists $boco] == 0 }  {
		errormsg "Can't run Prism -- file $boco wasn't found."
		return ""
	}
	set famnames ""
	if [ catch { set lines [cmd_grep ^\\* $boco] } ] {
		errormsg "$boco does not seem to be a boco file"
		return ""
	}
	
	foreach fam [split $lines \n] {
        	set ff [string range $fam 1 end]
        	lappend famnames $ff
    	}
	set famnames [lsort $famnames]
        return $famnames
}

proc app_prism {} {
    global par_on_off
    global place prism_path prism_sel gui_name prism_values ddnterm
    global n_processors max_binary_tetin family_on family_height 
    global family_ratio extra_name extra_value
    
    if {$place == ""} {
	errormsg "Can't run Prism -- the $gui_name(conf) or $gui_name(geo) is not set."
	return
    }
	

    set famnames [ get_famnames  ]

    foreach ff $famnames { 
	set family_on($ff) 1
	set family_height($ff) ""
	set family_ratio($ff) ""
    }
    
# parameter with blank defaults are not mandetory
# parameters are indexed by the names in the prism_params file
    set default_pars "input_file output_file surface_file log \
		height ratio layers smoothing_steps  \
		min_prism_quality graphics \
		n_triangle_smoothing_steps triangle_quality ortho_weight \
		fillet law \
		n_tetra_smoothing_steps \
		max_prism_angle \
		prism_height_limit \
		orfn new_volume \
		top_family side_family"

    set par_text(input_file) "Input mesh file"
    set par_default(input_file) "cut_domain.1"
    set par_type(input_file) file
	
    set par_text(output_file) "Output mesh file"
    set par_default(output_file) "prism.uns"
    set par_type(output_file) file

    set par_text(surface_file) "Tetin file"
    set par_default(surface_file) "tetin1"
    set par_type(surface_file) file

    set par_text(log) "Log file"
    set par_default(log) "prism.log"
    set par_type(log) file

    set par_text(height) "Initial height"
    set par_default(height) "1.0"
    set par_type(height) number

    set par_text(ratio) "Height ratio"
    set par_default(ratio) "2.0"
    set par_type(ratio) number
  
    set par_text(layers) "Number of layers"
    set par_default(layers) "3"
    set par_type(layers) number

    set par_text(smoothing_steps) "Smoothing steps"
    set par_default(smoothing_steps) "6"
    set par_type(smoothing_steps) number

    set par_text(fillet) "Fillet ratio"
    set par_default(fillet) 0.1
    set par_type(fillet) unit_number

    set par_text(max_aspect_ratio) "Max height over base"
    set par_default(max_aspect_ratio) ""
    set par_type(max_aspect_ratio) number

#    set par_text(area_power) "Area power"
#    set par_default(area_power) ""
#    set par_type(area_power) number

    set par_text(graphics) "Use interactive graphics"
    set par_default(graphics) 1
    set par_type(graphics) logical

    set par_text(max_prism_angle) "Max prism angle"
    set par_default(max_prism_angle) "180"
    set par_type(max_prism_angle) number

    set par_text(min_prism_quality) "Min prism quality"
    set par_default(min_prism_quality) ".01"
    set par_type(min_prism_quality) number

    set par_text(prism_height_limit) "Prism height limit factor"
    set par_default(prism_height_limit) ""
    set par_type(prism_height_limit) number

    set par_text(n_triangle_smoothing_steps) "Number of tri smoothing steps"
    set par_default(n_triangle_smoothing_steps) "5"
    set par_type(n_triangle_smoothing_steps) number

    set par_text(triangle_quality) "Triangle quality type"
    set par_default(triangle_quality) "inscribed_ratio"
    set par_type(triangle_quality) list
    set par_list(triangle_quality) "laplace height_over_base \
		skewness min_angle max_angle inscribed_ratio \
		inscribed_area"
    set par_on_off(triangle_quality) prism_values(n_triangle_smoothing_steps)

    set par_text(law) "Growth Law"
    set par_default(law) "exponential"
    set par_type(law) list
    set par_list(law) "linear exponential"

    set par_text(ortho_weight) "Ortho weight"
    set par_default(ortho_weight) .5
    set par_type(ortho_weight) unit_number
    set par_on_off(ortho_weight) \
		[ list  "prism_values(triangle_quality) laplace" ] 


    set par_text(orfn) "Extrude into orphan region"
    set par_default(orfn) 0
    set par_type(orfn) logical
   
    set par_text(new_volume) "New volume Family"
    set par_default(new_volume) ""
    set par_type(new_volume) family
    set par_list(new_volume) $famnames

    set par_text(side_family) "Side Family"
    set par_default(side_family) ""
    set par_type(side_family) family
    set par_list(side_family) $famnames

    set par_text(top_family) "Top Family"
    set par_default(top_family) ""
    set par_type(top_family) family
    set par_list(top_family) $famnames

    set par_text(n_tetra_smoothing_steps) "Number of tetra smoothing steps"
    set par_default(n_tetra_smoothing_steps) "10"
    set par_type(n_tetra_smoothing_steps) number

    check_tetin1
    set n_extra 0
    
    
    
# initialize the defaults
    if ![info exists prism_values] {
	foreach i [ array names par_default ] {
		set prism_values($i) $par_default($i)
        }
# this one is special since it is an on off button
	set prism_values(graphics) 0
    }

    set num 1
# if the tetin file is not set or is set to a file that
# doesn't exist then set it
    if { $prism_values(surface_file) == "" || \
		![file exists $place/mesh/$prism_values(surface_file)] } {
	    if ![string compare $num ""] {
		set prism_values(surface_file) tetin1
	    } else {
		set prism_values(surface_file) tetin[string range $num 1 end]
	    }
    }
    if ![file exists $place/mesh/$prism_values(surface_file)] {
	warningmsg "Tetin file $prism_values(surface_file) isn't there."
    }
    
# Read in the previous prism_params file.
    
    set ifile $place/mesh/prism_params

    
    if [file exists $ifile] {
	foreach ff $famnames {
	    set family_on($ff) 0
	    set family_height($ff) ""
	    set family_ratio($ff) ""
	}
	set fp [open $ifile r]
	while {![eof $fp]} {
	    set line [gets $fp]
# skip blank lines
	    set line [ string trim $line ]
	    if { $line == "" } continue
# skip comment lines
	    if { [ string match "#*" $line ] } continue
# family
	    set par [ lindex $line 0 ]
	    switch $par {
		family {
		    set ff [lindex $line 1]
		    set family_on($ff) 1
		    set family_height($ff) ""
		    set family_ratio($ff) ""
		    for {set i 2; set j 3} {[lindex $line $i] != ""} \
			{incr i 2; incr j 2} {
			    switch [lindex $line $i] {
				ratio {
				    set family_ratio($ff) [lindex $line $j]
				}
				height {
				    set family_height($ff) [lindex $line $j]
				}
			    }
		    }
	        }
		input_file -
		DomainInputFile {
			set prism_values(input_file) [lindex $line 1]
		}
		output_file -
		DomainOutputFile {
			set prism_values(output_file) [lindex $line 1]
		}
		surface_file -
		SurfaceFile {
			set prism_values(surface_file) [lindex $line 1]
		}
		n_processors {
		}
		default {
		    if { [ info exists par_text($par) ] == 0 } {
# unknown just read it in
			set prism_values($par) [lindex $line 1]
			set par_text($par) $par
			set par_type($par) number
		    } elseif { $par_type($par) == "logical" } {
			set prism_values($par) 1
		    } else {
			set prism_values($par) [lindex $line 1]
		    }
		}
	    }
	}
    }
# files should just show the tail
#    foreach i [ array names prism_values ] {
#	if { ! [ info exists par_type($i) ] } {
#		unset prism_values($i)
#	}
#    }
    foreach i [ array names prism_values ] {
	if { ! [ info exists par_type($i) ] } {
		set par_type($i) number
	}
	if { $par_type($i)  == "file" } {
    		set prism_values($i)  [ file tail $prism_values($i) ]
	}
    }
	
    
    set d [form_init .prism "Prism options"]
    if {$d != ""} {
	set bg [.prism cget -background]
	set ln 0
# default args
	set all_pars $default_pars
	foreach i [ array names prism_values ] {
	    if { [ lsearch $default_pars $i ] == -1 } {
		append all_pars " $i"
	    }
	}
	

	foreach i $all_pars {
		set on_off ""
		if { [ info exists par_on_off($i) ] } {
			set on_off $par_on_off($i)
		}
		switch $par_type($i) {
		    unit_number {
			form_label $d.l$i $par_text($i) " $ln 0" \
				$on_off
			form_scale $d.$i prism_values($i) \
				"" h 0 1 .01 "$ln 1 -cols 2 -fill x" \
				$on_off
		    }
		    default -
		    number - 
		    file {
			form_label $d.l$i $par_text($i) " $ln 0" \
				$on_off
			form_entry $d.$i prism_values($i) string  \
				"$ln 1 -cols 2" $on_off
		    }
		    logical {
			form_checkbutton $d.$i $par_text($i) \
			    prism_values($i) "$ln 0 -cols 2" \
				$on_off
		    }
		    list {
			form_label $d.l$i $par_text($i) " $ln 0 " \
				$on_off
			futil_listentry $d.$i prism_values($i) \
				 "list $par_list($i)" " $ln 1 "  \
				$on_off
		    }
		    family {
			form_label $d.l$i $par_text($i) " $ln 0 " \
				{{ prism_values(orfn) }} 
			futil_listentry $d.$i prism_values($i) \
			 "list $famnames" " $ln 1 "  {{ prism_values(orfn) }}
		    }
		}
		incr ln
	}

# extra args

# empty guy
#
	set extra_name ""
	set extra_value ""
	incr ln
	form_entry $d.extra_par_1 extra_name \
					string " $ln 0 -cols 2"
	form_entry $d.extra_val_1 extra_value \
					string " $ln 1 -cols 2"
	

	$d.graphics configure -background $bg
	form_label $d.pfl "Families for prisms" {20 0 -cols 3}
	form_label $d.fnl "Family name" {21 0}
	form_label $d.fhl "Height" {21 1}
	form_label $d.frl "Ratio" {21 2}
	set scr [form_scroller $d.scr 200 {22 0 -cols 3}]
	set r 0
	foreach ff $famnames {
	    form_checkbutton $scr.ff_$r $ff family_on($ff) "$r 0"
	    $scr.ff_$r configure -background $bg
	    form_entry $scr.ffh_$r family_height($ff) string "$r 1"
	    form_entry $scr.ffr_$r family_ratio($ff) string "$r 2"
	    incr r
	}
	
	pathentry on $d.input_file "" $place/domains
	pathentry on $d.output_file "" $place/domains
	pathentry on $d.surface_file "" $place/mesh
	
	form_finish +300+300
	
	# Hell if I know ...
	$scr configure -height [expr {[winfo reqheight $scr] + 1}]
    }
    if ![form_wait .prism] {
	form_kill .prism
	return
    }
    
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
# convert file names to long
    set prism_values(input_file) \
			$place/domains/$prism_values(input_file)
    set prism_values(output_file) \
			$place/domains/$prism_values(output_file)
    set prism_values(surface_file) \
			$place/mesh/$prism_values(surface_file)
    
    set fp [open $ifile w]
    foreach i [ array names prism_values ] {
	if { $i == "log" } continue
	if { $i == "orfn" } continue
	if { $i == "new_volume" || $i == "top_family" \
				|| $i == "side_family" } {
		if { $prism_values(orfn) == 0 } continue
	}
	if { $par_type($i) == "logical" } {
 		if { $prism_values($i) == 1 } {
			puts $fp $i
		}
	} elseif { $prism_values($i) != "" } {
		puts $fp "$i $prism_values($i)"
	}
    }
    if  { $extra_name != "" } {
	puts $fp "$extra_name $extra_value"
    }

# famililes
    foreach ff $famnames {
	if $family_on($ff) {
	    set line "family $ff"
# add ratio
	    if {$family_ratio($ff) != ""} {
		append line " ratio $family_ratio($ff)"
	    }
# add height
	    if {$family_height($ff) != ""} {
		append line " height $family_height($ff)"
	    }
	    puts $fp $line
	}
    }

    if { $n_processors > 1 } { puts $fp "n_processors $n_processors" }

    if { $max_binary_tetin >= 0 } { 
	puts $fp "max_binary_tetin $max_binary_tetin"
    }

    close $fp
    
    form_kill .prism
    
    set command "$prism_path $ifile"

    if { $prism_values(log) != "" } {
	append command " |& tee $place/mesh/$prism_values(log)"
    }
    
    runxcom PRISM $command "" 1 1
}

proc app_quad {} {
    global place quad_path gui_name
    
    check_tetin1
    
    if {$place == ""} {
	errormsg "Can't run Quad -- the $gui_name(conf) or $gui_name(geo) is not set."
	return
    }

    check_tetin1
    
    if [file exists $place/transfer/quadin] {
	set quadin $place/transfer/quadin
    } else {
	set quadin $place/transfer/
    }
    set quadin [query_path .query "Quad input file?" $quadin]
    if {$quadin == "*cancel*"} return
    
    set command "$quad_path -q $quadin"
    
    runxcom_remote QUAD $command "" 1 1
}

# Customization: new application.
# Since there are a wide variety of applications that one might want to
# add to this program, the only advice that can be given is to look at the
# above routines and try to follow their pattern.  In the case of a GPL
# application, the task is simpler, since there are two routines,
# "run_ddn_linked" and "run_ddn_interpreted", that can be used.
# run_ddn_linked takes four arguments -- a descriptive name (which must
# not contain any blanks) for the application, a character that must
# be either d or m, depending on whether the application is, in general,
# used to edit parts in the DDN or the MULCAD parts directory, the name
# of the GPL script file, and finally, any extra ddn commands that must be
# given at initialization time.  The routine run_ddn_interpreted takes
# these arguments plus one other -- the name of the library directory
# for the application.  These routines are defined in the file "misc" if
# you want to peruse them.

# Viewer routines. ----------------------------------------------------

proc view_grid_visualizer {} {
    global place domain_viewer_path icem_fluent icem_powermesh ddnterm gui_name
    
    check_tetin1
    
    if {$place == ""} {
	errormsg "Can't run domain viewer -- the $gui_name(conf) or $gui_name(geo) is not set."
	return
    }
    
    if { $icem_fluent || $icem_powermesh } { set boco $place/mesh/boco_info } else { set boco $place/mesh/boco }
    if [file exists $boco] {
	set boco "boco $boco"
    } else {
	set boco ""
    }
    set ifile [domain_select $place/domains "Select a domain." mixed 0]
    if {$ifile == {}} return
    
    if {[query_question .query "Allow modification?"] != "*cancel*" } {
	set modify "modify"
    } else {
	set modify ""
    }
    
    switch $ddnterm {
	x11     { set x " -x" }
	OpenGL  { set x " -ogl" }
	default { set x "" }
    }
    
    set command "$domain_viewer_path $ifile $modify $boco $x"

    runxcom DOMAIN_VIEWER $command "" 0 1
}

proc view_leo {} {
    global place leo_path domains ddnterm confname env 
    global icem_fluent icem_powermesh icem_stamp domain_type
    global black_and_white leo_which gui_name
    
    check_tetin1
    
    if {$place == ""} {
	errormsg "Can't run leo -- the $gui_name(conf) or $gui_name(geo) is not set."
	return
    }
    
    set useboco 1
    set usetopo 1
    set xyz 0
    set super 0
    set quad 0
    
    get_boco_topo

#   if { $icem_fluent || $icem_powermesh } {
#       set bocofile $place/mesh/boco_info
#   } else {
#       set bocofile $place/mesh/boco
#   }
    if {![file exists $bocofile]} {
	set bocofile $place/mesh/; set useboco 0
    }
    
    if { !$icem_fluent && !$icem_powermesh } {
#	set topofile $place/mesh/topo_mulcad_out
	if {![file exists $topofile]} {
	    set topofile $place/mesh/; set usetopo 0
	}
    } else {
	set topofile $place/mesh/topo_info
	if {![file exists $topofile]} {
#	    set topofile $place/mesh/; set usetopo 0
	}
    }
    
    if { !$icem_fluent && !$icem_powermesh } {
	set fluentfile $place/transfer/fluent
	if {![file exists $fluentfile]} {set fluentfile $place/transfer/}
    } else {
	set fluentfile $place/transfer/fluent
	if {![file exists $fluentfile]} {set fluentfile $place/transfer/}
    }
    
    if { !$icem_fluent && !$icem_powermesh } {
	set plot3dfile $place/transfer/plot3d
	if {![file exists $plot3dfile]} {set plot3dfile $place/transfer/}
    } else {
	set plot3dfile $place/transfer/plot3d
	if {![file exists $plot3dfile]} {set plot3dfile $place/transfer/}
    }
    
    set taurusfile $place/transfer/
    
    set tetinfile $place/mesh/tetin1
    if {![file exists $tetinfile]} {set tetinfile $place/mesh/}
    
    set plot3dqfile ""
    set igesfile ""
    set useiges 0
    set usetetin 0
    
    set type domain
    if ![info exists leo_which] {
	if {$icem_fluent || $icem_powermesh} {
	    set leo_which 2
	} else {
	    set leo_which 3
	}
    }
    
    if $icem_fluent {
	set options {
	    {type -opt {
		{Domain domain}
		{Fluent fluent}
	    } -title "File type" \
		    -help "This option determines whether Leo will read domain\
		    files, fluent files, or plot3d files. \
		    After completing this dialog, you will be asked to choose\
		    which domains you want to view."}
	    
	    {ddnterm -opt {{X11 x11} {Native native} {OpenGL OpenGL}} -title "Graphics system" \
		    -help "This option determines whether Leo will use X11 graphics, \
		    or GL graphics where available.  If you want to change this variable permanently, \
		    use the \"Edit Modals\" command in the Utility menu."}
	    
	    {super -opt {{Yes 1} {No 0}} -title "View superdomains" \
		    -active {$type == "domain"} \
		    -help "Is the domain to be considered a superdomain?"}
	    
	    {usetopo -opt {{Yes 1} {No 0}} -title "Read topo file" -group t \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a topology file."}
	    
	    {topofile -type path -title "Topo file" \
		    -active {$usetopo && ($type == "domain")} -group t \
		    -help "The name of the topology file, which is read\
		    if the \"Read topo file\" option is set."}
	    
	    {useboco -opt {{Yes 1} {No 0}} -title "Read boco file" -group b \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a\
		    boundary condition file."}
	    
	    {bocofile -type path -title "Boco file" \
		    -active {$useboco && ($type == "domain")} -group b \
		    -help "The name of the boundary condition file,\
		    which is read if the \"Read boco file\" option is set."}
	    
	    {fluentfile -type path -title "Fluent file" \
		    -active {$type == "fluent"} \
		    -help "The name of the fluent input file."}
	}
	
    } elseif $icem_powermesh {
	set options {
	    {type -opt {
		{Domain domain}
		{Plot3d plot3d}
	    } -title "File type" \
		    -help "This option determines whether Leo will read domain\
		    files, or plot3d files. \
		    After completing this dialog, you will be asked to choose\
		    which domains you want to view."}
	    
	    {ddnterm -opt {{X11 x11} {Native native} {OpenGL OpenGL}} -title "Graphics system" \
		    -help "This option determines whether Leo will use X11 graphics, \
		    or GL graphics where available.  If you want to change this variable permanently, \
		    use the \"Edit Modals\" command in the Utility menu."}
	    
	    {super -opt {{Yes 1} {No 0}} -title "View superdomains" \
		    -active {$type == "domain"} \
		    -help "Is the domain to be considered a superdomain?"}
	    
	    {usetopo -opt {{Yes 1} {No 0}} -title "Read topo file" -group t \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a topology file."}
	    
	    {topofile -type path -title "Topo file" \
		    -active {$usetopo && ($type == "domain")} -group t \
		    -help "The name of the topology file, which is read\
		    if the \"Read topo file\" option is set."}
	    
	    {useboco -opt {{Yes 1} {No 0}} -title "Read boco file" -group b \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a\
		    boundary condition file."}
	    
	    {bocofile -type path -title "Boco file" \
		    -active {$useboco && ($type == "domain")} -group b \
		    -help "The name of the boundary condition file,\
		    which is read if the \"Read boco file\" option is set."}
	    
	    {plot3dfile -type path -title "Plot3d formatted file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d input file."}
	    
	    {plot3dqfile -type path -title "Plot3d Q (result) file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d result input file."}
	    
	    {xyz -opt {{Whole 1} {Planes 0}} -title "Plot3d file type" -group p \
		    -active {$type == "plot3d"} \
		    -help "Whether the file is \"whole\" or in planes."}
	}
    } elseif $icem_stamp {
	# {leo_which -opt {{{Leo 2} 2} {{Leo 3} 3}} -title "Leo version"}
	set options {
	    {type -opt {
		{Domain domain}
		{Fluent fluent}
		{Plot3d plot3d}
		{Stamp  taurus}
	    } -title "File type" \
		    -help "This option determines whether Leo will read domain\
		    files, fluent files, plot3d files, or stamp files. \
		    After completing this dialog, you will be asked to choose\
		    which domains you want to view."}
	    
	    {ddnterm -opt {{X11 x11} {Native native} {OpenGL OpenGL}} -title "Graphics system" \
		    -help "This option determines whether Leo will use X11 graphics, \
		    or GL graphics where available.  If you want to change this variable permanently, \
		    use the \"Edit Modals\" command in the Utility menu."}
	    
	    {super -opt {{Yes 1} {No 0}} -title "View superdomains" \
		    -active {$type == "domain"} \
		    -help "Is the domain to be considered a superdomain?"}
	    
	    {usetopo -opt {{Yes 1} {No 0}} -title "Read topo file" -group t \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a topology file."}
	    
	    {topofile -type path -title "Topo file" \
		    -active {$usetopo && ($type == "domain")} -group t \
		    -help "The name of the topology file, which is read\
		    if the \"Read topo file\" option is set."}
	    
	    {useboco -opt {{Yes 1} {No 0}} -title "Read boco file" -group b \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a\
		    boundary condition file."}
	    
	    {bocofile -type path -title "Boco file" \
		    -active {$useboco && ($type == "domain")} -group b \
		    -help "The name of the boundary condition file,\
		    which is read if the \"Read boco file\" option is set."}
	    
	    {fluentfile -type path -title "Fluent file" \
		    -active {$type == "fluent"} \
		    -help "The name of the fluent input file."}
	    
	    {plot3dfile -type path -title "Plot3d formatted file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d input file."}
	    
	    {plot3dqfile -type path -title "Plot3d Q (result) file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d result input file."}
	    
	    {xyz -opt {{Whole 1} {Planes 0}} -title "Plot3d file type" -group p \
		    -active {$type == "plot3d"} \
		    -help "Whether the file is \"whole\" or in planes."}
	    
	    {taurusfile -type path -title "Stamp file" \
		    -active {$type == "taurus"} -group ta \
		    -help "The name of the stamp input file."}
	}
    } else {
	# {leo_which -opt {{{Leo 2} 2} {{Leo 3} 3}} -title "Leo version"}
	set options {
	    {type -opt {
		{Domain domain}
		{Fluent fluent}
		{Plot3d plot3d}
	    } -title "File type" \
		    -help "This option determines whether Leo will read domain\
		    files, fluent files, or plot3d files. \
		    After completing this dialog, you will be asked to choose\
		    which domains you want to view."}
	    
	    {ddnterm -opt {{X11 x11} {Native native} {OpenGL OpenGL}} -title "Graphics system" \
		    -help "This option determines whether Leo will use X11 graphics, \
		    or GL graphics where available.  If you want to change this variable permanently, \
		    use the \"Edit Modals\" command in the Utility menu."}
	    
	    {super -opt {{Yes 1} {No 0}} -title "View superdomains" \
		    -active {$type == "domain"} \
		    -help "Is the domain to be considered a superdomain?"}
	    
	    {quad -opt {{Yes 1} {No 0}} -title "Assume quadratic" \
		    -active {$type == "domain"} \
		    -help "Assume all domains are quadratic."}
	    
	    {usetopo -opt {{Yes 1} {No 0}} -title "Read topo file" -group t \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a topology file."}
	    
	    {topofile -type path -title "Topo file" \
		    -active {$usetopo && ($type == "domain")} -group t \
		    -help "The name of the topology file, which is read\
		    if the \"Read topo file\" option is set."}
	    
	    {useboco -opt {{Yes 1} {No 0}} -title "Read boco file" -group b \
		    -active {$type == "domain"} \
		    -help "This option determines whether Leo will read a\
		    boundary condition file."}
	    
	    {bocofile -type path -title "Boco file" \
		    -active {$useboco && ($type == "domain")} -group b \
		    -help "The name of the boundary condition file,\
		    which is read if the \"Read boco file\" option is set."}
	    
	    {fluentfile -type path -title "Fluent file" \
		    -active {$type == "fluent"} \
		    -help "The name of the fluent input file."}
	    
	    {plot3dfile -type path -title "Plot3d formatted file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d input file."}
	    
	    {plot3dqfile -type path -title "Plot3d Q (result) file" \
		    -active {$type == "plot3d"} -group p \
		    -help "The name of the plot3d result input file."}
	    
	    {xyz -opt {{Whole 1} {Planes 0}} -title "Plot3d file type" \
		    -group p -active {$type == "plot3d"} \
		    -help "Whether the file is \"whole\" or in planes."}
	    
	    {useiges -opt {{Yes 1} {No 0}} -title "Read IGES file" -group iges}
	    {igesfile -type path -title "IGES file" \
		    -active {$useiges} -group iges}
	    
	    {usetetin -opt {{Yes 1} {No 0}} -title "Read Tetin file" \
		    -group tetin}
	    {tetinfile -type path -title "Tetin file" \
		    -active {$usetetin} -group tetin}
	}
    }
    if ![dialog .leo "Leo Grid Visualizer"  \
	    "Please edit the following options for Leo." \
	    $options] return
    
    set fluent ""
    set plot3d ""
    set taurus ""
    case $type in {
	domain {
	    set sel [domain_select $place/domains "Select the domains." \
		     mixed 1 $useboco $usetopo]
	    if {$sel == {}} return
	}
	fluent {
	    set sel ""
	    if {[file exists $fluentfile]} {
		set fluent "-flu $fluentfile"
	    } else {
		errormsg "File $fluentfile doesn't exist"
		return
	    }
	    set useboco 0
	    set usetopo 0
	}
	plot3d {
	    set sel ""
	    if {[file exists $plot3dfile]} {
		set plot3d "-p3d $plot3dfile"
	    } else {
		errormsg "File $plot3dfile doesn't exist"
		return
	    }
	    if $xyz { set plot3d "$plot3d -xyz" }
	    
	    set useboco 0
	    set usetopo 0
	}
   	taurus {
	    set sel ""
	    if {[file exists $taurusfile]} {
		set taurus "-tau $taurusfile"
	    } else {
		errormsg "File $taurusfile doesn't exist"
		return
	    }
	    set useboco 0
	    set usetopo 0
	}
 }
    
    foreach d $sel {
	if {($domain_type($d) == "super1") || ($domain_type($d) == "super2")} {
	    set n [query_question .query "Warning: superdomain viewing\
		is not fully supported -- continue?"]
	    if {$n == "*cancel*"} return
	    if !$super { set super 1 }
	}
    }
    switch $ddnterm {
	native { set x "" }
	x11    { set x -x }
	OpenGL { set x -ogl }
    }
    if $super { set sup "-super" } else { set sup "" }
    if $quad { set qua "-quad" } else { set qua "" }
    if {$plot3dqfile != ""} {set q "-p3dq$ plot3dqfile"} else {set q ""}
    
    set topo ""
    if $usetopo {
	if {[file exists $topofile]} {
	    set topo "-t $topofile"
	} else {
	    warningmsg "File $topofile doesn't exist"
	}
    }
    
    set boco ""
    if $useboco {
	if {[file exists $bocofile]} {
	    set boco "-b $bocofile"
	} else {
	    warningmsg "File $bocofile doesn't exist"
	}
    }
    
    set nd [llength $sel]
    if {$nd > 20} {
	cmd_rm leo_domain_list
	set fp [open leo_domain_list w]
	foreach d $sel {
	    puts $fp $d
	}
	close $fp
	set sel "-dom_list leo_domain_list"
    }
    
    if $black_and_white { set bw -bw } else { set bw "" }
    
    set iges ""; set tetin ""
    set otcl $env(TCL_LIBRARY)
    set otk $env(TK_LIBRARY)
    
    set path $leo_path
    
    if $useiges {
	set iges "-iges $igesfile"
    }
    if $usetetin {
	set tetin "-tetin $tetinfile"
    }

    catch {unset env(LEO_DEVELOPMENT)}
    catch {unset env(LEO_TETRA_HACK)}
    set command "$path $x $bw $topo $boco $sup $qua $fluent $taurus $plot3d \
	    $q $sel $iges $tetin"
    runxcom Leo $command "" 1 1
    
    set env(TCL_LIBRARY) $otcl
    set env(TK_LIBRARY) $otk
}

# Translator routines. ---------------------------------------------

proc trans_ddn_iges {} {
    global partname partfile env
    
    if {$partfile == ""} {errormsg "No part selected!"; return}
    if [part_is_mulcad] {
	errormsg "The selected part must be in the DDN directory to convert to IGES."
	return
    }
    
    if [partfile_is_binary $partfile] {
	errormsg "The part must be in ASCII format before it can be converted\
                  to IGES.  Please edit the part using DDN, and change the \"Fmt\"\
                  option to \"B > A\", and save the part.  You can then convert it\
                  to IGES."
	return
    }
    
    update_iges
    put_iges
    
    set outfile [query_path_lc .query "Enter name of the IGES output file."\
		 "iges/[nice_partname]"]
    if {$outfile == "*cancel*"} {unput_iges; return}
    if [string match "*-*" $outfile] {
	warningmsg "IGES file names may not contain the - character"
	unput_iges; return
    }
    if {![file exists [file dirname $outfile]]} {
	cmd_mkdir [file dirname $outfile]
    }
    
    if [file exists $outfile] then {
	if {[query_question .query "File exists: overwrite?"] == \
	    "*cancel*"} {unput_iges; return}
    } else {
	if {![file exists iges]} {cmd_mkdir iges}
    }

    set dirf ""
    set resp [query_path_lc .query "Directive file?  (Blank if none)" ""]
    if {$resp == "*cancel*"} {unput_iges; return}
    if {$resp != ""} {set dirf "d=$resp"}
    
    set command "$env(ICEM_ACN)/iges/iges_pre i=$partfile o=$outfile l=iges_list $dirf"
    runcom $command iges_list
    # keep this around
    # catch {exec /bin/rm iges_list}
    
    unput_iges
}

proc trans_iges_ddn {} {
    update_iges
    put_iges
    
    set infile [query_waitvar .query "Click on an IGES input file from\
	    the list below to the right."]
    
    if {$infile == "*cancel*"} {unput_iges; return}
    
    trans_iges_file $infile
}

proc trans_iges_file {infile} {
    global partname partfile env icem_fluent icem_powermesh iges_direct_done
    global iges_whatdirect iges_transdos iges_datred_off
    global iges_userdirect iges_savelisting iges_listfile iges_ddnpart
    global iges_create31 iges_icempt
    
    if ![info exists iges_listfile] {
	set iges_listfile iges_list
	set iges_create31 0
    }
        
    catch {destroy .iges_directform}
    set iges_whatdirect default
    
    set iges_ddnpart [file tail [file rootname $infile]]

    set t .iges_directform
    toplevel $t
    
    set bback [$t cget -background]
    
    label $t.title -text "IGES translator options"
    
    frame $t.p
    entry $t.p.name -textvariable iges_ddnpart -background white -relief sunken
    label $t.p.nl -text "DDN name: "
    pack $t.p.nl $t.p.name -side left -fill both -expand 1
    
    label $t.dtitle -text "Directive file to use:" -anchor w
    radiobutton $t.ddefault -text Default -value default \
	    -variable iges_whatdirect -anchor w -relief flat -background $bback
    radiobutton $t.dnone -text None -value none \
	    -variable iges_whatdirect -anchor w -relief flat -background $bback
    radiobutton $t.dcatia -text Catia -value catia \
	    -variable iges_whatdirect -anchor w -relief flat -background $bback
    radiobutton $t.duser -text User-specified -value user \
	    -variable iges_whatdirect -anchor w -relief flat -background $bback
    frame $t.duserf
    entry $t.duserf.file -textvariable iges_userdirect \
	    -background white -relief sunken
    pathentry on $t.duserf.file
    label $t.duserf.l -text "File: "
    pack $t.duserf.l $t.duserf.file -side left -fill both -expand 1
    checkbutton $t.ipt -text "Run icempt" -variable iges_icempt\
	-anchor w -relief flat -background $bback
    set iges_icempt 1
    checkbutton $t.datred -text "Data reduction off" -variable iges_datred_off\
	-anchor w -relief flat -background $bback
    
    if 0 {
	radiobutton $t.v31 -text "Create 3.1 part" -variable iges_create31 \
	    -value 1 -anchor w -relief flat -background $bback
	radiobutton $t.v33 -text "Create 3.3 part" -variable iges_create31 \
	    -value 0 -anchor w -relief flat -background $bback
    }
    set iges_create31 0
    
    checkbutton $t.lsave -text "Save listing" -variable iges_savelisting \
	-anchor w -relief flat -background $bback
    checkbutton $t.dos -text "Translate from DOS" -variable iges_transdos \
	-anchor w -relief flat -background $bback
    frame $t.list
    entry $t.list.file -textvariable iges_listfile \
	    -background white -relief sunken
    label $t.list.l -text "File: "
    pack $t.list.l $t.list.file -side left -fill both -expand 1
    
    frame $t.buts
    button $t.buts.done -text Done -width 1 -command \
	    "set iges_direct_done 1; destroy $t"
    button $t.buts.cancel -text Cancel -width 1 -command \
	    "set iges_direct_done 0; destroy $t"
    pack $t.buts.done $t.buts.cancel -side left -fill x -expand 1
    
    pack $t.title $t.p $t.dtitle -side top -fill both -expand 1
    if $icem_fluent {
	pack $t.ddefault $t.duser $t.dnone \
		-side top -fill both -expand 1 -padx 20
    } else {
	pack $t.ddefault $t.dcatia $t.duser $t.dnone \
		-side top -fill both -expand 1 -padx 20
    }
    pack $t.duserf -fill both -expand 1
    pack $t.ipt $t.datred $t.dos $t.lsave -side top -fill both -expand 1 -padx 20
    #pack $t.v31 $t.v33 -side top -fill both -expand 1
    pack $t.list -side top -fill both -expand 1
    pack $t.buts -side top -fill both -expand 1 -ipady 20 -anchor s
    
    wm geometry $t +300+300
    
    tkwait window $t
    if !$iges_direct_done return
    
    if {$iges_ddnpart == ""} {
	errormsg "You must give a DDN part name"
	return
    }
    set dp [string tolower $iges_ddnpart]
    if [string compare $dp $iges_ddnpart] {
	warningmsg "Translated DDN part name to lowercase"
	set iges_ddnpart $dp
    }
    
    if {[find_part $iges_ddnpart] != ""} then {
	if {[query_question .query "Part exists: overwrite?"] == \
	    "*cancel*"} {unput_iges; return}
    }
    
    case $iges_whatdirect {
	none    { set dfile "" }
	default {
	    set dfile $env(ICEM_ACN)/iges/dir_iges_general
	}
	catia   { set dfile $env(ICEM_ACN)/iges/dir_from_catia }
	user    {
	    if {$iges_userdirect == ""} {
		errormsg "No user-defined directive file name given"
		return
	    }
	    set dfile $iges_userdirect
	}
    }
    
    if {($dfile != "") && ![file exists $dfile]} {
	if [file exists iges/$dfile] {
	    set dfile iges/$dfile
	}
	warningmsg "Directive file $dfile doesn't exist"
	set dfile ""
    }
    
    if {$iges_datred_off && ($dfile != "")} {
	# Strip CREATE_310_PART directive
	if ![catch {exec grep CREATE_310_PART $dfile}] {
	    cmd_grep -v CREATE_310_PART $dfile > _scratch_tmp
	    cmd_rename _scratch_tmp _directive_tmp
	    set dfile _directive_tmp
	}
	
	# Strip MAX_BSP_SEG directive
	if ![catch {exec grep MAX_BSP_SEG $dfile}] {
	    cmd_grep -v MAX_BSP_SEG $dfile > _scratch_tmp
	    cmd_rename _scratch_tmp _directive_tmp
	    set dfile _directive_tmp
	}
	
	# Strip BSP_RED_TOL directive
	if ![catch {exec grep BSP_RED_TOL $dfile}] {
	    cmd_grep -v BSP_RED_TOL $dfile > _scratch_tmp
	    cmd_rename _scratch_tmp _directive_tmp
	    set dfile _directive_tmp
	}
    }
    
    set dline ""
    if {$dfile != ""} { set dline d=$dfile }
    
    set listf iges_list
    set catlist iges_list
    if $iges_savelisting {
	set listf $iges_listfile
	set catlist ""
    }
    
    if $iges_transdos {
# took out sed {s/^Z//} |
	exec sed {s/
//} < iges/$infile | sed {s+\\+/+g} > \
		iges/$infile.TRANSLATED
	set infile $infile.TRANSLATED
    }
    
    if $iges_create31 {
	set tmp parts/$iges_ddnpart
    } else {
	set tmp iges/_tmp_ddn_part_
    }
    cmd_rm $tmp
    set command "$env(ICEM_ACN)/iges/iges_post i=iges/$infile \
	    o=$tmp name=$iges_ddnpart l=$listf logit=yes $dline"
    runcom $command $catlist
    if {$catlist != ""} { cmd_rm $catlist }
    
    if !$iges_create31 {
	if $iges_icempt {
	      set command "$env(ICEM_ACN)/bin/icempt i=$tmp \
		  o=parts/$iges_ddnpart t=BTA e=icempt_list"
	      runcom $command icempt_list
	      cmd_rm $tmp
	} else {
	    mess "Not running icempt on the output.\n"
	    cmd_rename $tmp parts/$iges_ddnpart
	}
    }
    
    update_partlist - 1
    unput_iges
    return parts/$iges_ddnpart
}

proc trans_split {} {
    global env icem_fluent icem_powermesh
    
if { !$icem_fluent && !$icem_powermesh } {

    set old iges/old.igs
    set new iges/new.igs
    set which split128
    
    if {![dialog .split "Split" \
	  "Please edit the following options for the split utility." {
	      {which -opt {{"Split 128" split128} {"Split only" splitonly}} \
		  -title "Utility"}
	      {old -type path -title "Old IGES file" -help "Old file"}
	      {new -type path -title "New IGES file" -help "New file"}
	  }]} return
    
    set prog $env(ICEM_ACN)/iges/$which.exe
    
    if {$which == "split128"} {
	# This is a pain.
	if ![file exists $old] {
	    errormsg "$old: file not found"
	    return
	}
	cmd_rm old.igs
	cmd_cp $old old.igs
	runxcom Split $prog "" 1 0
	cmd_cp new.igs $new
	cmd_rm old.igs new.igs
    } else {
	set command "$prog i=$old o=$new"	
	runxcom Split $command "" 1 0
    }

} else {

    set prog $env(ICEM_ACN)/iges/splitonly.exe
    set old iges/igs.old
    set new iges/igs.new
   
    if {![dialog .split "Split" \
          "Please edit the following options for the split utility." {
              {prog -type path -title "Program" -help "The program to run"}
              {old -type path -title "Old IGES file" -help "Old file"}
              {new -type path -title "New IGES file" -help "New file"}
          }]} return
   
    set command "$prog i=$old o=$new"

    runxcom Split $command "" 1 0

}

}

# --------------------------------------------------------------------

proc trans_ddn_tvda {} {
    global partname partfile sheetname env is_win
    
    if {$partfile == ""} {errormsg "No part selected!"; return}
    if [part_is_mulcad] {errormsg "The selected part must be in the \
DDN directory to convert to TVDA."; return}
    
    update_tvda
    put_tvda
    
    set outfile [query_path_lc .query "Enter name of the TVDA output file."\
		 "[pwd]/tvda/[nice_partname]"]
    if {$outfile == "*cancel*"} {unput_tvda; return}
    if {![file exists [file dirname $outfile]]} \
	{cmd_mkdir [file dirname $outfile]}
    
    if [file exists $outfile] then {
	if {[query_question .query "File exists: overwrite?"] == \
	    "*cancel*"} {unput_tvda; return}
    } else {
	if {![file exists tvda]} {cmd_mkdir tvda}
    }
    
    set fd [open tvda_dir w]
    puts $fd "*FROM,ICEM DDN"
    puts $fd "*TO,VDA"
    puts $fd "*PART=$partname"
    puts $fd "*SHEET=$sheetname"
    puts $fd "*CONVERT,PARTNAME"
    puts $fd "VDA=HEADER/1"
    puts $fd "     *******"
    puts $fd "VDA=END"
    close $fd
    
    if {$is_win} {
       set command "$env(ICEM_ACN)/tvda/tvda.exe i=$partfile o=$outfile \
                   d=tvda_dir l=tvda_list"
#      runxcom "" $command "" 1 1
       runcom $command tvda_list
       cmd_rm tvda_dir
    } else {
       set command "$env(ICEM_ACN)/tvda/icemtvda i=$partfile o=$outfile \
                   d=tvda_dir l=tvda_list"
       runcom $command tvda_list
       cmd_rm tvda_dir
    }
#   cmd_rm tvda_list tvda_dir
    
    unput_tvda
}

proc trans_tvda_ddn {} {
    global partname partfile sheetname env is_win
    
    update_tvda
    put_tvda	
    
    set infile [query_waitvar .query "Click on a TVDA input file from \
the list below to the right."]
    if {$infile == "*cancel*"} {unput_tvda; return}
    
    set outfile [query_enter .query "Enter name of the DDN part." \
		 [file tail $infile]]
    if {$outfile == "*cancel*"} {unput_tvda; return}
    
    if {[find_part $outfile] != ""} then {
	if {[query_question .query "Part exists: overwrite?"] == \
	    "*cancel*"} {unput_tvda; return}
    }
    
    #set sname [query_enter .query "Enter the sheet number." 1]
    #if {$sname == "*cancel*"} {unput_tvda; return}
    set sname 1
    
    set fd [open tvda_dir w]
    puts $fd "*FROM,VDA"
    puts $fd "*TO,ICEM DDN"
    puts $fd "*PART=$outfile"
    puts $fd "*SHEET=$sname"
    puts $fd "*DRAFT=ANSI"
    puts $fd "*UNITS=MM"
    close $fd
    
    if {$is_win} {
      set command "$env(ICEM_ACN)/tvda/tvda.exe i=tvda/$infile o=parts/$outfile \
                  d=tvda_dir l=tvda_list"
#     runxcom "" $command "" 1 1
      runcom $command tvda_list
      cmd_rm tvda_dir
    } else {
      set command "$env(ICEM_ACN)/tvda/icemtvda i=tvda/$infile o=parts/$outfile \
                  d=tvda_dir l=tvda_list"
      runcom $command tvda_list
      cmd_rm tvda_dir
    }
#   cmd_rm tvda_list tvda_dir
    update_partlist - 1
    unput_tvda
}

# --------------------------------------------------------------------

proc trans_ddn_set {} {
    global partname partfile sheetname env
    
    if {$partfile == ""} {errormsg "No part selected!"; return}
    if [part_is_mulcad] {errormsg "The selected part must be in the \
DDN directory to convert to SET."; return}
    
    update_set
    put_set
    
    set outfile [query_path_lc .query "Enter name of the SET output file."\
		 "[pwd]/set/[nice_partname]"]
    if {$outfile == "*cancel*"} {unput_set; return}
    if {![file exists [file dirname $outfile]]} \
	{cmd_mkdir [file dirname $outfile]}
    
    if [file exists $outfile] then {
	if {[query_question .query "File exists: overwrite?"] == \
	    "*cancel*"} {unput_set; return}
    } else {
	if {![file exists set]} {cmd_mkdir set}
    }
    
    # This will have to change **************
    
    set fd [open set_dir w]
    puts $fd "*FROM,ICEM DDN"
    puts $fd "*TO,VDA"
    puts $fd "*PART=$partname"
    puts $fd "*SHEET=$sheetname"
    puts $fd "VDA=HEADER/1"
    puts $fd "     *******"
    puts $fd "VDA=END"
    close $fd
    
    set command "$env(ICEM_ACN)/set/bin/icemset i=$partfile o=$outfile"
    runcom $command
    
    unput_set
}

proc trans_set_ddn {} {
    global partname partfile sheetname env
    
    update_set
    put_set	
    
    set infile [query_waitvar .query "Click on a SET input file from \
the list below to the right."]
    if {$infile == "*cancel*"} {unput_set; return}
    
    set outfile [query_enter .query "Enter name of the DDN part." \
		 [file tail $infile]]
    if {$outfile == "*cancel*"} {unput_set; return}
    
    if {[find_part $outfile] != ""} then {
	if {[query_question .query "Part exists: overwrite?"] == \
	    "*cancel*"} {unput_set; return}
    }
    
    #set sname [query_enter .query "Enter the sheet number." 1]
    #if {$sname == "*cancel*"} {unput_set; return}
    set sname 1
    
    # This also has to change ********************
    
    set fd [open set_dir w]
    puts $fd "*FROM,VDA"
    puts $fd "*TO,ICEM DDN"
    puts $fd "*PART=$outfile"
    puts $fd "*SHEET=$sname"
    puts $fd "*DRAFT=ANSI"
    puts $fd "*UNITS=MM"
    close $fd
    
    set command "$env(ICEM_ACN)/set/bin/icemset i=set/$infile o=parts/$outfile"
    runcom $command
    update_partlist - 1
    unput_set
}

# --------------------------------------------------------------------

proc trans_ddn_dxf {} {
    global partname partfile env is_win
    
    if {$partfile == ""} {errormsg "No part selected!"; return}
    if [part_is_mulcad] {
 	errormsg "The selected part must be in the DDN directory to convert to DXF."
 	return
    }
    
    if [partfile_is_binary $partfile] {
 	errormsg "The part must be in ASCII format before it can be converted\
                   to DXF.  Please edit the part using DDN, and change the \"Fmt\"\
                   option to \"B > A\", and save the part.  You can then convert it\
                   to DXF."
 	return
    }
    
    update_dxf
    put_dxf
    
    set outfile [query_path_lc .query "Enter name of the DXF output file."\
 		 "dxf/[nice_partname]"]
    if {$outfile == "*cancel*"} {unput_dxf; return}
    if {![file exists [file dirname $outfile]]} \
 	{cmd_mkdir [file dirname $outfile]}
    
    if [file exists $outfile] then {
 	if {[query_question .query "File exists: overwrite?"] == \
 	    "*cancel*"} {unput_dxf; return}
    } else {
 	if {![file exists dxf]} {cmd_mkdir dxf}
    }
    
    set dirf ""
    set resp [query_path_lc .query "Directive file?  (Blank if none)" ""]
    if {$resp == "*cancel*"} {unput_dxf; return}
    if {$resp != ""} {set dirf "D=$resp"}
    
    if $is_win {
        set command "$env(ICEM_ACN)/dxf/dxf_pre tm=AD I=$partfile O=$outfile L=dxf_list $dirf"
    } else {
        set command "$env(ICEM_ACN)/dxf/dxf_pre I=$partfile O=$outfile L=dxf_list $dirf"
    }
    runcom $command dxf_list
    # keep this around
    # catch {exec /bin/rm dxf_list}
    
    unput_dxf
}

proc trans_dxf_ddn {} {
    global partname partfile env is_win
    
    update_dxf
    put_dxf
    
    set infile [query_waitvar .query "Click on an DXF input file from \
the list below to the right."]
    
    if {$infile == "*cancel*"} {unput_dxf; return}
    
    set outfile [query_enter .query "Enter name of the DDN part." \
		 [file tail $infile]]
    if {$outfile == "*cancel*"} {unput_dxf; return}
    
    if {[find_part $outfile] != ""} then {
	if {[query_question .query "Part exists: overwrite?"] == \
	    "*cancel*"} {unput_dxf; return}
    }
    
    set dirf ""
    set resp [query_path_lc .query "Directive file?  (Blank if none)" ""]
    if {$resp == "*cancel*"} {unput_dxf; return}
    if {$resp != ""} {set dirf "D=$resp"}
    
    if $is_win {
        set command "$env(ICEM_ACN)/dxf/dxf_post tm=DA I=dxf/$infile O=parts/$outfile \
                L=dxf_list $dirf"
    } else {
        set command "$env(ICEM_ACN)/dxf/dxf_post I=dxf/$infile O=parts/$outfile \
                L=dxf_list $dirf"
    }
    
    runcom $command dxf_list
    # keep this around
    # catch {exec /bin/rm dxf_list}
    update_partlist - 1
    unput_dxf
}

# --------------------------------------------------------------------

proc trans_plot3d_domain {} {
    global place env pl3_domain_path
    
    set formatted 1
    set double 0
    set planes 0
    set iblank 0
    set dom 1
    set tria 0
    set list 0
    set plfile $place/transfer/plot3d
    set domain $place/domains/plot3d_domain
    set listfile $place/transfer/pl3d.list
    set tri_dom $place/import/tri_unstr
    
    if {![dialog .plot3d "Plot 3d -> Domain" \
	    "Please edit the following plot3d options." {
	{formatted -opt {{Formatted 1} {Unformatted 0}} \
		-title "Input type" -help "Input type"}
	{double -opt {{Single 0} {Double 1}} -title Precision -help "Precision"}
	{planes -opt {{"In planes" 1} {\"Whole\" 0}} -title "Data layout" \
		-help "This is the WHOLE option"}
	{iblank -opt {{Yes 1} {No 0}} -title "Include IBLANK array" \
		-help "Include the IBLANK array"}
	{dom -opt {{Yes 1} {No 0}} \
		-title "Write struct. multiblock domains"}
	{domain -type path -title "Struct. domain name" -active {$dom}}
	{tria -opt {{Yes 1} {No 0}} \
		-title "Write triangular surface mesh"}
	{tri_dom -type path -title "Unstruct. domain name" -active $tria}
	{list -opt {{"Block faces" 0} {"input list file" 1}} \
	       -active $tria -title "Faces to include in surface mesh"}
	{listfile -type path -title "Name of list file" \
		-active $list}
	{plfile -type path -title "Plot3d file" -help "Plot 3d file"}
    }]} return
	
    if !$formatted {set form " -u"} else {set form ""}
    if $planes {set plane " -p"} else {set plane ""}
    if $iblank {set ib " -i"} else {set ib ""}

    set command "$pl3_domain_path$form$plane$ib"
    if $dom {set command "$command -dom -d $domain"}
    if $tria {set command "$command -trias -t $tri_dom"}
    if $list {set command "$command -list -l $listfile"}
    if $double {set command "$command -double"}
    set command "$command $plfile"
    
    runxcom "" $command "" 1 0
}

proc trans_patran_domain {} {
    global place env patran_domain_path
    
    set plfile $place/import/patran
    set domain $place/import/patran_domain.1
    set only_tris 0

    if {![dialog .patran "Patran -> Domain" \
	    "Please edit the following Patran options." { \
	{plfile -type path -title "Patran file" -help "Patran file"} \
	{domain -type path -title "Output domain" -help "Domain file"} \
	{only_tris -opt {{"All Elements" 0} {"Only Triangles" 1}} -title \
			"Patran conversion type"}
    }]} return
    
    set files [glob -nocomplain $plfile]
    if {$files == ""} { errormsg "No patran files found"; return }
    if {[llength $files] == 1} {
	set command "$patran_domain_path $plfile $domain"
	if { $only_tris } {
		append command " -only_tris"
	}
        runxcom "" $command "" 1 0
    } else {
	set root [file rootname $domain]
	foreach f $files {
	    set ff [file rootname [file tail $f]]
	    set of $root.$ff
	    
	    set command "$patran_domain_path $f $of"
	    if { $only_tris } {
			append command " -only_tris"
	    }
	    runcom $command
	}
    }
}

proc trans_stl_domain {} {
    global place env stl_domain_path
    
    set plfile $place/import/stl
    set domain $place/import/stl_domain
    set ascii 0
    
    if {![dialog .stl "STL -> Domain" \
	    "Please edit the following STL options." {
	{plfile -type path -title "STL file" -help "STL file"}
	{domain -type path -title "Output prefix" -help "Domain file"}
	{ascii -opt {{Binary 0} {Ascii 1}} -title \
		"STL file format"}
    }]} return
	
    if $ascii { set asc -ascii } else { set asc "" }
    set command "$stl_domain_path $plfile $domain $asc"
	
    runxcom "" $command "" 1 0
}

proc trans_nastran_domain {} {
   global place env nastran_domain_path
    
    set plfile $place/import/nastran
    set domain $place/import/nastran_domain.1
    set trias 1
    set volume 1
    
    if {![dialog .nastran "Nastran -> Domain" \
	    "Please edit the following Nastran options." {
	{plfile -type path -title "Nastran file"}
	{domain -type path -title "Output file"}
	{trias -opt {{Yes 1} {No 0}} -title \
		"Convert QUADs to TRIs"}
	{volume -opt {{Yes 1} {No 0}} -title \
		"Include volume elements"}
    }]} return
	
    if $trias { set tri -only_trias } else { set tri "" }
    if $volume { set vol -volume } else { set vol "" }
    set command "$nastran_domain_path $tri $vol $plfile $domain"
	
    runxcom "" $command "" 1 0
}

proc trans_rampant_domain {} {
    global place env rampant_domain_path
    
    set plfile $place/import/rampant
    set domain $place/import/rampant_domain.1
    set trias 1
    
    if {![dialog .rampant "Rampant -> Domain" \
	    "Please edit the following Rampant options." {
	{plfile -type path -title "Rampant file"}
	{domain -type path -title "Output file"}
    }]} return
	
    set command "$rampant_domain_path $plfile $domain"
	
    runxcom "" $command "" 1 0
}

# --------------------------------------------------------------------

proc trans_prebfc_ddn {} {
    global partname partfile env sheetname
    
    update_prebfc
    put_prebfc
    
    set infile [query_waitvar .query "Click on an PreBFC input file from \
the list below to the right."]
    
    if {$infile == "*cancel*"} {unput_prebfc; return}
    
    set outfile [query_enter .query "Enter name of the DDN part." \
		 [file tail $infile]]
    if {$outfile == "*cancel*"} {unput_prebfc; return}
    
    if {[find_part $outfile] != ""} then {
	if {[query_question .query "Part exists: overwrite?"] == \
	    "*cancel*"} {unput_prebfc; return}
    }
    
    set scale [query_enter .query "Enter scale." 1.0]
    if {$scale == "*cancel*"} {unput_prebfc; return}

    unput_prebfc

    unselect_part
    set partname $outfile
    set sheetname 1

    run_ddn_linked PreBFC d prebfc "$infile\n$scale"
    update_partlist - 1

}

# --------------------------------------------------------------------

# Customization: new translator
# As suggested in the comments on adding a new application, the best
# way to do this is to copy one of the above routines and modify it
# for the new translator.  It would be best to start with one that
# goes from DDN to another format for a translator that also does this,
# and likewise for translators that go from another format to DDN.

# Part routines. --------------------------------------------------

proc part_move {} {
    global partfile partname place sheetname confname geoname
    global comak_objects gui_name
    
    if {$partname == ""} {errormsg "No part selected!"; return}
    if {$partfile == ""} {errormsg "Part doesn't exist yet!"; return}
    if {$place == ""} {errormsg "No $gui_name(conf) open!"; return}

    if [part_is_mulcad] {
	set odir parts
    } elseif [part_is_comak] {
	set odir parts
    } elseif $comak_objects {
	set odir objects/$confname/$geoname
    } else {
	set odir $place/parts
    }

    if {![file exists $odir]} {cmd_mkdir $odir}
    if {[query_question .query \
	 "Move $partname to directory $odir?"] \
	     == "*cancel*"} return
    if {[file exists $odir/[file tail $partfile]] &&
	([query_question .query \
	  "Overwrite file $odir/[file tail $partfile]"] \
	      == "*cancel*")} return
    cmd_rename $partfile $odir
    set partfile ""
    update_partlist - 1
}

proc part_copy {} {
    global partfile partname place comak_objects confname geoname gui_name
    
    if {$partname == ""} {errormsg "No part selected!"; return}
    if {$partfile == ""} {errormsg "Part doesn't exist yet!"; return}
    if {$place == ""} {errormsg "No $gui_name(conf) open!"; return}

    if [part_is_mulcad] {
	set odir parts
    } elseif [part_is_comak] {
	set odir parts
    } elseif $comak_objects {
	set odir objects/$confname/$geoname
    } else {
	set odir $place/parts
    }

    if {![file exists $odir]} {cmd_mkdir $odir}
    if {[query_question .query \
	 "Copy $partname to directory $odir?"] \
	     == "*cancel*"} return
    if {[file exists $odir/[file tail $partfile]] &&
	([query_question .query \
	  "Overwrite file $odir/[file tail $partfile]"] \
	      == "*cancel*")} return
    cmd_cp $partfile $odir
    update_partlist - 1
}

proc part_delete {} {
    global partfile partname place sheetname
    if {$partname == ""} {errormsg "No part selected!"; return}
    if {$partfile == ""} {errormsg "Part doesn't exist yet!"; return}
    set dir [file dirname $partfile]
    if {[query_question .query "Delete $partname in directory $dir?"] \
	== "*cancel*"} return
    cmd_rm $partfile
    update_partlist - 1
}

# Add command to set PCUBE_USER_TOL.
proc set_pcube_user_tol {} {
    global env place

    if {[info exists env(PCUBE_USER_TOL)]} {
        set default $env(PCUBE_USER_TOL)
    } else {
        set default 1.0
    }

    set response [query_enter .query "P-Cube Tolerance" $default]

    if {"$response" != "*cancel*" && $response != $default} {
        # Create or replace open.tcl initialization file.
        if {![file exists $place/open.tcl]} {
            infomsg "Storing this setting in $place/open.tcl."
        } else {
            infomsg "Updating this setting in $place/open.tcl."
        }
        exec echo "set env(PCUBE_USER_TOL) $response" > $place/open.tcl
        exec echo infomsg \"PCUBE_USER_TOL set to \$env(PCUBE_USER_TOL).\" \
                >> $place/open.tcl
        source $place/open.tcl
    }
}

# Add entry to Utility menu for deleting undo files.
proc delete_undos {} {
  global place
  set sel [select_files "$place/parts/cubdb/checkpoint/*.undo.*" "Select undo files to delete." files]
  if {$sel == {}} {
    errormsg "No undo files selected."
    return
  }
  runcom "/bin/rm -f $sel" ""
}

# Select files.
# This routine returns a list of the pathnames for the selected files.
# filespec is the path and wildcard(s) where the files are.
# message is use for the title of the list window.
#
# Example: select_files "./examples/*.dat" "My Example Files"

proc select_files {filespec message {type ""}} {
  global env fselect_done

  set specfiles [glob -nocomplain $filespec]
  if {$specfiles == ""} {
    errormsg "No files matching \"$filespec\"."
    return {}
  }
  set files {}
  foreach file $specfiles {
    if {($type == "") || \
        ($type == "directories" && [file isdirectory $file]) || \
        ($type == "files" && [file isfile $file])} {
      lappend files [file tail $file]
    }
  }
  set files [lsort $files]

  set fselect_done 0
  catch {destroy .fselect}
  toplevel .fselect
  wm withdraw .fselect
  wm geometry .fselect +300+300
  if {$type == ""} {
    set type "files"
  } else {
    set title $type
  }
  wm title .fselect "Select $type."
  message .fselect.message -aspect 600 -text "$message"

  frame .fselect.frame
  frame .fselect.buttons
  pack append .fselect \
        .fselect.message {top fill} \
        .fselect.buttons {bottom fill} \
        .fselect.frame {left right fill expand}

  multiselect_listbox .fselect.files "$filespec" {} {} 1 10 1
  foreach i $files {
    .fselect.files.list insert end $i
  }
  pack append .fselect.frame .fselect.files {top expand fill}

  # Restore standard bindings from listbox.tcl.
  # (ICEMAN replaced them for the Listbox class.)
  bind .fselect.files.list <B1-Motion> {
      set tkPriv(x) %x
      set tkPriv(y) %y
      tkListboxMotion %W [%W index @%x,%y]
  }

  button .fselect.done -text Done -command "set fselect_done 1"
  button .fselect.cancel -text Cancel -command "set fselect_done 0"
  pack append .fselect.buttons \
        .fselect.done {left fillx pady 10 expand} \
        .fselect.cancel {left fillx pady 10 expand}

  wm deiconify .fselect

  tkwait variable fselect_done

  set files {}
  if $fselect_done {
      set filepath [file dirname $filespec]
      set selections [.fselect.files.list curselection]
      foreach i $selections {
          set file [.fselect.files.list get $i]
          lappend files $filepath/$file
      }
  }

  destroy .fselect
  return $files
}

proc listbox_select_all {list} {
    $list select from 0
    $list select to [expr [$list size] - 1]
}

proc listbox_select_none {list} {
    $list selection clear 0 end
}

# Much of this function was borrowed from the domselect.tcl file for the
# ICEM CFD/CAE session manager.
proc multiselect_listbox {w label singlecom doublecom allnone height sb} {
  global scrollbar_inactivecolor scrollbar_activecolor

  frame $w -relief raised -borderwidth 2
  scrollbar $w.scroll -relief sunken -borderwidth 2 \
        -command "$w.list yview" -orient v
  if $height {
    listbox $w.list -yscroll "$w.scroll set" -borderwidth 2 -relief sunken \
            -width 20 -height $height -selectmode extended
  } else {
    listbox $w.list -yscroll "$w.scroll set" -borderwidth 2 -relief sunken \
            -selectmode extended
  }
  label $w.label -text $label
  frame $w.buttons
  pack append $w \
        $w.label {top fill} \
        $w.buttons {bottom fill} \
        $w.list {left expand fill}
  if $sb {
    pack append $w $w.scroll {right fill}
  }

  if $allnone {
    button $w.all -text All -command "tkListboxSelectAll $w.list"
    button $w.none -text None -command "listbox_select_none $w.list"
    pack append $w.buttons \
        $w.all {left expand pady 5 padx 5} \
        $w.none {left expand pady 5 padx 5}
  }

  if {$singlecom != ""} {
        bind $w.list <Button-1> "$singlecom \[%W get \[%W nearest %y\]\]"
  }
  if {$doublecom != ""} {
        bind $w.list <Double-Button-1> "$doublecom \[%W get \[%W nearest %y\]\]"  }
}

proc help_show_manual {manual_name} {
    global env
    
    if {$manual_name == "Dynatext"} {
	set command $env(ICEM_ACN)/bin/icem_manual_browser 
	runxcom "$manual_name" $command "" 1 0
	return
    }
}
