

proc v3_aie_startup {v3opts} {
   global env v3_started data_format v3_tool_args

   set env(V3PCLIENT_START_DIR) [file join [pwd] $file_name(project_dir)]

   eval v3_startup $v3opts
}


proc v3_startup {args} {
   global env tcl_platform tdv_current_viewer
   global v3_started v3_viewer_saved v3_viewer
   global v3_tool_args data_format

   if ![info exist v3_started] {
      global data_format v3_tool_args

      set v3_tool_args ""
      set n [llength $args]
      for {set i 0} {$i < $n} {incr i} {
         set g [lindex $args $i]
         switch -glob -- $g {
            -type {incr i; set data_format [lindex $args $i]}
            -* {
                mess "Warning: ignored unknown option \"$g\"\n"
                incr;
            }
            default { lappend v3_tool_args $g }
         }
      }
   }

   if {![info exist v3_viewer]} {
      setup_v3_gui_misc
   } elseif {![info exist v3_viewer_saved]} {
      set rr [pack info $tdv_current_viewer]
      set v3_viewer_saved [list $tdv_current_viewer $rr]
      pack forget $tdv_current_viewer

      eval pack $v3_viewer $rr
   }

   if ![info exist v3_started] {
      if ![info exist v3_tool_args] {set v3_tool_args ""}
      startup_before_misc
      test_startup
      set v3_started 1
   }
}

proc v3_quit {args} {
   global v3_viewer_saved v3_viewer

   if {![info exist v3_viewer_saved] || ![info exist v3_viewer]} {return ""}

   pack forget $v3_viewer
   foreach {w p} $v3_viewer_saved { eval pack $w $p }

   unset v3_viewer_saved
   return $v3_viewer
}


proc setup_pvm_env {} {
   global env tcl_platform

   if {![info exist env(VISUAL3P_ROOT)] || \
              ![info exist env(VISUAL3P_DEVELOPE)]} {
      if [info exist env(ICEM_ACN)] {set env(VISUAL3P_ROOT) $env(ICEM_ACN)}
   }
   if ![info exist env(VISUAL3P_ROOT)] {
      return "Failed to locate installation."
   }

   if {![info exist env(PVM_ROOT)] || \
                   ![info exist env(VISUAL3P_DEVELOPE)]} {
      set env(PVM_ROOT)  [file join $env(VISUAL3P_ROOT) pvm3]
   }

   if {$tcl_platform(platform) == "windows"} {
      if {$tcl_platform(machine) == "amd64"} {
         return "Not support WIN64AMD yet. Please use 32 bit Windows code."
      } else {
         set_env PVM_ARCH  WIN32
         set_env PVM_TMP  c:\\tmp
         set_env PVM_DPATH  [file join $env(PVM_ROOT) lib WIN32 pvmd3.exe]
      }
   } else {
      set v3p_app [info nameofexecutable]
      set pf "$tcl_platform(os),$tcl_platform(osVersion),$tcl_platform(machine)"
      switch -glob $pf {
         IRIX,* - IRIX64,* {
            set rr [exec file $v3p_app]
            if {[lsearch $rr "64-bit"] < 0} {
               set env(PVM_ARCH) SGI6
            } else {
               set env(PVM_ARCH) SGI64
            }
         }
         HP-UX,*,ia64 {
            set env(PVM_ARCH) HPIT
         }
         HP-UX,*,9* {
            set rr [exec file $v3p_app]
            if {[lsearch $rr "ELF-64"] < 0} {
               set env(PVM_ARCH) HPPA
            } else {
               set env(PVM_ARCH) HPPA64
            }
         }
         SunOS,*,* {
            set rr [exec file $v3p_app]
            if {[lsearch $rr "64-bit"] < 0} {
               set env(PVM_ARCH) SUN4SOL2
            } else {
               set env(PVM_ARCH) SUN64
            }
         }
         AIX,5*,* {
            set rr [exec file $v3p_app]
            if {[lsearch $rr "64-bit"] < 0} {
               set env(PVM_ARCH) AIX46K
            } else {
               set env(PVM_ARCH) IBM64
              #return "Not supported, Please use IBM 32-bit code"
            }
         }
         AIX,4*,* {
            set env(PVM_ARCH) AIX46K
         }
         Linux,*,ia64 {
            set env(PVM_ARCH) LINUX64
         }
         Linux,*,* {
            if {$tcl_platform(machine) == "ia64"} {
               set env(PVM_ARCH) LINUX64
            } else {
               set rr [exec file $v3p_app]
               if {[lsearch $rr "64-bit"] < 0} {
                  set env(PVM_ARCH) LINUX
               } else {
                  set env(PVM_ARCH) LINUX64AMD
                  #return "Not supported, Please use Linux 32-bit code"
               }
            }
         }
         default {
            set getarch [file join $env(PVM_ROOT) lib pvmgetarch]
            if ![file executable $getarch] {
               return "Can't set PVM_ARCH: incomplete installation"
            }
            set env(PVM_ARCH) [exec $getarch]
         }
      }
      set env(PVM_DPATH) [file join $env(PVM_ROOT) lib $env(PVM_ARCH) pvmd3]
   }

   if ![file exist $env(PVM_DPATH)] {
      return "Failed to locate $env(PVM_DPATH)."
   } elseif ![file executable $env(PVM_DPATH)] {
      return "$env(PVM_DPATH) is not an executable."
   }

   if [interp exists v3_batch_interp] {
      foreach {n v} [array get env PVM*] {
         v3_batch_interp eval [list set env($n) $v]
      }
   }

   return ""
}

