
# This code creates the user interface for the mesh editor.
#
# Copyright (c) 1997 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

proc cartfile_edit {} {
    
}

proc cartfile_initialize {{bbox ""}} {
    global file_name cartfile_visible cartfile_grid_type
    
    if [ic_cart_is_loaded] { ic_cart_unload }
    
    ic_cart_initialize 0 $bbox
    
    mess "[lindex [ic_cart_stats] 3] nodes\n"
    ic_cart_visible 1
    set cartfile_visible 1
    set cartfile_grid_type cartesian
}

proc cartfile_reset {} {
    global cartfile_visible file_name cartfile_grid_type
      
    if [ic_cart_is_loaded] { ic_cart_unload }
    
    ic_cart_initialize 1
    
    mess "[lindex [ic_cart_stats] 3] nodes\n"
    ic_cart_visible 1
    set cartfile_visible 1
    set cartfile_grid_type cartesian
}

proc cartfile_load {{file ""}} {
    global file_name cartfile_grid_type
    global cartfile_visible
    
    cartfile_unload 1
    
    if {$file == ""} {
	set file [med_file_select cart_file 0 "" "to load"]
    }
    if {$file == ""} { return 0 }
    set file_name(cart_file) $file
    
    ic_cart_load $file
    ic_cart_visible 1
    set cartfile_visible 1
    
    set cartfile_grid_type [ic_cart_grid_type]
}

proc cartfile_save {{file ""}} {
    global file_name
    
    set file [med_file_select cart_file 1 "" "to save"]
    if {$file == ""} return
    ic_cart_save $file
    set file_name(cart_file) $file
}

proc cartfile_unload {{ask 1}} {
    if {$ask && [ic_cart_is_modified]} { cartfile_save }
    ic_cart_unload
}

proc cartfile_is_ok {file} {
    if ![file isfile $file] { return 0 }
    set fp [open $file r]
    set line [gets $fp]
    close $fp
    return [expr [string match set_grid_type* $line]]
}

proc cartfile_display {{on ""}} {
    global cartfile_visible
    
    if {$on != ""} { set cartfile_visible $on }
    ic_cart_visible $cartfile_visible
}

proc cartfile_add_stations {} {
    global tdv_default

    cartfile_display 1
    
    banner "Select the position with the left button; middle = done."
    tdv_cur $tdv_default pick
    while 1 {
	set pt [graphics_loc_command_2d]
	if {[llength $pt] != 2} break
	set v [$tdv_default screen2world [lindex $pt 0] [lindex $pt 1]]
	ic_cart_add_screen [lindex $v 0] [lindex $v 1]
    }
    tdv_cur $tdv_default dynamics
    banner ""
}

proc cartfile_del_stations {} {
    global tdv_default

    cartfile_display 1
    
    banner "Select the position with the left button; middle = done, right = cancel."
    tdv_cur $tdv_default pick
    
    while 1 {
	set doit 0
	set numsel 0
	while 1 {
	    set pt [graphics_loc_command_2d]
	    if {[llength $pt] != 2} {
		set doit [expr $pt == 2]
		break
	    }
	    set v [$tdv_default screen2world [lindex $pt 0] [lindex $pt 1]]
	    ic_cart_select_screen [lindex $v 0] [lindex $v 1]
	    incr numsel
	}
	if {$doit && $numsel} {
	    ic_cart_delete_selected
	} else {
	    break
	}
    }
    tdv_cur $tdv_default dynamics
    banner ""
}

proc cartfile_edit_stations {} {
    global station_data cartfile_grid_type
    
    set ff .edit_stations_$cartfile_grid_type
    set buts {{Apply cartfile_edit_stations_apply} done}
    set d [form_init $ff "Edit stations" "" $buts]
    if {$d != ""} {
	if {$cartfile_grid_type == "cartesian"} {
	    form_text $d.stat0 "I stations" "" {0 0} "" 10x20
	    form_text $d.stat1 "J stations" "" {0 1} "" 10x20
	    form_text $d.stat2 "K stations" "" {0 2} "" 10x20
	} else {
	    form_text $d.stat0 "Z stations" "" {0 0} "" 10x20
	    form_text $d.stat1 "R stations" "" {0 1} "" 10x20
	    form_text $d.stat2 "Theta stations" "" {0 2} "" 10x20
	}
	form_finish bot
    }
    
    foreach i {0 1 2} {
	set stats [ic_cart_list_stations $i]
	form_text_set $ff.main.stat$i $stats
    }
}

