

proc aie_v3dset_win_menu {mm theNode win} {
   global dset_info

   v3p_win_menu_add $mm $win 3dview "Orient"
   v3p_win_menu_add $mm $win vframe "Multi-Views"
   v3p_win_menu_add $mm $win xyplots
   v3p_win_menu_add $mm $win 3d_misc "Misc Display"
  #v3p_win_menu_add $mm $win border "Win Border"
   v3p_win_menu_add $mm $win anno "Annotation"
   v3p_win_menu_add $mm $win hardcopy

   v3p_win_menu_add $mm $win record "Record ... "

   set top_tree [set ::AIEnv::GUIManagement::Tree::aieTree]
   $mm add command -label "Save View" -command \
               "aie_gsview_cmd $top_tree $theNode add"

   $mm add command -label "Save Result" \
               -command "aie_v3dset_tree write_domain $theNode"
}

proc aie_v3dset_tree {what node args} {
   global dset_info

   set top_tree [set ::AIEnv::GUIManagement::Tree::aieTree]

   switch -- $what {
      write_domain {
         set title [$top_tree itemcget $node -text]
         V3_setup_cmd to_client $title
         result_write_domain_cmd
      }
   } 
}

proc aie_add_setup_set {args} {
   global data_format backend_info opt_data dset_info

   if ![info exist dset_info(nread)] {
      set dset_info(nread) 0
      set dset_info(setups_list) ""
   }

   if ![info exist backend_info(open_sock)] {return ""}

   set i $dset_info(nread)
   incr dset_info(nread)

   set name [v3StartupDEZ get v3DataSetTitle]
   if {[lsearch $dset_info(setups_list) $name] >= 0} {
      mess "Data set name $name is in use, use default name\n" blue
      set name ""
   }
   if {$name == ""} {set name DataSet_$i}


   lappend dset_info(setups_list) $name $i
   V3_setup_cmd name_client $name

   set bvarName [lindex $backend_info($data_format) 2]
   if {$bvarName != ""} {global $bvarName}
   set dset_info($i,setups) [list $data_format $name [array get $bvarName]]

   set rr $::AIEnv::GUIManagement::ExclusiveGroup::ExclusiveGroupData(v3DataFormat,Children,Name)
   set k [lsearch $rr v3DataFormatNull]
   if {$k > -1} {
      set dset_info(not_new) 1
      update idletasks
      v3StartupDEZ set v3DataFormatVar $k
      update idletasks
      unset dset_info(not_new)
   }

   v3StartupDEZ set v3DataSetTitle ""

   unset backend_info(open_sock)
   lappend dset_info(read_list) "" ""
   set dset_info(iread) ""

   update idletasks
   set dset_info(read_list) $dset_info(setups_list)

   if {$::AIEnv::GUIManagement::ActiveDEZ == "v3StartupDEZ"} {
      ::AIEnv::GUIManagement::ToggleGrey v3DataSets 0
      ::AIEnv::GUIManagement::ToggleGrey v3DataSetsAdd 1
   }
}


proc aie_edit_setup_sets {what args} {
   global data_format backend_info opt_data dset_info

   switch -- $what {
      add {
      }
      delete { 
      }
   }
}


proc aie_delete_setup_set {args} {
   global data_format backend_info opt_data dset_info

   if [info exist backend_info(open_sock)] {
      mess "to close the current data set\n" blue

      V3_setup_cmd close_client 
      unset backend_info(open_sock)
   } else {
      set i $dset_info(iread)
      set k [lsearch $dset_info(setups_list) $i]
      if {$k <= 0} {return ""}
      set k0 [expr $k -1]

      set name [lindex $dset_info(setups_list) $k0]
      V3_setup_cmd close_client $name

      unset dset_info($i,setups)
      set dset_info(setups_list) [lreplace $dset_info(setups_list) $k0 $k]
   }

   lappend dset_info(read_list) "" ""
   set dset_info(iread) ""
   update idletasks

   set dset_info(read_list) $dset_info(setups_list)
}


