#!/bin/sh
# Do a little magic to run perl from anywhere in your path.

lines=`cat $0 | wc -l`
lines=`expr $lines - 10`
tail -$lines $0 > /tmp/visitperl$$
echo "__END__" >> /tmp/visitperl$$
echo "$0 $*" >> /tmp/visitperl$$
exec perl /tmp/visitperl$$ $0 ${1+"$@"}

unlink $0;
$0 = shift @ARGV;

###############################################################################
#
#         Run VisIt on various architectures
#
# Programmer:  Eric Brugger (adopted from a script by Jeremy Meredith and
#              Sean Ahern)
# Date      :  October 24, 2000
#
# Modifications:
#    Eric Brugger, Fri Feb 23 08:20:37 PST 2001
#    I added the setting of the environment variable MESA_GLX_FX to eliminate
#    a warning message on Linux when displaying to a remote display.
#
#    Jeremy Meredith, Fri Mar 16 16:39:02 PST 2001
#    Added the -v option, the -beta option, and the -dir option.
#    No longer is the current version picked by a number, but simply by
#    a symlink called "current".
#
#    Jeremy Meredith, Wed Mar 28 13:53:05 PST 2001
#    Added directory for the current script to the path.  This means users
#    don't have to have this script in their path to run within-box.
#
#    Jeremy Meredith, Fri Apr 20 10:38:47 PDT 2001
#    Pass versioning flags on to started process so we can then pass them
#    to remote processes.
#
#    Jeremy Meredith, Fri Apr 27 15:27:09 PDT 2001
#    Made all text output go to stderr.
#
#    Jeremy Meredith, Thu May 10 15:20:08 PDT 2001
#    Added plugin directory.  Also made the current dir get added to the 
#    front of the path.
#
#    Jeremy Meredith, Mon Jun 25 21:40:30 PDT 2001
#    Changed binary names so the engine is called engine_ser or engine_par.
#    Made it accept the "-par" argument so that parallel options can be
#    added manually by the user.
#
#    Jeremy Meredith, Fri Jun 29 15:29:18 PDT 2001
#    Added other LD_LIBRARY_PATH-like environment variables.
#
#    Jeremy Meredith, Mon Jul 16 13:35:29 PDT 2001
#    Reworked the script.  Arguments for parallel are now general, not
#    specific to any launch method.  The launch method (poe/psub/mpirun etc.)
#    may also be explicity given, although a default is selected for each
#    machine.  The default for AIX is now poe, not psub.  Removed the 
#    calculation of nodes based on processors since it varies too widely
#    for each platform.  Added basic support for a python based CLI.
#    Rewrote the usage message.  Other cleaning as well.
#
#    Jeremy Meredith, Mon Jul 23 00:50:26 PDT 2001
#    Fixed some stuff....  Made better use of $variable_set flags.
#    Removed more unused stuff.
#
#    Jeremy Meredith, Mon Jul 23 12:15:55 PDT 2001
#    Fixed argument parsing.  It was stopping when an argument evaluated
#    to 0 instead of when it ran out of arguments.  Fixed help text as well.
#    Removed /usr/lib from the library search paths....  It was messing
#    up parallel AIX when it was included in LIBPATH, and since we weren't
#    sure it was needed at all, I removed it from all of them.
#
#    Jeremy Meredith, Mon Jul 23 16:53:49 PDT 2001
#    Added -small option.
#
#    Jeremy Meredith, Tue Jul 24 12:21:42 PDT 2001
#    Added checks so we don't modify LD_LIBRARYN32_PATH (etc.) unless
#    they already exist.
#
#    Jeremy Meredith, Tue Sep  4 17:46:42 PDT 2001
#    Removed printing of the splashscreen launch command.
#
#    Jeremy Meredith, Mon Sep 10 18:30:33 PDT 2001
#    Added the "-norun" option to merely print the command it will use
#    to run, then exit nicely.  Multiple -norun options may be specified
#    any they should all be honored.  Note that one must specify either
#    'engine_ser' or 'engine_par', not just 'engine'.
#
#    Brad Whitlock, Fri Sep 14 16:32:03 PST 2001
#    Added flags that are useful for scripting.
#
#    Jeremy Meredith, Thu Apr 11 11:01:22 PDT 2002
#    Added a test for the mdserver's existence in addition to the given one.
#    This makes more things work on machines where we cannot build the GUI.
#
#    Jeremy Meredith, Tue Apr 16 11:41:12 PDT 2002
#    Added a few arguments to the help text.
#
#    Jeremy Meredith, Fri Jun 14 10:46:44 PDT 2002
#    Added line to set LIBPATH inside the psub script since LoadLever does
#    not pass it, even when PSUB is given the -x flag.  Removed the setting
#    of the display since that should be passed with the -x option, and we
#    shouldn't care about DISPLAY for the engine anyway.
#
#    Jeremy Meredith, Mon Jun 17 15:17:55 PDT 2002
#    Split linux into linux-intel and linux-alpha.  I did not split into
#    different vendors/kernel versions yet, but this can be done if needed.
#
#    Jeremy Meredith, Fri Jul  5 17:43:24 PDT 2002
#    Made it create a home ~/.visit directory to store user settings,
#    plugins, etc.  Made it append your home .visit/ARCH/plugins directory
#    to the VISITPLUGINDIR environment variable.
#
#    Jeremy Meredith, Tue Jul  9 17:40:47 PDT 2002
#    Made it avoid duplicates for the plugin search paths, and reversed
#    the order so private ones will override public ones.
#
#    Jeremy Meredith, Wed Jul 10 13:01:10 PDT 2002
#    Made the failure-to-launch messages a little smarter.
#
#    Jeremy Meredith, Mon Jul 15 01:09:12 PDT 2002
#    Made it set up a lot more things for generating makefiles for plugins.
#
#    Brad Whitlock, Mon Jul 15 09:58:49 PDT 2002
#    I made VISITHELPHOME point to the right place.
#
#    Jeremy Meredith, Thu Jul 18 12:27:26 PDT 2002
#    Added the -publicpluginsonly flag.  Added code to parse the version.
#    Added a check for versions prior to 0.9.12 to set the publiconly flag.
#    This check should be removed shortly after version 1.0.
#
#    Jeremy Meredith, Mon Jul 22 12:35:54 PDT 2002
#    Added silex.
#
#    Jeremy Meredith, Sat Aug  3 11:47:58 PDT 2002
#    Added all XML tools.
#
#    Brad Whitlock, Fri Aug 16 10:59:59 PDT 2002
#    Added the new xml2java XML tool.
#
#    Hank Childs, Mon Aug 26 15:20:39 PDT 2002
#    Removed support for -dir flag.  Intentionally left in help message for
#    -dir, since that may be used to determine what flags to put in the GUI.
#
#    Jeremy Meredith, Wed Sep 18 15:43:24 PDT 2002
#    Fixed a prun bug.  It should use "-n", not "-np", for the number of procs.
#
#    Jeremy Meredith, Fri Sep 20 09:27:31 PDT 2002
#    Added private database plugin support.
#    Added better support for sh/ksh users for psub.
#
#    Jeremy Meredith, Thu Oct 17 16:05:27 PDT 2002
#    Added XMLEdit, and put all xml tools into the help.
#
#    Sean Ahern, Tue Dec  3 09:54:55 PST 2002
#    Added -dump flag.
#
#    Brad Whitlock, Mon Dec 16 14:01:54 PST 2002
#    Added -verbose flag.
#
#    Jeremy Meredith, Thu Dec 19 12:08:08 PST 2002
#    Added support code for launching engines from the command line.
#
#    Hank Childs, Sun Dec 29 14:47:05 PST 2002
#    Added -text2polys flag.
#
#    Hank Childs, Mon Jan  6 07:50:37 PST 2003
#    Added -time_annotation flag.
#
#    Brad Whitlock, Thu Jan 2 12:43:25 PDT 2003
#    I added code to remove the -key argument from the printed arguments. I
#    also added support for debugging VisIt components with GDB. I also added
#    an -expedite flag so that the engine can be edpedited under DPCS.
#
#    Jeremy Meredith, Fri Jan 24 14:43:44 PST 2003
#    Added the ability to add arguments to the parallel launcher.
#
#    Sean Ahern, Thu Mar  6 00:57:10 PST 2003
#    Added support for debugging VisIt components with totalview.
#
#    Sean Ahern, Wed Mar 19 00:32:29 America/Los_Angeles 2003
#    Fixed gdb paths.
#
#    Jeremy Meredith, Wed Apr  9 12:52:53 PDT 2003
#    Made the list of plugin types be in exactly one spot.  This way things
#    like expression or query plugins will be easier to add.  Also improved
#    how home-directory .visit/* directories are created.
#
#    Jeremy Meredith, Sat Apr 12 13:43:21 PDT 2003
#    Added support for a "sub-launcher" using psub.  For example,
#    psub works in conjunction with prun/poe on Quadrics/IBM systems.
#
#    Jeremy Meredith, Mon Apr 14 15:33:45 PDT 2003
#    Made -launchengine default to localhost.
#
#    Eric Brugger, Wed Apr 16 10:58:16 PDT 2003
#    Set the LD_LIBRARY_PATH when submitting to batch.
#
#    Brad Whitlock, Thu Apr 24 07:31:07 PDT 2003
#    I prevented -v from being passed on as an argument to the visit
#    components since they now pass their internal version to other
#    components when they are launched.
#
#    Mark C. Miller, 01May03
#    Added -numrestarts option to viewer
#
#    Brad Whitlock, Thu May 15 13:53:09 PST 2003
#    Added support for MacOS X (Darwin).
#
#    Jeremy Meredith, Wed Apr  2 10:51:33 PST 2003
#    Added number of nodes to prun (needed by Q machine).
#
#    Jeremy Meredith, Mon May 19 17:31:33 PDT 2003
#    Added hack to allow version-passing for versions prior to 1.1.4
#    but since 1.0.  This should be removed when the oldest previous
#    version anyone will want to run is 1.1.4.
#
#    Brad Whitlock, Thu Jun 19 13:22:25 PST 2003
#    I removed splashscreen coding.
#
#    Jeremy Meredith, Thu Jun 26 10:05:12 PDT 2003
#    Added support for LANL's Q machine:  I added a hack to update
#    the user's paths.  I allowed the VCL to be launched in parallel.
#    I Added a parallel launcher ("-pl") argument.  It is much
#    like "-l", except it will only be triggered when launching the
#    engine.  I made the number of processors to be passed to the
#    parallel launcher only when the number of processors was actually
#    set.  I added support for "bsub" as a launcher.
#
#    Akira Haddox, Tue Jul  1 12:56:14 PDT 2003
#    Added the makemili tool.
#
#    Hank Childs, Wed Jul  2 11:40:48 PDT 2003
#    Added the surfcomp tool.
#
#    Jeremy Meredith, Thu Jul  3 15:10:36 PDT 2003
#    Added doc for "-nopty".  Made it stricter about when it will
#    allow non-private plugin installs.
#
#    Jeremy Meredith, Mon Jul  7 12:46:08 PDT 2003
#    They changed the path of "bsub" on Q, breaking things for the Q port.
#    I updated the path for the Q stuff to match it.
#
#    Jeremy Meredith, Thu Jul 24 15:58:45 PDT 2003
#    I added the ability to translate a known remotehost into a different
#    IP address.  This allows us to use the DISCOM pipes back to White from Q.
#
#    Brad Whitlock, Mon Jul 28 15:47:43 PST 2003
#    I added movie-making options.
#
#    Eric Brugger, Fri Aug  1 08:19:05 PDT 2003
#    I added back the splashscreen support so that the script would still
#    work with previous versions.
#
#    Eric Brugger, Mon Aug 25 16:47:04 PDT 2003
#    I corrected a bug in the logic that decided if the vcl should be
#    launched in the batch system.  The fix was actually made by Jeremy.
#
#    Hank Childs, Tue Sep  9 08:35:42 PDT 2003
#    Add 'convert' program.
#
#    Jeremy Meredith, Mon Sep 29 11:26:47 PDT 2003
#    Added help for the "-o" and "-launchengine" flags.
#
#    Brad Whitlock, Fri Oct 3 12:59:49 PDT 2003
#    I made the -s argument become -scriptfile when -movie is specified.
#
#    Jeremy Meredith, Thu Oct  9 13:12:51 PDT 2003
#    Added ability to guess remote client host name from SSH_CLIENT,
#    SSH2_CLIENT, or SSH_CONNECTION environment variables.
#    Added ia64 linux machine type.
#
#    Brad Whitlock, Thu Aug 21 14:34:42 PST 2003
#    Added support for MacOS X.
#
#    Jeremy Meredith, Thu Nov  6 10:59:45 PST 2003
#    Added fast pipe IP addresses for the SGI viz servers.
#
#    Jeremy Meredith, Thu Nov 13 12:01:20 PST 2003
#    Added srun (SLURM) launcher support.
#
#    Jeremy Meredith, Mon Nov 24 14:59:17 PST 2003
#    Added compression of ".." and stripping of "." dirs in the visit path.
#    Removed erroneous single quotes for the launcher args.
#
#    Jeremy Meredith, Tue Nov 25 10:50:40 PST 2003
#    Changed the help text for the -dir argument slightly.
#
#    Brad Whitlock, Fri Dec 5 11:44:32 PDT 2003
#    Added help for -sessionfile.
#
#    Eric Brugger, Tue Dec 23 10:15:11 PST 2003
#    Added support for logging usage.  It is off by default.
#
#    Brad Whitlock, Thu Jan 29 10:53:51 PDT 2004
#    Added support for Linux running on AMD Opteron 64 (x86_64).
#
#    Eric Brugger, Tue Mar 16 13:56:05 PST 2004
#    Added /usr/local/lib to LD_LIBRARY_PATH.
#
#    Jeremy Meredith, Tue Mar 23 14:21:57 PST 2004
#    Added better support for parallel engine arguments.  Instead of expecting
#    the viewer to pass them along, we concatenate them into a single
#    colon-delimited string and pass it as the argument to "-engineargs", which
#    is a new option the viewer can parse.
#
#    Jeremy Meredith, Fri Mar 26 09:21:08 PST 2004
#    Changed colons in engineargs to semicolons.
#
#    Jeremy Meredith, Tue Mar 30 09:42:51 PST 2004
#    I added support for a manual plugin installation destination.  Simply
#    set the VISITPLUGININST environment variable before running xml2makefile.
#
#    Jeremy Meredith, Thu Apr  1 16:11:43 PST 2004
#    Made the new parallel argument stuff backwards-compatible.
#
#    Brad Whitlock, Tue Apr 27 09:49:57 PDT 2004
#    I removed some obsolete MacOS X coding and I updated the GDB directories.
#
#    Hank Childs, Sun May  9 11:48:58 PDT 2004
#    Add a line to the usage regarding "default_format".
#
#    Eric Brugger, Thu Jun 24 11:12:44 PDT 2004
#    I modified the setting of the LD_LIBRARY_PATH so that /usr/local/lib
#    is at the end of the path instead of at the beginning.
#
#    Jeremy Meredith, Wed Aug 25 09:25:41 PDT 2004
#    Added help for "-timing".  Added the "-env" option.  Added 
#    "-h" and "--help" as valid arguments to priunt the help text.
#
#    Brad Whitlock, Fri Sep 24 11:03:03 PDT 2004
#    I made the xml2projectfile program be an option.
#
#    Mark C. Miller, Tue Oct  5 12:56:54 PDT 2004
#    Changed appearance of '-help' option. Added a '-fullhelp' option
#
#    Jeremy Meredith, Wed Oct 20 16:31:08 PDT 2004
#    Fixed security key for totalview.  Made "visit -env" print to 
#    stdout instead of stderr so it is easier to capture/redirect.
#
#    Jeremy Meredith, Tue Oct 26 22:11:23 PDT 2004
#    Added parallel sublauncher arguments.  Specifically needed for srun in
#    psub/srun because srun can't figure out the right number of processors.
#
#    Jeremy Meredith, Thu Dec  9 16:08:33 PST 2004
#    Moved this script over to legacy support only.  It will no longer
#    be used to launch development versions or new public versions.
#
###############################################################################