proc setup_misc_v3p_env {} {
   global env tcl_platform host_vendor

   if {![info exist env(PVM_DPATH)] || ![file executable $env(PVM_DPATH)]} {
      set rr [setup_pvm_env]
      if {$rr != ""} {
         mess "$rr\n"
         tk_messageBox -title "Post-processing Message" \
                  -message $rr -type ok
         return ""
      }
   }

      # set pV3_* used in pV3 libs ------------

   if {$tcl_platform(platform) == "windows"} {
      if {![info exists env(pV3_Group)] && [info exists env(LOGNAME)]} {
         set_env pV3_Group "pV3_$env(LOGNAME)"
      }
   }
   set_env pV3_TO 62208000

      # to skip setup hosts etc.  --------------

   set env(V3PUSEDEFAULTHOSTS) 1

   if ![info exists env(VISUAL3P_START)] {
      set env(VISUAL3P_START) 1
   }

      # to specify v3pclient dir  --------------

   if ![info exists env(V3PCLIENT_DIR)] {
       set env(V3PCLIENT_DIR) $env(ICEM_ACN)
   }

      # for readers ----------------

   if {$tcl_platform(platform) == "windows"} {
      foreach pp {LD_LIBRARY_PATH LD_LIBRARYN32_PATH LD_LIBRARY64_PATH} {
         if [info exists env($pp)] {
            if {[string first $env($pp) "result-interfaces"] < 0} {
               append env($pp) :$env(ICEM_ACN)/icemcfd/result-interfaces
            }
         } else {
            set env($pp) $env(ICEM_ACN)/icemcfd/result-interfaces
         }
      }   
   }
}