proc aie_v3p_setup_sets {args} {
   global data_format backend_info opt_data dset_info

   if [info exist backend_info(open_sock)] {
      mess "The current set need to be finished and added \
            before making any changes to the previous sets\n" blue
      set dset_info(iread) new
      return ""
   }

   if [info exist dset_info(last_set)] {
      set i $dset_info(last_set)
      if [info exist dset_info($i,setups)] {
         set data_format [lindex $dset_info($i,setups) 0]
         set name        [lindex $dset_info($i,setups) 1]
         set bvarName [lindex $backend_info($data_format) 2]
         if {$bvarName != ""} {global $bvarName}
         set dset_info($i,setups) [list $data_format $name [array get $bvarName]]
      } else {
         mess "A bug in the setup procedures\n" red
         return ""
      }
   }

   set dset_info(not_new) 1
   update idletasks

   if {$dset_info(iread) == "new"} {
      set rr $::AIEnv::GUIManagement::ExclusiveGroup::ExclusiveGroupData(v3DataFormat,Children,Name)
      set k [lsearch $rr v3DataFormatNull]
      if {$k > -1} { v3StartupDEZ set v3DataFormatVar $k }
   } else {
      set i $dset_info(iread)
   
      if ![info exist dset_info($i,setups)] { return "" }
      set dset_info(last_set) $i

      set data_format [lindex $dset_info($i,setups) 0]
      set name        [lindex $dset_info($i,setups) 1]

      set bvarName [lindex $backend_info($data_format) 2]
      if {$bvarName != ""} {
         global $bvarName
         foreach {n v} [lindex $dset_info($i,setups) 2] {
            set ${bvarName}($n) $v
         }
      }

      set dset_info(read_list) $dset_info(setups_list)
      lappend dset_info(read_list) Current new

      set val v3DataFormat[string toupper $data_format 0 0]
      if {[::AIEnv::GUIManagement::ExclusiveGroup::GetCurrentGroupName v3DataFormat] != $val} {
         set rr $::AIEnv::GUIManagement::ExclusiveGroup::ExclusiveGroupData(v3DataFormat,Children,Name)
         set k [lsearch $rr $val]
         if {$k > -1} { v3StartupDEZ set v3DataFormatVar $k }
      }

      V3_setup_cmd to_client $name
   }
   update idletasks
   unset dset_info(not_new)

   return $dset_info(iread)
}


proc aie_select_dataform {new args} {
   global data_format backend_info dset_info

   if {($new == "v3DataFormatNull") || [info exist dset_info(not_new)]} {return ""}
   ::AIEnv::GUIManagement::ToggleGrey $new
   aie_start_dataform [string tolower [string range $new 12 end] 0 0]
   if ![info exist dset_info(setups_list)] { set dset_info(setups_list) "" }
   set dset_info(read_list) $dset_info(setups_list)
   lappend dset_info(read_list) "Current" new
   set dset_info(iread) new
   ::AIEnv::GUIManagement::ToggleGrey $new
   if {$::AIEnv::GUIManagement::ActiveDEZ == "v3StartupDEZ"} {
      ::AIEnv::GUIManagement::ToggleGrey v3DataSetsAdd 0
   }
}

proc aie_start_dataform {dform} {
    global data_format backend_info v3_readers_dir env tcl_platform

    if ![info exist backend_info(open_sock)] {
        if {[info exists env(PVM_TMP)] && $tcl_platform(platform) == "windows"} {
            foreach fm [glob -nocomplain [file join $env(PVM_TMP) pvmd.*]] {
                mess "File $fm found in $env(PVM_TMP). Previous \"pvmd\" exit dirty\n"
                set em ""
                if [catch {file delete $fm} em] {
                    mess "Deleting $fm : $em\n" red
                } else {
                    mess "File $fm deleted\n" 
                }
            }
        }
        first_form only
        set backend_info(open_sock) 1
        if [info exist backend_info(read)] {unset backend_info(read)}
   }
   set data_format $dform

   mess "data_format = $data_format\n"

   if {[info command aie_setup_${data_format}] == ""} {
      set file [file join $v3_readers_dir ${data_format}_format_aie.tcl]
      if ![file readable $file] {return ""}

      uplevel \#0 source \"$file\"
   }
   return $dform
}

proc onv3StartupDEZLoad {} {
   global dset_info

   update idletasks
   if ![info exist ::dset_info(setups_list)] {
      set ::dset_info(setups_list) ""
   }
   set ::dset_info(read_list) $::dset_info(setups_list)
   update idletasks

   if ![info exist ::dset_info(iread)] {set ::dset_info(iread) ""}

   if {$::dset_info(setups_list) == ""} {
      ::AIEnv::GUIManagement::ToggleGrey v3DataSetsAdd 1 
      ::AIEnv::GUIManagement::ToggleGrey v3DataSets 1
   }
}

