
# This code defines the MED batch interface for translation
#
# Copyright (c) 1997 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com
# $Revision: 863695 $ on $Date: 2015-11-02 14:03:58 +0100 (Mon, 02 Nov 2015) $

# This file contains special comments of the form ## html ... which are
# used to automatically generate documentation

## <h3>Translation functions</h3>

## Transfer the given DDN part file into the named tetin file.

proc ic_trans_ddn_tetin {ddn tetin} {
    global env
    
    if ![file exists $ddn] {
        return -code error "File $ddn not found"
    }
    set oldtcl $env(TCL_LIBRARY)
    set oldpath $env(PATH)
    set env(TCL_LIBRARY) $env(ICEM_ACN)/lib/tcl8.3.3
    set env(PATH) "$env(PATH);$env(ICEM_ACN)/icemcfd"
    if ![catch {get_program bin ssish} prog] {
        set tmp [cmd_tempfile ssish_in .tmp]
        set fp [open $tmp w]
        puts $fp "prttotin \"$ddn\" \"$tetin\""
        close $fp
        set r [run_application_exec "\"$prog\" < \"$tmp\""]
        cmd_rm $tmp
    } else {
        set prog [get_program bin iparta_to_tetin 1]
        set r [run_application_exec "\"$prog\" -i \"$ddn\" -w \"$tetin\""]
    }
    set env(TCL_LIBRARY) $oldtcl
    set env(PATH) $oldpath
    return $r
}

## Transfer the given Unigraphics part file into the named tetin file.
## <table border>
## <tr><td><b>prt  </b></td><td> Path to UG part         </td></tr>
## <tr><td><b>tetin  </b></td><td> Path to new Tetin name </td></tr>
## <tr><td><b>mode  </b></td><td> Translation mode
##      <ul>
##      <li> ug_default -- same output as interactive interface
##      <li> named -- output only named entities
##      <li> levels -- output all entities; levels mapped to families
##      <li> user -- run user supplied script
##      </ul></td></tr>
## <tr><td><b>usr_script  </b></td><td> Custom script supplied by user </td></tr>
## <tr><td><b>usr_opts  </b></td><td> Options supplied for user script </td></tr>    
## </table>
## <br>
## For example usage, see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_ug_tetin.tcl">ic_trans_ug_tetin.tcl</a>.
proc ic_trans_ug_tetin {prt tetin {mode ug_default} {usr_script ""} {usr_opts ""}} {
    global is_win env
    #global ug_options
    
    if $is_win {
	set ug_script_flogger ug_run_script.cmd
    } else {
        set ug_script_flogger ug_run_script.sh
    }
    
    if ![file exists $prt] {
	return -code error "File $prt not found\n"
    }
    #
    #	Check to see if we can find UG
    if ![info exists env(UGII_BASE_DIR)] {
	return -code error "Environment variable UGII_BASE_DIR is not set\nUnigraphics is not properly configured\n"
    }

    #
    #set ug_options(batch) $env(ICEM_ACN)/dif/ug/lib/ug/ug_to_tin.tcl
    set script $usr_script
    set opts   ""
    switch $mode {
        ug_default { 
	    #set script $ug_options(batch)
	    set script $env(ICEM_ACN)/dif/ug/lib/ug/ug_to_tin.tcl
	}
        named {   set script $env(ICEM_ACN)/dif/ug/lib/ug/ug_names_to_tin.tcl }
        levels {  set script $env(ICEM_ACN)/dif/ug/lib/ug/ug_levels_to_tin.tcl }
        user {    set opts   $usr_opts }
    }
    
    if ![catch {get_program dif/ug/bin $ug_script_flogger } prog] {
        if $is_win { 
	    #  This is really cheesy, but . . . so is windoze
#            regsub -all { } $script {SpAcE} foo_scr
#            regsub -all { } $prt    {SpAcE} foo_prt 
#            regsub -all { } $tetin  {SpAcE} foo_tet
             set foo_scr $script
             set foo_prt $prt
	     set foo_tet $tetin
#            set r [run_application_exec "cmd /c start ug_run_script.cmd \"$foo_scr\" \"$foo_prt\" \"$foo_tet\" $opts"]
             if [catch {set r [run_application_exec "cmd /c start ug_run_script.cmd \"$foo_scr\" \"$foo_prt\" \"$foo_tet\" $opts"]} res] {
                  mess "$res\n" red
             }
	} else {
            set r [run_application_exec "\"$prog\" \"$script\" \"$prt\" \"$tetin\" $opts"]
      	}
	if ![file exists $tetin] {
	    return -code error "File $tetin not written\n"
	}
    } else {
        set r ""
        return -code error "UG Direct Interface Script Engine not found\n"
    }
    return $r
}

## Transfer the given GEMS surface file into the named tetin file<p>
## <table border>
## <tr><td><b>prt  </b></td><td> The gems file        </td></tr>
## <tr><td><b>tetin  </b></td><td> The output file. Defaults to a filename derived from the gems filename, <i>prt</i>.</td></tr>
## <tr><td><b>tol  </b></td><td> Specifies the tetin triangulation tolerance.  Defaults to 0.0001.</td></tr>
## <tr><td><b>isRel  </b></td><td> When set, the triangulation tolerance is scaled by the part radius.  Defaults to 1.</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_gems_tetin.tcl">ic_trans_gems_tetin.tcl</a>.
proc ic_trans_gems_tetin {prt {tetin ""} {tol 0.0001} {isRel 1}} {
    global is_win env
    
    if $is_win {
	set gems_exe gemstotin.exe
    } else {
	set gems_exe gemstotin
    }

    if $isRel {
	set isAbs ""
    } else {
	set isAbs -abs
    }
    if ![catch {get_program bin $gems_exe } prog] {
        set r [run_application_exec "\"$prog\" \"$prt\" -o \"$tetin\" -tol $tol $isAbs"]
    } else {
        set r ""
        mess "GemsToTin utility not found\n" red
    }
    return $r
}

## Transfer the given tetin file into the named DDN part file.
## <table border>
## <tr><td>tetin</td><td> tetin file 	   </td></tr>
## <tr><td>iparta</td><td> DDN IPARTA file </td></tr>
## <tr><td>pname </td><td> DDN Part Name   </td></tr>
## <tr><td>units </td><td> Units flag 	   </td></tr>
## </table>
## <b>Notes:</b>
## <ul>
## <li> If the <b>pname</b> argument is given that is used for the part name.
## Otherwise the name of the tetin file is used.
## <li> The units flag may take on the following values
##      <table >
##      <tr><td> -mm <i>(default)</i></td><td> millimeters </td></tr>
##      <tr><td> -inches             </td><td> inches </td> </tr>
##      <tr><td> -feet               </td><td> inches/feet</td></tr>
##      </table>
## <li> DDN likes IPARTA files to reside in a directory called <i>parts</i>.
## <li> For example usage see
##      <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_tetin_ddn.tcl">ic_trans_tetin_ddn.tcl</a>.
## </ul>
proc ic_trans_tetin_ddn {tetin iparta {pname ""} {units -mm}} {
    global env
    
    if ![file exists $tetin] {
        return -code error "Tetin file, $tetin, not found"
    }
    if {$pname == ""} {
        set pname [string toupper [file rootname [file tail $tetin]]]
    } 
    set oldpath $env(PATH)
    set env(PATH) "$env(PATH);$env(ICEM_ACN)/icemcfd"
    set oldtcl $env(TCL_LIBRARY)
    set env(TCL_LIBRARY) $env(ICEM_ACN)/lib/tcl8.3.3
    if ![catch {get_program bin ssish} path] {
        set tmp [cmd_tempfile ssish_in .tmp]
        set fp [open $tmp w]
        puts $fp "tintoprt \"$tetin\" \"$iparta\" \"$pname\" \"$units\""
        close $fp	
        set r [run_application_exec "\"$path\" < \"$tmp\""]
        cmd_rm $tmp
    } else {
        set r [run_application_exec "[get_program bin tetin_to_iparta] -r $tetin -o $iparta"]
    }
    # no need to update the ddn folder
    # ic_list_ddn_parts [file dirname $iparta] 1
    set env(PATH) $oldpath
    set env(TCL_LIBRARY) $oldtcl
    return $r
}

## Transfer the given tetin file into the named DesignSpace BrepXML file.
## If the <b>brepxmlfile</b> argument is given that is used for the part name.
## Otherwise the name of the tetin file is used. If <b>light_export</b> is
## specified, then the graphics only BrepXML file is written.

proc ic_trans_tetin_brepxml {tetin brepxmlfile {light_export ""}} {
 
    set args "\"$tetin\" \"$brepxmlfile\""
    if {"" != $light_export} { append args " -light" }
    set r [ic_run_application_exec . bin brepxml $args]
    return $r
}

## Transfer the given IGES file <em>igesfile </em>into the DDN file <em>ddnpart</em>.
## The type of directive file <em>dir_file</em> may be one of <em>none, default, catia or user</em>,
## among which default is the default; it if is <em>user</em> then must be specified. One may also
## specify data reduction <em>data_red</em>, a listing file <em>listing_file</em>, the option to run
## icempt <em>run_icempt</em> after the translation, and the option to translate DOS text <em>trans_dos</em>.

proc ic_trans_iges_ddn {igesfile ddnpart ddnfile {dir_file default} {dir_file_user ""} {data_red 0} {listing_file ""} {run_icempt 0} {trans_dos 0}} {
    global env
    
    switch $dir_file {
	none    { set dfile "" }
	default { set dfile $env(ICEM_ACN)/iges/dir_iges_general }
	catia   { set dfile $env(ICEM_ACN)/iges/dir_from_catia }
	user    { set dfile $dir_file_user }
    }
    
    set tmp_dfile ""
    if {$dfile != ""} {
	set tmp_dfile [tmp_filename]
	set fp [open $dfile r]
	set fp2 [open $tmp_dfile w]
	while {![eof $fp]} {
	    set line [gets $fp]
	    if !$data_red {
		if [string match *BSP_RED_TOL* $line] continue
	    }
	    puts $fp2 $line
	}
	close $fp
	close $fp2
    }
    
    set command "i=$igesfile o=$ddnfile.tmp name=$ddnpart logit=yes"
    if {"" != $listing_file} { append command " l=$listing_file" }
    if {"" != $tmp_dfile} { append command " d=$tmp_dfile" }    
    ic_run_application_exec . iges iges_post $command
    
    if $run_icempt {
	set command "i=$ddnfile.tmp \
		o=$ddnfile t=BTA e=icempt_list"
	ic_run_application_exec . bin icempt $command
	rm_tmp_file $ddnpart.tmp
    } else {
	ic_mess "Not running icempt on the output.\n"
	cmd_mv $ddnfile.tmp $ddnfile
    }
    ic_list_ddn_parts [file dirname $ddnfile] 1
    
    ic_mess "Translation from IGES to DDN complete. Bring up a\
	    DDN application from the Geometry menu to view or\
	    edit the part $ddnpart.\n"
    return $ddnfile
}

## Transfer the given IGES file <em>igesfile</em> into the tetin file <em>tetinfile</em>.
## The type of directive file <em>dir_file</em> may be one of <em>none, default, catia or user</em>,
## among which default is the default; it if is <em>user</em> then must be specified. One may also
## specify data reduction <em>data_red</em>, a listing file <em>listing_file</em>, the option to run
## icempt <em>run_icempt</em> after the translation, and the option to translate DOS text <em>trans_dos</em>.