# -----------------------------------------------------------------------------
#                                 Setup
# -----------------------------------------------------------------------------


# Set a secure and reasonable path
$ENV{PATH} = join ':' , ("$ENV{PATH}","/bin","/usr/bin","/usr/sbin",
                         "/usr/local/bin", "/usr/bsd","/usr/ucb" );

# Determine OS and set architecture directory "archdir"

# set base directory
chomp( $progdir = `dirname $0` );
chomp( $cwd     = `pwd`        );

# Add the program directory to the path!
$ENV{PATH} = join ':' , ("$progdir", "$ENV{PATH}");

for ($progdir) {
    /^\//  && do { $tmpdir = $progdir; last; }; # starts with `/'
    /^\.$/ && do { $tmpdir = $cwd; last; };     # is exactly  `.'
    $tmpdir = "$cwd/$progdir";
}

# strip single . paths
while ($tmpdir =~ s|(/\./)|/|) {}

# compress out remaining /dir/.. forms
while ($tmpdir =~ s|(/[^/]+/\.\.)||) {}

# Note: the above ".."-compression is safe because we already determined we
# had an absolute path, we know the substitution goes left-to-right, and
# we cannot legally .. above the root of the directory tree.  If at some
# point these assumptions change, we can use the following line instead,
# which is more complex but makes sure not to compress out /../.. forms.
#while ($tmpdir =~ s@(/([^/.][^/]*|[^/]*[^/.]|[^/]{3,})/\.\.)@@) {}