proc cartfile_edit_stations_apply {} {
    global cartfile_grid_type
    global tdv_default

    set ff .edit_stations_$cartfile_grid_type
    
    foreach i {0 1 2} {
	set data [form_text_get $ff.main.stat$i]
	ic_cart_set_stations $i $data
    }
    $tdv_default redraw
    set ss [ic_cart_stats]
    mess "Size is [lindex $ss 0]x[lindex $ss 1]x[lindex $ss 2] =\
		[lindex $ss 3] nodes\n"
}

proc cartfile_edit_ranges {} {
    global cartfile_grid_type
    
    if {$cartfile_grid_type == "cartesian"} {
	set ijk [list index Index choice I {I J K} cartfile_update_defs]
    } else {
	set ijk [list index Index choice Z {Z R Theta} cartfile_update_defs]
    }
    
    set ranges ""
    foreach i {0 1 2} n {I J K} n2 {Z R Theta} {
	foreach r [ic_cart_list_ranges $i] {
	    if {$cartfile_grid_type == "cartesian"} {
		lappend ranges [concat $n $r]
	    } else {
		lappend ranges [concat $n2 $r]
	    }
	}
    }
    set bb [ic_cart_get_bbox]
    set start_s [lindex [lindex $bb 0] 0]
    set end_s [lindex [lindex $bb 1] 0]
    set cols [list $ijk \
		  [list startp Start entry $start_s float] \
		  [list endp End entry $end_s float] \
		  [list type Distribution choice uniform \
		       {uniform geo_start geo_end geo_both}] \
		  [list count Count entry 2 int] \
		  [list starth "Start H" entry 0.0 float] \
		  [list startr "Start R" entry 2.0 float] \
		  [list endh "End H" entry 0.0 float] \
		  [list endr "End R" entry 2.0 float] \
		  [list key Keypoints checkbutton 1] \
		  [list maxh "Max H" entry 0.0 float] \
		 ]
    flexlist .cart_file_ranges "Cart file ranges" $cols $ranges \
	cartfile_edit_ranges_apply
}

proc cartfile_edit_ranges_apply {res} {
    global tdv_default

    if {$res == ""} return
    
    set bb [$tdv_default bbox interesting]
    if {$bb == ""} return
    
    foreach i {0 1 2} n {I J K} n2 {Z R Theta} {
	set ranges ""
	foreach r $res {
	    if {([lindex $r 0] == $n) || ([lindex $r 0] == $n2)} {
		lappend ranges [lrange $r 1 end]
	    }
	}
	if {$ranges != ""} {
	    ic_cart_set_ranges $i $ranges
	}
    }
    
    set ss [ic_cart_stats]
    mess "Size is [lindex $ss 0]x[lindex $ss 1]x[lindex $ss 2] = [lindex $ss 3] nodes\n"
    cartfile_display 1
}

proc cartfile_update_defs {w num name nval} {
    global tdv_default

    if {$name != "index"} { return "" }
    
    set bb [$tdv_default bbox interesting]
    if {$bb == ""} return
    set bmin [lindex $bb 0]; set bmax [lindex $bb 1]
    switch [lindex [ic_cart_get_axes] 1] {
	"1 0 0" { set zax 0 }
	"0 1 0" { set zax 1 }
	"0 0 1" { set zax 2 }
	default { error "axes are not units" }
    }
    set xax [expr ($zax + 1) % 3]; set yax [expr ($zax + 2) % 3]
    switch $nval {
	I {
	    set min [lindex $bmin 0]; set max [lindex $bmax 0]
	}
	J {
	    set min [lindex $bmin 1]; set max [lindex $bmax 1]
	}
	K {
	    set min [lindex $bmin 2]; set max [lindex $bmax 2]
	}
	Z {
	    set min [lindex $bmin $zax]; set max [lindex $bmax $zax]
	}
	R {
	    set dx [expr [lindex $bmax $xax] - [lindex $bmin $xax]]
	    set dy [expr [lindex $bmax $yax] - [lindex $bmin $yax]]
	    set min 0; set max [expr sqrt($dx * $dx + $dy * $dy) / 2]
	}
	Theta {
	    set min 0; set max 6.28318
	}
    }
    return [list startp $min endp $max]
}