proc ic_trans_iges_tetin {igesfile tetinfile {dir_file default} {dir_file_user ""} {data_red 0} {list_file ""} {run_icempt 0} {trans_dos 0}} {    
    set igesroot [file rootname [file tail $igesfile]]
    set workdir  [file dirname  $igesfile]
    set partdir  $workdir/parts
    if ![file exists $igesfile] {
	return -code error "IGES File, $igesfile, not found"
    }
    if ![file exists $partdir] { cmd_mkdir $partdir }

    set tmp_ddn_part $partdir/${igesroot}.ipa
    ic_trans_iges_ddn $igesfile $igesroot $tmp_ddn_part $dir_file $dir_file_user $data_red $list_file \
	    $run_icempt $trans_dos
    ic_trans_ddn_tetin $tmp_ddn_part $tetinfile
    return $tetinfile
}

## Trasnfer the given DDN part file <em>ddn_file</em> to the IGES file <em>iges_name</em>. 
## The listing file <em>listing_file</em> will be saved if specified, and the directive 
## file <em>dir_file</em> if specified.

proc ic_trans_ddn_iges {ddn_file iges_name {listing_file ""} {dir_file ""}} {
    global env
    set env(CFD_IGES_ONLY) 1
    
    set command "i=$ddn_file o=$iges_name"
    if {"" != $listing_file}  { append command " l=$listing_file" }
    if {"" != $dir_file} { append command " d=$dir_file" }
    ic_run_application_exec . iges iges_pre $command
    
}

## Transfer the given DDN part <em>infile</em> to the TVDA file <em>outfile</em>.
## The DDN selected partname <em>selected</em> is specified for the directive
## file created. The directive file <em>tvda_dir</em> is optional, as is the
## output list file <em>tvda_list</em>.

proc ic_trans_ddn_tvda {infile outfile selected {tvda_dir ""} {tvda_list ""}} {    
    
    if {"" == $tvda_dir} { set tvda_dir tvda_dir }
    
    set fd [open $tvda_dir w]
    puts $fd "*FROM,ICEM DDN"
    puts $fd "*TO,VDA"
    puts $fd "*PART=$selected"
    puts $fd "*SHEET=1"
    puts $fd "VDA=HEADER/1"
    puts $fd "     *******"
    puts $fd "VDA=END"
    close $fd
    
    if {"" == $tvda_list} { set tvda_list tvda_list }
    
    set command "i=$infile o=$outfile d=$tvda_dir l=$tvda_list"
    ic_run_application_exec . tvda icemtvda $command
    
    if [file exists $tvda_list] {
	set fp [open tvda_list r]
	mess "[read $fp]\n" blue
	close $fp
    }
}

## Transfer the given TVDA file <em>infile</em> to the DDN part file <em>outfile</em>.
## The directive file <em>tvda_dir</em> is optional, as is the output list
## file <em>tvda_list</em>.

proc ic_trans_tvda_ddn {infile outfile {tvda_dir ""} {tvda_list ""}} {
    
    if {"" == $tvda_dir} { set tvda_dir tvda_dir }
    
    set fd [open $tvda_dir w]
    puts $fd "*FROM,VDA"
    puts $fd "*TO,ICEM DDN"
    puts $fd "*PART=[file tail $outfile]"
    puts $fd "*SHEET=1"
    puts $fd "*DRAFT=ANSI"
    puts $fd "*UNITS=MM"
    close $fd
        
    if {"" == $tvda_list} { set tvda_list tvda_list }
    
    set command "i=$infile o=$outfile d=$tvda_dir l=$tvda_list"
    ic_run_application_exec . tvda icemtvda $command
    
    ic_list_ddn_parts [file dirname $outfile] 1
}

## Transfer the DDN part file <em>file</em> to the DXF file <em>outfile</em>.
## The DXF listing file <em>dxf_list</em> may be specified and the
## directive file <em>directive_file</em>may also be specified.

proc ic_trans_ddn_dxf {file outfile {dxf_list ""} {directive_file ""}} {
    global is_win
    
    if {"" == $dxf_list} { set dxf_list "dxf_list" }
    
    set command ""
    if $is_win { append command "tm=AD " }
    append command "I=$file O=$outfile L=$dxf_list "
    if {"" != $directive_file} { append command "D=$directive_file" }
    ic_run_application_exec . dxf dxf_pre $command

    if [file exists $dxf_list] {
	set fp [open $dxf_list r]
	mess "[read $fp]\n" blue
	close $fp
    }
}

## Transfer the DXF file <em>infile</em> to the DDN part file <em>file</em>.
## The DXF listing file <em>dxf_list</em> may be specified and the
## directive file <em>directive_file</em>may also be specified.

proc ic_trans_dxf_ddn {infile file {dxf_list ""} {directive_file ""}} {
    global is_win
    
    if {"" == $dxf_list} { set dxf_list "dxf_list" }
    
    set command ""
    if $is_win { append command "tm=DA " }    
    
    append command "I=$infile O=$file L=$dxf_list "
    if {"" != $directive_file} { append command "D=$directive_file " }
    ic_run_application_exec . dxf dxf_post $command
    ic_list_ddn_parts [file dirname $file] 1
}

## Transfer the given IDI surface file into the named tetin file<p>
## <table border>
## <tr><td><b>prt  </b></td><td> The idi file        </td></tr>
## <tr><td><b>tetin  </b></td><td> The output file. Defaults to a filename derived from the idi filename, <i>prt</i>.</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_idi_tetin.tcl">ic_trans_idi_tetin.tcl</a>.
proc ic_trans_idi_tetin {prt {tetin ""} {tol 0.0001} {isRel 1} {idi_options ""}} {
    global env
    
    if $isRel {
	set isAbs ""
    } else {
	set isAbs -abs
    }
    if ![file exists $prt] {
	return -code error "File $prt not found\n"
    }
    if [catch {ic_run_application_exec . bin idi2tetin "$idi_options \"$prt\" \"$tetin\"" } res] {
	return -code error $res
    }
    return $res

}

## Transfer the given proe part file into the named tetin file<p>
## <table border>
## <tr><td><b>prt  </b></td><td> The SolidWorks file        </td></tr>
## <tr><td><b>prt  </b></td><td> The output file. Defaults to a filename derived from the SolidWorks filename, <i>prt</i>.</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_proe_tetin.tcl">ic_trans_proe_tetin.tcl</a>.
proc ic_trans_sw_tetin {infile {swVer ""}} {

   global env is_win file_name

   set env(IC_SW_BATCH) 1

   if ![file exists $infile] {
       return -code error "Model $infile not found\n"
   }  else {
       mess "Model is $infile\n"
   }

   if $is_win {
       regsub -all {\/} $infile {\\\\} infile
   } 

   set keyName2005  {HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\SolidWorks 2005\Setup}
   set keyName2006  {HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\SolidWorks 2006\Setup}
   set keyName2007  {HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\SolidWorks 2007\Setup}

   catch {load $env(ICEM_ACN)/bin/tclreg83.dll registry}

   if {$swVer == ""} {
      if [catch {set apploc [registry get $keyName2006 "SolidWorks Location"]} res] {
         mess "Warning: SolidWorks 2006 not detected, trying for SolidWorks 2007\n\n" blue
         if [catch {set apploc [registry get $keyName2007 "SolidWorks Location"]} res] {
            if [catch {set apploc [registry get $keyName2007 "XchangeWorks Installed"]} res] {
               mess "Warning: SolidWorks 2007 not detected, trying for SolidWorks 2005\n\n" blue
               if [catch {set apploc [registry get $keyName2005 "SolidWorks Location"]} res] {
                  mess "Warning: Unable to detect any local SolidWorks installations.  Aborting\n\n" red
                  return
               }
            }
         }
      }
   } else {
      if [catch {set apploc [registry get $keyName2007 "SolidWorks Location"]} res] {
         if [catch {set apploc [registry get $keyName2007 "XchangeWorks Installed"]} res] {
            mess "Warning: SolidWorks 2007 not detected, trying for SolidWorks 2007\n\n" blue
            if [catch {set apploc [registry get $keyName2006 "SolidWorks Location"]} res] {
               mess "Warning: SolidWorks 2006 not detected, trying for SolidWorks 2005\n\n" blue
               if [catch {set apploc [registry get $keyName2005 "SolidWorks Location"]} res] {
                  mess "Warning: Unable to detect any local SolidWorks installations.  Aborting\n\n" red
                  return
               }
            }
         }
      }
   }

   if $is_win {
      regsub -all {\/} $apploc {\\\\} apploc
   } 

   set cut_point [string last "\\" $apploc]
   set idx [expr $cut_point-1]
   set appLoc2 [string range $apploc 0 $idx]
#   if $is_win {
#      regsub -all {\\} $appLoc2 {\\\\} appLoc2
#   }

   ic_run_application_exec . $appLoc2 SLDWORKS.EXE "\"$infile\""	
}

## Transfer the given proe part file into the named tetin file<p>
## <table border>
## <tr><td><b>prt  </b></td><td> The proe file        </td></tr>
## <tr><td><b>prt  </b></td><td> The output file. Defaults to a filename derived from the proe filename, <i>prt</i>.</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_proe_tetin.tcl">ic_trans_proe_tetin.tcl</a>.
proc ic_trans_proe_tetin_protcl {prt {tetin ""}} {
    global env is_win
 
    if ![file exists $prt] {
	return -code error "File $prt not found\n"
    }

#    if ![info exists env(PROMIF_ACN140)] {
#	return -code error "PROMIF_ACN140 is not set!\n    Pro Interface is not configured"
#   }

#    set ICEM_ACN_BAK $env(ICEM_ACN)
#    set PROMIF_ACN_BAK $env(PROMIF_ACN140)

    if $is_win {
        regsub -all {\/} $prt {\\\\} argprtfile
        regsub -all {\/} $tetin {\\\\} argtetinfile
        regsub -all {\/} $env(ICEM_ACN) {\\} env(ICEM_ACN)
#	regsub -all {\\} $env(PROMIF_ACN140) {/} env(PROMIF_ACN140)
    }

    set argprtfile $prt
    set argtetinfile $tetin

    set fname [cmd_tempfile protcl_int .tmp]
#   set filename "$env(PROMIF_ACN140)/$fname"

     set fp [open $fname w]
#    set line1 "proStartMed proe2001"
#    set line2 "proOpenPartMed $argprtfile"
#    set line3 "proWriteTetinMedDump $argtetinfile"
#    set line4 "proClosePart"
#    set line5 "proEnd"

	if $is_win {
		regsub -all {\\} $env(PROE_START_CMD140) {\\\\} proStartLine
		set line1 "proStartNoGraphics $proStartLine"
	} else {
		set line1 "proStartNoGraphics $env(PROE_START_CMD140)"
	}

	if {[string first ".asm" $argprtfile] > 0} {
		set line2 "proOpenAsm $argprtfile"
		set line3 "proWriteAsmSingleMed $argtetinfile"
	} else 	{

		set line2 "proOpenPart $argprtfile"
		set line3 "proWriteTetinMedDump $argtetinfile"
	}

    set line4 ""
    if {![string first ".asm" $argprtfile] > 0} {
		set line4 "proClosePart"
	}
    set line5 "proEnd"
    set line6 "exit"
	
    puts $fp $line1
    puts $fp $line2
    puts $fp $line3
#   puts $fp $line4
    puts $fp $line5
    puts $fp $line6
    close $fp

#    set input_file "< $filename"

    if [catch {ic_run_application_exec . bin protcl $fname} res] {
	if $is_win {
#	    set env(ICEM_ACN) $ICEM_ACN_BAK
#	    set env(PROMIF_ACN140) $PROMIF_ACN_BAK
	}
	return -code error $res
    }
    if $is_win {
#	set env(ICEM_ACN) $ICEM_ACN_BAK
#	set env(PROMIF_ACN140) $PROMIF_ACN_BAK
    }
    return $res

}