chomp( $visitdir = `dirname $tmpdir` );

# setup the usage note about full help
$helpnote = "
    NOTE: For a more complete list of options, use '-fullhelp'.";

# Do the usage help text
$usage = "
    Interface options
    ---------------------------------------------------------------------------
        -gui                 Run with the Graphical User Interface (default).
        -cli                 Run with the Command Line Interface.

    Movie making options
    ---------------------------------------------------------------------------
        -mpeg_encode         Run the MPEG encoder support tool to produce an
			     mpeg file from a set of image files.
        -movie               Run the CLI in a movie making mode. Must be
                             combined with -sessionfile. Will produce a simple
			     movie by drawing all the plots in the specified
			     session for every timestep of the database.

    Startup options
    ---------------------------------------------------------------------------
        -o <filename>        Open the specified data file at startup.
        -s <filename>        Run the specified VisIt script. Note: This
                             argument only takes effect with -cli or -movie.
        -sessionfile <filename>  Open the specified session file at startup
                             Note that this argument only takes effect with
                             -gui or -movie.
        -config <filename>   Initialize the viewer at startup using the named
                             config file from your .visit directory.
        -noconfig            Don't process configuration files at startup.
        -launchengine <host> Launch an engine at startup. The <host> parameter
                             is optional. If it is not specified, the engine
                             will be launched on the local host. If you wish
                             to launch an engine on a remote host, specify 
                             the host's name as the <host> parameter.
	-nosplash            Do not display the splash screen at startup.

    Window options
    ---------------------------------------------------------------------------
        -small               Use a smaller desktop area/window size.
        -geometry <spec>     What portion of the screen to use.  This is a
                             standard X Windows geometry specification. This
                             option can be used to set the size of images
                             generated from scripts and movies.
        -style <style>       One of: windows,cde,motif,sgi.
        -background <color>  Background color for GUI.
        -foreground <color>  Foreground color for GUI.
        -nowin               Run with viewer windows off-screen (i.e. OSMesa).
			     This is typically used with the -cli option.

    Version options
    ---------------------------------------------------------------------------
	-version             Do NOT run VisIt. Just print the current version.
        -beta                Run the current beta version.
        -v <version>         Run a specified version (e.g. '1.3.3').

    Other resources for help
    ---------------------------------------------------------------------------
        run-time:            While running VisIt, look under the \"Help\" menu.
        on-line:             http://www.llnl.gov/visit
        email:               visit-help\@llnl.gov
";

# Do the full usage help text
$fullusage = "$usage

    ***************************************************************************
                              ADDITIONAL OPTIONS
    ***************************************************************************

    Other VisIt tools
    ---------------------------------------------------------------------------
        -silex               Run the Silo Explorer tool. 
        -convert             Run a database conversion tool that converts files
                             from format A to format B.
        -makemili            Run the .mili file generator.
        -surfcomp            Run the surface-compare tool.
        -text2polys          Run a tool to generate polygons from text data.
        -time_annotation     Run the time annotation tool for creating a
                             graphical annotation for position in time.

    Parallel launch options
    ---------------------------------------------------------------------------
        Notes: All of these options are ordinarily obtained from host profiles.
	However, the command line options override anything in the profiles. 

	When parallel arguments are added but the engine is not the
        component being launched, -launchengine is implied.  Explicitly
        add -launchengine to launch a remote parallel engine.
    ---------------------------------------------------------------------------
        -par                 Run the parallel version. This option is implied
                             by any of the other parallel options listed below.
        -l    <method>       Launch in parallel using the given method.
        -pl   <method>       Launch only the engine in parallel as specified.
        -la   <args>         Additional arguments for the parallel launcher.
        -np   <# procs>      The number of processors to use.
        -nn   <# nodes>      The number of nodes to allocate.
        -p    <part>         Partition to run in.
        -n    <name>         The parallel job name.
        -b    <bank>         Bank from which to draw resources.
        -t    <time>         Maximum job run time.
        -expedite            Makes DPCS give priority scheduling.

    Load balance options
    ---------------------------------------------------------------------------
	Note: Each time VisIt executes a pipeline the relevant domains for the
	execution are assigned to processors. This list of domains is sorted in
	increasing global domain number. The options below effect how domains
	in this list are assigned to processors. Assuming there are D domains
	and P processors...
    ---------------------------------------------------------------------------
        -lb-block            Assign the first D/P domains to processor 0, the
                             next D/P domains to processor 1, etc.
        -lb-stride           Assign every Pth domain starting from the first
                             to processor 0, every Pth domain starting from the
                             second to processor 1, etc.
        -lb-random           Randomly assign domains to processors.

    Advanced options
    ---------------------------------------------------------------------------
        -guesshost           Try to guess the client host name from one of
                             the SSH_CLIENT, SSH2_CLIENT, or SSH_CONNECTION
                             environment variables.
        -noint               Disable interruption capability.
        -nopty               Run without PTYs.
        -verbose             Prints status information during pipeline
                             execution.
        -default_format      Sets the database plugin format to use as a
			     default if a file type cannot be determined
			     from its extension.
        -dir <directory>     Run a version of VisIt in the specified directory.
                             The directory argument should specify the 
                             path to a visit installation directory.
                             /bin is automatically appended to this path.
        -publicpluginsonly   Disable all plugins but the default ones.

    Developer options
    ---------------------------------------------------------------------------
        -xmledit             Run the XML plugin editor
        -xml2plugin          Run the XML plugin generator
        -xmltest             Run the XML plugin tester
        -xml2atts            Run the XML plugin attribute generator
        -xml2avt             Run the XML plugin AVT generator
        -xml2info            Run the XML plugin dynamic info generator
        -xml2makefile        Run the XML plugin Makefile generator
        -xml2python          Run the XML plugin Python generator
        -xml2window          Run the XML plugin GUI window generator
        -xml2java            Run the XML plugin Java generator
        -public              xml2makefile: force install plugins publicly
        -private             xml2makefile: force install plugins privately
        -clobber             Permit xml2... tools to overwrite old files
        -noprint             do not print any debugging output

    Debugging options
    ---------------------------------------------------------------------------
        Note: Debugging options may degrade performance 
    ---------------------------------------------------------------------------
        -debug <level>       Run with <level> levels of output logging.
                             <level> must be between 1 and 5.
	-pid                 Append process ids to the names of log files.
        -timing              Save timing data to files.
        -env                 Print env. variables VisIt will use when run.
	-dump                Dump intermediate results from AVT filters.
        -gdb                 Run under gdb.
        -gdb-gui             Run the gui under gdb.
        -gdb-cli             Run the cli under gdb.
        -gdb-viewer          Run the viewer under gdb.
        -gdb-engine          Run the engine under gdb.
        -gdb-mdserver        Run the mdserver under gdb.
        -break <funcname>    Add the specified breakpoint in gdb.
        -xterm               Run gdb in an xterm window.
        -totalview <comp>    Run totalview on the given component.
        -numrestarts <#>     Number of attempts to restart a failed engine.
";

# Get our location
chomp($host   = `hostname`);
($node)       = split /\./,$host;
($sector      = $node) =~ tr/[0-9]//d;


# -----------------------------------------------------------------------------
#                            Parse the arguments
# -----------------------------------------------------------------------------