proc aie_start_reader {args} {
   global data_format backend_info opt_data

   if {$data_format == "user"} {
      # --- to clean old v3p_client processes
      tk_messageBox -message "You need to start the result backend now" -type ok
      return 1
   }

   set cmd aie_setup_${data_format}
   if {[info command $cmd] == ""} { return "" }
   set rr [eval $cmd $args]

   if {($rr != "") && [info exist backend_info($data_format)]} {
      if ![info exist v3_tool_args] {set v3_tool_args ""}
      startup_before_misc

      after_first_form

      set bvarName [lindex $backend_info($data_format) 2]
      if {$bvarName != ""} {
         global $bvarName
         set rr [linsert $rr 0 $bvarName [array get $bvarName]] 
      } else {
         set rr [linsert $rr 0 "" ""]
      }

      if [info exist opt_data(use_old_startup)] {
         eval V3_startup_pv $rr
      } else {
         eval V3_reader_start $rr
      }

      set backend_info(read) 1
      return 1
   } else {
      return 0
   }
}

proc onv3StartupDEZOK {} {
   global data_format backend_info opt_data dset_info

   if [info exist backend_info(loading)] {return ""}
   set backend_info(loading) 1
   update idletasks

   v3StartupDEZ cancel

   set todo 1
   if [info exist backend_info(open_sock)] {
      aie_add_setup_set
   }

   if {[info exist dset_info(setups_list)] && \
       ($dset_info(setups_list) != "")} {

      foreach {t i} $dset_info(setups_list) {
         if [info exist dset_info($i,read)] {continue}
         if ![info exist dset_info($i,setups)] { continue }

         set data_format [lindex $dset_info($i,setups) 0]
         set name        [lindex $dset_info($i,setups) 1]

         set bvarName [lindex $backend_info($data_format) 2]
         if {$bvarName != ""} {
            global $bvarName
            foreach {n v} [lindex $dset_info($i,setups) 2] {
               set ${bvarName}($n) $v
            }
         }
         
         V3_setup_cmd to_client $name
         busy 1
         set todo [aie_start_reader]

         if {$todo == 1} {
            set rr $::AIEnv::GUIManagement::ExclusiveGroup::ExclusiveGroupData(v3DataFormat,Children,Name)
            set k [lsearch $rr v3DataFormatNull]
            if {$k > -1} { v3StartupDEZ set v3DataFormatVar $k }
         }
         busy 0
      }
   }

   if $todo {
      global opt_data
      if ![info exist opt_data(use_old_startup)] {
         V3_setup_get bind_vars
         V3_startup_cmd
      }
      busy 1
      aie_do_startup
      busy 0
      V3_setup_cmd set v3_started 1
      V3_setup_cmd reset
   }
   unset backend_info(loading)
}