proc ic_trans_proe_tetin { {prtfile ""} {tetfileloc ""} {method "0"} } {
   global env is_win file_name proe_trans pro_com_path

	if ![info exists env(PROE_START_CMD140)] {
		mess "Please set the environment variable PROE_START_CMD140 to the full path\n\
	     of your Pro/Engineer start script. This is typically located in the bin\n\
		 directory of your Pro/Engineer installation\n" red	 
		 return 
	}

	if ![info exists env(PROMIF_ACN140)] {
		mess "Your PROMIF_ACN140 variable is not set, without this the import will likely fail \n" red	 
	}

    set promif_dll_file $env(PROMIF_ACN140)/promif.dll
	if ![file exists $promif_dll_file] {
	    mess "Your PROMIF_ACN140 variable may not be set correctly to load the translator module.\n" red
	}

	set proe_trans(type) 0
	if {![info exists proe_trans(meth)] || $proe_trans(meth) == "" } {
		set proe_trans(meth) $method
	}
	
	if {![info exists file_name(project_dir)] || $file_name(project_dir) ==  "" } {
		set file_name(project_dir) .
	}
	
   set start_parse 0
   set open_proe_str ""

   if {$prtfile == ""} return

   if {$tetfileloc == ""} {
        mess "Invalid Input File\n"
        return
    }

#    set tetinfile [file rootname $tetfileloc]
#    mess "tetinfile = $tetinfile" blue
#    if {$tetinfile == $tetfileloc} return

    set tetinfile $tetfileloc
    regsub -all .prt $tetinfile {} $tetinfile

##   automatically use the part file to generate the tetin file
#    set tetinfile [med_file_select tetin 1 $tetinfile.tin]

	if $is_win {
        regsub -all {\/} $tetinfile {\\\\} argtetinfile
	} else {
	  set argtetinfile $tetinfile
	}
    if $is_win {
        set part_name {~ Activate `main_dlg_cur` `File.psh_open`
~ Select `file_open` `Ph_list.Filelist` \\ 
 `Part`
~ Activate `file_open` `Inputname` \
 `Part`}
        } else {
                 set part_name {~ Activate `main_dlg_cur` `File.psh_open`
~ Select `file_open` `Ph_list.Filelist` \\ 
 `Part`
~ Activate `file_open` `Inputname` \
 `Part`}
        }
        regsub -all  Part  $part_name $prtfile    part_name
        set PF $part_name

        set TF $tetinfile
        regsub -all .tin $TF {} TF
        set cut_point [string last "/" $TF]
        set idx [expr $cut_point+1]
        set TF  [string range $TF $idx end]
        expr 5 / ( [string length "abcd"] + 0.0 )

        set PROJ $file_name(project_dir)
        set cut_point [string first "/" $TF]
        set idx [expr $cut_point+1]
        set PROJ  [string range $PROJ $idx end]

        set proe_dump_trail {!trail file version No. 1151
!Pro/ENGINEER  TM  2001  (c) 1988-2001 by Parametric Technology Corporation  All Rights Reserved.
@@PARTNAME
#ICEM CFD
.
#DIRECT INTERFACE SETTINGS
~ Activate `settings` `optimizeButton` 1
~ Activate `settings` `autoGeomDumpButton` 1
~ Activate `settings` `OK`
#WRITE TETIN
@@TETFILE
#DEFAULT
#OVERWRITE EXISTING FILE
#DEFAULT
~ Select `main_dlg_cur` `MenuBar1` \
1  `File`
~ Close `main_dlg_cur` `MenuBar1`
~ Activate `main_dlg_cur` `File.psh_exit`
~ FocusIn `UI Message Dialog` `no`
~ FocusIn `UI Message Dialog` `yes`
~ Activate `UI Message Dialog` `yes`
!}

#        regsub -all @@PROJ      $proe_dump_trail $PROJ         proe_dump_trail
        regsub -all @@TETFILE   $proe_dump_trail $TF           proe_dump_trail
        regsub -all @@PARTNAME  $proe_dump_trail $PF           proe_dump_trail

        set isasm [string first .asm $prtfile]
        if {$isasm != -1} {
                set sub {#WRITE ASSEMBLY
#SINGLE FILE}
                set replace_me {#WRITE TETIN}
                regsub -all $replace_me   $proe_dump_trail $sub  proe_dump_trail
        }
		#Dump Output
		mess "Generating trail file " blue
		if {$proe_trans(meth) == "0"} {
		        mess "using geometry dump\n" blue
			    set dump_str {`autoGeomDumpButton` 0}
			    set sub {`autoGeomDumpButton` 1}
			    regsub -all $dump_str  $proe_dump_trail $sub  proe_dump_trail
		}
        #Normal Output
        if {$proe_trans(meth) == "1"} {
		        mess "using families\n" blue
                set dump_str {`autoGeomDumpButton` 1}
                set sub {`autoGeomDumpButton` 0}
                regsub -all $dump_str  $proe_dump_trail $sub  proe_dump_trail
        }

        #Layers Output
        if {$proe_trans(meth) == "2"} {
		        mess "using proe layers dump\n" blue
                set dump_str {`autoGeomDumpButton` 1}
                set sub {`autoGeomDumpButton` 0
~ Activate `settings` `writeAllLayersButton` 1
~ Activate `settings` `writeHiddenLayersButton` 1}
                regsub -all $dump_str  $proe_dump_trail $sub  proe_dump_trail
        }

    set fname tmp_trail.txt

    set fp [open $fname w]
    puts $fp "$proe_dump_trail"
    close $fp

    set env(NMSD_TIMEOUT) "15"
	set lm_license_file $env(LM_LICENSE_FILE)
	
	if !$is_win {unset env(LM_LICENSE_FILE)}

	# clean out std* files.
	set file "std.err"
	if [file exists $file] {
		mess "cleaning up std.err\n"
		file delete $file
	}

	set file "std.out"
	if [file exists $file] {
		mess "cleaning up std.out\n"
		file delete $file
	}


    mess "Importing ProE Model, please wait ...\n" blue 
	set exec_path $env(PROE_START_CMD140)
	busy 1
	if  $proe_trans(type) {
		set env(IS_PROTCL) TRUE
        ic_run_application_exec . bin proe2tin "$argprtfile $argtetinfile"
		unset env(IS_PROTCL)
    } else {
	    catch {exec $exec_path -g:no_graphics $fname} res
	}

	set file "std.err"
	if [file exists $file] {
		mess "Possible Translation Errors listed in 'std.err':" red
		set x 0
		set f [open $file r]
		while (![eof $f]) {
		    set line($x) [gets $f]
			mess "$f\n" red
			incr x
			}
	    close $f

		set file std_out($file) 
	}

	busy reset
	if !$is_win {set env(LM_LICENSE_FILE) $lm_license_file}
    
	mess "Translation/Import complete. \n" blue

	#set tetinfile $tetinfile.tin
	if [file exists $tetinfile] {
		#file_check_load_tetin $tetinfile
		mess "Tetin file written sucessfully \n"
	}

    if ![file exists $tetinfile] {
	    mess "Import failed to generate a tetin file.  Please refer to the 'std.out' \n\
		file in your project directory for details concerning problems encountered\n\
		during the import.\n" red    
	}
}

## Import an External Scan File<p>
## <table border>
## <tr><td><b>prt</td><td> esf file to read</td></tr>
## <tr><td><b>fam</td><td> name of family containing created surfaces</td></tr>
## <tr><td><b>return</td><td> list of created surfaces</td></tr>
## </table>
## <b>Notes:</b>
## <ul>
## <li> If the <i>fam</i> parameter is omitted, a family will be created
## for each surface.
## <li> Example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_read_esf_file.tcl">ic_trans_read_esf_file.tcl</a>.
## </ul>
proc ic_trans_read_esf_file {prt {do_tri 0} {fam ""}} {
    global projlib
    global env
    
    if { $fam != "" } {
    	set new_fam [ic_geo_new_family $fam]    
    }

    if ![file exists $prt] {
	return -code error "File $prt not found\n"
    }
    
    set esf $prt

    if {[file extension $prt] == ".xyz"} {set do_tri 1}
    if {$do_tri == 1} {
	mess "Found a point scan file\n"
	set tmp [cmd_tempfile esf_tmp .esf]
	set esf [cmd_tempfile esf_image .esf]
	if [catch {ic_run_application_exec . bin pnttoesf "$prt -tmp \"$tmp\" -o \"$esf\"" } res] {
	    return -code error $res
	}
    }
    ic_empty_tetin
    if {$fam == ""} {
	if [catch {trans_read_esf_file $esf} res] {
	    return -code error $res
	} 
    } else {
	if [catch {trans_read_esf_file $esf $fam} res] {
	    return -code error $res
	}
    }
    set srfs ""
    set nums [lindex $res 0]
    foreach n $nums {
        set nb [define_geom_object surface $n]
        update_geom_visible_obj $nb
	set name [$projlib get_name surface $n]
	lappend srfs $name
	if {$fam == ""} {
	    set srf_fam_name [ $projlib get_family surface $n ]
	    set fam_no [$projlib lookup_family_pid $name]
	    display_update geo $fam_no
	}
    }
    if {$fam != ""} {
	display_update geo $new_fam
    }
    return $srfs
}

## Import an ACIS SAT File<p>
## <table border>
## <tr><td>acisfile </td> <td> The SAT file         </td></tr>
## <tr><td>outfile  </td> <td> The TETIN output file</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_acis_tetin.tcl">ic_trans_acis_tetin.tcl</a>.
proc ic_trans_acis_tetin {acisfile outfile} {
    global env
    
    if ![file exists $acisfile] {
        return -code error "File $acisfile not found\n"
    }
  
    if [catch {ic_run_application_exec . bin acistotin "-sat \"$acisfile\" -tin \"$outfile\""} res] {
        return -code error $res
    } 
    return $res
}

## Import a DWG File<p>
## <table border>
## <tr><td>dwgfile </td> <td> The DWG file         </td></tr>
## <tr><td>outfile  </td> <td> The TETIN output file</td></tr>
## </dl>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_dwg_tetin.tcl">ic_trans_dwg_tetin.tcl</a>.
proc ic_trans_dwg_tetin {dwgfile outfile} {
    global env
    
    if ![file exists $dwgfile] {
	return -code error "File $dwgfile not found\n"
    }
  
    if [catch {ic_run_application_exec . bin dwg2tin "-onefamilyperbody \"$dwgfile\" \"$outfile\""} res] {
	return -code error $res
    } 
    return $res
}

## Import a ANF File<p>
## <table border>
## <tr><td>anffile </td> <td> The ANF file         </td></tr>
## <tr><td>outfile  </td> <td> The TETIN output file</td></tr>
## </dl>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_anf_tetin.tcl">ic_trans_anf_tetin.tcl</a>.
proc ic_trans_anf_tetin {anffile outfile} {
    global env
    
    if ![file exists $anffile] {
	return -code error "File $anffile not found\n"
    }
  
    if [catch {ic_run_application_exec . bin anftotin "\"$anffile\" -o \"$outfile\""} res] {
	return -code error $res
    } 
    return $res
}

## Import an I-DEAS Model File using Capri<p>
## <table border>
## <tr><td>mdlfile    </td> <td> The IDEAS MF1 File         </td></tr>
## <tr><td>tetinfile  </td> <td> The TETIN output file</td></tr>
## </dl>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_ideas_tetin.tcl">ic_trans_ideas_tetin.tcl</a>.
proc ic_trans_ideas_tetin {mdlfile tetinfile} {
    global env is_win
    if ![info exists env(SDRC_INSTL)] {
	return -code error "I-DEAS configuration problem. SDRC_INSTL not set."
    }
    if ![file exists $mdlfile.mf1] {
	return -code error "File $mdlfile.mf1 not found\n"
    }
    #
    #	We absolutely like absolute paths
    if {[file pathtype $mdlfile] == "relative"} {
        set mdlfile [pwd]/$mdlfile
    }
    if {[file pathtype $tetinfile] == "relative"} {
        set tetinfile [pwd]/$tetinfile
    }
  
    set currdir [pwd]
    cd [file dirname $mdlfile]
    set mdlfile [pwd]/[file tail $mdlfile]
    cd [file dirname $tetinfile]
    set tetinfile [pwd]/[file tail $tetinfile]
    cd $currdir


    # On Windows, change all forward slashes to back slashes
    if $is_win {
        regsub -all {\/} $mdlfile {\\\\} mdlfile
    }

    if [catch {ic_run_application_exec . bin ideas2tin "\"$mdlfile\" \"$tetinfile\""} res] {
	return -code error $res
    } 

    return $res
}

## Triangulate a raw point file<p>
## <table border>
## <tr><td>mdlfile    </td> <td> The IDEAS MF1 File         </td></tr>
## <tr><td>tetinfile  </td> <td> The TETIN output file</td></tr>
## </dl>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_ideas_tetin.tcl">ic_trans_ideas_tetin.tcl</a>.
proc ic_trans_ideas_tetin {mdlfile tetinfile} {
    global env is_win
    if ![info exists env(SDRC_INSTL)] {
	return -code error "I-DEAS configuration problem. SDRC_INSTL not set."
    }
    if ![file exists $mdlfile.mf1] {
	return -code error "File $mdlfile.mf1 not found\n"
    }
    #
    #	We absolutely like absolute paths
    if {[file pathtype $mdlfile] == "relative"} {
        set mdlfile [pwd]/$mdlfile
    }
    if {[file pathtype $tetinfile] == "relative"} {
        set tetinfile [pwd]/$tetinfile
    }
  
    set currdir [pwd]
    cd [file dirname $mdlfile]
    set mdlfile [pwd]/[file tail $mdlfile]
    cd [file dirname $tetinfile]
    set tetinfile [pwd]/[file tail $tetinfile]
    cd $currdir


    # On Windows, change all forward slashes to back slashes
    if $is_win {
        regsub -all {\/} $mdlfile {\\\\} mdlfile
    }

    if [catch {ic_run_application_exec . bin ideas2tin "\"$mdlfile\" \"$tetinfile\""} res] {
	return -code error $res
    } 

    return $res
}

## Import STEP or IGES File<p>
## <table border>
## <tr><td>infile   </td> <td> A STEP or IGES file  </td></tr>
## <tr><td>outfile  </td> <td> The TETIN output file</td></tr>
## <tr><td>facet    </td> <td> == 1 - Import as facetted geometry <br>
##                             -- 0 - Import as spline geometry  </td></tr>
## </table>
## </dl>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_step_tetin.tcl">ic_trans_step_tetin.tcl</a>.
proc ic_trans_step_tetin {infile outfile {facet 0} {tolarg ""} {stepver 0} {args ""}} {
    global env tcl_platform
    
    set env(CFD_IGES_ONLY) 1

    if ![file exists $infile] {
	return -code error "File $infile not found\n"
    }
 
    set igestrans [file join $env(ICEM_ACN) dif iges igestotin]

    if { $tcl_platform(platform) == "windows" } {
           set igestrans "${igestrans}.exe"
    }

    if {[file exists $igestrans] && !$stepver} {
       if {$facet != 0} { 
           if [catch {ic_run_application_exec . dif/iges igestotin " $args \"$infile\" \"$outfile\""} res] {
	       return -code error $res
	  }
       } else {
           if [catch {ic_run_application_exec . dif/iges igestotin " $args \"$infile\" \"$outfile\""} res] {
	       return -code error $res
	 }
       }
 
    } else {

       if {$facet != 0} { 
           if [catch {ic_run_application_exec . dif/step steptotin "-t $tolarg \"$infile\" \"$outfile\""} res] {
	       return -code error $res
	 }
       } else {
           if [catch {ic_run_application_exec . dif/step steptotin "$tolarg \"$infile\" \"$outfile\""} res] {
	       return -code error $res
	 }
       }

    } 
    return $res
}

## Export STEP or IGES File<p>
## <table border>
## <tr><td>infile  </td> <td> The TETIN output file</td></tr>
## <tr><td>outfile </td> <td> A STEP or IGES file  </td></tr>
## </table>
## </dl>
## <b>Note:</b>
## <ul>
## <li> The type of output (i.e. step or iges) is determined by the
## extension (i.e. .stp or .igs) of the output file.
## </ul>
proc ic_trans_tetin_step {infile outfile {tolarg ""}} {
    global env tcl_platform
    set env(CFD_IGES_ONLY) 1
    if ![file exists $infile] {
	return -code error "File $infile not found\n"
    }
 
    set igestrans [file join $env(ICEM_ACN) dif iges igestotin]

    if { $tcl_platform(platform) == "windows" } {
           set igestrans "${igestrans}.exe"
    }

    if [file exists $igestrans] {

       if [catch {ic_run_application_exec . dif/iges igestotin " \"$infile\" \"$outfile\""} res] {
	    return -code error $res
       } 

    } else {

       if [catch {ic_run_application_exec . dif/step steptotin "$tolarg \"$infile\" \"$outfile\""} res] {
	    return -code error $res
       } 

    } 
    return $res
}

## Import Parasolid File<p>
## <table border>
## <tr><td>infile   </td> <td> A parasolid file  </td></tr>
## <tr><td>outfile  </td> <td> The TETIN output file</td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_ps_tetin.tcl">ic_trans_ps_tetin.tcl</a>.
proc ic_trans_ps_tetin {infile outfile {units "meter"} } {
    global env
	
    if ![info exists env(PS2TIN_SCALE)] {
    	switch $units {
	    	meter { set env(PS2TIN_SCALE) 1}
    		centimeter { set env(PS2TIN_SCALE) 100}
    		millimeter { set env(PS2TIN_SCALE) 1000}
    		inch { set env(PS2TIN_SCALE) 39.3700787}
    		foot { set env(PS2TIN_SCALE) 3.2808399}
		}
		set set_internal 1
	}    
    
    if ![file exists $infile] {
	return -code error "File $infile not found\n"
    }
 
    if [catch {ic_run_application_exec . bin pstotin "\"$infile\" \"$outfile\""} res] {
	    return -code error $res
    }
        
    if {[info exists set_internal] && $set_internal} {
	    unset set_internal
	    unset env(PS2TIN_SCALE)
	}
	
	return $res
}

## Export Parasolid File<p>
## <table border>
## <tr><td>infile  </td> <td> The TETIN file</td></tr>
## <tr><td>infile   </td> <td> Parasolid  outputfile  </td></tr>
## </table>
## <br>
## For example usage see
## <a href="file:../../../icemcfd/samples/ProgrammersGuide/med_test/ic_trans_tetin_ps.tcl">ic_trans_tetin_ps.tcl</a>.
proc ic_trans_tetin_ps {infile outfile} {
    global env
    if ![file exists $infile] {
	return -code error "File $infile not found\n"
    }

    #Strip off file extensions, since these are generated by the translator.
    set cut_point [string last "." $outfile]
    set suffix [string range $outfile $cut_point end]
    if {$suffix == ".x_t"     ||  $suffix == ".xmt_txt" || $suffix == ".x_b" || $suffix == ".x_m" || $suffix == ".xmt_bin" ||  $suffix == ".xmt_txt" } {
       set cut_point [expr $cut_point-1]
       set outfile [string range $outfile 0 $cut_point]
    }
 
    if [catch {ic_run_application_exec . bin tintops "\"$infile\" \"$outfile\""} res] {
	    return -code error $res
    }
    return $res
}


## Import a workbench model
##

proc ic_wb_set_default_properties {} {

    if {[ic_get_global vid_options wb_import_mat_points] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_mat_points
    }
    if {[ic_get_global vid_options wb_NS_to_subset] == "___NA___"} {
        ic_set_global vid_options 0 wb_NS_to_subset
    }
    if {[ic_get_global vid_options wb_NS_to_entity_parts] == "___NA___"} {
        ic_set_global vid_options 0 wb_NS_to_entity_parts
    }
    if {[ic_get_global vid_options wb_import_solid_bodies] == "___NA___"} {
        ic_set_global vid_options 1 wb_import_solid_bodies
    }
    if {[ic_get_global vid_options wb_import_surface_bodies] == "___NA___"} {
        ic_set_global vid_options 1 wb_import_surface_bodies
    }
    if {[ic_get_global vid_options wb_import_line_bodies] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_line_bodies
    }
    if {[ic_get_global vid_options wb_import_work_points] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_work_points
    }
    if {[ic_get_global vid_options wb_import_delete_solids] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_delete_solids
    }
    if {[ic_get_global vid_options wb_import_create_solids] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_create_solids
    }
    if {[ic_get_global vid_options wb_import_cad_att_trans] == "___NA___"} {
        ic_set_global vid_options 1 wb_import_cad_att_trans
    }
    if {[ic_get_global vid_options wb_import_cad_att_pre] == "___NA___"} {
        ic_set_global vid_options {SDFEA;DDM} wb_import_cad_att_pre
    }
    if {[ic_get_global vid_options wb_import_sel_proc] == "___NA___"} {
        ic_set_global vid_options 1 wb_import_sel_proc
    }
    if {[ic_get_global vid_options wb_import_sel_pre] == "___NA___"} {
        ic_set_global vid_options {} wb_import_sel_pre
    }
    if {[ic_get_global vid_options wb_import_mix_res] == "___NA___"} {
        ic_set_global vid_options -1 wb_import_mix_res
    }
    if {[ic_get_global vid_options wb_import_mix_res_solid] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_mix_res_solid
    }
    if {[ic_get_global vid_options wb_import_mix_res_surface] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_mix_res_surface
    }
    if {[ic_get_global vid_options wb_import_mix_res_line] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_mix_res_line
    }
    if {[ic_get_global vid_options wb_import_mix_res_point] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_mix_res_point
    }
    if {[ic_get_global vid_options wb_import_en_sym_proc] == "___NA___"} {
        ic_set_global vid_options 1 wb_import_en_sym_proc
    }
    if {[ic_get_global vid_options wb_import_scale_geo] == "___NA___"} {
        ic_set_global vid_options "Default" wb_import_scale_geo
    }
    if {[ic_get_global vid_options wb_import_save_pmdb] == "___NA___"} {
        ic_set_global vid_options "" wb_import_save_pmdb
    }
    if {[ic_get_global vid_options wb_import_load_pmdb] == "___NA___"} {
        ic_set_global vid_options "" wb_import_load_pmdb
    }
    if {[ic_get_global vid_options wb_import_refresh_pmdb] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_refresh_pmdb
    }
    if {[ic_get_global vid_options wb_import_cad_associativity] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_cad_associativity
    }
    if {[ic_get_global vid_options wb_import_save_partfile] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_save_partfile
    }
    if {[ic_get_global vid_options wb_import_pluginname] == "___NA___"} {
        ic_set_global vid_options "" wb_import_pluginname
    }
    if {[ic_get_global vid_options wb_NS_only] == "___NA___"} {
        ic_set_global vid_options 0 wb_NS_only
    }
    if {[ic_get_global vid_options wb_import_tritol] == "___NA___"} {
        ic_set_global vid_options 0.001 wb_import_tritol
    }
    if {[ic_get_global vid_options wb_import_reference_key] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_reference_key
    }
    if {[ic_get_global vid_options wb_import_lcs] == "___NA___"} {
        ic_set_global vid_options 0 wb_import_lcs
    }
}

## Set the parameters for the workbench reader file import
## 

proc ic_wb_set_parameters {{wb_import_geom ""} {wb_import_mesh ""} {wb_import_mat_points ""} {wb_NS_to_subset ""} \
    {wb_NS_to_entity_parts ""} {wb_import_solid_bodies ""} {wb_import_surface_bodies ""} {wb_import_line_bodies ""} \
    {wb_import_cad_att_trans ""} {wb_import_cad_att_pre ""} {wb_import_sel_proc ""} {wb_import_sel_pre ""} \
    {wb_import_mix_res ""} {wb_import_en_sym_proc ""} {wb_import_scale_geo "Default"} {wb_import_work_points ""} \
    {wb_import_delete_solids ""} {wb_import_create_solids ""} {wb_import_save_pmdb ""} {wb_import_load_pmdb ""} \
    {wb_import_refresh_pmdb ""} {wb_import_cad_associativity ""} {wb_import_save_partfile ""} {wb_import_pluginname ""} \
    {wb_NS_only ""} {wb_import_tritol 0.001} {wb_import_reference_key 0} \
    {wb_import_lcs 0}} {
    
    ic_set_global vid_options $wb_import_geom wb_import_geom
    ic_set_global vid_options $wb_import_mesh wb_import_mesh
    ic_set_global vid_options $wb_import_mat_points wb_import_mat_points
    ic_set_global vid_options $wb_NS_to_subset wb_NS_to_subset
    ic_set_global vid_options $wb_NS_to_entity_parts wb_NS_to_entity_parts
    ic_set_global vid_options $wb_import_solid_bodies wb_import_solid_bodies
    ic_set_global vid_options $wb_import_surface_bodies wb_import_surface_bodies
    ic_set_global vid_options $wb_import_line_bodies wb_import_line_bodies
    ic_set_global vid_options $wb_import_cad_att_trans wb_import_cad_att_trans
    ic_set_global vid_options $wb_import_cad_att_pre wb_import_cad_att_pre
    ic_set_global vid_options $wb_import_sel_proc wb_import_sel_proc
    ic_set_global vid_options $wb_import_sel_pre wb_import_sel_pre
    ic_set_global vid_options $wb_import_mix_res wb_import_mix_res
    ic_set_global vid_options $wb_import_en_sym_proc wb_import_en_sym_proc
    ic_set_global vid_options $wb_import_scale_geo wb_import_scale_geo
    ic_set_global vid_options $wb_import_work_points wb_import_work_points
    ic_set_global vid_options $wb_import_delete_solids wb_import_delete_solids
    ic_set_global vid_options $wb_import_create_solids wb_import_create_solids
    ic_set_global vid_options $wb_import_save_pmdb wb_import_save_pmdb
    ic_set_global vid_options $wb_import_load_pmdb wb_import_load_pmdb
    ic_set_global vid_options $wb_import_refresh_pmdb wb_import_refresh_pmdb
    ic_set_global vid_options $wb_import_cad_associativity wb_import_cad_associativity
    ic_set_global vid_options $wb_import_save_partfile wb_import_save_partfile 
    ic_set_global vid_options $wb_import_pluginname wb_import_pluginname
    ic_set_global vid_options $wb_NS_only wb_NS_only
    ic_set_global vid_options $wb_import_tritol wb_import_tritol
    ic_set_global vid_options $wb_import_reference_key wb_import_reference_key
    ic_set_global vid_options $wb_import_lcs wb_import_lcs
}

## Run the workbench reader file import
## 

proc ic_wb_brep_read {prt {make_absolute_paths 1} {merge 0} {mesh 0} {subset 0} {geom 1} \
    {executable 0} {batch 0} {refresh_pmdb 0} {save_pmdb ""} {entity_parts 0} {line 0} \
    {ns_only 0} {create_material 0}} {
    global is_win env tcl_platform batch_mode 
    
    set debug 0
    set custom_python_file ""
    
    regsub -all "\\|" $prt "" prt
    
    if !$merge { 
        ic_unload_tetin
        ic_empty_tetin
    } else {
        if {[ic_get_global vid_options wb_import_geom] == "1" && [ic_geo_is_loaded]} {
            if {($batch_mode && [ic_get_global import_model_options always_convert] == "1") || \
                (!$batch_mode && [ic_get_global vid_options wb_import_from_gui] != "1" && [ic_get_global import_model_options always_convert] == "1") || \
                (!$batch_mode && [ic_get_global vid_options wb_import_scale_geo] != "Default")} {
                foreach type "point curve surface material density" {
                    set objs [ic_geo_get_objects $type]
                    if {$objs != ""} {
                        set do_not_scale($type) "$objs"
                    }
                }
            }
            foreach obj [ic_geo_get_objects point] {
                set mpoints($obj) [list [ic_geo_get_part point $obj] [ic_geo_get_point_location $obj]]
            }
        }
    }
    
    ic_wb_set_default_properties
    
    # wb_brep_read mapping NS into subsets
    # Convert into part by default. Keep existing subsets
    set old_subset(_NULL) ""
    foreach subset [ic_geo_subset_list] {
        set old_subset($subset) 1
    }
    if ![file exists $prt] {
        mess "Error: file $prt not found\n" red
        return 1
    }
    
    # Something on the Ansys side does not like relative paths.
    if {$make_absolute_paths && [file pathtype $prt] == "relative"} {
        set prt [pwd]/$prt
    }

    set import_geom [ic_get_global vid_options wb_import_geom]
    set import_mesh [ic_get_global vid_options wb_import_mesh]
    set import_mat_points [ic_get_global vid_options wb_import_mat_points]
    set import_subset [ic_get_global vid_options wb_NS_to_subset]
    set import_entity_parts [ic_get_global vid_options wb_NS_to_entity_parts]
    set import_solid [ic_get_global vid_options wb_import_solid_bodies]
    set import_surface [ic_get_global vid_options wb_import_surface_bodies]
    set import_line [ic_get_global vid_options wb_import_line_bodies]
    set import_trans [ic_get_global vid_options wb_import_cad_att_trans]
    set import_pre [ic_get_global vid_options wb_import_cad_att_pre]
    set import_proc [ic_get_global vid_options wb_import_sel_proc]
    set import_sel [ic_get_global vid_options wb_import_sel_pre]
    set import_mix [ic_get_global vid_options wb_import_mix_res]
    set import_sym [ic_get_global vid_options wb_import_en_sym_proc]
    set import_scale [ic_get_global vid_options wb_import_scale_geo]
    set import_wpoints [ic_get_global vid_options wb_import_work_points]
    set import_del_solids [ic_get_global vid_options wb_import_delete_solids]
    set import_cre_solids [ic_get_global vid_options wb_import_create_solids]
    set import_refresh_pmdb [ic_get_global vid_options wb_import_refresh_pmdb]
    set import_load_pmdb [ic_get_global vid_options wb_import_load_pmdb]
    set import_save_pmdb [ic_get_global vid_options wb_import_save_pmdb]
    set import_cad_associativity [ic_get_global vid_options wb_import_cad_associativity]
    set import_save_partfile [ic_get_global vid_options wb_import_save_partfile]
    set import_pluginname [ic_get_global vid_options wb_import_pluginname]
    set import_ns_only [ic_get_global vid_options wb_NS_only]
    set import_reference_key [ic_get_global vid_options wb_import_reference_key]
    set import_lcs [ic_get_global vid_options wb_import_lcs]
    
    set import_tritol 0.0
    if {[info exists env(AI_ENV_BETA)] && $env(AI_ENV_BETA) == "1"} {
        set import_tritol [ic_get_global vid_options wb_import_tritol]
    } else {
        foreach {n v} [ic_set_meshing_params global 0] {
            if {$n == "gttol"} { set tritol $v }
            if {$n == "gtrel"} { set tritolabs $v }	
        } 
    }
    
    if $batch_mode {
        if {[ic_get_global import_model_options always_ref_key] == "1"} {
            set import_reference_key 1
        }
        if {[ic_get_global import_model_options always_create_mpoint] == "1"} {
            set import_mat_points 1
        }
        if {[ic_get_global import_model_options named_sel_only] == "1"} {
            set import_ns_only 1
        }
    }

    if {$batch || (($import_geom == "0" || $import_geom == "") && ($import_mesh == "0" || $import_mesh == ""))} {
    
        set import_geom 0
        if {$geom} {
            set import_geom 1
        }
        set import_mesh 0
        if {$mesh} {
            set import_mesh 1
        }
        set import_mat_points 0
        set import_subset 0
        if {$subset} {
            set import_subset 1
        }
        set import_entity_parts 0
        if {$entity_parts} {
            set import_entity_parts 1
        }
        set import_solid 1
        set import_surface 1
        set import_line 0
        if {$line} {
            set import_line 1
        }
        set import_trans 1
        set import_pre {SDFEA;DDM}
        set import_proc 1 
        set import_sel ""
        set import_mix 0
        set import_sym 1
        set import_scale Default
        set import_wpoints 0
        set import_del_solids 0
        set import_cre_solids 0
        set import_cad_associativity 0
        if $refresh_pmdb {
            set import_refresh_pmdb 1
            set import_cad_associativity 1
        } else {
            set import_refresh_pmdb 0
        }
        set import_load_pmdb ""
        if {$save_pmdb != ""} {
            set import_save_pmdb $save_pmdb
        } else {
            set import_save_pmdb ""
        }
        set import_save_partfile 0
        set import_pluginname ""
        set import_ns_only 0
    }

    if $batch_mode {
        if {$ns_only} {
            set import_ns_only 1
        } else {
            set import_ns_only [ic_get_global import_model_options named_sel_only]
        }
        if {$create_material} { set import_mat_points 1 }
    }

    if $import_refresh_pmdb {
        if $import_cad_associativity {
            if [file exists $import_save_pmdb] {
                set import_load_pmdb $import_save_pmdb
            }
        } else {
            set import_load_pmdb $prt
        }
    } else {
        set import_load_pmdb ""
    }
    

    if {($import_cad_associativity == "1" && $import_refresh_pmdb == "0") && ([file extension $prt] == ".prt")} {
        ic_set_global vid_options "[file tail $prt]" wb_import_associativity_model_name
    }

    if {($import_cad_associativity == "1" && $import_refresh_pmdb == "1") && ([file extension $prt] == ".prt")} {
        set model_name [ic_get_global vid_options wb_import_associativity_model_name]
        if {($model_name != "___NA___" && $model_name != "") && ($model_name != [file tail $prt])} {
            set temp_dir [ic_temp_dir] 
            if [file isdirectory $temp_dir] {
                set temp_file "$temp_dir/$model_name"
                ic_cp "$prt" "$temp_file"
                set prt "$temp_file"
            }
        }
    }

    if [ic_wb2_is_running] {
        if !$merge {
            if [info exists old_subset] {
                unset old_subset
            }
        }
    }
    
    if {$import_geom == ""} { set import_geom 0 }
    if {$import_mesh == ""} { set import_mesh 0 }
    
    if $import_mesh {
        set tmp_mesh_file [pwd]/__tmp_wb_mesh_file[pid].uns
        set import_subset_2 0
    } else {
        set tmp_mesh_file ""
        set import_subset_2 $import_subset
    }
    
    set ext [file extension $prt]
    if {$ext == ".mechdb" || $ext == ".meshdb"} {
        if {$ext == ".mechdb"} { set ext2 .mechdat }
        if {$ext == ".meshdb"} { set ext2 .meshdat }
        set tmp_name ${prt}__[pid]__tmp__$ext2
        ic_cp $prt $tmp_name
        set tmp_infile $prt
        set prt $tmp_name
    } 
    
    # Parasolid files
    set import_mat_points2 0
    if {$ext == ".x_t" || $ext == ".xmt_txt" || $ext == ".xmt_b" || $ext == ".xmt_bin" || $ext == ".x_b"} {
        if $import_mat_points {
            set import_mat_points 0
            set import_mat_points2 1
        }
    }
    
    # currently use the workbench readers via the fieldmesher executable only on linux
    if $is_win {
        # on windows use the "old" implementation
        if {$ext == ".fmdb"} {
            # use the fieldmesher executable in case of a fieldmesher geometry file
            set use_fieldmesher_exe 1
        } else {
            set use_fieldmesher_exe 0
        }
    } elseif {$tcl_platform(os) == "Linux"} {
        # on linux use the implementation via the fieldmesher executable
        set use_fieldmesher_exe 1
    }
    if $use_fieldmesher_exe {
        set executable 1
    }

    set r ""
    set error 0

    if {!$executable && $is_win} {
        set tmp_path $env(PATH)
        # needed for ic_regression tests 
        if {[info exists env(AWP_ROOT)] && [info exists env(AWP_FRAMEWORK_PLATFORM)]} {
            if {$env(PROCESSOR_ARCHITECTURE)=="x86" && $env(AWP_FRAMEWORK_PLATFORM) != "Win32"} {
                set env(PATH) "$env(AWP_ROOT)/Framework/Bin/Win32;$env(PATH)"
            } elseif {$env(PROCESSOR_ARCHITECTURE) =="AMD64" && $env(AWP_FRAMEWORK_PLATFORM) != "Win64"} {
                set env(PATH) "$env(AWP_ROOT)/Framework/Bin/Win64;$env(PATH)"
            }
        }
        if $debug {
            mess "wb_brep_read $prt $import_subset_2 $tmp_mesh_file $import_geom $import_mesh \
                $import_solid $import_surface $import_line $import_trans $import_pre $import_proc \
                $import_sel $import_mix $import_sym $import_mat_points $import_wpoints \
                $import_refresh_pmdb \"$import_load_pmdb\" \"$import_save_pmdb\" $import_save_partfile \
                $import_entity_parts \"$import_pluginname\" $import_ns_only $import_tritol $import_reference_key $import_lcs\n"
        }
        if {$ext == ".scdoc"} {
            set Version [ic_version]
            if {$Version == ""} {
                mess "ERROR: missing version path to AnsysCadController.$Version.dll\n" red
                if [info exists tmp_path] { set env(PATH) $tmp_path }
                return 1
            }
            if {[file exists "$env(AWP_ROOT)/scdm/Addins/ANSYS $Version/AnsysCadController.$Version.dll"]} {
                set env(PATH) "$env(AWP_ROOT)/scdm/Addins/ANSYS $Version/;$env(PATH)"
            } else {
                mess "ERROR: missing AnsysCadController.$Version.dll\n" red
                if [info exists tmp_path] { set env(PATH) $tmp_path }
                return 1
            }
        }
        if [ic_wb2_is_running] {
            ic_set_global wb2_icemcfd_running 1
        }
        if !$batch_mode { busy 1 }
        if [catch {wb_brep_read $prt $import_subset_2 $tmp_mesh_file $import_geom $import_mesh \
            $import_solid $import_surface $import_line $import_trans $import_pre $import_proc \
            $import_sel $import_mix $import_sym $import_mat_points $import_wpoints \
            $import_refresh_pmdb $import_load_pmdb $import_save_pmdb $import_save_partfile \
            $import_entity_parts $import_pluginname $import_ns_only $import_tritol $import_reference_key $import_lcs} res] {
            regsub -all \{ $res "" res; regsub -all \} $res "" res
            mess "ERROR:\n $res\n" red
            set error 1
        }
        if !$batch_mode { busy 0 }
	    if [ic_wb2_is_running] {
	        ic_unset_global wb2_icemcfd_running
	    }
        if {$res != "" && $error != "1"} {
            # warning message, no error
            mess "$res\n" blue
            set res ""
        }
        set env(PATH) $tmp_path
        if [info exists tmp_name] { ic_rm $tmp_name }
        if [info exists tmp_file] { ic_rm $tmp_file }
        if $error { return 1 }
    } else {
        #
        #  On Linux and for the FM prototype, we should start the
        #  FMWorkBenchReadersExecutable(.exe) with a Params_ICEMCFD.xml
        #  file and then load the tetin and/or the mesh file.
        #
        if ![info exists env(AWP_ROOT)] {
            set env(AWP_ROOT) $env(ICEM_ACN)/../..
            mess "Setting environment variable AWP_ROOT to $env(ICEM_ACN)\n" 
        }
        if $is_win {
            set env(AWP_ROOT) [win_shortname $env(AWP_ROOT)]
        }

        if $is_win {
           set platform ""
            if {$env(PROCESSOR_ARCHITECTURE)=="x86"} {
                set platform intel
                set ansys_sysdir intel
                set framework_sysdir Win32
                set python_sysdir win32
            } elseif {$env(PROCESSOR_ARCHITECTURE) =="AMD64"} {
                set platform winx64
                set ansys_sysdir winx64
                set framework_sysdir Win64
                set python_sysdir winx64
            } else {
                mess "ERROR: environment variable PROCESSOR_ARCHITECTURE should contain either \"x86\" or \"AMD64\"\n" red
                if [info exists tmp_name] {  ic_rm $tmp_name }
                return 1
            }
        } elseif {$tcl_platform(os) == "Linux"} {
            set rr [exec uname -a]
            if {[lsearch $rr "ia64"] >= 0} {
                set platform "linx64"
            } elseif {[lsearch $rr "x86_64"] >= 0} {
                set platform "linx64"
                set ansys_sysdir linx64
                set framework_sysdir Linux64
                set python_sysdir linx64
            } else {
                set platform "linia32"
                set ansys_sysdir linia32
                set framework_sysdir Linux32
                set python_sysdir lin32
            }
        } else {
            mess "Operating system $tcl_platform(os) not supported\n" red
            if [info exists tmp_name] {  ic_rm $tmp_name }
            return 1
        }

        set python_exe "no_exe"
        if $use_fieldmesher_exe {
            set orig_path $env(PATH)
            # python settings
            set python_version "2_7_13"
            set cpython_path "$env(AWP_ROOT)/commonfiles/CPython/$python_version"
            set python_configuration ""
            if $debug {
                set python_configuration "Debug"
                if {[file exists "$cpython_path/$python_sysdir/$python_configuration/python"] && [file exists "$cpython_path/$python_sysdir/$python_configuration/Ansys"]} {
                    set python_exe "python_d"
                } else {
                    set python_configuration "Release"
                    if {[file exists "$cpython_path/$python_sysdir/$python_configuration/python"] && [file exists "$cpython_path/$python_sysdir/$python_configuration/Ansys"]} {
                        set python_exe "python"
                    }
                }
            }
            if {$python_exe == "no_exe"} {
                set python_configuration "Release"
                if {[file exists "$cpython_path/$python_sysdir/$python_configuration/python"] && [file exists "$cpython_path/$python_sysdir/$python_configuration/Ansys"]} {
                    set python_exe "python"
                } else {
                    set python_configuration "Debug"
                    if {[file exists "$cpython_path/$python_sysdir/$python_configuration/python"] && [file exists "$cpython_path/$python_sysdir/$python_configuration/Ansys"]} {
                        set python_exe "python_d"
                    }
                }
            }
            if {$python_exe != "no_exe"} {
                set default_python_path "$cpython_path/$python_sysdir/$python_configuration"
            } else {
                set default_python_path "not_set"
            }
            if $debug { mess "DEBUG: default python path: $default_python_path\n" }
            
            if $is_win {
                set python_path "not_set"
                if [info exists env(PYTHONPATH)] {
                    set python_path $env(PYTHONPATH)
                    if $debug { mess "DEBUG: python path set by environment variable PYTHONPATH: $python_path\n" }
                }
                if {$python_path == "not_set" || ![file exists "$python_path"]} {
                    if {$default_python_path != "no_set"} {
                        set python_path "$default_python_path"
                        set env(PYTHONPATH) "$python_path"
                        if $debug { mess "DEBUG: Setting environment PYTHONPATH variable to $python_path\n" }
                    }
                }
                set python_home "not_set"
                if [info exists env(PYTHONHOME)] {
                    set python_home $env(PYTHONHOME)
                }
                if {$python_home == "not_set" || ![file exists "$python_home"]} {
                    if {$default_python_path != "no_set"} {
                        set python_home "$default_python_path/python"
                        set env(PYTHONHOME) "$python_home"
                        if $debug { mess "DEBUG: Setting environment PYTHONHOME variable to $python_home\n" }
                    }
                }
                if {[file exists "$python_home"]} {
                    set env(PATH) "$env(PYTHONHOME);$env(AWP_ROOT)/Framework/bin/$framework_sysdir;$env(PATH)"
                    if $debug { mess "DEBUG: Adding $env(AWP_ROOT)/Framework/bin/$framework_sysdir to PATH environment variable\n" }
                } else {
                    mess "ERROR: PYTHONHOME=$python_home does not exist!\n" red
                }

            } elseif {$tcl_platform(os) == "Linux"} {
                set python_path "not_set"
                if [info exists env(PYTHONPATH)] {
                    set python_path $env(PYTHONPATH)
                    if $debug { mess "DEBUG: python path set by environment variable PYTHONPATH: $python_path\n" }
                }
                if {$python_path == "not_set" || ![file exists "$python_path"]} {
                    if {$default_python_path != "no_set"} {
                        set python_path "$default_python_path"
                        set env(PYTHONPATH) "$python_path"
                        if $debug { mess "DEBUG: Setting environment PYTHONPATH variable to $python_path\n" }
                    }
                }

                if {[file exists "$python_path"]} {
                    set env(PATH) "$env(PYTHONPATH)/python/bin/:$env(PATH)"
                    if $debug { mess "DEBUG: Adding $env(PYTHONPATH)/python/bin/ to PATH environment variable\n" }

                    set orig_ld_lib_path $env(LD_LIBRARY_PATH)
                    set env(LD_LIBRARY_PATH) "$env(PYTHONPATH)/python/lib:$env(PYTHONPATH)/sip/lib:$env(PYTHONPATH)/openssl/lib:$env(AWP_ROOT)/Framework/bin/$framework_sysdir:$env(LD_LIBRARY_PATH)"
                    if $debug { mess "DEBUG: Adding $env(PYTHONPATH)/python/lib:$env(PYTHONPATH)/sip/lib:$env(PYTHONPATH)/openssl/lib:$env(AWP_ROOT)/Framework/bin/$framework_sysdir to LD_LIBRARY_PATH environment variable\n" }
                } else {
                    mess "ERROR: PYTHONPATH=$python_path does not exist!\n" red
                }

                # this is needed only for python 2.7
                #  set env(LD_PRELOAD)"$env(PYTHONPATH)/python/lib/libpython2.7.so" 
            }

            # choose python script
            if {$custom_python_file == ""} {
                set python_template "$env(PYTHONPATH)/Ansys/ICEMCFD/FieldMesherController.py"
            } else {
                set python_template $custom_python_file
            }
        }

        # write the parameter file
        set fm_readers_file [pwd]/Params_ICEMCFD_[pid].xml
        if $debug {
            mess "ic_wb_write_params_xml_file $fm_readers_file $prt $import_subset_2 $tmp_mesh_file \
                $import_geom $import_mesh $import_solid $import_surface $import_line $import_trans \
                $import_pre $import_proc $import_sel $import_mix $import_sym $import_mat_points $import_wpoints \
                $import_refresh_pmdb $import_load_pmdb $import_save_pmdb $import_save_partfile $import_entity_parts \
                $import_pluginname $import_ns_only $import_tritol $import_reference_key $import_lcs\n"
        }
        set tmp_geom_file [ic_wb_write_params_xml_file $fm_readers_file $prt $import_subset_2 $tmp_mesh_file \
            $import_geom $import_mesh $import_solid $import_surface $import_line $import_trans \
            $import_pre $import_proc $import_sel $import_mix $import_sym $import_mat_points $import_wpoints \
            $import_refresh_pmdb $import_load_pmdb $import_save_pmdb $import_save_partfile $import_entity_parts \
            $import_pluginname $import_ns_only $import_tritol $import_reference_key $import_lcs]
        if ![file exists $fm_readers_file] {
            mess "ERROR: unable to write params file $fm_readers_file\n" red
            if [info exists tmp_name] {  ic_rm $tmp_name }
            return 1
        }
        
        set error 0
        if $use_fieldmesher_exe {
            # run executable
            set env(ANSYS_ICEMCFD_FIELDMESHER_XMLFILE) $fm_readers_file
            if $is_win {
                set fieldmesher_exe "$env(PYTHONHOME)/$python_exe.exe"
                # check the installation
                if ![file exists $fieldmesher_exe] {
                    mess "ERROR: $fieldmesher_exe not available. Please check your ANSYS Workbench installation.\n" red
                    set error 1
                } else {
                    regsub -all \\\\ $python_template / python_template
                    regsub -all \\\\ $fieldmesher_exe / fieldmesher_exe
                    if [catch {ic_run_application_exec . "" "$fieldmesher_exe" "\"$python_template\" > nul: 2>&1"} res] {
                        mess "ERROR FieldMesher application failed: $res\n" red
                        set error 1
                    }
                }
                set env(PATH) $orig_path
            } else {
                set fieldmesher_exe "$env(AWP_ROOT)/aisol/CommonFiles/$ansys_sysdir/ansys.meshing.fieldmesher.exe"
                # check the installation
                if ![file exists $fieldmesher_exe] {
                    mess "ERROR: $fieldmesher_exe not available. Please check your ANSYS Workbench installation.\n" red
                    set error 1
                } else {
                    if [catch {ic_run_application_exec . "" "$env(AWP_ROOT)/aisol/.workbench" "-cmd $fieldmesher_exe -B $python_template >& /dev/null"} res] {
                        mess "ERROR FieldMesher application failed: $res\n" red
                        set error 1
                    }
                }
                set env(PATH) $orig_path
                set env(LD_LIBRARY_PATH) $orig_ld_lib_path
            }
            if $error { return 1 }
            
            ic_rm $fm_readers_file
            if {$import_geom  && ![ic_geo_is_loaded]} {
                 if ![file exists $tmp_geom_file] {
                    mess "ERROR: Import geometry failed\n" red
                    set error 1
                }
                if [catch {ic_load_tetin [list $tmp_geom_file]} res] {
                    mess "ERROR: $res\n" red
                    set error 1
                } else {
                    ic_rm $tmp_geom_file
                }
                if [info exists tmp_name] { ic_rm $tmp_name }
            }
            if $error { return 1 }
        } else {
            set fm_readers_exe ansys.meshing.icworkbenchreaders.exe
            if $is_win {
                set fm_readers_bin $env(AWP_ROOT)/Aisol/bin/$platform
            } else {
                set fm_readers_bin $env(AWP_ROOT)/aisol/CommonFiles/$platform
            }
            regsub -all \\\\ $fm_readers_bin / fm_readers_bin
            if ![file exists $fm_readers_bin/$fm_readers_exe] {
                mess "ERROR: missing executable $fm_readers_bin/$fm_readers_exe\n" red
                if [info exists tmp_name] { ic_rm $tmp_name }
                set error 1
            }
            if $error { return 1 }
            
            mess "Running..."
            if !$batch_mode { busy 1 }
            if $is_win {  
                set win_path $env(PATH)
                set env(PATH) $env(PATH)\;$fm_readers_bin
                if [catch {ic_run_application_exec . "" "$fm_readers_bin/$fm_readers_exe" "\"$fm_readers_file\" > nul: 2>&1"} res] {
                    mess "ERROR FieldMesher application failed: $res\n" red
                    set error 1
                }
                set env(PATH) $win_path
            } else {
                set vg "valgrind -v --tool=memcheck --error-limit=no --show-reachable=yes --max-stackframe=1936901630"
                set vg ""
                if [catch {ic_run_application_exec . "" "$env(AWP_ROOT)/aisol/.workbench" "-cmd $vg $fm_readers_bin/$fm_readers_exe -B $fm_readers_file >& /dev/null"} res] {
                    mess "ERROR FieldMesher application failed: $res\n" red
                    set error 1
                }
            }
            if !$batch_mode { busy 0 }
            if [info exists tmp_name] { ic_rm $tmp_name }
            if $error { return 1 }
            
            ic_rm $fm_readers_file
            if {$import_geom  && ![ic_geo_is_loaded]} {
                if ![file exists $tmp_geom_file] {
                    mess "ERROR: Import geometry failed\n" red
                    set error 1
                }
                if [catch {ic_load_tetin [list $tmp_geom_file]} res] {
                    mess "ERROR: $res\n" red
                    set error 1
                } else {
                    ic_rm $tmp_geom_file
                }
            }
            if $error { return 1 }
        }
    }

    if $import_geom {
        if [array exists mpoints] {
            foreach p [array names mpoints] {
                 if {[ic_geo_check_objects_exist point $p] == ""} {
                     ic_geo_cre_pnt [lindex $mpoints($p) 0] $p [lindex $mpoints($p) 1]
                 }
            }
        }
        if $import_mat_points2 {
            ic_geo_build_material_from_solids "" 1 0
        }
        define_geom_objects        
    }
    if $import_mesh {
        if $is_win {
            set tmp_mesh_file_load [win_shortname $tmp_mesh_file]
        } else {
            set tmp_mesh_file_load $tmp_mesh_file
        }
        if ![file exists $tmp_mesh_file_load] {
            set use_fieldmesher_exe 0
            mess "ERROR: Import mesh failed\n" red
        } else {
            ic_uns_load_one_domain $tmp_mesh_file_load 3 1 {} 2
            ic_rm $tmp_mesh_file
        }
    }
    update_fam_window
    
    if $import_geom {
        # old import scale values
        switch $import_scale {
            0 { set import_scale Default }
            1 { set import_scale meters }
            2 { set import_scale inches }
            3 { set import_scale centimeters }
            4 { set import_scale feet }
            5 { set import_scale millimeters }
        }
        if {($batch_mode && [ic_get_global import_model_options always_convert] == "1") || \
            (!$batch_mode && [ic_get_global vid_options wb_import_from_gui] != "1" && [ic_get_global import_model_options always_convert] == "1")} {
            set import_scale [ic_get_global import_model_options convert_to]
        }
        if {$import_scale != "Default" && $import_scale != ""} {
            set units [ic_geo_get_units 1]
            set scale 1
            if {$units != ""} {
                set scale [ic_geo_convert_units $units $import_scale]
            }
            set unit [string tolower $import_scale]
            if {$scale != 1 && $unit != "Default"} {
                mess "Converting geometry from \"$units\" to \"$unit\"\n"
                foreach type "point curve surface material density" {
                    set objs [ic_geo_get_objects $type]
                    if {$objs != ""} {
                        if ![info exists do_not_scale($type)] {
                            ic_move_geometry $type names "$objs" scale "$scale $scale $scale" cent "0 0 0" detach 0
                        } else {
                            foreach obj $objs {
                                if {[lsearch $do_not_scale($type) $obj] < 0} {
                                    ic_move_geometry $type names "$obj" scale "$scale $scale $scale" cent "0 0 0" detach 0
                                }
                            } 
                        }
                    }
                }
                ic_geo_set_units $unit
                if !$batch_mode { ic_set_global units_message [ic_geo_get_units 1] }
                ic_geo_reset_data_structures
                if {$import_mesh && [ic_uns_is_loaded] && [ic_uns_non_empty_families] != ""} {
                    mess "Converting mesh from \"$units\" to \"$unit\"\n"
                    ic_uns_move_elements all scale "$scale $scale $scale" cent "0 0 0"
                }
            } else {
                if {$unit != ""} {
                    ic_geo_set_units $unit
                    if !$batch_mode { ic_set_global units_message [ic_geo_get_units 1] }
                    if {$scale == "1"} {
                        mess "Geometry is already \"$unit\"; no need to convert\n"
                    }
                    ic_geo_reset_data_structures
                }
            }
        }
    }

    if $import_geom {
        # Convert NEW Subsets into parts
        if !$import_subset {
            foreach subset [ic_geo_subset_list] {
                if [info exists old_subset($subset)] continue
                set fam [get_valid_name $subset]
                ic_geo_new_family $fam
                foreach {type name} [ic_geo_subset_get_items $subset] {
                    ic_geo_set_family $type $fam names $name
                }
                ic_geo_subset_delete $subset
            }
        }
        if {![info exists env(AI_ENV_BETA)] || $env(AI_ENV_BETA) != "1"} {
            if [info exists tritol] {
                ic_set_meshing_params global 0 gttol $tritol
            }
            if [info exists tritolabs] {
                ic_set_meshing_params global 0 gtrel $tritolabs
            }
        }
        ic_delete_empty_parts
        if {!$batch_mode && [ic_geo_get_units 1] != ""} { ic_set_global units_message [ic_geo_get_units 1] }
    }
    if [info exists tmp_name] { ic_rm $tmp_name }
    if {$import_geom && [ic_wb2_input_parameter_mode]} {
        ic_wb2_update_parameters input
    }
    return $r
}

proc ic_read_geometry {prt {merge 0} {subset 0}} {
    return [ic_wb_brep_read "$prt" 1 $merge 0 $subset 1 0 1 0 "" 0 0 0 1]
}

## Import a workbench model
##
## Returns 1 if build topology is required as a postprocessing
## step.  Returns 0 otherwise.
## 
proc ic_wb_brep_load {{load_file ""} {module_name ""} {doUpdate 0} {assemId 0xFFFFFFFF}} {
    global is_win env
    ic_empty_tetin
    ##
    if { $module_name != "" } {
        # Hack to fix brackets in name problem
        regsub "___LB___" $module_name "\[" module_name
        regsub "___RB___" $module_name "\]" module_name
    }

    if [catch {wb_brep_load $load_file $doUpdate $assemId $module_name} r] {
        mess "Error: $r\n" red
    }
    ##
    define_geom_objects
    update_fam_window  
    return $r
}

proc ic_wb_write_params_xml_file {file prt import_subset_2 tmp_mesh_file import_geom import_mesh import_solid import_surface \
    import_line import_trans import_pre import_proc import_sel import_mix import_sym import_mat_points import_wpoints \
    import_refresh_pmdb import_load_pmdb import_save_pmdb import_save_partfile import_entity_parts import_pluginname \
    import_ns_only import_tritol import_reference_key import_lcs} {
    
    global env is_win
    
    set f [open $file w]
    puts $f "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>"
    puts $f "<WorkBenchReaders>"
    puts $f " <RunICPartMgr>"
    if $import_geom {
        puts $f "  <ReadGeometry>true</ReadGeometry>"
    } else {
        puts $f "  <ReadGeometry>false</ReadGeometry>"
    }
    if $import_mesh {
        puts $f "  <ReadMesh>true</ReadMesh>"
    } else {
        puts $f "  <ReadMesh>false</ReadMesh>"
    }
    if $import_subset_2 {
        puts $f "  <UseSubsets>true</UseSubsets>"
    } else {
        puts $f "  <UseSubsets>false</UseSubsets>"
    }
    if $import_entity_parts {
        puts $f "  <CreateEntityPartNames>true</CreateEntityPartNames>"
    } else {
        puts $f "  <CreateEntityPartNames>false</CreateEntityPartNames>"
    }
    if 0 {
        #puts $f "  <PrefixWorkPointNameByPartName>true</PrefixWorkPointNameByPartName>"
    } else {
        #puts $f "  <PrefixWorkPointNameByPartName>false</PrefixWorkPointNameByPartName>"
    }
    if {$import_refresh_pmdb && $import_load_pmdb != ""} {
        puts $f "   <RefreshGeometry>true</RefreshGeometry>"
        puts $f "   <LoadFromReferencePMDBFilename>$import_load_pmdb</LoadFromReferencePMDBFilename>"
    } else {
        puts $f "   <RefreshGeometry>false</RefreshGeometry>"
    }
    if {$import_save_pmdb != ""} {
        puts $f "   <SaveToReferencePMDBFilename>$import_save_pmdb</SaveToReferencePMDBFilename>"
    }
    if $import_save_partfile {
        puts $f "   <ReaderSaveFile>true</ReaderSaveFile>"
    } else {
        puts $f "   <ReaderSaveFile>false</ReaderSaveFile>"
    }
    if $import_mat_points {
        puts $f "  <CreateMaterialPoints>true</CreateMaterialPoints>"
    } else {
        puts $f "  <CreateMaterialPoints>false</CreateMaterialPoints>"
    }
    if $import_ns_only {
        puts $f "   <OnlyNamedSelections>true</OnlyNamedSelections>"
    } else {
        puts $f "   <OnlyNamedSelections>false</OnlyNamedSelections>"
    }
    if $import_reference_key {
        puts $f "   <DeriveNameFromRefKey>true</DeriveNameFromRefKey>"
    } else {
        puts $f "   <DeriveNameFromRefKey>false</DeriveNameFromRefKey>"
    }
    if $import_lcs {
        puts $f "   <ImportLCS>true</ImportLCS>"
    } else {
        puts $f "   <ImportLCS>false</ImportLCS>"
    }
    puts $f "  <GeometryImportParams>"
    if $is_win {
        puts $f "   <Filename>$prt</Filename>"
    } else {
        puts $f "   <Filename>[encoding convertto utf-8 $prt]</Filename>"
    }
    if $import_solid {
        puts $f "   <ImportSolids>true</ImportSolids>"
    } else {
        puts $f "   <ImportSolids>false</ImportSolids>"
    }
    if $import_surface {
        puts $f "   <ImportSheets>true</ImportSheets>"
    } else {
        puts $f "   <ImportSheets>false</ImportSheets>"
    }
    if $import_line {
        puts $f "   <ImportWires>true</ImportWires>"
    } else {
        puts $f "   <ImportWires>false</ImportWires>"
    }
    if $import_wpoints {
        puts $f "   <ImportWorkPoints>true</ImportWorkPoints>"
    } else {
        puts $f "   <ImportWorkPoints>false</ImportWorkPoints>"
    }
    if $import_sym {
        puts $f "   <DoEnclosureAndSymmetryProcessing>true</DoEnclosureAndSymmetryProcessing>"
    } else {
        puts $f "   <DoEnclosureAndSymmetryProcessing>false</DoEnclosureAndSymmetryProcessing>"
    }
    if $import_trans {
        puts $f "   <TransferAttributes>true</TransferAttributes>"
    } else {
        puts $f "   <TransferAttributes>false</TransferAttributes>"
    }
    if $import_proc {
        puts $f "   <TransferNamedSelections>true</TransferNamedSelections>"
    } else {
        puts $f "   <TransferNamedSelections>false</TransferNamedSelections>"
    }
    puts $f "   <AttributePrefixes>$import_pre</AttributePrefixes>"
    puts $f "   <NamedSelectionPrefixes>$import_sel</NamedSelectionPrefixes>"
    # Values for MixedImportResolutionType are: 
    # None, All, Solid, Sheet, Wire, Point, SolidAndSheet, SolidAndWire, 
    # SolidAndPoint, SheetAndWire, SheetAndPoint, WireAndPoint
    # SheetAndWireAndPoint, SolidAndWireAndPoint, SolidAndSheetAndPoint
    # SolidAndSheetAndWire
    if {$import_mix == 1} {
        puts $f "   <MixedImportResolutionType>Solid</MixedImportResolutionType>"
    } elseif {$import_mix == 2} {
        puts $f "   <MixedImportResolutionType>Sheet</MixedImportResolutionType>"
    } elseif {$import_mix == 3} {
        puts $f "   <MixedImportResolutionType>Wire</MixedImportResolutionType>"
    } elseif {$import_mix == 4} {
        puts $f "   <MixedImportResolutionType>Point</MixedImportResolutionType>"
    } elseif {$import_mix == 5} {
        puts $f "   <MixedImportResolutionType>SolidAndSheet</MixedImportResolutionType>"
    } elseif {$import_mix == 6} {
        puts $f "   <MixedImportResolutionType>SolidAndWire</MixedImportResolutionType>"
    } elseif {$import_mix == 7} {
        puts $f "   <MixedImportResolutionType>SolidAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 8} {
        puts $f "   <MixedImportResolutionType>SheetAndWire</MixedImportResolutionType>"
    } elseif {$import_mix == 9} {
        puts $f "   <MixedImportResolutionType>SheetAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 10} {
        puts $f "   <MixedImportResolutionType>WireAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 11} {
        puts $f "   <MixedImportResolutionType>SheetAndWireAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 12} {
        puts $f "   <MixedImportResolutionType>SolidAndWireAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 13} {
        puts $f "   <MixedImportResolutionType>SolidAndSheetAndPoint</MixedImportResolutionType>"
    } elseif {$import_mix == 14} {
        puts $f "   <MixedImportResolutionType>SolidAndSheetAndWire</MixedImportResolutionType>"
    } elseif {$import_mix == 15} {
        puts $f "   <MixedImportResolutionType>All</MixedImportResolutionType>"
    } else {
        puts $f "   <MixedImportResolutionType>None</MixedImportResolutionType>"
    }
    if {$import_pluginname != ""} {
        puts $f "   <PlugInName>$import_pluginname</PlugInName>"
    }
    if {$import_tritol != 0.0} {
        puts $f "   <TriangulationTolerance>$import_tritol</TriangulationTolerance>"
    }
    puts $f "  </GeometryImportParams>"
    puts $f "  <GeometryExportParams>"
    if $import_geom {
        set tmp_geom_file [pwd]/__tmp_wb_geom_file[pid].tin
    } else {
        set tmp_geom_file ""
    }
    puts $f "   <Filename>$tmp_geom_file</Filename>"
    puts $f "  </GeometryExportParams>"
    puts $f "  <MeshExportParams>"
    puts $f "   <Filename>$tmp_mesh_file</Filename>"
    puts $f "  </MeshExportParams>"
    puts $f " </RunICPartMgr>"
    puts $f "</WorkBenchReaders>"
    close $f
    return $tmp_geom_file
}

## Attach to a workbench model
##
proc ic_wb_brep_attach {{load_file ""}} {
    if [catch {wb_brep_attach $load_file} r] {
        mess "Error: $r\n" red
    }
    return 1
}

## Save the coordinate system to CFX Command Language (CCL) file

proc ic_trans_cos_ccl {file} {
    global projlib whoami
    if {$projlib == ""} {
	    user_error "No geometry data is available for CCL"
        return
    }
    if [catch {$projlib save_cclfile $file $whoami} ] {
        return
    }
    mess "Saved CCL data to $file\n"
}

proc ic_wb_contains_blocking {file} {
    global env is_win

    if !$is_win { return 0 }
    if ![file exists "$file"] { return 0 }
    
    if ![info exists env(AWP_ROOT)] {
        set env(AWP_ROOT) $env(ICEM_ACN)/../..
        mess "Setting environment variable AWP_ROOT to $env(ICEM_ACN)\n" 
    }   
    set found_geom 0; set found_block 0
    if [file exists $env(AWP_ROOT)/installer/util/7zip/7z.exe] {
        set zip [win_shortname $env(AWP_ROOT)/installer/util/7zip/7z.exe]
        set files [exec $zip l $file]"
        regsub -all \\\\ $files / files
        foreach line $files {
            if [string match "SpaceClaim/Blockings/*.tin" $line] {
                set found_geom 1 
            }
            if [string match "SpaceClaim/Blockings/*.blk" $line] {
                set found_block 1
            }
        }
    } else {
        return 0
    }
    if {$found_geom && $found_block} {
        return 1
    } else {
        return 0
    }
}
set dont_record_command(ic_wb_contains_blocking) 1

proc ic_wb_import_blockings {file} {
    global env batch_mode
    
    catch { unset import(geom); unset import(blocking); unset import(unstruct) }
    if ![info exists env(AWP_ROOT)] {
        set env(AWP_ROOT) $env(ICEM_ACN)/../..
        mess "Setting environment variable AWP_ROOT to $env(ICEM_ACN)\n" 
    }
    if [file exists $env(AWP_ROOT)/installer/util/7zip/7z.exe] {
        set zip [win_shortname $env(AWP_ROOT)/installer/util/7zip/7z.exe]
        set files [exec $zip l $file]
        regsub -all \\\\ $files / files
        foreach line $files {
            if [string match "SpaceClaim/Blockings/*.tin" $line] {
                lappend import(geom) "$line"
            }
            if [string match "SpaceClaim/Blockings/*.blk" $line] {
                lappend import(blocking) "$line"
            }
            if [string match "SpaceClaim/Blockings/*.uns" $line] {
                lappend import(unstruct) "$line"
            }
       } 
    } else {
        mess "Error: missing executable $env(AWP_ROOT)/installer/util/7zip/7z.exe\n" red
        return
    }
    
    if {![info exists import(geom)] || ![info exists import(blocking)]} {
        mess "Error: file $file does not contain any blockings\n" red
        return
    }

    if [ic_geo_is_loaded] ic_unload_tetin
    if [ic_hex_blocking_loaded] ic_hex_unload_blocking
    if [ic_uns_is_loaded] { ic_unload_mesh 1 }

    set here [pwd]
    cd [ic_temp_dir]
    set temp_dir "__icem__space__claim__files__[pid]"
    if ![file exists $temp_dir] {
        ic_mkdir $temp_dir
    }
    cd $temp_dir
    set len [llength $import(geom)]
    mess "Importing blockings from $file\n" blue
    for {set i 0} {$i < $len} {incr i} {
        set tin [lindex $import(geom) $i]
        if {$tin == ""} continue
        exec $zip x -y $file $tin
        regsub -all \\\\ $tin / tin
        ic_load_tetin $tin 0 1 0 1
        ic_rm $tin
        set block [lindex $import(blocking) $i]
        if {$block == ""} continue
        exec $zip x -y $file $block
        regsub -all \\\\ $block / block
        if {$i == "0"} {
            ic_hex_restore_blocking $block 
            ic_hex_switch_blocking root
        } else {
            ic_hex_restore_blocking $block root[expr $i + 1]
            ic_hex_switch_blocking root[expr $i + 1]
        }
        if ![info exists import(unstruct)] continue
        set uns [lindex $import(unstruct) $i]
        if {$uns == ""} continue
        exec $zip x -y $file $uns
        regsub -all \\\\ $uns / uns
        ic_hex_read_blocking_mesh $uns
        set fams [string trimright [ic_hex_list_block_families_without] \n]
        set dim [format %g [ic_hex_dim_to_mesh]]
        set proj 2
        set hex hex$i.uns
        eval ic_hex_write_file $hex $fams proj $proj dim_to_mesh $dim no_boco
        ic_uns_load $hex 3 1 {} 1
        # pre-mesh should be up-to-date
        ic_hex_set_out_of_date 0
        # pre-mesh dim_to_project should be set to proj
        ic_hex_set_dim_to_project $proj
        ic_rm $hex
    }
    catch { unset import(geom); unset import(blocking); unset import(unstruct) }
    cd ..
    ic_rm $temp_dir
    cd "$here"
}