# Set some defaults.
$exe_name     = "gui";
$parallel     = 0;
$launch       = "";
@launchargs   = ();
$want_version = 0;
$ver          = "";
$beta         = 0;
@norun        = ();
$publiconly   = 0;
$launchengine = "";
@breakpoints  = ();
$debug_gdb    = 0;
$debug_totalview = "";
$add_movie_args = 0;
$envonly        = 0;
$logging        = 0;

# Parse the arguments 
@visitargs = ();
while (scalar(@ARGV) > 0) {
    $arg = shift @ARGV;
    if    ($arg eq "-par" || $arg eq "-parallel")  { $parallel = 1; }
    elsif ($arg eq "-np")        { $procs= shift; $procs_set= 1; $parallel = 1; }
    elsif ($arg eq "-nn")        { $nodes= shift; $nodes_set= 1; }
    elsif ($arg eq "-l")         { $launch=shift; $launch_set=1; }
    elsif ($arg eq "-pl")        { $parlaunch=shift; $parlaunch_set=1; }
    elsif ($arg eq "-la")        { $_=shift; @launchargs=split; $launchargs_set=1; }
    elsif ($arg eq "-n" )        { $name = shift; $name_set = 1; }
    elsif ($arg eq "-p" )        { $part = shift; $part_set = 1; }
    elsif ($arg eq "-b" )        { $bank = shift; $bank_set = 1; }
    elsif ($arg eq "-t")         { $time = shift; $time_set = 1; }
    elsif ($arg eq "-v" )        { $ver  = shift; $ver_set  = 1; }
    elsif ($arg eq "-expedite")  { if($exe_name eq "engine") { $expedite_engine = 1;} else { push @visitargs, $arg; }}
    elsif ($arg eq "-host")      { $remotehost = shift; $remotehost_set = 1; }
    elsif ($arg eq "-beta")      { $beta = 1; push @visitargs,$arg;}
    elsif ($arg eq "-key" )      { $security_key = shift; $security_key_set = 1;}
    elsif ($arg eq "-viewer" )   { $exe_name = "viewer"; }
    elsif ($arg eq "-gui" )             { $exe_name = "gui"; }
    elsif ($arg eq "-cli" )             { $exe_name = "cli"; }
    elsif ($arg eq "-splashscreen" )    { $exe_name = "splashscreen"; }
    elsif ($arg eq "-mdserver" )        { $exe_name = "mdserver"; }
    elsif ($arg eq "-engine" )          { $exe_name = "engine"; }
    elsif ($arg eq "-vcl" )             { $exe_name = "vcl"; }
    elsif ($arg eq "-xml2atts")         { $exe_name = "xml2atts"; }
    elsif ($arg eq "-xml2avt")          { $exe_name = "xml2avt"; }
    elsif ($arg eq "-xml2info")         { $exe_name = "xml2info"; }
    elsif ($arg eq "-xml2makefile")     { $exe_name = "xml2makefile"; }
    elsif ($arg eq "-xml2projectfile")  { $exe_name = "xml2projectfile"; }
    elsif ($arg eq "-xml2plugin")       { $exe_name = "xml2plugin"; }
    elsif ($arg eq "-xml2python")       { $exe_name = "xml2python"; }
    elsif ($arg eq "-xml2window")       { $exe_name = "xml2window"; }
    elsif ($arg eq "-xml2java")         { $exe_name = "xml2java"; }
    elsif ($arg eq "-xmltest")          { $exe_name = "xmltest"; }
    elsif ($arg eq "-xmledit")          { $exe_name = "xmledit"; }
    elsif ($arg eq "-makemili" )        { $exe_name = "makemili"; }
    elsif ($arg eq "-convert" )         { $exe_name = "convert"; }
    elsif ($arg eq "-silex" )           { $exe_name = "silex"; }
    elsif ($arg eq "-surfcomp" )        { $exe_name = "surfcomp"; }
    elsif ($arg eq "-text2polys" )      { $exe_name = "text2polys"; }
    elsif ($arg eq "-time_annotation" ) { $exe_name = "time_annotation"; }
    elsif ($arg eq "-mpeg_encode" )     { $exe_name = "mpeg_encode"; }
    elsif ($arg eq "-movie" )           { $exe_name = "cli"; $add_movie_args = 1; }
    elsif ($arg eq "-s")                { if($add_movie_args) { $sfile = shift; push @visitargs, "-scriptfile", $sfile;} else { push @visitargs, $arg;}}
    elsif ($arg eq "-publicpluginsonly"){ $publiconly = 1; push @visitargs, $arg; }
    elsif ($arg eq "-version")   { $want_version = 1; }
    elsif ($arg eq "-help")      { print STDERR "\nUSAGE: visit [options]
				   $helpnote\n $usage\n"; exit(0); }
    elsif ($arg eq "-h")         { print STDERR "\nUSAGE: visit [options]
				   $helpnote\n $usage\n"; exit(0); }
    elsif ($arg eq "--help")     { print STDERR "\nUSAGE: visit [options]
				   $helpnote\n $usage\n"; exit(0); }
    elsif ($arg eq "-fullhelp")  { print STDERR "\nUSAGE: visit [options]
				   $fullusage\n"; exit(0); }
    elsif ($arg eq "--fullhelp") { print STDERR "\nUSAGE: visit [options]
				   $fullusage\n"; exit(0); }
    elsif ($arg eq "-norun")     { $nr = shift; push @norun, $nr; push @visitargs, "-norun", $nr; }
    elsif ($arg eq "-env")              { $envonly = 1; }
    elsif ($arg eq "-launchengine")     { if (scalar(@ARGV)>0) {$launchengine = shift;}
                                          if ($launchengine eq "") { $launchengine="localhost"; }
                                          elsif ($launchengine =~ /^-/) { unshift @ARGV, $launchengine; $launchengine = "localhost";}}
    elsif ($arg eq "-gdb")              { $debug_gdb = 1; $gdb_xterm = 1;}
    elsif ($arg eq "-gdb-gui")          { if($exe_name eq "gui") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-gdb-cli")          { if($exe_name eq "cli") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-gdb-viewer")       { if($exe_name eq "viewer") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-gdb-engine")       { if($exe_name eq "engine") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-gdb-mdserver")     { if($exe_name eq "mdserver") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-gdb-vcl")          { if($exe_name eq "vcl") {$debug_gdb = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-xterm")            { if($debug_gdb) {$gdb_xterm = 1;} else {push @visitargs, $arg;}}
    elsif ($arg eq "-break")            { if($debug_gdb) {$bp = shift; push @breakpoints, $bp; } else {push @visitargs, $arg;}}
    elsif ($arg eq "-totalview" )       {
                                          $debug_totalview = shift;
                                          push @norun, $debug_totalview;
                                          push @visitargs, "-norun", $debug_totalview;
                                          if ($exe_name ne $debug_totalview)
                                          {
                                            push @visitargs, "-totalview", $debug_totalview;
                                          }
                                        }
    elsif ($arg eq "-guesshost" )       { $guesshost=1; }
    else                         { push @visitargs, $arg; }
}

if ($guesshost)
{
    if ($ENV{SSH_CLIENT})
    {
        ($remotehost) = split /\s/, $ENV{SSH_CLIENT};
        $remotehost_set = 1;
    }
    elsif ($ENV{SSH2_CLIENT})
    {
        ($remotehost) = split /\s/, $ENV{SSH2_CLIENT};
        $remotehost_set = 1;
    }
    elsif ($ENV{SSH_CONNECTION})
    {
        ($remotehost) = split /\s/, $ENV{SSH_CONNECTION};
        $remotehost_set = 1;
    }
    else
    {
        print STDERR "Error: -guesshost was specified, but it was\n".
                     "unable to parse the SSH_CLIENT/CONNECTION\n".
                     "environment variable to get a valid host name\n";
        exit 1;
    }
}

# ----
#  TEMPORARY HACK:
#  for versions prior to 1.1.4, we need to pass the version info
#  on the command line ourselves.
#
#  As soon as version 1.1.4 is liable to be the oldest one run,
#  we should remove this.
# ----
if ($ver_set)
{
    if ($ver =~ /^1\.(\d)$/)
    {
        $minor = $1;
        if ($minor <= 1)
        {
            push @visitargs, "-v", $ver;
        }
    }
    elsif ($ver =~ /^1\.(\d)\.(\d)$/)
    {
        $minor = $1;
        $tiny  = $2;
        if (($minor < 1) or
            ($minor == 1 and $tiny < 4))
        {
            push @visitargs, "-v", $ver;
        }
    }
}

# ----
#  HACK for LANL's Q machine:
#
#  If we're on LANL's Q machine, then we need to make sure BSUB is in our
#  path and that libstdc++ and libmpi are in our library path.
# ----
if ($host =~ /^q\d+$/ || $host =~ /^qfe\d$/)
{
    # These are the DISCOM pipes to White from Q.  Four per login node;
    # choose one at random.
    $interface = int(rand(4)+1);
    $remotehost = "172.16.$interface.1"    if ($remotehost =~ /^white128/);
    $remotehost = "172.16.$interface.5"    if ($remotehost =~ /^white129/);
    $remotehost = "172.16.$interface.9"    if ($remotehost =~ /^white269/);
    $remotehost = "172.16.$interface.13"   if ($remotehost =~ /^white432/);

    $ENV{PATH} = join ':' , ("$ENV{PATH}","/lsf/bin");
    $ENV{LD_LIBRARY_PATH} = join ':' ,
                         ("$ENV{LD_LIBRARY_PATH}",
                          "/usr/local/gnu/packages/gcc-3.0.4/lib",
                          "/lsfdir/Q_CD/4.2/alpha5-rms/lib",
                          "/usr/local/opt/Compaq_MPI_64_2.5UK1_r1/usr/shlib");
}

# ----
#  HACK to default fast connections from white to tidalwave:
#
#  If we're on white trying to connect back to tidalwave, use one of the
#  jumbo gig-E paths back to tidalwave.
# ----
if ($host =~ /^white\d+.asci.llnl.gov$/)
{
    # As above, four pipes per machine, choose one at random
    $interface = int(rand(4)+1);
    $remotehost = "172.16.$interface.53" if ($remotehost =~ /^tidalwave/);
    $remotehost = "172.16.$interface.54" if ($remotehost =~ /^whitecap/);
    $remotehost = "172.16.$interface.57" if ($remotehost =~ /^edgewater/);
}

# ----
#  HACK to allow other talk-back interfaces
#
#  We stripped off the "host" argument above, so put it back here.
#  (This allowed us to change it if needed, e.g. for Q)
#  VisIt seems to need the -host argument before the -nread and -nwrite
#  values, so when we put it back, put it at the beginning.
# ----
if ($remotehost_set)
{
    unshift @visitargs, $remotehost;
    unshift @visitargs, "-host";
}


# -----------------------------------------------------------------------------
#                               Check for errors
# -----------------------------------------------------------------------------

if ((!$procs_set) and ($name_set or $part_set or $bank_set or
                       $time_set or $part_set or $nodes_set))
{
    print STDERR "You specified a parallel argument without using -np to specify\n".
                 "the number of processors.  Please add an -np argument.\n";
    print STDERR $usage;
    exit 1;
}

if (($procs_set) and ($procs < 1))
{
    print STDERR "You must specify more at least one processor to execute a parallel Visit engine.\n".
                 "You specified \"$procs\" processor(s).\n";
    exit 1;
}

@engine_parallel_args = ();
$had_to_strip_parallel_args = 0;
if ((($parallel) or ($launchengine)) and
    ($exe_name ne "engine") and
    (($exe_name ne "vcl") or (!$parlaunch_set)))
{
    $had_to_strip_parallel_args = 1;
    # If we're trying to run in parallel, or we've been explicitly
    # told to launch an engine, add any parallel arguments back on
    push @engine_parallel_args, "-par"                   if ($parallel && !$procs_set);
    push @engine_parallel_args, "-l",  $launch           if ($launch_set);
    push @engine_parallel_args, "-la", "@launchargs"     if ($launchargs_set);
    push @engine_parallel_args, "-np", $procs            if ($procs_set);
    push @engine_parallel_args, "-nn", $nodes            if ($nodes_set);
    push @engine_parallel_args, "-n",  $name             if ($name_set);
    push @engine_parallel_args, "-p",  $part             if ($part_set);
    push @engine_parallel_args, "-b",  $bank             if ($bank_set);
    push @engine_parallel_args, "-t",  $time             if ($time_set);

    # ... but don't confuse the script
    $parallel=0;
    $launchargs_set=0;
    $procs_set=0;
    $name_set=0;
    $part_set=0;
    $bank_set=0;
    $time_set=0;
    $nodes_set=0;

    #
    # The makemili and convert tool needs these parallel arguments, but to not
    # confuse the script, we turn off the parallel flag. So we
    # translate the executable name here.
    #
    if (($exe_name eq "makemili") or ($exe_name eq "convert"))
    {
        $exe_name .= "_par";
    }
    else
    {
        # If we didn't specify a location for the engine, assume localhost.
        push @visitargs, "-launchengine", "localhost"   if (!$launchengine);
        push @visitargs, "-launchengine", $launchengine if ($launchengine);
    }
}

# -----------------------------------------------------------------------------
#                         Determine the architecture
# -----------------------------------------------------------------------------

$archdir = "unsupported";
chomp( $os = `uname -s` );
$os =~ tr/[A-Z]/[a-z]/;
for ($os) {
    /irix/ && do {
        $version = `uname -r`;
        $version =~ s/(^[6])\..*/irix$1/ ;
        for ($version) {
            /irix6/ && do {
                $archdir = "sgi-irix6-mips2";
                last;
            };
        }
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /sunos/ && do {
        chomp( $mach    = `uname -m` );
        chomp( $version = `uname -r` );
        $version =~ s/([45])\..*/sunos$1/ ;
        if ($mach =~ /^sun4/) {
            $archdir = "sun4-$version-sparc";
        }
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /hp-ux/ && do {
        if (`uname -m` =~ /9000\/[78]/) {
            $archdir = "hp-hpux-pa";
        }
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /aix/ && do {
        $archdir = "ibm-aix-pwr";
        $launch = "poe" if ($procs_set && $launch eq "");
        last;
    };
    /osf/ && do {
        $archdir = "dec-osf1-alpha";
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /linux/ && do {
        chomp( $mach    = `uname -m` );
        if ($mach =~ /alpha/) {
            $archdir = "linux-alpha";
        }
        elsif ($mach =~ /ia64/) {
            $archdir = "linux-ia64";
        }
        elsif ($mach =~ /x86_64/) {
            $archdir = "linux-x86_64";
        }
        else {
            $archdir = "linux-intel";
        }
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /darwin/ && do {
        $archdir = "darwin-ppc";
        $launch = "mpirun" if ($procs_set && $launch eq "");
        last;
    };
    /tflops/ && do {
        $archdir = "intel-tflops-ppro";
        $launch = "yod" if ($procs_set && $launch eq "");
        last;
    };
}

if ($archdir eq "unsupported")
{
    print STDERR <<"EOF";
This hardware platform is not supported by VisIt.
EOF
    exit 1;
}

# Set any unfinished defaults
if (!$part_set && (substr($launch,0,4) eq "psub"))
{
    # Set a reasonable partition for psub assuming the IBM SP environment
    $part = "pbatch,$sector";
    $part_set = 1;
}

# -----------------------------------------------------------------------------
#                             Determine versions
# -----------------------------------------------------------------------------

# If we still think the exe_name is makemili or convert, we're not running 
# in parallel.
if (($exe_name eq "makemili") or ($exe_name eq "convert"))
{
    $exe_name .= "_ser" if (!$parallel);
}

# Determine the version number of the executable.
if ($exe_name eq "engine")
{
    $exe_name .= "_ser" if (!$parallel);
    $exe_name .= "_par" if ($parallel);

    # if we've designated a parallel launcher, then we are sharing
    # one batch job between the mdserver and engine (through the vcl)
    # so: if we're launching a parallel engine with -pl specified, then
    # make the real launcher the parallel launcher
    if ($parallel and $parlaunch_set)
    {
        $launch = $parlaunch;
    }
}

#
# We KNOW we're running a public version, because this script is now
# only for legacy support of older versions.  It cannot be used within
# any new builds.
#
if (1)
{
    @exe = <$visitdir/*/$archdir/bin/$exe_name>;
    @exeversions = map {m|^$visitdir/(.*?)/|; $_ = $1;} @exe;
    $current_version = readlink("$visitdir/current");
    $beta_version    = readlink("$visitdir/beta");

    if ($want_version)
    {
        if (! defined $current_version)
        {
            print STDERR "There is no current version of VisIt.\n";
            exit 1;
        }

        print STDERR "The latest version of VisIt installed on this ".
                     "platform is $current_version.\n";
        exit 0;
    }

    if (! $ver_set)
    {
        if ($beta)
        {
            if (! defined $beta_version)
            {
                print STDERR "There is no beta version of VisIt.\n";
                exit 1;
            }
            $ver = $beta_version;
        }
        else
        {
            if (! defined $current_version)
            {
                print STDERR "There is no current version of VisIt.\n";
                exit 1;
            }

            $ver = $current_version;
        }
    }

    if ($ver_set && ! grep /$ver/, @exeversions)
    {
        print STDERR "Version $ver of '$exe_name' does not exist.\n";
        if ($exe_name eq "engine_par")
        {
            print STDERR "Note that the serial engine may still work.\n";
        }
        exit 1;
    }

    $visitdir     = "$visitdir/$ver";
    $visitarchdir = "$visitdir/$archdir";
    $visitbindir  = "$visitdir/$archdir/bin";
    if($os eq "darwin" and ($exe_name eq "gui" or $exe_name eq "viewer" or $exe_name eq "xmledit" or $exe_name eq "silex"))
    {
        $visitbindir = "$visitbindir/$exe_name.app/Contents/MacOS";
    }
    $visitlibdir  = "$visitdir/$archdir/lib";
    $visithelpdir = "$visitdir/$archdir/help";
    $visitplugins = "$visitdir/$archdir/plugins";
    $publicversion = 1;

    # Parse the version
    if (grep /^\d+\.\d+$/, $ver)
    {
        ($ver_major = $ver) =~ s/^(\d+)\.\d+$/$1/;
        ($ver_minor = $ver) =~ s/^\d+\.(\d+)$/$1/;
        ($ver_tiny  = 0);
        ($ver_beta  = 0);
    }
    elsif (grep /^\d+\.\d+\.\d+$/, $ver)
    {
        ($ver_major = $ver) =~ s/^(\d+)\.\d+\.\d+$/$1/;
        ($ver_minor = $ver) =~ s/^\d+\.(\d+)\.\d+$/$1/;
        ($ver_tiny  = $ver) =~ s/^\d+\.\d+\.(\d+)$/$1/;
        ($ver_beta  = 0);
    }
    elsif (grep /^\d+\.\d+b\d+$/, $ver)
    {
        ($ver_major = $ver) =~ s/^(\d+)\.\d+b\d+$/$1/;
        ($ver_minor = $ver) =~ s/^\d+\.(\d+)b\d+$/$1/;
        ($ver_tiny  = 0);
        ($ver_beta  = $ver) =~ s/^\d+\.\d+b(\d+)$/$1/;
    }
    elsif (grep /^\d+\.\d+\.\d+b\d+$/, $ver)
    {
        ($ver_major = $ver) =~ s/^(\d+)\.\d+\.\d+b\d+$/$1/;
        ($ver_minor = $ver) =~ s/^\d+\.(\d+)\.\d+b\d+$/$1/;
        ($ver_tiny  = $ver) =~ s/^\d+\.\d+\.(\d+)b\d+$/$1/;
        ($ver_beta  = $ver) =~ s/^\d+\.\d+\.\d+b(\d+)$/$1/;
    }
}

if ($had_to_strip_parallel_args)
{
    if ($ver_major == 1 and $ver_minor < 3)
    {
        if (scalar(@engine_parallel_args) > 0)
        {
            push @visitargs, @engine_parallel_args;
        }
    }
    else
    {
        if (scalar(@engine_parallel_args) > 0)
        {
            $engine_arg_string = ";".join(';', @engine_parallel_args);
            push @visitargs, "-engineargs", $engine_arg_string;
        }
    }
}


# Confirm we have found some version
$msg = "";
if (! -e "$visitbindir/$exe_name")
{
    $msg = "parallel " if ($parallel);
    print STDERR <<"EOF";
No versions of ${msg}VisIt have been installed for this hardware platform.
EOF
    exit 1;
}

# Add the movie script to the arguments.
if($add_movie_args)
{
    push @visitargs, "-s", "$visitbindir/makemovie.py", "-nowin";
}

# -----------------------------------------------------------------------------
#                   Set up the plugin/shared library environment
# -----------------------------------------------------------------------------

@plugincategories = ("plots", "operators", "databases");


# Make sure there is a .visit directory in the user's home directory
# and that it includes all current plugin types.
if (defined($ENV{HOME}))
{
    $makedir  = "$ENV{HOME}/.visit";  mkdir $makedir, 0777 if (! -e $makedir);
    $makedir .= "/$archdir";          mkdir $makedir, 0777 if (! -e $makedir);
    $makedir .= "/plugins";           mkdir $makedir, 0777 if (! -e $makedir);

    foreach (@plugincategories)
    {
        mkdir "$makedir/$_", 0777 if (! -e $makefir);
    }
}

# Set up stuff for shared libraries for various platforms
$ENV{LD_LIBRARY_PATH}    = "$visitlibdir:$ENV{LD_LIBRARY_PATH}";
$ENV{LD_LIBRARY32_PATH}  = "$visitlibdir:$ENV{LD_LIBRARY32_PATH}";
$ENV{LD_LIBRARYN32_PATH} = "$visitlibdir:$ENV{LD_LIBRARYN32_PATH}";
$ENV{LD_LIBRARY64_PATH}  = "$visitlibdir:$ENV{LD_LIBRARY64_PATH}";
$ENV{LIBPATH}            = "$visitlibdir:$ENV{LIBPATH}";

# Add /usr/local/lib to the shared library path.  This was added for the
# c++ library on some sun systems, but it may have broader applicability.
$ENV{LD_LIBRARY_PATH}    = "$ENV{LD_LIBRARY_PATH}:/usr/local/lib";

# Set up some environment flags that let VisIt run on Darwin.
if($os eq "darwin")
{
    $ENV{DYLD_LIBRARY_PATH}   = "$visitlibdir:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries:$ENV{DYLD_LIBRARY_PATH}";
}

# Set up plugin search paths in the correct order
$visitprivateplugins = "$ENV{HOME}/.visit/$archdir/plugins";
if ($publiconly)
{
    # Forget the private and user-specified paths, and only use the public one
    $ENV{VISITPLUGINDIR}="$visitplugins";
}
elsif (!grep /$visitprivateplugins/, $ENV{VISITPLUGINDIR})
{
    # Don't keep adding the same paths over and over again (avoid duplicates)
    $ENV{VISITPLUGINDIR}="$ENV{VISITPLUGINDIR}:$visitprivateplugins:$visitplugins";
}


# If we are using a public version, or if any main plugin directory is
# not writeable, then we should default to a private plugin installation.
$ENV{VISITPLUGININSTPUB}="$visitplugins";
$ENV{VISITPLUGININSTPRI}="$visitprivateplugins";

# Only set up the default installation path if needed
if (!defined($ENV{VISITPLUGININST}))
{
    $shouldinstallprivate = $publicversion;
    foreach (@plugincategories)
    {
        $shouldinstallprivate=1  if (! -w "$visitplugins/$_");
    }

    if ($shouldinstallprivate)
    {
        $ENV{VISITPLUGININST}="$visitprivateplugins";
    }
    else
    {
        $ENV{VISITPLUGININST}="$visitplugins";
    }
}

# Set required environment variables
$ENV{VISITHOME}     = "$visitdir";
$ENV{VISITARCHHOME} = "$visitarchdir";
$ENV{VISITHELPHOME} = "$visithelpdir";
$ENV{PYTHONHOME}    = "$visitlibdir/python";

# Turn off trapping of floating point exceptions.
$ENV{TRAP_FPE} = "";

# Turn off a warning message when running on Linux systems displaying
# to a remote display.  The message messes up the communication between
# the GUI and Viewer.
$ENV{MESA_GLX_FX} = disable;


# If logging is true and we are running the mdserver, then add usage
# information to the log file.
if ($logging and $exe_name eq "mdserver")
{
    chomp ( $user_info = `whoami` );
    chomp ( $host_info = `hostname` );
    chomp ( $date_info = `date` );
    $info = "$user_info"." "."$host_info"." "."$date_info"."\n";

    $filename=">>$visitdir/usagelog";
    open(USERINFO, $filename);
    print USERINFO "$info";
    close(USERINFO);
}

# -----------------------------------------------------------------------------
#                                   Run it!
# -----------------------------------------------------------------------------

if ($envonly)
{
    PrintEnvironment();
    exit(0);
}

@visitcmd = ("$visitbindir/$exe_name", @visitargs);
$printonly = grep(/^$exe_name$/, @norun) unless ($debug_totalview);

if ($procs_set or ($parallel and $parlaunch_set))
{
    # mpirun
    if ($launch eq "mpirun")
    {
        @parcmd = ("mpirun");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-np", $procs if $procs_set;
        push @parcmd, "-p",  $part  if $part_set;
        push @parcmd, @visitcmd;

        @printcmd = @parcmd;
        if ($security_key_set) { push @parcmd, "-key", $security_key; }
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    # dmpirun
    elsif ($launch eq "dmpirun")
    {
        @parcmd = ("dmpirun");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-np", $procs if $procs_set;
        push @parcmd, "-p",  $part  if $part_set;
        push @parcmd, @visitcmd;

        @printcmd = @parcmd;
        if ($security_key_set) { push @parcmd, "-key", $security_key; }
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    # poe
    elsif ($launch eq "poe")
    {
        @parcmd = @visitcmd;
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-procs",  $procs if $procs_set;
        push @parcmd, "-nodes",  $nodes if $nodes_set;
        push @parcmd, "-rmpool", $part  if $part_set;

        @printcmd = @parcmd;
        if ($security_key_set) { push @parcmd, "-key", $security_key; }
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    # prun
    elsif ($launch eq "prun")
    {
        @parcmd = ("prun");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-n",  $procs if $procs_set;
        push @parcmd, "-N",  $nodes if $nodes_set;
        push @parcmd, "-p",  $part  if $part_set;
        push @parcmd, @visitcmd;

        @printcmd = @parcmd;
        if ($security_key_set) { push @parcmd, "-key", $security_key; }
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    # srun
    elsif (substr($launch,0,4) eq "srun")
    {
        @parcmd = ("srun");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-n",  $procs if $procs_set;
        push @parcmd, "-N",  $nodes if $nodes_set;
        push @parcmd, "-J",  $name  if $name_set;
        push @parcmd, "-p",  $part  if $part_set;
        push @parcmd, "-t",  $time  if $time_set;
        #push @parcmd, "-b";  # Could be used for "batch mode"
        push @parcmd, @visitcmd;

        @printcmd = @parcmd;
        if ($security_key_set) { push @parcmd, "-key", $security_key; }
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    # psub
    elsif (substr($launch,0,4) eq "psub")
    {
        ($psubcmd, $sublauncher) = split /\W+/, substr($launch,4);
        $sublauncher = "" if (!defined $sublauncher);
	if ($sublauncher eq "srun" and $procs_set)
        {
            $sublauncherargs = "-n $procs";
        }

        if (grep(/csh/, "$ENV{SHELL}"))
        {
            $libpathcmd="setenv LIBPATH $ENV{LIBPATH} ; setenv LD_LIBRARY_PATH $ENV{LIBPATH}";
        }
        else
        {
            $libpathcmd="LIBPATH=$ENV{LIBPATH} ; export LIBPATH ; LD_LIBRARY_PATH=$ENV{LIBPATH} ; export LD_LIBRARY_PATH";
        }
        if ($security_key_set) { push @visitcmd, "-key", $security_key; }
        @parcmd = ("psub");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-x";
        push @parcmd, "-g",  $procs if $procs_set;
        push @parcmd, "-ln", $nodes if $nodes_set;
        push @parcmd, "-r",  $name  if $name_set;
        push @parcmd, "-c",  $part  if $part_set;
        push @parcmd, "-b",  $bank  if $bank_set;
        push @parcmd, "-tM", $time  if $time_set;
        push @parcmd, "-expedite"   if $expedite_engine;
        push @parcmd, "-i", "cd $cwd ; $libpathcmd ; ".
                            " $sublauncher $sublauncherargs @visitcmd";
        @printcmd = @parcmd;
        push @printcmd, ("\"".(pop @printcmd)."\"");
    }
    # bsub
    elsif (substr($launch,0,4) eq "bsub")
    {
        ($bsubcmd, $sublauncher) = split /\W+/, substr($launch,4);
        $sublauncher = "" if (!defined $sublauncher);
        if ($security_key_set) { push @visitcmd, "-key", $security_key; }
        @parcmd = ("bsub");
        push @parcmd, "-I";
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-n",  $procs if $procs_set;
        push @parcmd, "-q",  $part  if $part_set;
        push @parcmd, "-W" , $time  if $time_set;
        push @parcmd, $sublauncher;
        push @parcmd, @visitcmd;
        @printcmd = @parcmd;
        push @printcmd, ("\"".(pop @printcmd)."\"");
    }
    # yod
    elsif ($launch eq "yod")
    {
        @parcmd = ("/cougar/bin/yod");
        push @parcmd, @launchargs if $launchargs_set;
        push @parcmd, "-sz", $procs if $procs_set;
        push @parcmd, @visitcmd;

        @printcmd = @parcmd;
        chomp($printcmd[0] = `basename $printcmd[0]`);
    }
    else
    {
        print STDERR "Attempted an unsupported launch method (\"$launch\").\n";
        exit 1;
    }

    if ($printonly)
    {
        print STDERR "RUN USING: @parcmd\n\n";
        PrintEnvironment();
        exit 0;
    }
    else
    {
        print STDERR "Running: @printcmd\n";
        exec @parcmd or die "Can't launch using $launch: $!\n";
    }
}
else
{
    if ($printonly)
    {
        if ($security_key_set) { push @visitcmd, "-key", $security_key; }
        print STDERR "RUN USING: @visitcmd\n\n";
        PrintEnvironment();
        exit 0;
    }
    elsif ($debug_totalview eq $exe_name)
    {
        # Run totalview
        @debugcmd = ("totalview", $exe_name, "-a", "-dograb", @visitargs);
        if ($security_key_set) { push @debugcmd, "-key", $security_key; }
        print STDERR "Running: @debugcmd\n";
        $exec_totalview_failed = 0;
        exec @debugcmd or $exec_totalview_failed = 1;
    }
    elsif ($debug_gdb)
    {
        # Determine the name of the program. This is only necessary on
        # MacOS X to make sure that we run the executable from its
        # bundle directory so it gets events while we debug it.
        $real_exe = $exe_name;
        if($os eq "darwin" and ($exe_name eq "gui" or $exe_name eq "viewer" or $exe_name eq "xmledit" or $exe_name eq "silex"))
        {
            $real_exe = "$visitbindir/$exe_name";
        }

        $gdbfilename = "$exe_name$ver-gdbcommands";
        $gdbfile_opened = 1;
        open(GDBFILE, ">$gdbfilename") or $gdbfile_opened = 0;
        if($gdbfile_opened)
        {
            # Write a GDB command file to run the desired VisIt component.
            print GDBFILE "set environment LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}\n";
            print GDBFILE "set environment LD_LIBRARY32_PATH=$ENV{LD_LIBRARY32_PATH}\n";
            print GDBFILE "set environment LD_LIBRARYN32_PATH=$ENV{LD_LIBRARYN32_PATH}\n";
            print GDBFILE "set environment LD_LIBRARY64_PATH=$ENV{LD_LIBRARY64_PATH}\n";
            print GDBFILE "set environment LIBPATH=$ENV{LIBPATH}\n";
            print GDBFILE "set environment VISITHOME=$ENV{VISITHOME}\n";
            print GDBFILE "set environment VISITHELPHOME=$ENV{VISITHELPHOME}\n";
            print GDBFILE "set environment VISITPLUGINDIR=$ENV{VISITPLUGINDIR}\n";
            print GDBFILE "set environment PYTHONHOME=$ENV{PYTHONHOME}\n";
            if($ENV{TRAP_FPE} ne "")
            {
                print GDBFILE "set environment TRAP_FPE=$ENV{TRAP_FPE}\n";
            }
            print GDBFILE "set environment MESA_GLX_FX=$ENV{MESA_GLX_FX}\n";
            print GDBFILE "path $ENV{VISITHOME}/bin\n";
            print GDBFILE "file $real_exe\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/Exceptions/Database\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/Exceptions/Pipeline\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/Exceptions/VisWindow\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/comm\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/state\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/misc\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/parser\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/proxybase\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/plugin\n";
            print GDBFILE "directory $ENV{VISITHOME}/common/utility\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/DBAtts/MetaData\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/DBAtts/SIL\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Database/Database\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Database/Formats\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Database/Ghost\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/Abstract\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/Conditional\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/Derivations\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/General\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/Management\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/Math\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Expressions/MeshQuality\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Filters\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Math\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/MIR/Base\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/MIR/Tet\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/MIR/Zoo\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Pipeline/Data\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Pipeline/Pipeline\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Pipeline/PrivateFilters\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Pipeline/Sinks\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Pipeline/Sources\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Plotter\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Preprocessor\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/QtVisWindow\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Queries/Abstract\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Queries/Misc\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/Queries/Queries\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/View\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/VisWindow/Colleagues\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/VisWindow/Interactors\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/VisWindow/Proxies\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/VisWindow/Tools\n";
            print GDBFILE "directory $ENV{VISITHOME}/components/VisWindow/VisWindow\n";
            print GDBFILE "directory $ENV{VISITHOME}/engine/main\n";
            print GDBFILE "directory $ENV{VISITHOME}/engine/proxy\n";
            print GDBFILE "directory $ENV{VISITHOME}/engine/rpc\n";
            print GDBFILE "directory $ENV{VISITHOME}/gui\n";
            print GDBFILE "directory $ENV{VISITHOME}/launcher/main\n";
            print GDBFILE "directory $ENV{VISITHOME}/launcher/proxy\n";
            print GDBFILE "directory $ENV{VISITHOME}/launcher/rpc\n";
            print GDBFILE "directory $ENV{VISITHOME}/mdserver/main\n";
            print GDBFILE "directory $ENV{VISITHOME}/mdserver/proxy\n";
            print GDBFILE "directory $ENV{VISITHOME}/mdserver/rpc\n";
            print GDBFILE "directory $ENV{VISITHOME}/viewer/main\n";
            print GDBFILE "directory $ENV{VISITHOME}/viewer/proxy\n";
            print GDBFILE "directory $ENV{VISITHOME}/viewer/rpc\n";
            print GDBFILE "directory $ENV{VISITHOME}/visitpy\n";
            print GDBFILE "directory $ENV{VISITHOME}/visit_vtk/full\n";
            print GDBFILE "directory $ENV{VISITHOME}/visit_vtk/lightweight\n";
            print GDBFILE "directory $ENV{VISITHOME}/visit_vtk/sl_io\n";
            print GDBFILE "directory $ENV{VISITHOME}/vtkqt\n";
            print GDBFILE "directory $ENV{VISITHOME}/winutil\n";

            if ($security_key_set)
            {
                print GDBFILE "set args @visitargs -dograb -key $security_key\n";
            }
            else
            {
                print GDBFILE "set args @visitargs -dograb \n";
            }

            # Set up any breakpoints
            if($#breakpoints eq -1)
            {
                # No breakpoints. Just run.
                print GDBFILE "run\n";
            }
            else
            {
                # See if the user wants to break in main.
                $breakmain = grep /^main$/, @breakpoints;
                print GDBFILE "break main\n";
                print GDBFILE "run\n";
                # Print the breakpoints that are not main.
                foreach (@breakpoints)
                {
                    if($_ ne "main") { print GDBFILE "break $_\n"; }
                }
                # If the user did not break in main, continue.
                if($breakmain eq 0) { print GDBFILE "continue\n"; }
            }
            close GDBFILE;

            # Run gdb directly
            @debugcmd = ("gdb", $real_exe, "-x", $gdbfilename);
            if($gdb_xterm)
            {
                # Run GDB under an xterm
                $debugtitle = "\"Debug $real_exe\"";
                @debugcmd = ("xterm", "-title", $debugtitle, "-fn", "fixed", "-e", "gdb", $real_exe, "-x", $gdbfilename);
            }

            print STDERR "Running: @debugcmd\n";
            $exec_gdb_failed = 0;
            exec @debugcmd or $exec_gdb_failed = 1;
            if($exec_gdb_failed)
            {
                print STDERR "Could not run $real_exe in the gdb debugger. Running VisIt normally.\n";
                RunComponent($real_exe, $ver, $security_key_set, $security_key, @visitcmd);
            }
        }
        else
        {
            print STDERR "Could not create GDB command file \"$gdbfilename\". Running VisIt normally.\n";
            RunComponent($real_exe, $ver, $security_key_set, $security_key, @visitcmd);
        }
    }
    else
    {
        if ($exe_name ne "splashscreen")
        {
            @printcmd = ("$exe_name$ver", @visitargs);
            chomp($printcmd[0] = `basename $printcmd[0]`);
            print STDERR "Running: @printcmd\n";
        }
        if ($security_key_set) { push @visitcmd, "-key", $security_key; }
        exec @visitcmd or die "Can't execute visit: $!\n";
    }
}

sub RunComponent {
   my $exe_name = shift;
   my $ver = shift;
   my $security_key_set = shift;
   my $security_key = shift;
   my @visitcmd = shift;

   if ($exe_name ne "splashscreen")
   {
       @printcmd = ("$exe_name$ver", @visitargs);
       chomp($printcmd[0] = `basename $printcmd[0]`);
       print STDERR "Running: @printcmd\n";
   }
   if ($security_key_set) { push @visitcmd, "-key", $security_key; }
   exec @visitcmd or die "Can't execute visit: $!\n";
}

sub PrintEnvironment {
    if ($envonly)
    {
        print STDOUT <<"EOF"
LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}
LD_LIBRARY32_PATH=$ENV{LD_LIBRARY32_PATH}
LD_LIBRARYN32_PATH=$ENV{LD_LIBRARYN32_PATH}
LD_LIBRARY64_PATH=$ENV{LD_LIBRARY64_PATH}
LIBPATH=$ENV{LIBPATH}
VISITHOME=$ENV{VISITHOME}
VISITHELPHOME=$ENV{VISITHELPHOME}
VISITPLUGINDIR=$ENV{VISITPLUGINDIR}
PYTHONHOME=$ENV{PYTHONHOME}
TRAP_FPE=$ENV{TRAP_FPE}
MESA_GLX_FX=$ENV{MESA_GLX_FX}
EOF
    }
    elsif (grep(/csh/, "$ENV{SHELL}"))
    {
        print STDERR <<"EOF"
Be sure to set your environment variables:
    setenv LD_LIBRARY_PATH $ENV{LD_LIBRARY_PATH}
    setenv LD_LIBRARY32_PATH $ENV{LD_LIBRARY32_PATH}
    setenv LD_LIBRARYN32_PATH $ENV{LD_LIBRARYN32_PATH}
    setenv LD_LIBRARY64_PATH $ENV{LD_LIBRARY64_PATH}
    setenv LIBPATH $ENV{LIBPATH}
    setenv VISITHOME $ENV{VISITHOME}
    setenv VISITHELPHOME $ENV{VISITHELPHOME}
    setenv VISITPLUGINDIR $ENV{VISITPLUGINDIR}
    setenv PYTHONHOME $ENV{PYTHONHOME}
    setenv TRAP_FPE $ENV{TRAP_FPE}
    setenv MESA_GLX_FX $ENV{MESA_GLX_FX}
EOF
    }
    else
    {
        print STDERR <<"EOF"
Be sure to set your environment variables:
    LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}
    LD_LIBRARY32_PATH=$ENV{LD_LIBRARY32_PATH}
    LD_LIBRARYN32_PATH=$ENV{LD_LIBRARYN32_PATH}
    LD_LIBRARY64_PATH=$ENV{LD_LIBRARY64_PATH}
    LIBPATH=$ENV{LIBPATH}
    VISITHOME=$ENV{VISITHOME}
    VISITHELPHOME=$ENV{VISITHELPHOME}
    VISITPLUGINDIR=$ENV{VISITPLUGINDIR}
    PYTHONHOME=$ENV{PYTHONHOME}
    TRAP_FPE=$ENV{TRAP_FPE}
    MESA_GLX_FX=$ENV{MESA_GLX_FX}
EOF
    }
}