proc aie_setup_v3p_first {args} {
   global env v3p_setup_error

   if {[info exist v3p_setup_error] && ($v3p_setup_error != "")} {
      mess "$v3p_setup_error\n"
      tk_messageBox -title "Post-processing Message" \
                  -message $v3p_setup_error -type ok
      return ""
   }

   if ![info exist env(V3PCLIENT_START_DIR)] {
      global file_name
      if {[info exist file_name(settings)] && ($file_name(settings) != "")} {
         set env(V3PCLIENT_START_DIR) [file dirname $file_name(settings)]         
      } elseif {[info exist file_name(project_dir)] \
                 && ($file_name(project_dir) != "")} {
         set env(V3PCLIENT_START_DIR) [file join [pwd] $file_name(project_dir)]
      } else {
         set env(V3PCLIENT_START_DIR) [pwd]
      }
   }

   ::AIEnv::GUIManagement::TabbedIconPageRaise "Post-processing"

   global v3_started
   if {[info exist v3_started] && ($v3_started > 0)} {
      set ok [tk_dialog .diag "Close previous session" "A Post-processing session started.\
                   Do you want to close it and start a new session?" "" 0 Yes Cancel]
      if {$ok} { return "" }

      aie_v3p_close_dataset

      return 1
   }

   global did_setup_v3p_first
   if [info exist did_setup_v3p_first] {return 0}
   V3_setup_cmd set did_setup_v3p_first 1 

   # ----------- did the following in InitializeVisual3p
   #setup_v3p_first_misc

   update

   # to disable setup_oned_mg setup_anno_mg
   proc setup_oned_mg {} { }
   proc setup_anno_mg {} { }

   V3_check_license

   global tdv_workspace
   if {[info exist tdv_workspace] && [winfo exist $tdv_workspace]} {
      set w [winfo parent $tdv_workspace]
      set ww [winfo width $w]
      set hh [winfo height $w]

      if {$ww < 300} {
         OneDWin::var set width $ww
      } elseif {$ww < 900} {
         OneDWin::var set width [expr 300 + ($ww -300)/4]
   #  } else {
   #     OneDWin::var set width [expr $ww / 2]
      }

      if {$hh < 300} {
         OneDWin::var set height $hh
      } elseif {$hh < 900} {
         OneDWin::var set height [expr 300 + ($hh -300)*3/8]
      }
   }

   V3_setup_cmd clean_new

   global v3_script_file replay_file replay_dir replay_doing
   if {[info exist v3_script_file] && [file readable $v3_script_file]} {
      set replay_doing 1
      set replay_dir [file dirname $v3_script_file]
      set replay_file $v3_script_file
      replay_load $v3_script_file
      replay_doit_all

      update idletasks
      unset v3_script_file

      aie_update_v3gui_states
      unset replay_doing 
   }

   return 0
}

proc aie_v3p_startup_cmd {args} {
   global data_format 
    global lsdynainfo

   if {[aie_setup_v3p_first] == ""} {return ""}

   set data_format ""
   set startup_files ""
   set dsetname ""

   set opts ""
   foreach {n v} $args {
      switch -regexp (${n}) {
         {-data_format} - {-dsetname} {
            set [lindex [split $n -] 1] $v
         }
         {-startup_files} {
            set startup_files $v
            lappend opts startup_files $v
         }
         {-*} {lappend opts [lindex [split $n -] 1] $v}
      }
   }
   if {$data_format == ""} {
      mess "aie_v3p_startup_cmd $args\n\ unknown format\n" red
      return ""
   } 

   if {$startup_files == ""} {
      if {($data_format != "lsdyna") && ($data_format != "user")} {
         mess "aie_v3p_startup_cmd $args\n\ unknown file\n" red
         return ""
      }
   }

   if {$data_format == "lsdyna"} {
      set file_tmp $::lsdynainfo(file)
      set dir_tmp $::lsdynainfo(dir_loc)
      set mat_tmp $::lsdynainfo(group_by_material)
   }

   global toplevel
   set toplevel(framew) 3

   global backend_info

   if {$data_format != "user"} {
      if {[aie_start_dataform $data_format] == ""} {
         mess "unknown format $data_format\n" red
         return ""
      }
   }

   if {$data_format == "lsdyna"} {
      set ::lsdynainfo(file) $file_tmp
      set ::lsdynainfo(dir_loc) $dir_tmp
      set ::lsdynainfo(group_by_material) $mat_tmp
   }

   if {$dsetname == ""} {set dsetname DSet_$data_format}

   V3_setup_cmd name_client $dsetname
   V3_setup_cmd to_client $dsetname

   if [info exist backend_info(open_sock)] {
      unset backend_info(open_sock)
   }

   busy 1
   if {[eval aie_start_reader $opts] == 1} {
      global opt_data
      if ![info exist opt_data(use_old_startup)] {
         V3_startup_cmd
      }
      aie_do_startup

      V3_setup_cmd set v3_started 1

      V3_setup_cmd reset
   }
   busy 0
}

proc aie_v3p_startup {what args} {
   global backend_info

   switch -- $what {
      files {
         if {[aie_setup_v3p_first] == ""} {return ""}

         global toplevel
         set toplevel(framew) 3

    #    first_form only
    #    set backend_info(open_sock) 1

         v3StartupDEZ show
      }
      custom {
         setup_v3_gui_misc

         start_v3p
      }
      close_result {
         global v3_started
         if {[info exist v3_started] && ($v3_started > 0)} {
            set ok [tk_dialog .diag "Close Result" \
                    "Close a post-processing session?" "" 0 Yes Cancel]
            if {$ok} { return "" }

            aie_v3p_close_dataset

            return 1
         }
         return 0
      }
      save_result {
         aie_v3p_iconbar save_result
      }
   }
}


