proc rmi_File { mess what { w "" } } {
global rmi file_browser_runs
   
  if ![ info exist file_browser_runs ] {
    set file_browser_runs 1
  } else {
    return
  }
  
  set where [ pwd ]
 
  switch $what {
    settings_fn {
      if {[info exists rmi(configuration)] && ($rmi(configuration) != "")} {
        set stuff [glob -nocomplain $rmi(configuration)/*/*.set]
        if {$stuff == ""} {
          set stuff [glob -nocomplain $rmi(configuration)/*/*.def]
        }
        if {$stuff == ""} {
          set stuff [glob -nocomplain $rmi(configuration)/*.set]
        }        
        if {$stuff == ""} {
          set stuff [glob -nocomplain $rmi(configuration)/*.def]
        }        
        if {$stuff != ""} {
          set set_dir [file dirname [lindex $stuff 0]]
        } else {
          set set_dir $rmi(configuration)
        }
      } else {
        set set_dir .
      }
      if { $mess == "Save settings" } {
        set new_on 1
      } else {
        set new_on 0
      } 
      set file [ file_selection -message "$mess file:" -new_ok $new_on -absolute 0 -default $set_dir \
      	 -visible_func {has_suffix "Setting file (.set .def)" .set .def} -ok_func rmi_FileIsSettingFile]
      cd $where
      if { $file == "" } {
        rmi_ShowMessage "No settings file selected.\n"
        unset file_browser_runs
        return
      }
      if { $mess == "Save settings" } {
        if [ file exists $file ] {
          if ![ file isdir $file ] {
            if [ rmi_ShowQuestion WARNING "Overwrite existing file\n<$file> ?" ] {
              set rmi($what) $file
              rmi_SaveSettings
              set name [ file tail $file ]
              rmi_ShowMessage "Setting saved as file <$name>.\n"
            } else {
              rmi_ShowMessage "Nothing saved.\n"
            }
          } else {
            rmi_ShowMessage "Can not save file <$file>. It is a directory.\n"
          }
        } else {
          set rmi($what) $file         
          rmi_SaveSettings
          set name [ file tail $file ]
          rmi_ShowMessage "Setting saved as file <$name>.\n"
        }        
      } elseif { $mess == "Open settings" } {
        if [ file exists $file ] {
          if ![ file isdir $file ] {
            set rmi($what) $file
            set name [ file tail $file ]
            rmi_ShowMessage "Loading setting from file <$name>...\n"
            ### There was a bug in rmi_SaveSettings and for old setting files the
            ### following 4 values will be saved before loading an old one
            set tmp(ValveMesh1Small) $rmi(ValveMesh1Small)
            set tmp(ValveMesh2Small) $rmi(ValveMesh2Small)
            set tmp(ValveMesh1) $rmi(ValveMesh1)
            set tmp(ValveMesh2) $rmi(ValveMesh2)
            set error [ rmi_OpenSettings ]
            ### Restore the 4 values to their correct values
            set rmi(ValveMesh1Small) $tmp(ValveMesh1Small)
            set rmi(ValveMesh2Small) $tmp(ValveMesh2Small)
            set rmi(ValveMesh1) $tmp(ValveMesh1)
            set rmi(ValveMesh2) $tmp(ValveMesh2)
            if !$error {
              #rmi_CheckSettings
            }
            if $rmi(chadice) {
              set num 0
              if { $rmi(intake_motion) == "1" } { set num 1 }
              if { $rmi(exhaust_motion) == "1" } {  set num 2 }
              if { $rmi(intake_motion) == "1" && $rmi(exhaust_motion) == "1" } { set num 3 }
              rmi_SetMotion $num GrayOut
              rmi_SetStaticButtons
            }
            if !$error {
              rmi_ShowMessage "Setting loaded.\n"
            }
          } else {
            rmi_ShowMessage "Can not open file <$file>. It is a directory.\n"
          }
        } else {
          rmi_ShowMessage "No such file <$file>.\n"
        }
      }
    }
    tetin_fn {
      if [ file isdirectory mulcad ] {
        set dir mulcad
      } else {
        set dir $where
      }
      if { [ info exists rmi(configuration) ] && \
      	    ($rmi(configuration) == "") } {
        rmi_ShowMessage "No project selected - select one project first.\n"
        set file [ file_select "Select an existing project." $dir \
			       "Select project" 1 ]
        if { $file == "" } {
          rmi_ShowMessage "No project selected.\n"
          set rmi(configuration) ""
          set rmi($what) ""
          set rmi(ConfigurationSelected) 0
          set rmi(TetinSelected) 0
          unset file_browser_runs
          return
        } else {
          set rmi(configuration) $file
          rmi_ShowMessage "Selected project is $rmi(configuration)\n"
          set rmi(ConfigurationSelected) 1
        }
      }
      if [ file exists $rmi(configuration)/mesh ] {
        set def $rmi(configuration)/mesh
      } else {
        set def $rmi(configuration)
      }
      set file [ file_select $mess $def "Tetin file" 0 0 file_is_tetin "" \
		 	     [ list select_tetin_extra_widgets load ] ]
      cd $where
      if { $file == "" } {
        rmi_ShowMessage "No new geometry (tetin) file selected.\n"
        if { $rmi($what) == "" } {
          set rmi(TetinSelected) 0
        }
        unset file_browser_runs
        return
      }
      set file [ file tail $file ]
      set rmi($what) $file
      set rmi(TetinSelected) 1
      rmi_GetNumberOfValves
      $w xview end
    }
    intake_lift_fn {
      set file [ file_selection -message "$mess file:" -new_ok 0 -absolute 0 -default ./ ]
      cd $where
      if { $file == "" } {
        rmi_ShowMessage "No intake valve lift profile file selected.\n"
        unset file_browser_runs
        return
      }
      set rmi($what) $file 
      set rmi(value_layers_at_lift_intake) 0.5
      if $rmi(all_intake_valves) {
        for { set i 1 } { $i <= $rmi(intake_number_valve) } { incr i } {
          set rmi($what,$i) $file
          set rmi(value_layers_at_lift_intake,$i) $rmi(value_layers_at_lift_intake)
        }
      } else {
        set rmi($what,$rmi(current_intake_valve)) $file
        set rmi(value_layers_at_lift_intake,$rmi(current_intake_valve)) \
        	$rmi(value_layers_at_lift_intake)
      }
      $w xview end  
    }
    exhaust_lift_fn {
      set file [ file_selection -message "$mess file:" -new_ok 0 -absolute 0 -default ./ ]
      cd $where
      if { $file == "" } {
        rmi_ShowMessage "No exhaust valve lift profile file selected.\n"
        unset file_browser_runs
        return
      }
      set rmi($what) $file
      set rmi(value_layers_at_lift_exhaust) 0.5
      if $rmi(all_exhaust_valves) {
        for { set i 1 } { $i <= $rmi(exhaust_number_valve) } { incr i } {
          set rmi($what,$i) $file
          set rmi(value_layers_at_lift_exhaust,$i) $rmi(value_layers_at_lift_exhaust)
        }
      } else {
        set rmi($what,$rmi(current_exhaust_valve)) $file
        set rmi(value_layers_at_lift_exhaust,$rmi(current_intake_valve)) \
        	$rmi(value_layers_at_lift_exhaust)
      }
      $w xview end   
    }
  }
  unset file_browser_runs
  update
}

proc rmi_XviewEnd {} {
global rmi

  foreach a [ winfo children .rmi.main.2 ] {
    foreach b [ winfo children $a ] {
      foreach c [ winfo children $b ] {
        if { [ winfo class $c ] == "Entry" } { 
          if [string match rmi(*_fn) [$c cget -textvariable]] {
            $c xview end
          } else {
            $c xview 0
          }
        }
        foreach d [ winfo children $c ] {
          if { [ winfo class $d ] == "Entry" } { 
            if [string match rmi(*_fn) [$d cget -textvariable]] { 
              $d xview end
            } else {           
              $d xview 0
            }
          }
        }
      }
    }
  }
}

proc rmi_FileIsSettingFile {file} {
  if {![file isfile $file] || ![file readable $file]} { return 0 }
  set fp [open $file r]; set line [gets $fp]; close $fp
  if {![string match "# Settings file for ramm-ice" $line] && \
      ![string match "# Settings file for ic3m" $line] && \
      ![string match "# Settings file for chadice" $line]} {
    return 0
  }
  return 1
}

proc rmi_OpenSettings {} {
global rmi batch_mode

  if ![rmi_FileIsSettingFile $rmi(settings_fn)] {
    rmi_ShowMessage "\nFile <$rmi(settings_fn)> contains no settings. Select an other one.\n"
    return 1
  }
  
  set is_new_setting 0 
  set f [ open $rmi(settings_fn) r ]
  set line [ gets $f ]
  while { ![eof $f] } {
    set item [ gets $f ]
    set value [ gets $f ]
    if [ info exists rmi($item) ] {
      if { [ string match configuration $item ] } {
        set rmi(last_configuration) $rmi(configuration)
      }
      set rmi($item) $value
    }
    if {[string match all_intake_valves $item] || \
        [string match all_exhaust_valves $item]} {
      set is_new_setting 1
    }
  }
  close $f

  foreach i [ array names rmi ] {
    set item $i
    set value $rmi($i)
    if {[string match configuration $item]} {
      rmi_SearchForFile $item $value
    }
  }

  foreach i [ array names rmi ] {
    set item $i
    set value $rmi($i)
    if {[string match *_fn $item] || [string match *_fn,* $item]} {
      rmi_SearchForFile $item $value
      if {$item == "tetin_fn"} {
        rmi_GetNumberOfValves
        if !$batch_mode {
          if !$rmi(chadice) {
            $rmi(ValveMotionButton) configure -state normal
          }
        }
      }
    }
    if {!$is_new_setting} {
      foreach type { intake exhaust } {
        if {$type == "intake"} { set what Intake }
        if {$type == "exhaust"} { set what Exhaust }
        if [string match ${type}_lift_fn $item] {
          set rmi(value_layers_at_lift_${type}) 0.5
          for { set x 1 } { $x <= $rmi(${type}_number_valve) } { incr x } {
            set rmi(${type}_lift_fn,$x) $rmi(${type}_lift_fn)
            set rmi(value_layers_at_lift_${type},$x) $rmi(value_layers_at_lift_${type})
          }
        }
        if [string match ${type}_max_lift $item] {
          for { set x 1 } { $x <= $rmi(${type}_number_valve) } { incr x } {
            set rmi(${type}_max_lift,$x) $rmi(${type}_max_lift)
          }
        }
      }
    }
  }
  
  if {[info exists rmi(StationsList)] && $rmi(StationsList) != ""} {
    set value $rmi(StationsList)
    set len [llength $value]
    ic_rmi_adddel_stations 0
    for { set m 0 } { $m < $len } { incr m } {
      set list_elem [lindex $value $m]
      set type [string trim [lindex $list_elem 0]]
      set dca [lindex $list_elem 1]
      set info [lindex $list_elem 2]
      set layers [lindex $list_elem 3]
      set layers_in1 [lindex $list_elem 4]
      set layers_in2 [lindex $list_elem 5]
      ic_rmi_set_station $type $dca $info $layers $layers_in1 $layers_in2
    }
  }
  
  if {[info exists rmi(StationsInfo)] && $rmi(StationsInfo) != ""} {
    set value $rmi(StationsInfo)
    set elem1 [lindex $value 0]
    set elem2 [lindex $value 1]
    for { set i 0 } { $i < 7 } { incr i } {
      set a$i [lindex $elem1 $i]
    }
    for { set i 0 } { $i < 8 } { incr i } {
      set b$i [lindex $elem2 $i]
    }
    ic_rmi_set_station_info $a0 $a1 $a2 $a3 $a4 $a5 $a6 $b0 $b1 $b2 $b3 $b4 $b5 $b6 $b7
  }
  
  if !$batch_mode {
    if !$rmi(chadice) {
      if $rmi(hpc) {
        rmi_CreateFieldProcessors $rmi(HpcButton)
      }
    }
    rmi_XviewEnd
    update
  }
    
  return 0
}

proc rmi_SaveSettings {} {
global rmi

  set f [ open $rmi(settings_fn) w ]
  if !$rmi(chadice) {
    puts $f "# Settings file for ic3m"
  } else {
    puts $f "# Settings file for chadice"
  }
  foreach item [ array names rmi ] {
    if { [string match Mask* $item] || [string match Logo* $item] || \
         [string match Image* $item] || [string match CheckOut* $item] || \
         [string match Frame* $item] || [string match *Buttons* $item] || \
         [string match Version $item] || [string match *Button $item] || \
         [string match Browse $item] || [string match *Window $item] || \
         [string match MeshValid $item] || [string match ViewPid $item] || \
         [string match *Bitmap $item] || [string match MessLines $item] || \
         [string match WhichSetting* $item] || [string match settings_fn $item] || \
         [string match CopyParameters* $item] || [string match last_configuration $item] || \
         [string match chadice $item] || [string match ValveMesh*Small $item] || \
         [string match ValveMesh1 $item] || [string match ValveMesh2 $item] || \
         [string match batch_mode $item]} {
      continue
    }
    if { $item != "" } {
      puts $f "$item" 
      puts $f "$rmi($item)"
    }
  }
  close $f
}

proc rmi_SearchForFile { name path } {
global rmi

  if { ($path == "") || [ string match settings_fn $name ] } {
    return
  }
    
  set what [ lindex [ split $name , ] 0 ]
  if { [ string match $name $what ] && [ info exists rmi($what,1) ] } {
    return
  }
  set found [ file exists $path ]
  set number ""

  switch $what {
    configuration {
      if !$found {
        rmi_ShowMessage "ERROR: No such project: $path\n" red
        return
      } else {
        rmi_ShowMessage "Project $rmi(configuration) loaded.\n"
      }
    }
    tetin_fn {
      if !$found {
        if [ file exists $rmi(configuration)/mesh/$path ] {
          set found 1
        }
      }
      set which "Geometry (tetin)"
    }
    intake_lift_fn - exhaust_lift_fn {
      set which "Valve lift profile"      
    }
  }
  
  if !$found {
    if [ string match *intake* $what ] {
      append which " (intake"
    } elseif [ string match *exhaust* $what ] {
      append which " (exhaust"
    }
    if { [ string match *intake* $what ] || [ string match *exhaust* $what ] } {
      if { $number != "" } {
        append which " ${number})"
      } else {
        append which ")"
      }
    }
    rmi_ShowMessage "ERROR: $which file not found at path <$path>.\n" red
  }
}

proc rmi_GetNumberOfValves {} {
global rmi
  
    if !$rmi(TetinSelected) { return }
    if {$rmi(tetin_fn) == ""} { return }
    
    set file $rmi(configuration)/mesh/$rmi(tetin_fn)
    set tmp(intake) 0
    set tmp(exhaust) 0
    if [file exists $file] {
      rmi_ShowMessage "Searching for number of valves in current project...\n"
      busy 1
      set f [open $file r]
      while {![eof $f]} {
        set line [string toupper [gets $f]]
        if [string match "*DEFINE_SURFACE*" $line] {
          if {[string match "*FAMILY*IV1 *" $line] || \
              [string match "*FAMILY*INTAKE_VALVE_1 *" $line]} {
            if {$tmp(intake) < "1"} { set tmp(intake) 1 }
          }
          if {[string match "*FAMILY*IV2 *" $line] || \
              [string match "*FAMILY*INTAKE_VALVE_2 *" $line]} {
            if {$tmp(intake) < "2"} { set tmp(intake) 2 }
          }
          if {[string match "*FAMILY*IV3 *" $line] || \
              [string match "*FAMILY*INTAKE_VALVE_2 *" $line]} {
            if {$tmp(intake) < "3"} { set tmp(intake) 3 }
          }
          if {[string match "*FAMILY*EV1 *" $line] || \
              [string match "*FAMILY*EXHAUST_VALVE_1 *" $line]} {
            if {$tmp(exhaust) < "1"} { set tmp(exhaust) 1 }
          }
          if {[string match "*FAMILY*EV2 *" $line] || \
              [string match "*FAMILY*EXHAUST_VALVE_2 *" $line]} {
            if {$tmp(exhaust) < "2"} { set tmp(exhaust) 2 }
          }
        }
      }
      busy 0
      close $f
    }
    if {$tmp(intake) != "0"} {
      set rmi(intake_number_valve) $tmp(intake)
      rmi_ShowMessage "Number of intake valves in current project: $rmi(intake_number_valve)\n"
    } else {
      rmi_ShowMessage "No intake valves found in current project.\n"
    }
    if {$tmp(exhaust) != "0"} {
      set rmi(exhaust_number_valve) $tmp(exhaust)
      rmi_ShowMessage "Number of exhaust valves in current project: $rmi(exhaust_number_valve)\n"
    } else {
      rmi_ShowMessage "No exhaust valves found in current project.\n"
    }
    
    rmi_IsTetinSelected
    rmi_GetTipFamilies
}

proc rmi_GetTipFamilies {} {
global rmi
  
    if !$rmi(TetinSelected) { return }
    if {$rmi(tetin_fn) == ""} { return }
    
    set file $rmi(configuration)/mesh/$rmi(tetin_fn)
    set tmp(intake) $rmi(intake_number_valve)
    set tmp(exhaust) $rmi(exhaust_number_valve)
    if [file exists $file] {
      rmi_ShowMessage "Searching for family names in current project..."
      busy 1
      set f [open $file r]
      while {![eof $f]} {
        set line [string toupper [gets $f]]
        if [string match "*DEFINE_CURVE*" $line] {
          for { set m 1 } { $m <= $tmp(intake) } { incr m } {
            if {[string match "*FAMILY*IV${m}_EDGE4 *" $line] || \
                [string match "*FAMILY*IV${m}_LSEAT *" $line] || \
                [string match "*FAMILY*INTAKE_VALVE_${m}_EDGE4 *" $line]} {
              set tmp(intake,$m,edge4) 1
            }
            if {[string match "*FAMILY*IV${m}_EDGE1 *" $line] || \
                [string match "*FAMILY*INTAKE_VALVE_${m}_EDGE1 *" $line]} {
              set tmp(intake,$m,edge1) 1
            }
            if {[string match "*FAMILY*IV${m}_EDGE2 *" $line] || \
                [string match "*FAMILY*INTAKE_VALVE_${m}_EDGE2 *" $line]} {
              set tmp(intake,$m,edge2) 1
            }
            if {[string match "*FAMILY*IV${m}_EDGE3 *" $line] || \
                [string match "*FAMILY*INTAKE_VALVE_${m}_EDGE3 *" $line]} {
              set tmp(intake,$m,edge3) 1
            }
          }
          for { set m 1 } { $m <= $tmp(exhaust) } { incr m } {
            if {[string match "*FAMILY*EV${m}_EDGE4 *" $line] || \
                [string match "*FAMILY*EV${m}_LSEAT *" $line] || \
                [string match "*FAMILY*EXHAUST_VALVE_${m}_EDGE4 *" $line]} {
              set tmp(exhaust,$m,edge4) 1
            }
            if {[string match "*FAMILY*EV${m}_EDGE1 *" $line] || \
                [string match "*FAMILY*EXHAUST_VALVE_${m}_EDGE1 *" $line]} {
              set tmp(exhaust,$m,edge1) 1
            }
            if {[string match "*FAMILY*EV${m}_EDGE2 *" $line] || \
                [string match "*FAMILY*EXHAUST_VALVE_${m}_EDGE2 *" $line]} {
              set tmp(exhaust,$m,edge2) 1
            }
            if {[string match "*FAMILY*EV${m}_EDGE3 *" $line] || \
                [string match "*FAMILY*EXHAUST_VALVE_${m}_EDGE3 *" $line]} {
              set tmp(exhaust,$m,edge3) 1
            }
          }
        }
      }
      busy 0
      close $f
      rmi_ShowMessage "done.\n"
    }
    foreach type {intake exhaust} {
      for { set m 1 } { $m <= $tmp($type) } { incr m } {
        if {[info exists tmp($type,$m,edge1)] && \
            [info exists tmp($type,$m,edge2)] && \
            [info exists tmp($type,$m,edge3)] && \
            [info exists tmp($type,$m,edge4)]} {
          set rmi($type,$m,tip_edges) 1
        }
      }
    }
}