proc cartfile_update_type {} {
    global cartfile_grid_type no_cartfile_display_type_warning
    
    ic_cart_set_grid_type $cartfile_grid_type
}

proc cartfile_edit_cylparams {} {
    global cartfile_origin cartfile_axis0 cartfile_axis1 cartfile_axis2
    
    if ![ic_cart_is_loaded] { error "no cart file is loaded yet" }
    
    set ax [ic_cart_get_axes]
    foreach {p i} {origin 0 axis0 1 axis1 2 axis2 3} {
	set cartfile_$p [lindex $ax $i]
    }
    
    set buts {{Apply cartfile_edit_cylparams_apply} done}
    set d [form_init .edit_cartcp "Cart file parameters" "" $buts]
    if {$d != ""} {
	form_label $d.orl "Origin" {0 0}
	form_label $d.ax1l "Axis 1" {1 0}
	form_label $d.ax2l "Axis 2" {2 0}
	form_label $d.ax3l "Axis 3" {3 0}
	form_entry $d.or cartfile_origin coords {0 1}
	form_entry $d.ax0 cartfile_axis0 coords {1 1}
	form_entry $d.ax1 cartfile_axis1 coords {2 1}
	form_entry $d.ax2 cartfile_axis2 coords {3 1}
	foreach i {or ax0 ax1 ax2} { $d.$i configure -width 20 }
	form_finish bot
    }
}

proc cartfile_edit_cylparams_apply {} {
    global cartfile_origin cartfile_axis0 cartfile_axis1 cartfile_axis2
    
    if [ic_cart_is_from_ddn] {
	error "This geometry was pre-transformed by the DDN mesher interface,\
		so you can't modify the origin or axes now."
    }
    ic_cart_set_axes $cartfile_origin $cartfile_axis0 \
	$cartfile_axis1 $cartfile_axis2
}

proc cartfile_merge {} {
  global cartfile_merge file_name
  
  if [winfo exists .crtmerge] { destroy .crtmerge }
  array set cartfile_merge {
    crt_file1 ""
    crt_file2 ""
    crt_file3 ""
  }
  set cartfile_merge(pwd) [pwd]
  if {$cartfile_merge(pwd) != $file_name(project_dir)} {
    cd $file_name(project_dir)
  }
  set buttons {
    {"Done" "cartfile_merge_done"}
  }
  set d [form_init .crtmerge "Merge cart files" "" $buttons]
  if {$d != ""} {    
    form_frame $d.1 ridge 3 "0 0"
    form_frame $d.1.f1 flat 3 "0 0"
    form_label $d.1.f1.1 "cart file 1" "0 0"
    file_select_entry $d.1.f1.2 cartfile_merge(crt_file1) 0 1 "cart file 1" "0 1" \
	    "" "" "" "" {has_suffix "Cart file (.crt)" .crt}
    form_label $d.1.f1.3 "cart file 2" "1 0" 
    file_select_entry $d.1.f1.4 cartfile_merge(crt_file2) 0 1 "cart file 2" "1 1" \
	    "" "" "" "" {has_suffix "Cart file (.crt)" .crt}
    form_label $d.1.f1.5 "cart output file" "2 0" 
    file_select_entry $d.1.f1.6 cartfile_merge(crt_file3) 0 1 "cart output file" "2 1"
    form_frame $d.1.f2 flat 3 "1 0"
    form_button $d.1.f2.1 " Merge cart files " "cartfile_merge_start" "0 0 -pady 2"
    form_finish +800+400 1 0
    if ![form_wait .crtmerge] { cartfile_merge_done }
  }
}

proc cartfile_merge_done {} {
  global cartfile_merge
  cd $cartfile_merge(pwd)
  destroy .crtmerge
}