proc setup_v3p_first_misc {} {
   global v3_gui_dir v3_tool_dir visual3p_root env
   global v3_batch_dir vpost_batch_library vpost_library
   global v3_viewer v3_root_menu
   global batch_mode
   
   if {[info command V3_*] != ""} {return ""}

   setup_misc_v3p_env

   global guibase_dir has_blt botform_geo

   if {!$batch_mode && ![info exist has_blt]} {
      uplevel #0 source [file join $guibase_dir pathentry.tcl]
      uplevel #0 source [file join $guibase_dir formutil.tcl]
      uplevel #0 source [file join $guibase_dir fileselect.tcl]

      set has_blt 0
      set botform_geo -0-0
   }

   if ![info exist v3_gui_dir] {
       set env(VISUAL3P_ROOT) $env(MED_ROOT)
       set visual3p_root $env(VISUAL3P_ROOT)
       set v3_gui_dir $env(VISUAL3P_ROOT)/lib/v3p_gui
       set v3_tool_dir $v3_gui_dir
   }
   if ![info exist vpost_batch_library] {
       set vpost_batch_library $env(MED_ROOT)/lib/vpost_batch
       set vpost_library $vpost_batch_library
   }
   if ![info exist v3_batch_dir] {
       set v3_batch_dir $env(MED_ROOT)/lib/v3p_batch
   }

   uplevel \#0 source \"$v3_gui_dir/v3p_gui_med.tcl\"

   setup_v3_batch_interp

   if $batch_mode {return }

   global bwidget_path auto_path
   if {![info exists bwidget_path] || ![file exists $bwidget_path]} {
      set bwidget_path $v3_gui_dir/bwidget1.4
   }

 #  mess "bwidget_path = $bwidget_path\n"

   if ![file exists $bwidget_path] {
      set bwidget_path $env(VISUAL3P_ROOT)/lib/bwidget1.4
   }

   if {[lsearch [package names] BWidget] < 0} {
      if [file exist $bwidget_path] {
         lappend auto_path $bwidget_path
         package require BWidget
      }
   } else {
      set bw_versions [package versions BWidget]
     # mess "BWidget $bw_versions loaded already ! \n" red
   }

 # if {[info command SelectColor] == ""} {
      proc SelectColor {args} { return [eval SelectColorMenu $args] }
 # }

   create_all_photos
   setup_cbut_popbitmaps

}


proc setup_v3_gui_misc {} {
   global v3_gui_dir v3_tool_dir visual3p_root env
   global v3_batch_dir vpost_batch_library vpost_library
   global v3_viewer v3_root_menu v3p_dset

   setup_v3p_first_misc

   set rr [aie_create_gwin ""]
   set w [lindex $rr 0]; set iset[lindex $rr 1]

   set mm .post_menu_v3
   if ![winfo exist $mm] {
      menu $mm -title "Visual3p Toolbox" -tearoff 1
      if [info exist v3_root_menu] {
         setup_v3_menu_m $mm 0
      } else {
         setup_v3_menu_m $mm 1 
      }
   }
   bind $w <Control-Button-3> "v3_post_menu %W $mm %R %X %Y"
   
   set ctl_cmap [control_colormap "" 2]
   if [winfo exist $ctl_cmap] {top_withdraw $ctl_cmap}

   V3_variables init

   global v3p_dset v3_viewer
   set iset $v3p_dset(iset)
   aie_v3p_init Post_Set_$iset $v3_viewer

   return ""
}


proc setup_v3_menu {} {
   global v3_gui_dir v3_tool_dir visual3p_root v3_root_menu env

   set env(VISUAL3P_ROOT) $env(MED_ROOT)
   set visual3p_root $env(VISUAL3P_ROOT)
   set v3_tool_dir $v3_gui_dir

   set mm .v.top.panel2.output.visual3.m
   if {![winfo exist $mm] || ([winfo class $mm] != "Menu")} {
      return ""
   }

   $mm delete 0 1000
   setup_v3_menu_m $mm 1

   set v3_root_menu $mm
}

proc v3_post_menu {w mm args} {
   set r   [lindex $args 0]
   set xp  [lindex $args 1]
   set yp  [lindex $args 2]

   if {$xp == ""} {set xp [winfo pointerx $w]}
   if {$yp == ""} {set yp [winfo pointery $w]}

   tk_popup $mm $xp $yp
}

