
# Copyright (c) 1997 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com
# Note: these functions are also used for mesh import

proc geo_import_plot3d {infiles outfiles {only_trias 1} {s2u 0} {skip 0}} {
    global env file_name
    global mess_frame

    set formatted 1
    set double 0
    set planes 0
    set iblank 0
    set oneblock 0
    set swap 0
    set guess_flag 1
    set s2u2 1
    set toler 0.0
    set dim2d 0
        
    set params {
	{guess_flag -opt {{"User Input" 0} {"Take a guess" 1}} \
	    -title "Describe Plot3D File Content" -help ""}
	{formatted -opt {{Formatted 1} {Unformatted 0} {Binary 2} {Windows_Unformatted 3}} \
	     -title "Input type" -active {!$guess_flag} -help ""}
	{dim2d -opt {{3D 0} {2D 1}} -title "Dimension" -active {!$guess_flag} -help ""}
	{oneblock -opt {{Single 1} {Multiple 0}} -title "Number of blocks" -active {!$guess_flag} -help ""}
	{double -opt {{Single 0} {Double 1}} -title Precision -active {!$guess_flag} -help ""}
	{planes -opt {{"In planes" 1} {\"Whole\" 0}} -title "Data layout" -active {!$guess_flag} -help ""}
	{iblank -opt {{Yes 1} {No 0}} -title "Include IBLANK array" -active {!$guess_flag} -help ""}
	{swap -opt {{Yes 1} {No 0}} -title "Swap byte order" -active {!$guess_flag} -help ""}
    }
    if !$s2u { lappend params {s2u2 -opt {{Yes 1} {No 0}} -title "Convert to unstruct" -help ""}}
    if $only_trias {
	lappend params {toler -type string -title "tolerance value" \
			-help "Enter tolerance value for node & interface merging"}
    }

    if {!$skip && ![dialog .plot3d "Plot3d import" "Please edit the following plot3d options." $params]} {
	    return ""
    }

    set files ""
    foreach infile $infiles outfile $outfiles {
	    set command ""
	    if $guess_flag { 
	        set command "$command -guess"
	    } else {
            case $formatted in {
                1 { }
                0 { set command "$command -u" }
                2 { set command "$command -bin" }
                3 { set command "$command -u_win" }
            }
	        if $planes { append command " -p" }
	        if $iblank { append command " -i" }
	        if $double { append command " -double" }
	        if $oneblock { append command " -oneblock" }
	        if $swap { append command " -swap" }
	    }
	    if $dim2d {
		    set command "$command -dim2d"
	    }
	    if $only_trias {
            append command " -trias -t \"$outfile\" -tol $toler"    
        } else {
	        set outfile $file_name(domains_dir)/domain
	        append command " -dom -d \"$outfile\""
	        if ![file exists $file_name(domains_dir)] {
		        ic_mkdir $file_name(domains_dir)
	        }
	    }
	    set now [$mess_frame.text index "end -1c"]
        ic_run_application_exec . icemcfd/output-interfaces pl3d2domain "$command \"$infile\""
	    if $only_trias {
	        lappend files $outfile
	    } else {
	        for {set i 1} {[file exists $outfile.$i]} {incr i} {
		        lappend files $outfile.$i
	        }
	    }
    }
    
    if {$files == ""} { return "" }
    if $only_trias {
        if {[llength "$files"] == 1 && [file extension $files] == ".uns"} {
            ic_uns_load $files 3 1
            if {[ic_count_nodes] != 0} { 
                ic_unload_mesh 1
                return [list 1 $files]
            } else {
                mess "Error: found 0 nodes after import, trying a second time\n" red
                return [list 3 $files]
            }
        }
    }

    set tmpdomains $file_name(domains_dir)/domain
    if {$s2u || $s2u2} {
       # this options runs struct->unstruct and loads the unstruct domain
       set auto_topo 0
       ic_str_load $tmpdomains {} {} {} "" $auto_topo
       if [winfo exists .comptopo] { top_destroy .comptopo }
       set topofile $file_name(domains_dir)/topo_mulcad_out.tmp
       lappend tmpfiles $topofile
       set familytopo $file_name(domains_dir)/family_topo.tmp
       set familyboco $file_name(domains_dir)/family_boco.tmp
       set subface_proj $file_name(domains_dir)/subface_proj.tmp
       lappend tmpfiles $familytopo $familyboco $subface_proj
    } else {
       ic_load_struct $tmpdomains "" "" ""
       set topofile $file_name(domains_dir)/topo_mulcad_out.top
       set familytopo $file_name(domains_dir)/family_topo.fto
       set familyboco $file_name(domains_dir)/family_boco
       set subface_proj $file_name(domains_dir)/subface_proj
    }

    if !$guess_flag {
        if {[$mess_frame.text search "THAT IS NOT GOOD" $now end] != ""} {
            set mess "The mesh seems to be corrupt.\nUse the \"Take a guess\" option to create a valid mesh"
            tk_messageBox -title "Error" -message $mess -icon error
            ic_unload_mesh 1
            return ""
        }
    }
    ic_str_topo_make_surfs domain 0
    ic_str_save $file_name(domains_dir) $topofile $familytopo $subface_proj
    ic_boco_save $familyboco

    if {$s2u || $s2u2} {
       set unsfile $file_name(domains_dir)/tmpdomain.uns
       set domain_list ""
       for {set i 1} {[file exists $tmpdomains.$i]} {incr i} {
           lappend tmpfiles $tmpdomains.$i
           append domain_list "$i "
       }
       set options "-new" ;#-tria
       ic_convert_struct_to_unstruct $file_name(domains_dir) $domain_list $topofile $familytopo $familyboco $unsfile $options
       ic_unload_mesh 1
       display_update
       foreach f $tmpfiles { cmd_rm $f }
       return [list 1 $unsfile]

    }
    initialize_struct_visibility
    return [list 2 $files]
}

proc geo_import_plot3d_trias {pl3dfile} {
    set tmpdom [cmd_tempfile tmpdomain .uns]
    geo_import_plot3d $pl3dfile $tmpdom 1
    if [file exists $tmpdom] {
	geo_import domain $tmpdom
    } else { mess "could not get triangle from Plot3d file\n" red }
}

proc geo_import_patran {infiles outfiles {only_tris 1}} {
    global env
    
    set params {
	{one_fam -opt {{"Multiple" 0} {"Single" 1}} \
	     -title "Transfer family information"}
    }
    if {![dialog .patran "Patran import" \
	      "Please edit the following patran options." $params]} {
	return ""
    }
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	set cmd "\"$infile\" \"$outfile\""
	if $only_tris { append cmd " -only_tris" }
	if $one_fam { append cmd " -one_family" }
	ic_run_application_exec . icemcfd/output-interfaces patran2df $cmd
	if ![file exists $outfile] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_ugrid {infiles outfiles} {
    global env
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	set cmd "\"$infile\" \"$outfile\""

	ic_run_application_exec . icemcfd/output-interfaces ugrid2df $cmd
	if ![file exists $outfile] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_stl {infiles outfiles} {
    set ignore 0
    if {![dialog .stl "STL import options" "STL file options" {
        {use_original -opt {{"Generate" 0} {"From file" 1}} -title "Part names"}
        }]} { return "" }
    if $use_original { set ignore 1 } else { set ignore 0 }
    set files ""
    foreach infile $infiles outfile $outfiles {
        if [catch {ic_file_is_ascii $infile} ret] { mess "$ret\n"; continue }
        if $ret {
            set asc " -ascii"
            mess "STL file \"[file tail $infile]\" format: "; mess "ascii\n" blue
        } else {
            set asc ""
            mess "STL file \"[file tail $infile]\" format: "; mess "binary\n" blue
        }
        rm_tmp_file $outfile
        set part [lindex [split [file tail $infile] .] 0]
        set part [ic_geo_valid_name $part 1]
        set part [ic_geo_get_unused_part $part 1]
        if {$ignore && $asc != ""} { set part __IGNORE__ }
        if {$ignore && $asc == ""} { mess "File is binary; part names will be generated\n" blue }
        ic_run_application_exec . icemcfd/output-interfaces stl2df "\"$infile\" \"$outfile\" $asc -fam $part"
        if ![file exists $outfile] {
            mess "Error: no file was created from [file tail $infile]\n" red
            continue
        }
        lappend files $outfile
    }
    return [list 1 $files]
}

proc geo_import_nastran {infiles outfiles {vol 0}} {
    global env
    
    # this is necessary for getting geometry from an all tet mesh--->
    set vol 1
    # <-------- JKA, 11 March 2002
    if $vol { set volf "-volume" } else { set volf "" }
    
    set files ""
    foreach infile $infiles outfile $outfiles {
	if 0 {
	    # this is the old code
	    rm_tmp_file $outfile
	    ic_run_application_exec . icemcfd/output-interfaces nastran2df \
		"$volf $infile $outfile"
	    set res [glob -nocomplain $outfile*]
	    if {$res == ""} {
		mess "Error: no files were created that match $outfile*\n" red
		return ""
	    }
	    # nastran2df might make multiple output files
	    # Bugzilla #4500: changing '[file tail $r]' to '$r' --jka
	    foreach r $res { lappend files $r }
	}
	file delete temp_nastran_input.dat
	file copy $infile temp_nastran_input.dat
	file delete temp_nastran_input.uns
	ic_run_application_exec . icemcfd/output-interfaces IcedNastran \
	    "-i temp_nastran_input.dat -p temp_nastran_input"
	set out temp_nastran_input.uns
	if ![file exists $out] {
	    mess "Error: no domain file $out was created\n" red
	    #return ""
	} else {
	   file delete $outfile
	   file rename $out $outfile
	   lappend files $outfile
         }
    }
    return [list 1 $files]
}

proc geo_import_capri {infiles outfiles} {
    global env
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	ic_run_application_exec . icemcfd/output-interfaces capri2df \
	    "[file rootname $infile] $outfile"
	if ![file exists $outfile] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_ansys {infiles outfiles} {
    global env
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	ic_run_application_exec . icemcfd/output-interfaces ansys2df \
	    "-d \"$outfile\" \"$infile\""
	if ![file exists "${outfile}.uns"] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_lsdyna {infiles outfiles} {
    global env
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	ic_run_application_exec . icemcfd/output-interfaces lsdyna2df \
	    "-d \"$outfile\" \"$infile\""
	if ![file exists $outfile] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_rampant {infiles outfiles} {
    global env
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	ic_run_application_exec . icemcfd/output-interfaces rampant2df \
	    "\"$infile\" \"$outfile\""
	if ![file exists $outfile] { return "" }
    }
    return [list 1 $outfiles]
}

proc geo_import_starcd {outfile {cmdfile ""} {cellfile ""} {vertfile ""} \
	{bndfile ""}} {
    global env
    
    set args "\"$outfile\""
    if {"" != $cmdfile} {
	append args " -inp \"$cmdfile\""
    } elseif {"" != $cellfile && "" != $vertfile} {
	append args " -sc \"$cellfile\" -sv \"$vertfile\""
#	if {"" != $bndfile} {
#	    append args " -sb \"$bndfile\""
#	}
    } else {
	mess "incorrect args in geo_import_starcd"
	return ""
    }
    
    rm_tmp_file $outfile
    ic_run_application_exec . icemcfd/output-interfaces starcd2df $args
    
    if [file exists $outfile] {
	return [list 1 $outfile]
    } else {
	return ""
    }
}

proc geo_import_vrml {infiles outfiles} {
    global env

    set file_list ""
    
    foreach infile $infiles outfile $outfiles {
	rm_tmp_file $outfile
	ic_run_application_exec . icemcfd/output-interfaces vrml2df \
	    "\"$infile\" \"$outfile\""
         set dir_tmp [file dirname $outfile]
         set root_tmp [file rootname [file tail $outfile]]
         set out_tmp [file join $dir_tmp $root_tmp]
         append out_tmp "*"
         set out_list [glob -nocomplain $out_tmp]
         set file_list [concat $file_list $out_list]
    }
    if {[llength $file_list] == 0} { 
       return "" 
   } else {
       return [list 1 $file_list]
   }
}

proc geo_import_sauna {topofile gridfile outfile} {
    global env
    
    set flow_type 6
    
    if {![dialog .sauna "SAUNA options" "SAUNA options." {
        {flow_type -opt {{Euler 3} {Navier-Stokes 6}} -title "Euler or NS grid"}
    }]} { return "" }

    #rm_tmp_file $outfile
    ic_run_application_exec . icemcfd/output-interfaces sauna2df \
            "-st \"$topofile\" -fgrid \"$gridfile\" -dom \"$outfile\" -flow_type $flow_type"
    if ![file exists $outfile] { return "" }
    
    return [list 1 $outfile]
}

proc geo_import_cfx5 {infile outfile} {
    global env
    
    set zone 0
    set regions 0
    set params {
        {zone -type string \
            -title "Zone Number (0 for all)"}
        {regions -opt {{"BC Patches" 0} {Surfaces 1}} \
            -title "Set Face Parts from:"}
    }
    if {![dialog .cfx5 "CFX5 Import" "CFX5 Import Options" $params]} {return ""}

    rm_tmp_file $outfile
    set args "-s0"
    if {$zone != "" && $zone != "0"} {lappend args "-z$zone"}
    if {$regions} {lappend args "-r"}
    lappend args $infile $outfile
    ic_run_application_exec . icemcfd/output-interfaces cfx2df $args
    if ![file exists $outfile] { return "" }
    return [list 1 $outfile]
}

global env 
if [file exists $env(ICEM_ACN)/icemcfd/output-interfaces/units.cfx] {
    if ![info exists env(CFX_UNITS_DIR)] {
        set env(CFX_UNITS_DIR) $env(ICEM_ACN)/icemcfd/output-interfaces
    } else {
        if ![string match *output-interfaces* $env(CFX_UNITS_DIR)] {
            #set env(CFX_UNITS_DIR) $env(CFX_UNITS_DIR):$env(ICEM_ACN)/icemcfd/output-interfaces
        }
    }
    if ![info exists env(CFX_DATA_DIR)] {
        set env(CFX_DATA_DIR) $env(ICEM_ACN)/icemcfd/output-interfaces
    } else {
        if ![string match *output-interfaces* $env(CFX_DATA_DIR)] {
            #set env(CFX_DATA_DIR) $env(CFX_DATA_DIR):$env(ICEM_ACN)/icemcfd/output-interfaces
        }
    }
}
    
proc geo_readerargs_acusolve {} {
    return ""
}

proc geo_import_reader {source infiles outfiles {type ""} {save 1}} {
        
    set reader [v3reader_backend_for $source]
    if {"" == $reader} {
	    mess "No reader available for $source\n"
	    return ""
    }
    if {"" == $type || ("uns" != $type && "str" != $type)} {
	if ![tk_dialog .overwrite "File type" \
		"Is this mesh structured or unstructured?" "" -1 \
		"Structured" "Unstructured"] {
	    set type "str"
	} else {
	    set type "uns"
	}
    }
    
    if {[info proc geo_readerargs_${source}] != ""} {
	set args [geo_readerargs_${source}]
    } else {
	set args "2d_to_3d 0"
    }
    
    set create [expr ![ic_uns_is_loaded]]
    set isuns 1
    foreach infile $infiles outfile $outfiles {
	set info [import_reader_file $reader $infile $create 2 0 $args]
	if {$info != ""} {
	    set isuns [expr $isuns && [lindex $info 1]]
	    if $save { 
		ic_save_unstruct $outfile
		ic_unload_mesh 
	    }
	    set create 0
	}
    }
    return $isuns
}

proc backend_readers {{reader ""}} {
    global backend file_name
     
    if ![info exists backend(unstruct)] { set backend(unstruct) 1 }
    if ![info exists backend(reader)] { set backend(reader) $reader }
    if ![info exists backend(files)] { set backend(files) "" }
    if ![info exists backend(prec)] { set backend(prec)  1 }
    if ![info exists backend(tstep)] { set backend(tstep) 0 }
    if ![info exists backend(args)] { set backend(args)  "" }

    # {{acusolve { AcuSolve readacusolve }} {avs { AVS readucd avs }}}
    set key [v3readers_available]
    set rlist ""
    foreach a $key {
	set stats [lindex $a 1]
	lappend rlist [lindex $stats 0]
    }
    
    #set buts {Accept cancel}
    set d [form_init .backimp "Import mesh with backend reader"]    
    if {$d != ""} {
	
	form_label $d.backl "Reader:" {0 0} 
        futil_menuentry $d.back backend(reader) "list $rlist" {0 1}
	
	form_label $d.filel "File:" {1 0}
        futil_fileentry $d.file backend(files) $file_name(project_dir) {1 1}
	 
	form_label $d.precl "Precision:" {3 0}
	form_radiobutton $d.precs "Single"    backend(prec) 1 {3 1}
	form_radiobutton $d.precd "Double" backend(prec) 2 {3 2}
	form_label $d.tstepl "Time step:" {4 0}
	form_entry $d.tstep  backend(tstep) string {4 1}
	form_label $d.argsl "Arguments:" {5 0}
	form_entry $d.args  backend(args) string {5 1}
	
	form_finish +300+300
    }
    if ![form_wait .backimp] return
    
    set backend(create) 1
    # this could be more complicated
    if {[ic_uns_is_loaded] || [ic_str_is_loaded]} {
	if ![tk_dialog .overwrite "Unload mesh" \
		 "Unload existing mesh?" "" -1 "Yes" "No"] {
	    ic_unload_mesh
	} else {
	    set backend(create) 0
	}
    }
    puts "backend files = $backend(files)"
    import_reader_file $backend(reader) $backend(files) $backend(create) \
	$backend(prec) $backend(tstep) $backend(args)
}

proc import_reader_file {reader files {create 1} {prec 1} {tstep 0} args} {

    set bend [v3reader_backend_for $reader]    
    set args [join $args]
    set fileinfo [eval list [ic_read_external $bend $files $create $prec $tstep $args]]
    if {$fileinfo == ""} {return ""}
    
    set nunodes [lindex $fileinfo 0]
    set nsnodes [lindex $fileinfo 1]
    set createdesc [lindex $fileinfo 2]
    set createstr [lindex $createdesc 1]
    
    set showstr 0
    set showuns 0
    
    if {$nsnodes > 0} {
        set merging [expr !$createstr]
        ic_str_settopo $merging
        set showstr 1
    }
    if {$nunodes > 0} {set showuns 1}
    
    if {$showstr && $showuns} {
    	if ![tk_dialog .showunstr "Mixed Unstruct / Struct Mesh" \
		 "Show Unstruct(Yes) or Struct(No)" "" -1 "Yes" "No"] {
		     set showstr 0
		 } else {
		     set showuns 0
		 }
    }
    
    if {$showuns} {
        display_update unstruct
    } elseif {$showstr} { 
        ic_str_summary
        ic_str_set_modified 0
        initialize_struct_visibility
    }
    return [list $fileinfo $showuns $showstr]
}