proc cartfile_merge_start {} {
  global cartfile_merge
    
  foreach {item num} {crt_file1 1 crt_file2 2} { 
    if {$cartfile_merge($item) == ""} {
      mess "ERROR: Missing cart file $num name.\n" red
      return
    }
    if ![file exists $cartfile_merge($item)] {
      mess "ERROR: Not found: cart file $cartfile_merge($item).\n" red
      return
    }
    if ![cartfile_is_ok $cartfile_merge($item)] {
      mess "ERROR: Unknown file type: $cartfile_merge($item).\n" red
      return      
    }
  }
  
  if {$cartfile_merge(crt_file3) == ""} {
    mess "ERROR: Missing cart output file name.\n" red
    return
  }
  if [file exists $cartfile_merge(crt_file3)] {
    if [tk_dialog .overwrite "Overwrite" "Output cart file file exists.\
    	\nOverwrite ?" "" -1 "Yes" "No"] {
      return
    } 
  }
  
  mess "Start merging cart file $cartfile_merge(crt_file1) and cart file \
  	$cartfile_merge(crt_file2) into file $cartfile_merge(crt_file3)\n" blue
  
  set file [open $cartfile_merge(crt_file1) r]
  set num1 0
  while {![eof $file]} {
    set line1($num1) [gets $file]
    incr num1
  }
  close $file
  set file [open $cartfile_merge(crt_file2) r]
  set num2 0
  while {![eof $file]} {
    set line2($num2) [gets $file]
    incr num2
  }
  close $file

  set grid(i) ""
  set grid(j) ""  
  set grid(k) ""
    
  for {set x 0} {$x < $num1} {incr x} {
    if [info exists ijk] {
      lappend grid($ijk) "[lindex $line1($x) 0]"
      if {$last == $i} {
        unset ijk
      } else {
        incr i
      }
    }
    set a [lindex $line1($x) 0]
    if {$a == "define_grid"} {
      set i 1
      set ijk [lindex $line1($x) 1]
      set last [lindex $line1($x) 2]
    } elseif {$a == "set_grid_type"} {
      set grid(file1,set_grid_type) $line1($x)
    } elseif {$a == "define_coordinate_system"} {
      set grid(file1,define_coordinate_system) $line1($x)
    }
  }
  mess "Summary stations before merge: $cartfile_merge(crt_file1)\n"
  foreach item {i j k} {
    set grid_len1($item) [llength $grid($item)]
    mess "$item : $grid_len1($item)\n"
  }
      
  for {set x 0} {$x < $num2} {incr x} {
    if [info exists ijk] {
      lappend grid($ijk) "[lindex $line2($x) 0]"
      if {$last == $i} {
        unset ijk
      } else {
        incr i
      }
    }
    set a [lindex $line2($x) 0]
    if {$a == "define_grid"} {
      set i 1
      set ijk [lindex $line2($x) 1]
      set last [lindex $line2($x) 2]
    } elseif {$a == "set_grid_type"} {
      set grid(file2,set_grid_type) $line2($x)
    } elseif {$a == "define_coordinate_system"} {
      set grid(file2,define_coordinate_system) $line2($x)
    }
  }
  mess "Summary stations before merge: $cartfile_merge(crt_file2)\n"
  foreach item {i j k} {
    set grid_len2($item) [expr [llength $grid($item)] - $grid_len1($item)]
    mess "$item : $grid_len2($item)\n"
  }

  foreach item {set_grid_type define_coordinate_system} {
    if {$grid(file1,$item) != $grid(file2,$item)} {
      mess "ERROR: Parameter <$item> is different in both cart files.\n" red
      return
    }
  }
  
  foreach ijk {i j k} {
    set the_grid($ijk) ""
    set grid($ijk) [ lsort -real $grid($ijk) ]
    foreach item $grid($ijk) {
      if ![info exists tmp($ijk,$item)] {
        lappend the_grid($ijk) $item
        set tmp($ijk,$item) 1
      }
    }
    set the_grid_len($ijk) [llength $the_grid($ijk)]
  }  
  mess "Summary stations after merge: $cartfile_merge(crt_file3)\n"
  foreach item {i j k} {
    set the_grid_len($item) [llength $the_grid($item)]
    mess "$item : $the_grid_len($item)\n"
  }
 
  set file [open $cartfile_merge(crt_file3) w]  
  puts $file $grid(file1,set_grid_type)
  puts $file $grid(file1,define_coordinate_system)
  foreach ijk {i j k} {
    puts $file "define_grid $ijk $the_grid_len($ijk)"
    foreach item $the_grid($ijk) {
      puts $file "$item"
    }
  }
  puts $file "return"
  close $file
  if [file exists $cartfile_merge(crt_file3)] {
    mess "Output cart file $cartfile_merge(crt_file3) created.\n" blue 
  } else {
    mess "ERROR: No output cart file $cartfile_merge(crt_file3) created.\n" red
  } 
}