proc aie_update_v3gui_states {} {
   global toolBarInfo
   global v3_started did_startup_v3p did_setup_v3p_first 
   global dset_info transient_info

   set state disable
   if {[info exist did_startup_v3p] && [info exist did_setup_v3p_first]} {
      set state normal
   }
   
   foreach b {v3VarsG v3ProbePtBut v3ExSurfBut v3AnalysisBut \
              v3AnimaBut annoBut reportAddBut onedBut v3ReplayBut} {
      if [info exist toolBarInfo(widget,$b)] {
         $toolBarInfo(widget,$b) configure -state $state
      }
   }

   set st $state
   if {$state == "normal"} {
      if {!$dset_info(is3d)} { set st disable }
   }
   
   foreach b {v3CutPBut v3IsoSfBut v3StreamBut} {
      if [info exist toolBarInfo(widget,$b)] {
         $toolBarInfo(widget,$b) configure -state $st
      }
   }

   set st $state
   if {$state == "normal"} {
      if ![info exist transient_info(i_or_p)] { set st disable }
   }
 
   set b v3TmStepBut
   if [info exist toolBarInfo(widget,$b)] {
      $toolBarInfo(widget,$b) configure -state $st
   }
}

proc aie_v3p_iconbar {what args} {
   global dset_info tdv_current_viewer
   global custom_format data_format

   if {![info exist custom_format] || ![info exist data_format]} {
      mess "No valid result was loaded yet\n" red
      return ""
   }

   set theTree [set ::AIEnv::GUIManagement::Tree::aieTree]

   switch -- $what {
      vartab  {
         global var_tab; set var_tab(aie_dez) v3VarsDEZ
         v3VarsDEZ show
      }
      var_exg {
         global var_tab; set var_tab(aie_dez) v3VarsGDEZ

         switch -- $custom_format {
            nastran { v3NastranVarsDEZ show }
            ansys   { v3AnsysVarsDEZ show }
            lsdyna  { v3LsDynaVarsDEZ show }
            default { v3VarsGDEZ show }
         }
      }
      1d_exg {
         switch -- $custom_format {
            lsdyna  { v3LsDynaXYpDEZ show }
            default { aie_oned_iconbar exg }
         }
      }
      cutp    {v3DynamicCutPDEZ show}
      isosurf  {v3DynamicIsoDEZ show}
      import_surf {v3ImportSfDEZ show}
      paramsurf {v3ParamSfDEZ show}
      tetinsurf {v3TetinSfDEZ show}
      3dptssurf {load_surface_cmd 3dpts}
      domainsurf {load_surface_cmd domain}
      strm_seed {
         set w [tdv_get_workspace_topviewer 23]
         if [info exist dset_info($w,v3dset)] {
            set dset $dset_info($w,v3dset)
            aie_set_v3strmgrp_v3dset $theTree $dset
            global str_data
            set str_data(2dpickwin) [lindex [$theTree itemcget $dset -data] 1]
         }
         v3CreateStrmDEZ show
      }
      seed_2d {
         set w [tdv_get_workspace_topviewer 23]
         if [info exist dset_info($w,v3dset)] {
            set dset $dset_info($w,v3dset)
            aie_set_v3strmgrp_v3dset $theTree $dset
            global str_data
            set str_data(2dpickwin) [lindex [$theTree itemcget $dset -data] 1]
         }
         v3CreateStrm2dDEZ show
      }
      seed_sf {
         v3CreateStrmsfDEZ show
      }
      probe   { v3ProbePtDEZ show }
      animate {v3AnimateDEZ show}
      def_svar {v3DefSVarDEZ show}
      def_vec  {v3DefVVarDEZ show}
      timestep {
         aie_v3p_update_timesteps show         
      }
      save_result {
         global tdv_current_viewer
         set title [$theTree itemcget $dset_info($tdv_current_viewer,v3dset) -text]
         V3_setup_cmd to_client $title
         result_write_domain_cmd
      }
      compare { v3CompareDEZ show }
      reporting {
         #v3ReportDEZ show
         v3DocDEZ load
      }
   }
}