proc setup_v3_menu_m {mm with_start} {
   global v3_root_menu

   if {$with_start == 1} {
      $mm add command -label "START" -command "v3_startup"
   }
   $mm add command -label "Surfaces" -command "setup_surfaces_mg"
   $mm add cascade -label "Variables" -menu $mm.var
       menu $mm.var -tearoff 0
       $mm.var add command -label "Define Scalar Variable" \
                  -command "user_function_calc scalar"
       $mm.var add command -label "Define Vector Variable" \
                  -command "user_function_calc vector"
       $mm.var add command -label "Global Lists" \
                  -command "control_gvars_form"
   $mm add cascade -label "XY Plots"  -menu $mm.xys
       menu $mm.xys -tearoff 0
       $mm.xys add command -label "Manager" -command "setup_oned_mg"
       $mm.xys add command -label "Create new window" \
                  -command "update_oned_mg new_win"
       $mm.xys add command -label "Create polar window" \
                  -command "update_oned_mg polar_win"
   $mm add cascade -label "Comparison"  -menu $mm.dv
       menu $mm.dv -tearoff 0
       $mm.dv add command -label "Manager" -command "setup_dvalid_mg"
       $mm.dv add command -label "Compare scatter points" \
                 -command "update_dvalid_mg load_pts"
       $mm.dv add command -label "Compare curve" \
                 -command "update_dvalid_mg load_curve"
       $mm.dv add command -label "Compare surface" \
                 -command "update_dvalid_mg load_surf"
   $mm add command -label "Streams" -command "setup_streams_mg"
   $mm add cascade -label "Animate" -menu $mm.am
       menu $mm.am -tearoff 0
       $mm.am add command -label "Controller" \
                   -command "control_animate_all"
       $mm.am add checkbutton -label "Animate Views" -variable \
           animate_data(views) -command "setup_animation_fm trans"
       $mm.am add checkbutton -label "Rotate about line" -variable \
           animate_data(linerot) -command "setup_animation_fm rot"
       $mm.am add checkbutton -label "Animate Streams" -variable \
           animate_data(streams) -command "setup_animation_fm str"
       $mm.am add checkbutton -label "Animate Dynamic Surfs" -variable \
           animate_data(dynamic) -command "setup_animation_fm dyn"
       $mm.am add checkbutton -label "Animate Modal/Deform" -variable \
           animate_data(modal) -command "setup_animation_fm mod"
   $mm add cascade -label "MultiViews" -menu $mm.mw
       menu $mm.mw -tearoff 0
       $mm.mw add command -label "4 Views" -command "make_4_views"
       $mm.mw add command -label "Remove 4 Views" \
                 -command "remove_4_views"
       $mm.mw add command -label "Post 3D" -command "post_3d_view"
       $mm.mw add command -label "Post 2D" -command "post_2d_view"
   $mm add cascade -label "Annos" -menu $mm.an
       menu $mm.an -tearoff 0 
       $mm.an add command -label "Manager" -command "v3_control_anno mg"
       $mm.an add command -label "Move" -command "v3_control_anno move"
       $mm.an add command -label "Delete" -command "v3_control_anno delete"
       $mm.an add command -label "Clear" -command "v3_control_anno clear"
   $mm add cascade -label "Outputs" -menu $mm.out
       menu $mm.out -tearoff 0 
       $mm.out add command -label "Hardcopy"  -command "hardcopy_form"
       $mm.out add cascade -label "Set window size" -menu $mm.out.m
           menu $mm.out.m -tearoff 0 
           $mm.out.m add command -label maximum \
                        -command "v3_set_view_size \"\" max"
           $mm.out.m add command -label 800x600 \
                        -command "v3_set_view_size \"\" 800 600"
           $mm.out.m add command -label 640x480 \
                        -command "v3_set_view_size \"\" 640 480"
           $mm.out.m add command -label 480x360 \
                        -command "v3_set_view_size \"\" 480 360"
           $mm.out.m add command -label 320x200 \
                        -command "v3_set_view_size \"\" 320 240"
           $mm.out.m add command -label custom -command "v3_set_view_size"

       $mm.out add checkbutton -label "Auto-generate image files" \
           -variable hardcopy(auto) -command "hardcopy_auto_cmd"
       $mm.out add command -label "Create MPEG file" -command "hardcopy_mpeg"
       $mm.out add command -label "Create animated GIF file" \
                  -command "hardcopy_gifa_fm"
       $mm.out add command -label "Save result domain" \
                  -command "result_write_domain_cmd"
   $mm add cascade -label "Replay" -menu $mm.rep
       menu $mm.rep -tearoff 0
       $mm.rep add command -label "Replay Control" -command "file_replay"
       $mm.rep add command -label "Load script file" \
                  -command "update_replay_cmd load"
       $mm.rep add command -label "Run from script file" \
                  -command "update_replay_cmd run_file"
       $mm.rep add checkbutton -label "Recording" -variable \
            replay_recording -command "update_replay_cmd recording"
       $mm.rep add command -label "Record current view" \
                  -command "v3_save_window view"
       $mm.rep add command -label "Record multiviews" \
                  -command "v3_save_window subs"
       $mm.rep add command -label "Record annotations" \
                  -command "v3_save_window annos"
   $mm add command -label "Quit" -command "v3_quit"
}

proc setup_v3_batch_interp {} {
   global env whoami

   global v3_batch_dir
   v3_batch_interp eval [list set batch_dir $v3_batch_dir]

   foreach var {
      v3_batch_dir
      batch_mode
      is_win
      guibase_dir
      tdv_library
      tdv_default
   } {
      global $var
      v3_batch_interp eval [list set $var [set $var]]
   }
   v3_batch_interp eval [list source $v3_batch_dir/v3p_batch.tcl]
 
   foreach cmd [v3_batch_interp eval info commands V3_*] {
          if [string match V3_*_get $cmd] {
       proc $cmd args "\
         global errorInfo; \
         set err \[catch {v3_batch_interp eval $cmd \$args} ret] ;\
         if \$err { error \"\$ret\n\$errorInfo\" } ;\
         if [info exists env(ICEM_REPLAY_DEBUG)] { \
                puts \"CMD: $cmd \$args\" ;\
                puts \"RES: \$ret\" ;\
         } ;\
         return \$ret"
     } else {
       proc $cmd args "\
         global command_hook in_$cmd errorInfo ; \
         if \[info exists in_$cmd\] \{ user_error \
              \"\[set in_$cmd\] \| $cmd \$args called re-entrantly\"; unset in_$cmd\};\
         if \[info exists command_hook\] { \$command_hook \"$cmd \$args\" } ;\
         set in_$cmd \"$cmd \$args\";\
         set err \[catch {v3_batch_interp eval $cmd \$args} ret] ;\
         catch \{ unset in_$cmd \} ;\
         if \$err { error \"\$ret\n\$errorInfo\" } ;\
         if \[info exists after_command_hook\] { \
                  \$after_command_hook \"$cmd \$args\" } ;\
         if [info exists env(ICEM_REPLAY_DEBUG)] { \
                puts \"CMD: $cmd \$args\" ;\
                puts \"RES: \$ret\" ;\
         } ;\
         return \$ret"
     }
   }

   # The list of functions in the GUI interpreter that the batch interpreter
   # can call.

   foreach cmd [info commands v3b2g_*] {
      v3_batch_interp alias $cmd $cmd
   }

   v3_batch_interp alias bgerror bgerror


   set gui_variables {
      black_and_white
      use_xwindows
   }

   foreach var $gui_variables {
      global $var
      trace variable $var w v3_batch_interp_update_var
      v3_batch_interp_update_var $var "" w
   }

   v3_batch_interp eval set whoami \"$whoami\"

}

proc v3_batch_interp_update_var {name sub op} {
   global $name

   if [array exists $name] {
      if {$sub == ""} {
         foreach sub [array names $name] {
            set val [set ${name}($sub)]
            v3_batch_interp eval [list set ${name}($sub) $val]
         }
      } else {
         set val [set ${name}($sub)]
         v3_batch_interp eval [list set ${name}($sub) $val]
      }
   } elseif [info exists $name] {
      set val [set $name]
      v3_batch_interp eval [list set $name $val]
   }
}
