#!/bin/sh
#
#  Name:
#     mbuild    compilation program for executable programs
#     
#  Usage:
#    MBUILD [option1 ... optionN] sourcefile1 [... sourcefileN]
#           [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN]
#           [exportfile1 ... exportfileN]
#  
#  Description:
#    MBUILD compiles and links source files that call functions in the MATLAB
#    C/C++ Math Library or MATLAB C/C++ Graphics Library into a stand-alone
#    executable or shared library.
#  
#    The first file name given (less any file name extension) will be the name
#    of the resulting executable. Additional source, object, or library files
#    can be given to satisfy external references. Either C or C++ source files
#    can be specified when building executables. In addition, both C and C++
#    source files can be specified at the same time as long as the C files are
#    C++ compatible, and the -lang cpp option is specified (see -lang below).
#  
#    Both an options file and command line options affect the behavior of
#    MBUILD. The options file contains a list of variables that are passed as
#    arguments to various tools such as the compiler, linker, and other
#    platform-dependent tools (such as the resource linker on Windows). Command
#    line options to MBUILD may also affect what arguments are passed to these
#    tools, or may control other aspects of MBUILD's behavior.
#  
#  Command Line Options:
#    Options available on all platforms:
#  
#    -c
#        Compile only. Creates an object file but not an executable.
#    -D<name>
#        Define a symbol name to the C/C++ preprocessor. Equivalent to a
#        "#define <name>" directive in the source.
#    -D<name>#<value>
#        Define a symbol name and value to the C/C++ preprocessor. Equivalent
#        to a "#define <name> <value>" directive in the source.
#    -f <optionsfile>
#        Specify location and name of options file to use. Overrides MBUILD's
#        default options file search mechanism.
#    -g
#        Create a debuggable executable. If this option is specified, MBUILD
#        appends the value of options file variables ending in DEBUGFLAGS with
#        their corresponding base variable. (For example, the value of
#        LINKDEBUGFLAGS would be appended to the LINKFLAGS variable before
#        calling the linker.) This option also disables MBUILD's default
#        behavior of optimizing built object code.
#    -h[elp]
#        Print this message.
#    -I<pathname>
#        Add <pathname> to the list of directories to search for #include
#        files.
#    -inline
#        Inline matrix accessor functions (mx*). The executable generated may
#        not be compatible with future versions of the MATLAB C/C++ Math
#        Library or MATLAB C/C++ Graphics Library.
#    -lang <language>
#        Specify compiler language. <language> can be c or cpp. By
#        default, MBUILD determines which compiler (C or C++) to use by
#        inspection of the source file's extension. This option overrides that
#        mechanism.
#    -n
#        No execute mode. Print out any commands that MBUILD would otherwise
#        have executed, but do not actually execute any of them.
#    -O
#        Optimize the object code by including the optimization flags listed in
#        the options file. If this option is specified, MBUILD appends the
#        value of options file variables ending in OPTIMFLAGS with their
#        corresponding base variable. (For example, the value of LINKOPTIMFLAGS
#        would be appended to the LINKFLAGS variable before calling the
#        linker.) Note that optimizations are enabled by default, are disabled
#        by the -g option, but are reenabled by -O.
#    -outdir <dirname>
#        Place all output files in directory <dirname>.
#    -output <resultname>
#        Create executable named <resultname> (an appropriate executable
#        extension is automatically appended). Overrides MBUILD's default
#        executable naming mechanism.
#    -setup
#        Interactively specify the compiler options file to use as default for
#        future invocations of MBUILD by placing it in
#        "<UserProfile>\Application Data\MathWorks\MATLAB\R12" (for Windows) or
#        $HOME/.matlab/R12 (for UNIX). When this option is specified, no other
#        command line input is accepted.
#    -U<name>
#        Remove any initial definition of the C preprocessor symbol <name>.
#        (Inverse of the -D option.)
#    -v
#        Print the values for important internal variables after the options
#        file is processed and all command line arguments are considered.
#        Prints each compile step and final link step fully evaluated to see
#        which options and files were used. Very useful for debugging.
#    <name>#<value>
#        Override an options file variable for variable <name>. See the
#        platform-dependent discussion of options files below for more details.
#        This option is processed after the options file is processed and all
#        command line arguments are considered.
#  
#  Additional options available on Windows platforms:
#  
#    @<rspfile>
#        Include contents of the text file <rspfile> as command line arguments
#        to MBUILD.
#  
#  Additional options available on Unix platforms:
#  
#    -<arch>
#        Assume local host has architecture <arch>. Possible values for <arch>
#        include sol2, hpux, hp700, alpha, ibm_rs, sgi, and glnx86.
#    -D<name>=<value>
#        Define a symbol name and value to the C preprocessor. Equivalent to a
#        "#define <name> <value>" directive in the source.
#    -l<name>
#        Link with object library "lib<name>" (for "ld(1)").
#    -L<directory>
#        Add <directory> to the list of directories containing object-library
#        routines (for linking using "ld(1)").
#    <name>=<value>
#        Override an options file variable for variable <name>. See the
#        platform-dependent discussion of options files below for more details.
#  
#  Shared Libraries and Exports Files:
#    MBUILD can also create shared libraries from C source code. If a file or
#    files with the extension ".exports" is passed to MBUILD, then it builds a
#    shared library. The .exports file must be a flat text file, with each line
#    containing either an exported symbol name, or starting with a # or * in
#    the first column (in which case it is treated as a comment line). If
#    multiple .exports files are specified, then all symbol names in all
#    specified .exports files are exported.
#  
#  Options File Details:
#    On Windows:
#      The options file is written as a DOS batch file. If the -f option is not
#      used to specify the options file name and location, then MBUILD searches
#      for an options file named compopts.bat in the following directories: the
#      current directory, then the directory "<UserProfile>\Application
#      Data\MathWorks\MATLAB\R12". Any variable specified in the options file
#      can be overridden at the command line by use of the <name>#<value>
#      command line argument. If <value> has spaces in it, then it should be
#      wrapped in double quotes (e.g., COMPFLAGS#"opt1 opt2"). The definition
#      can rely on other variables defined in the options file; in this case
#      the variable referenced should have a prepended "$" (e.g.,
#      COMPFLAGS#"$COMPFLAGS opt2").
#  
#    On UNIX:
#      The options file is written as a UNIX shell script. If the -f option is
#      not used to specify the options file name and location, then MBUILD
#      searches for an options file named mbuildopts.sh in the following
#      directories: the current directory (.), then $HOME/.matlab/R12, then
#      $MATLAB/bin. Any variable specified in the options file can be
#      overridden at the command line by use of the <name>=<def> command line
#      argument. If <def> has spaces in it, then it should be wrapped in single
#      quotes (e.g., CFLAGS='opt1 opt2'). The definition can rely on other
#      variables defined in the options file; in this case the variable
#      referenced should have a prepended "$" (e.g., CFLAGS='$CFLAGS opt2').
#  
#  Examples:
#      The following command will compile "myprog.c" into "myprog.exe" (when
#      run under Windows):
#  
#        mbuild myprog.c
#  
#      When debugging, it is often useful to use "verbose" mode as well
#      as include symbolic debugging information:
#  
#        mbuild -v -g myprog.c
#  
#      The following command will compile "mylib.c" into "mylib.dll" (when run
#      under Windows). "mylib.dll" will export the symbols listed in
#      "mylib.exports":
#  
#        mbuild mylib.c mylib.exports
#
#  See Also:
#     MATLAB C/C++ Math Library User's Guide
#
# Copyright (c) 1984-2000 The MathWorks, Inc. All Rights Reserved.
# All Rights Reserved.
# $Revision: 1.41 $  $Date: 2000/08/16 20:06:01 $
#____________________________________________________________________________
#
    arg0_=$0

    abort='rm -f $INTERMEDIATE $basename.o > /dev/null 2>&1; \
          echo ""; \
          echo "    mbuild:  interrupted."; \
          echo ""'
#
    trap "eval $abort; exit 1" 1 2 3 15
#
#========================= archlist.sh (start) ============================
#
# usage:        archlist.sh
#
# abstract:     This Bourne Shell script creates the variable ARCH_LIST.
#
# note(s):      1. This file is always imbedded in another script
#
# Copyright 1997-2000 The MathWorks, Inc.
# $Revision: 1.8 $  $Date: 2000/06/16 16:08:59 $
#----------------------------------------------------------------------------
#
    ARCH_LIST='sol2 hpux hp700 alpha ibm_rs sgi glnx86'
#=======================================================================
# Functions:
#   check_archlist ()
#=======================================================================
    check_archlist () { # Sets ARCH. If first argument contains a valid
			# arch then ARCH is set to that value else
		        # an empty string. If there is a second argument
			# do not output any warning message. The most
			# common forms of the first argument are:
			#
			#     ARCH=arch
			#     MATLAB_ARCH=arch
			#     argument=-arch
			#
                        # Always returns a 0 status.
                        #
                        # usage: check_archlist arch=[-]value [noprint]
                        #
	if [ $# -gt 0 ]; then
	    arch_in=`expr "$1" : '.*=\(.*\)'`
	    if [ "$arch_in" != "" ]; then
	        ARCH=`echo "$ARCH_LIST EOF $arch_in" | awk '
#-----------------------------------------------------------------------
	{ for (i = 1; i <= NF; i = i + 1)
	      if ($i == "EOF")
		  narch = i - 1
	  for (i = 1; i <= narch; i = i + 1)
		if ($i == $NF || "-" $i == $NF) {
		    print $i
		    exit
		}
	}'`
#-----------------------------------------------------------------------
	       if [ "$ARCH" = "" -a $# -eq 1 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo ' '
echo "    Warning: $1 does not specify a valid architecture - ignored . . ."
echo ' '
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       fi
	    else
		ARCH=""
	    fi
	else
	    ARCH=""
	fi
#
	return 0
    }
#=======================================================================
#========================= archlist.sh (end) ==============================
#
#============================================================================
#  FUNCTION DEFINITIONS
#============================================================================
#
#****************************************************************************
#
# NOTE: A call to cleanup MUST precede any call to exit within this script,
#       except for within trap calls.
  cleanup () {
#
# Clean up temporary and intermediate files (usually in preparation
# for exiting)
#
    trap "eval $abort; exit 1" 1 2 3 15
    if [ -f $SO_LOCATIONS ]; then
        rm -f $SO_LOCATIONS > /dev/null 2>&1
    fi
    rm -f $INTERMEDIATE > /dev/null 2>&1
    }
#   end cleanup ()
#
#****************************************************************************
#
  describe () {
#
    case "$1" in
        unknown_architecture)
    echo ''
    echo '    Sorry! We could not determine the machine architecture'
    echo '           for your host. Please contact:'
    echo ''
    echo '               MathWorks Technical Support'
    echo ''
    echo '           for further assistance.'
    echo ''
            ;;
        lang)
    echo ''
    echo '   The argument to -lang must be either c or cpp.'
    echo "   You specified: $lang"
    echo ''
            ;; 
        link)
    echo ''
    echo '   The argument to -link must be either exe or shared.' 
    echo "   You specified: $linkarg"
    echo ''
            ;; 
        no_options_file)
    echo ''
    echo '    You need to specify an options file for mbuild'
    echo '           to use.  This defines all compiler flags'
    echo '           necessary to compile a given type of executable.'
    echo '           See TMW_ROOT/bin/engopts.sh for an example.'
    echo ''
    echo '           Here'
    echo ''
    echo "               TMW_ROOT = $TMW_ROOT"
    echo ''
            ;;
        final_options)
    echo '----------------------------------------------------------------'
            if [ "$SOURCE_DIR" = "none" ]; then
    echo "-> options file specified on command line:"
    echo "   FILE = $OPTIONS_FILE"
            elif [ "$SOURCE_DIR" != "" ]; then
    echo "-> `basename $OPTIONS_FILE` sourced from directory (DIR = $SOURCE_DIR)"
    echo "   FILE = $OPTIONS_FILE"
            fi
    echo '----------------------------------------------------------------'
    echo "->    TMW_ROOT              = $TMW_ROOT"
    echo "->    CC                    = $CC"
    echo "->    CC flags:"
    echo "         CFLAGS             = $CFLAGS"
    echo "         CDEBUGFLAGS        = $CDEBUGFLAGS"
    echo "         COPTIMFLAGS        = $COPTIMFLAGS"
    echo "         CLIBS              = $CLIBS"
    echo "         arguments          = $cc_flags"
    echo "->    LD                    = $LD"
    echo "->    Link flags:"
    echo "         LDFLAGS            = $LDFLAGS"
    echo "         LDDEBUGFLAGS       = $LDDEBUGFLAGS"
    echo "         LDOPTIMFLAGS       = $LDOPTIMFLAGS"
    echo "         arguments          = $ld_flags"
    echo '----------------------------------------------------------------'
    echo ''
            ;;
        status)
    echo ""
    echo "    mbuild:  $stat"
            ;;
        help)
    cat<<'EOF'

Usage:
  MBUILD [option1 ... optionN] sourcefile1 [... sourcefileN]
         [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN]
         [exportfile1 ... exportfileN]

Description:
  MBUILD compiles and links source files that call functions in the MATLAB
  C/C++ Math Library or MATLAB C/C++ Graphics Library into a stand-alone
  executable or shared library.

  The first file name given (less any file name extension) will be the name
  of the resulting executable. Additional source, object, or library files
  can be given to satisfy external references. Either C or C++ source files
  can be specified when building executables. In addition, both C and C++
  source files can be specified at the same time as long as the C files are
  C++ compatible, and the -lang cpp option is specified (see -lang below).

  Both an options file and command line options affect the behavior of
  MBUILD. The options file contains a list of variables that are passed as
  arguments to various tools such as the compiler, linker, and other
  platform-dependent tools (such as the resource linker on Windows). Command
  line options to MBUILD may also affect what arguments are passed to these
  tools, or may control other aspects of MBUILD's behavior.

Command Line Options:
  Options available on all platforms:

  -c
      Compile only. Creates an object file but not an executable.
  -D<name>
      Define a symbol name to the C/C++ preprocessor. Equivalent to a
      "#define <name>" directive in the source.
  -D<name>#<value>
      Define a symbol name and value to the C/C++ preprocessor. Equivalent
      to a "#define <name> <value>" directive in the source.
  -f <optionsfile>
      Specify location and name of options file to use. Overrides MBUILD's
      default options file search mechanism.
  -g
      Create a debuggable executable. If this option is specified, MBUILD
      appends the value of options file variables ending in DEBUGFLAGS with
      their corresponding base variable. (For example, the value of
      LINKDEBUGFLAGS would be appended to the LINKFLAGS variable before
      calling the linker.) This option also disables MBUILD's default
      behavior of optimizing built object code.
  -h[elp]
      Print this message.
  -I<pathname>
      Add <pathname> to the list of directories to search for #include
      files.
  -inline
      Inline matrix accessor functions (mx*). The executable generated may
      not be compatible with future versions of the MATLAB C/C++ Math
      Library or MATLAB C/C++ Graphics Library.
  -lang <language>
      Specify compiler language. <language> can be c or cpp. By
      default, MBUILD determines which compiler (C or C++) to use by
      inspection of the source file's extension. This option overrides that
      mechanism.
  -n
      No execute mode. Print out any commands that MBUILD would otherwise
      have executed, but do not actually execute any of them.
  -O
      Optimize the object code by including the optimization flags listed in
      the options file. If this option is specified, MBUILD appends the
      value of options file variables ending in OPTIMFLAGS with their
      corresponding base variable. (For example, the value of LINKOPTIMFLAGS
      would be appended to the LINKFLAGS variable before calling the
      linker.) Note that optimizations are enabled by default, are disabled
      by the -g option, but are reenabled by -O.
  -outdir <dirname>
      Place all output files in directory <dirname>.
  -output <resultname>
      Create executable named <resultname> (an appropriate executable
      extension is automatically appended). Overrides MBUILD's default
      executable naming mechanism.
  -setup
      Interactively specify the compiler options file to use as default for
      future invocations of MBUILD by placing it in
      "<UserProfile>\Application Data\MathWorks\MATLAB\R12" (for Windows) or
      $HOME/.matlab/R12 (for UNIX). When this option is specified, no other
      command line input is accepted.
  -U<name>
      Remove any initial definition of the C preprocessor symbol <name>.
      (Inverse of the -D option.)
  -v
      Print the values for important internal variables after the options
      file is processed and all command line arguments are considered.
      Prints each compile step and final link step fully evaluated to see
      which options and files were used. Very useful for debugging.
  <name>#<value>
      Override an options file variable for variable <name>. See the
      platform-dependent discussion of options files below for more details.
      This option is processed after the options file is processed and all
      command line arguments are considered.

Additional options available on Windows platforms:

  @<rspfile>
      Include contents of the text file <rspfile> as command line arguments
      to MBUILD.

Additional options available on Unix platforms:

  -<arch>
      Assume local host has architecture <arch>. Possible values for <arch>
      include sol2, hpux, hp700, alpha, ibm_rs, sgi, and glnx86.
  -D<name>=<value>
      Define a symbol name and value to the C preprocessor. Equivalent to a
      "#define <name> <value>" directive in the source.
  -l<name>
      Link with object library "lib<name>" (for "ld(1)").
  -L<directory>
      Add <directory> to the list of directories containing object-library
      routines (for linking using "ld(1)").
  <name>=<value>
      Override an options file variable for variable <name>. See the
      platform-dependent discussion of options files below for more details.

Shared Libraries and Exports Files:
  MBUILD can also create shared libraries from C source code. If a file or
  files with the extension ".exports" is passed to MBUILD, then it builds a
  shared library. The .exports file must be a flat text file, with each line
  containing either an exported symbol name, or starting with a # or * in
  the first column (in which case it is treated as a comment line). If
  multiple .exports files are specified, then all symbol names in all
  specified .exports files are exported.

Options File Details:
  On Windows:
    The options file is written as a DOS batch file. If the -f option is not
    used to specify the options file name and location, then MBUILD searches
    for an options file named compopts.bat in the following directories: the
    current directory, then the directory "<UserProfile>\Application
    Data\MathWorks\MATLAB\R12". Any variable specified in the options file
    can be overridden at the command line by use of the <name>#<value>
    command line argument. If <value> has spaces in it, then it should be
    wrapped in double quotes (e.g., COMPFLAGS#"opt1 opt2"). The definition
    can rely on other variables defined in the options file; in this case
    the variable referenced should have a prepended "$" (e.g.,
    COMPFLAGS#"$COMPFLAGS opt2").

  On UNIX:
    The options file is written as a UNIX shell script. If the -f option is
    not used to specify the options file name and location, then MBUILD
    searches for an options file named mbuildopts.sh in the following
    directories: the current directory (.), then $HOME/.matlab/R12, then
    $MATLAB/bin. Any variable specified in the options file can be
    overridden at the command line by use of the <name>=<def> command line
    argument. If <def> has spaces in it, then it should be wrapped in single
    quotes (e.g., CFLAGS='opt1 opt2'). The definition can rely on other
    variables defined in the options file; in this case the variable
    referenced should have a prepended "$" (e.g., CFLAGS='$CFLAGS opt2').

Examples:
    The following command will compile "myprog.c" into "myprog.exe" (when
    run under Windows):

      mbuild myprog.c

    When debugging, it is often useful to use "verbose" mode as well
    as include symbolic debugging information:

      mbuild -v -g myprog.c

    The following command will compile "mylib.c" into "mylib.dll" (when run
    under Windows). "mylib.dll" will export the symbols listed in
    "mylib.exports":

      mbuild mylib.c mylib.exports

EOF
            ;;
        usage)
    cat<<'EOF'

    Usage:
      MBUILD [option1 ... optionN] sourcefile1 [... sourcefileN]
             [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN]
             [exportfile1 ... exportfileN]

    Use the -help option for more information, or consult the MATLAB C/C++ Math
    Library User's Guide.

EOF
            ;;
        file_not_found)
    echo ''
    echo "    mbuild:  $file not a normal file or does not exist."
    echo ''
            ;;
        compile_stage)
    echo "-> $compile_command"
    echo ''
            ;;
        failed_compile)
    echo ''
    echo "    mbuild: compile of '$file' failed."
    echo ''
            ;;
        makedef_stage)
    echo ''
    echo "-> $SHLMAKEDEF $LI_EXPFILE > $EXPFILE"
    echo ''
            ;;
        link_stage)
    echo "-> $LD $LDFLAGS $ld_flags -o $outname $libetc"
    echo ''
            ;;
        solaris_linker_patch)
    echo ''
    echo '    The Solaris linker requires patch #102303-05.'
    echo '    This script has determined that your linker does'
    echo '    not have this patch; please install it.  For more'
    echo "    information run the 'matlabdoc' command at the UNIX"
    echo '    prompt and read Section 8.2 of the Appendix in'
    echo '    UNIX News for MATLAB 5.0. If these documents are'
    echo '    unavailable, contact The MathWorks technical support.'
    echo ''
    echo 'Link stage not attempted.'
    echo ''
            ;;
        failed_link)
    echo ''
    echo "    mbuild: link of '$outname' failed."
    echo ''
            ;;
        cant_make_shl)
    echo ''
    echo "    mbuild: The current options file is not configured to create shared"
    echo "            libraries. You can use mbuild -setup to set up an options"
    echo "            file which is configured to create shared libraries."
    echo ''
            ;;
        *)
    echo ''
    echo " Internal error 4: unimplemented message $1"
    echo ''
            ;;
    esac
  }
# end describe ()
#
#****************************************************************************
#
  smart_quote () {
#
# Return a quoted version of the input string if it has spaces in it.
#
    if [ $# -gt 1 ]; then
        echo \"$*\"
    else
        echo $1
    fi   
  }
# end smart_quote ()
#
#****************************************************************************
#
  find_options_file () {
#
# Find a file in the list of search directories
#
#  ./<filename>                  (<filename> in current directory)
#  $HOME/.matlab/R12/<filename>  (<filename> in user's matlab directory)
#  $TMW_ROOT/bin/<filename>      (<filename> in TMW_ROOT/bin directory)
#
#
    if [ -f ./$1 ]; then
        SOURCE_DIR='.'
        SOURCE_DIReval=`pwd`
        OPTIONS_FILE="./$1"
    elif [ -f $HOME/.matlab/R12/$1 ]; then
        SOURCE_DIR='$HOME/.matlab/R12'
        SOURCE_DIReval=$HOME/.matlab/R12
        OPTIONS_FILE="$HOME/.matlab/R12/$1"
    elif [ -f $TMW_ROOT/bin/$1 ]; then
#
# NOTE: At this point we will use the TMW_ROOT determined earlier to
#       source the file.
#
        SOURCE_DIR='$TMW_ROOT/bin'
        SOURCE_DIReval=$TMW_ROOT/bin
        OPTIONS_FILE="$TMW_ROOT/bin/$1"
    else
        describe no_options_file >&2
        cleanup
        exit 1
    fi
}
# end find_options_file ()
#
#****************************************************************************
#
  get_ext () {
#
#   Determine extension for shared library file
#
    if [ "$linkarg" = "shared" ]; then
        case "$Arch" in
            alpha)
                mbuild_ext='.so'
                ;;
            glnx86)
                mbuild_ext='.so'
                ;;
            hpux)
                mbuild_ext='.sl'
                ;;
            hp700)
                mbuild_ext='.sl'
                ;;
            ibm_rs)
                mbuild_ext='.a'
                ;;
            lnx86)
                mbuild_ext='.so'
                ;;
            sgi)
                mbuild_ext='.so'
                ;;
            sgi64)
                mbuild_ext='.so'
                ;;
            sol2)
                mbuild_ext='.so'
                ;;
        esac
    else
        mbuild_ext=''
    fi
  }
# end get_ext ()
#
#****************************************************************************
#
# embed the setup_options_file finction declaration. The #imbed statement
# causes the imbed program to replace this line with the contents of the
# indicated file.
#
#========================= optsetup.sh (start) ============================
#!/bin/sh
#
#  Name:
#     optsetup    sh function declaration of setup_options_file
#     
#  Usage: (not for interactive use. To be sourced and called as a function)
#
#     . optsetup
#     setup_options_file [<filename>]
#
#   Description:
#     When invoked without a parameter, setup_options_file generates a list
#     of options files from which to select one to be copied to the default
#     options file location and name.
#
#     When invoked with a parameter, setup_options_file copies the
#     specified file to the default options file location and name.
#
#     setup_options_file is context sensitive. When invoked from mex, it
#     uses 'mexopts.sh' as the default options file target. When invoked
#     from mbuild, it uses 'mbuildopts.sh' as the default options file
#     target. 
#
#  See Also:
#     MATLAB API Guide
#
# Copyright (c) 1984-2000 by The MathWorks, Inc.
#  $Revision: 1.15 $  $Date: 2000/08/17 18:59:14 $
#____________________________________________________________________________
#
#****************************************************************************
#


setup_describe () {

SCRIPT_NAME=`basename $arg0_`

cat << EOF

    Using the '$SCRIPT_NAME -setup' command selects an options file that is
    placed in ~/.matlab/R12 and used by default for '$SCRIPT_NAME'. An options 
    file in the current working directory or specified on the command line 
    overrides the default options file in ~/.matlab/R12.

    Options files control which compiler to use, the compiler and link command
    options, and the runtime libraries to link against.
 
    To override the default options file, use the '$SCRIPT_NAME -f' command
    (see '$SCRIPT_NAME -help' for more information).
EOF
 
}


setup_options_file () {


    TAG="#SELECTION_TAG"
    DEFAULT_OPTIONS_FILE="mbuildopts.sh"

    #
    # Determine what script invoked this routine
    #
    SOURCE_SCRIPT=`basename $arg0_`

    #
    # if source script is MEX set the selection tag for MEX
    #
    if [ "$SOURCE_SCRIPT" = "mex" ]; then 
      TAG="#SELECTION_TAG_MEX_OPT:"
      DEFAULT_OPTIONS_FILE="mexopts.sh"
    fi

    #
    # if source script is MBUILD set the selection tag for all non generic...
    #
    if [ "$SOURCE_SCRIPT" = "mbuild" ]; then 
      TAG="#SELECTION_TAG_ML_OPT:"
      DEFAULT_OPTIONS_FILE="mbuildopts.sh"
    fi

    #
    # When given an input file that exists process it
    #
    if [ "X$1" != "X" -a -f "$1" ]; then
	FOUND_FILE=$1
    else

	setup_describe

	#
	# Inform the user of the available options files
	#
        echo
        echo The options files available for $SOURCE_SCRIPT are:
        echo

	#
	# For each *opt*.sh file in the options file path generate a prompt and
	# identifier for that file to be selected to copy to the default options
	# file. 
	#
	# Find *opts.sh files in the list of search directories
	#
	#  $TMW_ROOT/bin/<filename> 
	#
        file_list="`ls $TMW_ROOT/bin/*opts.sh 2> /dev/null`"

        opt_count=0
        file_array=""
        for file in $file_list ; do 
            file_comment=`egrep "^$TAG" $file | cut -f 2,3,4,5,6,7,8 -d:`
            if [ "$file_comment" != "" ]; then 
	        opt_count=`expr $opt_count + 1` ;
	        file_array="$file_array$file:"
	        echo "  $opt_count: $file : "
		echo "     $file_comment"
		echo ' '
            fi
        done
 
	#
	# Prompt user for a file selection, unless there's only one file
	# in which case just do the selection.
	#

	if [ "$opt_count" = "1" ]; then
	    fname_number=1
        else
            echo
	    echo Enter the number of the options file to use as your default options file:
            echo
            read fname_number
	fi

	#
	# providing the file selection was within the valid range, copy it to...
	#
        if [ `expr $fname_number` -ge 1 -a `expr $fname_number` -le $opt_count ]; then
	    FOUND_FILE="`echo $file_array | cut -f $fname_number -d:`"
        else
            describe no_options_file >&2
            trap ""
            exit 1
        fi
    fi

    #
    # Create $HOME/.matlab/R12 for the user, if it doesn't already exist
    #
    if [ ! -d $HOME/.matlab/R12 ]; then
        echo
        echo $HOME/.matlab/R12 does not exist. It will be created.
        echo
	mkdir -p $HOME/.matlab/R12
    fi

    if [ -d $HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE ]; then
        echo "$HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE is a directory. Please remove it."
        exit 1
    fi
    if [ -f $HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE ]; then
        echo "Overwrite $HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE ([y]/n)? "
        read action
        if [ "$action" = "n" ]; then
            echo "Will not overwrite existing file. Options file not changed."
            exit 1
        fi
        rm -f $HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE
    fi
    echo
    echo "$FOUND_FILE is being copied to "
    echo "$HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE"
    echo
    cp $FOUND_FILE $HOME/.matlab/R12/$DEFAULT_OPTIONS_FILE

}
# end setup_options_file ()
#
#****************************************************************************
#
#========================= optsetup.sh (end) ==============================
#
#****************************************************************************
#
  get_arch () {
#========================= arch.sh (start) ============================
#!/bin/sh
#
# usage:        arch.sh
#
# abstract:     This Bourne Shell script determines the architecture
#		of the the current machine.
#
#		ARCH	  - Machine architecture
#
#		IMPORTANT: The shell function 'check_archlist' is used
#			   by this routine and MUST be loaded first.
#			   This can be done by sourcing the file,
#
#			       archlist.sh
#
#			   before using this routine.
#
# note(s):	1. This routine must be called using a . (period)
#
#		2. Also returns ARCH_MSG which may contain additional
#		   information when ARCH returns 'unknown'.
#
# Copyright 1986-2000 The MathWorks, Inc.
# $Revision: 1.16 $  $Date: 2000/08/31 21:58:11 $
#----------------------------------------------------------------------------
#
#=======================================================================
# Functions:
#   realfilepath ()
#   matlab6_arch ()
#=======================================================================
    realfilepath () { # Returns the actual path in the file system
		      # of a file. It follows links. It returns an
		      # empty path if an error occurs.
		      #
                      # Returns a 1 status if the file does not exist
		      # or appears to be a circular link. Otherwise, 
		      # a 0 status is returned. 
                      #
                      # usage: realfilepath filepath
                      #
	file=$1
	n=1
#
	dir=`dirname $file`
	dir=`(cd $dir; /bin/pwd)`
 	file=`basename $file`
#
# Try up to 8 links
#
    	while [ $n -le 8 ]
    	do
	    (cd $dir) >/dev/null 2>&1
	    if [ $? -eq 0 ]; then
	        lscmd=`(cd $dir; ls -l $file 2>/dev/null)`
#
# Check for link portably
#
                if [ `expr "//$lscmd" : '//.*->.*'` -ne 0 ]; then
                    link=`echo "$lscmd" | awk '{ print $NF }'`
		    dirnext=`dirname $link`
		    dir=`(cd $dir; cd $dirnext; /bin/pwd)`
		    file=`basename $link`
                elif [ "$lscmd" != "" ]; then
	            echo `(cd $dir; /bin/pwd)`/$file
	            return 0
	        else
		    return 1
	        fi
	    else
		return 1
	    fi
	    n=`expr $n + 1`
        done
	return 1
    }
#
#=======================================================================
    matlab6_arch () { # Determine the architecture for MATLAB 6.x
		      # It returns the value in the ARCH variable.
		      # If 'unknown' is returned then sometimes a
		      # diagnostic message is returned in ARCH_MSG.
                      #
                      # Always returns a 0 status.
                      #
                      # usage: matlab6_arch
                      #
	ARCH="unknown"
#
	if [ -f /bin/uname ]; then
   	    case "`/bin/uname`" in
	        SunOS)					# sol2
	            if [ -d /dev/pts ]; then
		        ARCH="sol2"
	            fi
	            ;;
	        HP-UX)					# hp 700 & 800
		    majorversion=`/bin/uname -r | awk '
#-----------------------------------------------------------------------
			{ split(substr($1,3),a,"."); print a[1] }'`
#-----------------------------------------------------------------------
	            if [ -f /bin/hp9000s700 ]; then
		        (/bin/hp9000s700) > /dev/null 2>&1
		        if [ $? -eq 0 ]; then
			    if [ $majorversion -lt 11 ]; then
	    	                ARCH="hp700"
			    else
				ARCH="hpux"
			    fi
		        fi
	            fi
	            if [ -f /bin/hp9000s800 ]; then
		        (/bin/hp9000s800) > /dev/null 2>&1
		        if [ $? -eq 0 ]; then
			    if [ $majorversion -lt 11 ]; then
	    	                ARCH="hp700"
			    else
				ARCH="hpux"
			    fi
		        fi
	            fi
	            ;;
	        IRIX|IRIX64)				# sgi
    	            if [ -f /bin/4d ]; then
		        (/bin/4d) > /dev/null 2>&1
		        if [ $? -eq 0 ]; then
		            if [ -f /bin/hinv ]; then
			        ARCH_MSG=`/bin/hinv | awk '
#-----------------------------------------------------------------------
# If we want -mips4 -n32. Must be cpu >= 5000
# If we want -mips3 -n32. Must be cpu >= 4000
#
	$1 == "CPU:" { cpu = substr($3,2) + 0
		       if (cpu < 5000)
#-----------------------------------------------------------------------
print "Appears to be sgi: But processor must be at least a R5000 ..."
#-----------------------------------------------------------------------
		     }'`
#-----------------------------------------------------------------------
			        if [ "$ARCH_MSG" = "" ]; then
			            ARCH=sgi
			        fi
			    else
#-----------------------------------------------------------------------
ARCH_MSG='Appears to be sgi: But processor could not be determined ...'
#-----------------------------------------------------------------------
			    fi
			fi
		    fi
	            ;;
	        OSF1)					# alpha
	    	    ARCH="alpha"
	            ;;
	        AIX*)					# ibm_rs
#
# With AIX 4.1, uname can return more than just 'AIX'
#
	            ARCH="ibm_rs"
	            ;;
	        Linux)
		    if [ -e /lib/libc.so.6 ]; then
			ARCH_MSG=`realfilepath /lib/libc.so.6 | awk '
#-----------------------------------------------------------------------
	BEGIN { num = "0123456789" }
	{ n = split($1,path,"/")
	  file = path[n]
#
# Get the version by shaving off the front and back until a digit
# is found.
#
	  for (i = 1; i <= length(file); i = i + 1) {
	      ix = index(num,substr(file,i,1))
	      if (ix != 0) break
	  }
	  ix = i
	  for (i = length(file); i >= 1; i = i - 1) {
	      ix2 = index(num,substr(file,i,1))
	      if (ix2 != 0) break
	  }
	  ix2 = i
	  if (ix2 < ix) {
#-----------------------------------------------------------------------
print "Appears to be Linux: But libc.so.6 version could not be determined ..."
#-----------------------------------------------------------------------
	     exit
	  }
	  n = split(substr(file,ix,ix2 - ix + 1),ver,".")
#
# We must have version >= 2.1
#
	  if (ver[1] + 0 >= 2 && n >= 2 && ver[2] + 0 >= 1) exit
#
# Just libc.so.6 - Assume OK.
#
	  if (substr(file,1,ix-2) == "libc.so" && ver[1] + 0 >= 6 && n == 1) exit
#
#-----------------------------------------------------------------------
print "Appears to be Linux: But libc.so.6 version must be at least 2.1 ..." 
#-----------------------------------------------------------------------
	}'`
#-----------------------------------------------------------------------
			if [ "$ARCH_MSG" = "" ]; then
			    ARCH="glnx86"
			fi
		    else
#-----------------------------------------------------------------------
ARCH_MSG='Appears to be Linux: But a version using libc.so.6 is required ...'
#-----------------------------------------------------------------------
		    fi
		    ;;
	        *)
		    :
	            ;;
	    esac
	fi
	return 0
    }
#=======================================================================
#
# The local shell function check_archlist is assume to be loaded before this
# function is sourced.
#
    ARCH_MSG=''
    check_archlist ARCH=$ARCH
    if [ "$ARCH" = "" ]; then
	if [ "$MATLAB_ARCH" != "" ]; then
	    check_archlist MATLAB_ARCH=$MATLAB_ARCH
	fi
	if [ "$ARCH" = "" ]; then
	    matlab6_arch
	fi
    fi
    Arch=$ARCH
#========================= arch.sh (end) ==============================
    if [ "$Arch" = "unknown" ]; then
        describe unknown_architecture >&2
        cleanup
        exit 1
    fi
    if [ "$verbose" = "1" ]; then
        temp_file=/tmp/$$b
        INTERMEDIATE="$INTERMEDIATE $temp_file"
#========================= oscheck.sh (start) ============================
#!/bin/sh
#set -x
#
# usage:        oscheck.sh
#
# abstract:     This Bourne Shell script determines the OS level of the
#               system and responds according to what it finds. There
#               are four numbers of interest:
#
#                   minimum_ver - minimum version allowed to run
#                   release_ver - release version
#                   future_ver  - future version that we know doesn't work
#
#                                 Note: "-" means infinite and is allowed
#                                       only for future_ver
#
#                   version     - current version
#
#		and the environment variable:
#
#		    OSCHECK_ENFORCE_LIMITS - used to determine whether to
#					     ignore the limits when
#					     deciding how to respond.
#
#					  !=  0  (enforce limits: DEFAULT)
#					   =  0  (ignore limits)
#
#               We check for:
#
#                   minimum_ver<=release_ver<=future_ver
#
#               If this condition is not met on the current platform
#               no further analysis is done and the behavior depends
#               on the value of oscheck_debug set in this script.
#               If oscheck_debug=1 an internal error message is
#               generated and you are asked to quit. If oscheck_debug=0
#               then a normal return is done with no messages produced
#               and an attempt is made to start MATLAB.
#
#               Here are the cases testing and the resulting behavior:
#
#               If version > future_ver ||
#                  version == future_ver && release_ver < future_ver
#		     if OSCHECK_ENFORCE_LIMITS != 0
#                        too new warning message
#                        request to stop
#		     else
#                        no message
#                        continue
#               If release_ver <= version <= future_ver
#                    no message
#                    continue
#               If minimum_ver <= version <= release_ver 
#                    standard warning message
#                    continue
#               If version < minimum_ver
#		     if OSCHECK_ENFORCE_LIMITS != 0
#                        too old warning message
#                        request to stop
#		     else
#                        standard warning message
#                        continue
#
#               Arch      - Machine architecture variable must be set
#
# note(s):      1. This routine must be called using a . (period)
#
#               2. token is the version in N.N... form
#
#                  sol2:   uname -r          -> token
#                  hp700:  uname -r          -> token(1)(3:end)
#		   hpux:   uname -r          -> token(1)(3:end)
#                  alpha:  uname -v -r       -> token(1)(2:end).token(2)
#                  ibm_rs: /usr/bin/oslevel  -> token
#                  sgi:    uname -r          -> token
#                  glnx86: uname -r          -> token                   
#                  
#               3. Cases to watch out for
#
#		   hp700:  B.11.00	- starts with a capital letter and
#					  a period.
#                  OSF1:   V4.0 1229    - first token starts with v or V. 
#
#               4. This requires at least the System V Bourne Shell since
#                  internal functions are used.
#
#               5. Algorithm:
#
#		   a. Generate version results.
#                  b. If no results then nothing to do.
#		   c. Otherwise fix error state depending on results
#		      and OSCHECK_ENFORCE_LIMITS.
#		   d. Output any messages.
#		   e. Handle input user interaction when
#		      action required to continue.
#
#               6. Assume that this routine is called using the
#                  unused temporary file defined by
#
#                     $temp_file
#
#               7. The calling routine will exit if the variable,
#                  oscheck_status, is set as follows:            
#
#                      oscheck_status=1
#
#               8. Also, any cleanup associated with of an interrupt
#                  will be handled by the calling routine.
#
#               9. Set oscheck_debug=1 to check for the consistency 
#                  of the data. Set oscheck_debug=0 for shipping.
#
# Copyright 1996-2000 The MathWorks, Inc.
# $Revision: 1.19 $  $Date: 2000/08/31 21:58:13 $
#----------------------------------------------------------------------------
#
    oscheck_status=0
#
#                   arch   OSprefix minimum_ver release_ver future_ver
#
    oslist="        sol2   SunOS    5.5.1       5.6         -"
    oslist="$oslist hp700  HP-UX    10.00       10.20       -"
    oslist="$oslist hpux   HP-UX    11.00       11.00       -"
    oslist="$oslist alpha  OSF1     4.0.1229    4.0.1229    -"
    oslist="$oslist ibm_rs AIX      4.3.3.0     4.3.3.0     -"
    oslist="$oslist sgi    IRIX     6.5         6.5         -"
    oslist="$oslist glnx86 Linux    2.2.1       2.2.15      -"
#
    if [ -f /bin/uname ]; then
        case $Arch in
            sol2|sgi|glnx86)
                ver=`/bin/uname -r`
                ;;
            hp700)  # Remove the leading capital letter and period
                ver=`/bin/uname -r | awk '{print substr($1,3)}'`
                ;;
            hpux)  # Remove the leading capital letter and period
                ver=`/bin/uname -r | awk '{print substr($1,3)}'`
                ;;
            alpha)  # Remove the leading V(v) from the first token and
		    # combine with the second token separated by a period
                ver=`/bin/uname -v -r | awk '{print substr($1,2) "." $2 }'`
                ;;
            ibm_rs)
		ver=`/usr/bin/oslevel`
                ;;
            *)
                ver=`/bin/uname -r | awk '{print $1}'`
                ;;
        esac
    fi
#
# Be sure that OSCHECK_ENFORCE_LIMITS has a value
#
    if [ "$OSCHECK_ENFORCE_LIMITS" = "" -o "$OSCHECK_ENFORCE_LIMITS" != "0" ]; then
	OSCHECK_ENFORCE_LIMITS=1
    fi
#
#  Set oscheck_debug=0 for shipping
#
    oscheck_debug=0
#
    results=`echo $Arch $ver "$oslist"| awk '
#---------------------------------------------------------------------------
        BEGIN { str = "0123456789"; strp = str "."
                astr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }
        { arch = $1;
          origver = $2;
#
# remove any non-numeric prefix from the version like V, etc.
#
          ver = ""
          for (j = 1; j <= length(origver); j = j + 1)
              if (index(strp,substr(origver,j,1)) != 0) {
                  ver = substr(origver,i)
                  break
              }
          lver = length(ver)
          for (i = 3; i <= NF; i = i + 5) {
              n[$i] = $(i+1) ""
              m[$i] = $(i+2) ""
              r[$i] = $(i+3) ""
              f[$i] = $(i+4) ""
          }
          mver = m[arch]
          rver = r[arch]
          if (rver == "") exit 
          fver = f[arch]  
#
# split the minimum version
#
          nmver = split(mver,mv,".")
          for (i = 1; i <= nmver; i = i + 1)
              if (mv[i] == "") mv[i] = 0
#
# split the release version
#
          nrver = split(rver,rv,".")
          for (i = 1; i <= nrver; i = i + 1)
              if (rv[i] == "") rv[i] = 0
#
# split the future version if there is one
#
          if (fver != "-") {
              nfver = split(fver,fv,".")
              for (i = 1; i <= nfver; i = i + 1)
                  if (fv[i] == "") fv[i] = 0
          }
#
# split the actual version
# remove everything in a word after a nondigit
#
          nver = split(ver,v,".")
          for (i = 1; i <= nver; i = i + 1) {
              new = ""
              for (j = 1; j <= length(v[i]); j = j + 1)
                  if (index(str,substr(v[i],j,1)) != 0)
                      new = new substr(v[i],j,1)
                  else
                      break
              v[i] = new
              if (v[i] == "") v[i] = 0
          }
#
# errmode: 0 - no warning
#          1 - too old warning
#          2 - warning
#          3 - too new warning
#          4 - internal error (not shipped)
#
          errmode = 0
#
# check: minimum_ver<=release_ver<=future_ver
#        minimum_ver != "-"
#        release_ver != "-"
#
          if (nmver < nrver)
              ncd = nmver
          else 
              ncd = nrver
          for (i = 1; i <= ncd; i = i + 1)
              if (mv[i] + 0 > rv[i] + 0) {
                   errmode = 4
                   break
              }
              else if (mv[i] + 0 < rv[i] + 0)
                   break
          if (errmode == 0 && i == ncd + 1 && nmver > nrver)
              for (i = ncd + 1; i <= nmver; i = i + 1)
                  if (mv[i] + 0 != 0 ) {
                      errmode = 4
                      break
                  }
          if (errmode == 0 && fver != "-") {
              if (nrver < nfver)
                  ncd = nmver
              else 
                  ncd = nfver
              for (i = 1; i <= ncd; i = i + 1)
                  if (rv[i] + 0 > fv[i] + 0) {
                      errmode = 4
                      break
                  }
                  else if (rv[i] + 0 < fv[i] + 0)
                      break
              if (errmode == 0 && i == ncd + 1 && nrver > nfver)
                  for (i = ncd + 1; i <= nrver; i = i + 1)
                      if (rv[i] + 0 != 0 ) {
                          errmode = 4
                          break
                      }
          }
          if (errmode == 0 && nmver == 1 && mver == "-")
              errmode = 4
          else if (errmode == 0 && nrver == 1 && rver == "-")
              errmode = 4
#
# check whether release_ver < future_ver (futuremode = 1)
#
          if (errmode == 0) {
              futuremode = 1
              if (fver != "-") {
                  if (nrver < nfver)
                      ncd = nrver
                  else
                      ncd = nfver
                  futuremode = 0
                  for (i = 1; i <= ncd; i = i + 1)
                      if (rv[i] + 0 < fv[i] + 0) {
                          futuremode = 1
                          break
                      }
                 if (futuremode == 0)
                     for (i = ncd + 1; i <= nfver; i = i + 1)
                         if (fv[i] + 0 != 0) {
                             futuremode = 1
                             break
                         }
              }
          }
#
# check if version > future_ver ||
#          version == future_ver && release_ver < future_ver
#
          if (errmode == 0 && fver != "-") {
              if (nfver < nver)
                  ncd = nfver
              else
                  ncd = nver
              for (i = 1; i <= ncd; i = i + 1)
                  if (v[i] + 0 > fv[i] + 0) {
                      errmode = 3
                      break
                  }
                  else if (v[i] + 0 < fv[i] + 0)
                      break
              if (errmode == 0 && i == ncd + 1 && ncd == nver) {
                  for (i = ncd + 1; i <= nfver; i = i + 1)
                      if (fv[i] + 0 != 0)
                          break
                  if (i == nfver + 1 && futuremode == 1)
                      errmode = 3
                  else if (i == nfver + 1 && futuremode == 0)
#
# case: version == future_ver && release_ver == future_ver
#
                      exit
              }
              else if (errmode == 0 && i == ncd + 1 && ncd == nfver) {
                  for (i = ncd + 1; i <= nver; i = i + 1)
                      if (v[i] + 0 != 0) {
                          errmode = 3
                          break
                      }
                  if (i == nver + 1 && futuremode == 1)
                      errmode = 3
                  else if (i == nver + 1 && futuremode == 0)
#
# case: version == future_ver && release_ver == future_ver
#
                      exit
              }
          }
#
# check if release_ver <= version
#
          if (errmode == 0) {
              if (nrver < nver)
                  ncd = nrver
              else
                  ncd = nver
              for (i = 1; i <= ncd; i = i + 1)
                  if (rv[i] + 0 > v[i] + 0)
                      break
                  else if (rv[i] + 0 < v[i] + 0)
                      exit
              if (i == ncd + 1 && ncd == nrver)
                  exit
              else if (i == ncd + 1 && ncd == nver) {
                  for (i = ncd + 1; i <= nrver; i = i + 1)
                      if (rv[i] + 0 != 0)
                          break
                  if (i == nrver + 1)
                      exit
              }
          }   
#
# check if minimum_ver <= version || version < minimum_ver
#
          if (errmode == 0) {
              if (nmver < nver)
                  ncd = nmver
              else
                  ncd = nver
              for (i = 1; i <= ncd; i = i + 1)
                  if (mv[i] + 0 > v[i] + 0) {
                      errmode = 1
                      break
                  }
                  else if (mv[i] + 0 < v[i] + 0) {
                      errmode = 2
                      break
                  }
              if (i == ncd + 1 && ncd == nmver) {
                  errmode = 2
              }
              else if (i == ncd + 1 && ncd == nver) {
                  for (i = ncd + 1; i <= nmver; i = i + 1)
                      if (mv[i] + 0 != 0) {
                          errmode = 1
                          break
                      }
                  if (i == nmver + 1) 
                      errmode = 2
              }
          }   
	  print errmode, n[arch], ver, mver, rver, fver
        }'`
#---------------------------------------------------------------------------
#
# No results means no error.
#
    if [ "$results" != "" ]; then
        errmode=`echo $results | awk '{ print $1}'`
        errflag=$errmode
#
# Fix errflag depending on the value of $OSCHECK_ENFORCE_LIMITS
#
        if [ "$errmode" = "1" -a "$OSCHECK_ENFORCE_LIMITS" = "0" ]; then
	    errflag=2
        elif [ "$errmode" = "3" -a "$OSCHECK_ENFORCE_LIMITS" = "0" ]; then
	    errflag=0
        fi
#
        echo $errflag $results $oscheck_debug | awk '
#---------------------------------------------------------------------------
	{ errmode = $1
	  arch = $3
	  ver = $4
	  mver = $5
	  rver = $6
	  fver = $7
	  debug = $8
          if (errmode == 1) {
print " "   
print "----------------------------------------------------------------------------"
printf "Warning: %s %-10s - Unsupported Operating System\n", arch, ver
printf "         %s %-10s - MATLAB built using this Operating System\n", arch, rver
print "----------------------------------------------------------------------------"
          }
          else if (errmode == 2) {
print " "   
print "----------------------------------------------------------------------------"
printf "Warning: %s %-10s - Your Operating System\n", arch, ver
printf "         %s %-10s - MATLAB built using this Operating System\n", arch, rver
print "----------------------------------------------------------------------------"
          }
          else if (errmode == 3) {
print " "   
print "----------------------------------------------------------------------------"
printf "Warning: %s %-10s - Unqualified Operating System\n", arch, ver
printf "         %s %-10s - MATLAB built using this Operating System\n", arch, rver
print "----------------------------------------------------------------------------"
          }
          else if (errmode == 4) {
              if (debug == 0) exit
print " "   
print "----------------------------------------------------------------------------"
printf "Error: %s %-10s - Internal Error - oscheck.sh has inconsistent data\n", arch, ver
printf "       %s %-10s - Minimum supported Operating System\n", arch, mver
printf "       %s %-10s - MATLAB built using this Operating System\n", arch, rver
printf "       %s %-10s - Maximum supported Operating System\n", arch, fver
print "----------------------------------------------------------------------------"
print " "
          }
        }' > $temp_file
#---------------------------------------------------------------------------
#=======================================================================
# Functions:
#=======================================================================
    echon ()    { # echo without a newline - UNIX dependent
                  #
                  # usage: echon
                  #
        if [ "`echo -n`" != "" ]; then
            echo "$1\c"
        else
            echo -n "$1"
        fi
    }
#=======================================================================
        if [ -s $temp_file ]; then
            cat $temp_file
            errtype=`cat $temp_file | awk 'NR == 3 {print $5}'`
            case "$errtype" in
                'Unsupported')
#---------------------------------------------------------------------------
echo '-> Your Operating System APPEARS to be too OLD to run this MATLAB program!'
echo '----------------------------------------------------------------------------'
#---------------------------------------------------------------------------
                    ;;
                'Unqualified')
#---------------------------------------------------------------------------
echo '-> Your Operating System APPEARS to be too NEW to run this MATLAB program!'
echo '----------------------------------------------------------------------------'
#---------------------------------------------------------------------------
                    ;;
                'Your')
		    if [ "$errmode" = "1" ]; then
#---------------------------------------------------------------------------
echo '-> Please Note: This program may work on this host but MATLAB will not!'
echo '----------------------------------------------------------------------------'
echo 'Please wait . . .'
echo ' '
#---------------------------------------------------------------------------
		        sleep 5
		    else
#---------------------------------------------------------------------------
echo ' '
#---------------------------------------------------------------------------
		    fi
		    ;;
                 *)
                    :
                    ;;
            esac
#
            case "$errtype" in
                'Unsupported'|'Unqualified')
#---------------------------------------------------------------------------
echo '   For system requirements consult http://www.mathworks.com ...'
#---------------------------------------------------------------------------
                    ;;
                'Internal')
#---------------------------------------------------------------------------
echo 'Please report this problem to The MathWorks, Inc. Technical Support'
echo '       phone: (508) 647-7000'
echo '       email: support@mathworks.com'
#---------------------------------------------------------------------------
                    ;;
                 *)
                    :
                    ;;
            esac
#
            case "$errtype" in
                'Unsupported'|'Unqualified'|'Internal')
#---------------------------------------------------------------------------
echo ' '
echo '***************************************************************************'
echo '-> Best to quit by pressing <return> at the next prompt ...'
echo ' '
echon '   Do you still want to try to continue? (y/[n]) > '
#---------------------------------------------------------------------------
                    if [ "$batch" != "1" ]; then
                        read ans
                        if [ `expr "//$ans" : '//[Yy].*'` -gt 0 ]; then
                            :
                        else
                            oscheck_status=1
                        fi
                    else
#---------------------------------------------------------------------------
     echo 'y'               
#---------------------------------------------------------------------------
                    fi
#---------------------------------------------------------------------------
echo ' '
#---------------------------------------------------------------------------
                    ;;
                 *)
                    :
                    ;;
            esac
	fi
    fi
    rm -f $temp_file
#========================= oscheck.sh (end) ==============================
        if [ "$oscheck_status" = "1" ]; then
            cleanup
            exit 1
        fi
    fi
  }
# end get_arch ()
#
#****************************************************************************
#
  eval_assignments () {
#
# Source the file of argument variables, name=[def]
#
    if [ -f /tmp/$$a ]; then
        . /tmp/$$a
    fi
#
# Make sure that LD is fully evaluated to handle LD=$COMPILER assignment
#
    LD="`eval echo $LD`"

  }

# end eval_assignments ()
#
#****************************************************************************
#
  error_check () {
#
#   Check for errors in calling syntax
#
    if [ "$files" != "" -a "$cfiles" != "1" -a "$ffiles" != "1" ]; then
        cfiles=1
    fi
    if [ "$stat" != "OK" ]; then                  # An error occurred.
        if [ "$stat" != "" ]; then
            describe status >&2
        fi
        describe usage >&2
        cleanup
        exit 1
    fi
  }
# end error_check ()
#
#****************************************************************************
#
  get_name () {
#
#   Use the first file name to determine the name of the executable.
#   If there is already a mbuild name, -output was used.
#   If there are no files, don't complain (error_check comes later).
#
    if [ "$1" != "" -a "$outname" = "" ]; then
        ext=`expr "$1" : '\.*[^.].*\.\([^.]*\)$'`
        outname=`expr "//$1" : ".*/\(.*\)\.${ext}$" \| "//$1" : ".*/\(.*\)"`
        outname=$outname$mbuild_ext
    elif [ "$outname" != "" ]; then
        ext=`expr "$outname" : ".*\.$mbuild_ext$"`
        if [ "$ext" = "0" ]; then
            outname=$outname$mbuild_ext
        fi
    fi

    if [ "$OUTDIR" != "" ]; then
	outname="$OUTDIR/$outname"
    fi
    outname=`smart_quote $outname`
  }
# end get_name ()
#
#****************************************************************************
#
  compile () {
    trap "eval $abort; exit 1" 1 2 3 15
#
#   For each file, compile source files and add other files
#   to the list of link options.
#
    file="$1"
    if [ ! -f "$file" ]; then
        describe file_not_found >&2
        cleanup
        exit 1
    fi
#
# determine extension and basename
#
    ext=`expr "$file" : '\.*[^.].*\.\([^.]*\)$'`
    if [ "$ext" = "" ]; then
        ext=`expr "$file" : '\.*[^.].*\.\(so\)[.0-9]*$'`
    fi
    basename=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$file : ".*/\(.*\)"`
#
    if [ "$TEMP" != "" -a "$compile_only" != "1" ]; then
        basename=$TEMP/$basename$$
    elif [ "$OUTDIR" != "" ]; then
        basename=$OUTDIR/$basename
    fi
    basename=`smart_quote $basename`
#
# Source file extensions: .c .C .cc .cxx .cpp .f .for .F
#
    case "$ext" in
        c | C | cc | cpp | cxx) # C/C++ source file.
#
# determine whether to optimize or debug
#
            if [ "$debug" != "1" ]; then
                flags="$COPTIMFLAGS"
            elif [ "$optimize" = "1" ]; then
                flags="$CDEBUGFLAGS $COPTIMFLAGS"
            else
                flags="$CDEBUGFLAGS"
            fi
#
# Determine final compile command for C source code.
#
            flags="$CFLAGS $cc_flags $flags"
            compile_command="$CC -c $include_dirs $flags $file"
            ;;

        *)
#
# Object files: Don't need to do anything except add to compiled list
#
            objs="$objs $file"
            return 0
            ;;
    esac
#

    if [ "$TEMP" != "" -a "$compile_only" != "1" ]; then
        compile_command="$compile_command -o $basename.o"
    elif [ "$OUTDIR" != "" ]; then
        compile_command="$compile_command -o $basename.o"
    fi
#
    if [ "$verbose" = "1" -o "$no_execute" = "true" ]; then
        describe compile_stage
    fi
#
    if [ "$no_execute" != "true" ]; then eval "$compile_command"; fi
    if [ $? -ne 0 ]; then
        describe failed_compile >&2
	cleanup
        exit 1
    fi
    if [ "$compile_only" != "1" ]; then
        if [ "$Arch" = "sol2" -a "$debug" = "1" ]; then
            # We need to keep the object files around
            :
        else
            INTERMEDIATE="$INTERMEDIATE $basename.o"
        fi
    fi
    objs="$objs $basename.o"
  }
# end compile ()
#
#****************************************************************************
#
  makedef () {
    trap "eval $abort; exit 1" 1 2 3 15
    
# Just in case there are no .exports files specified by the user,
# make sure it does
    touch $LI_EXPFILE

    if [ "$verbose" = "1" ]; then
        describe makedef_stage
    fi

    eval $SHLMAKEDEF $LI_EXPFILE > $EXPFILE
  }
# end makedef ()
#
#****************************************************************************
#
  link () {
    trap "eval $abort; exit 1" 1 2 3 15
#
# Fix LD_LIBRARY_PATH
#
    case "$Arch" in
        sol2|alpha|sgi|lnx86|glnx86)
            if [ "$LD_LIBRARY_PATH" != "" ]; then
                LD_LIBRARY_PATH=$TMW_ROOT/extern/lib/$Arch:$LD_LIBRARY_PATH
            else
                LD_LIBRARY_PATH=$TMW_ROOT/extern/lib/$Arch
            fi
            export LD_LIBRARY_PATH
            ;;
        hpux|hp700)
            if [ "$SHLIB_PATH" != "" ]; then
                SHLIB_PATH=$TMW_ROOT/extern/lib/$Arch:$SHLIB_PATH
            else
                SHLIB_PATH=$TMW_ROOT/extern/lib/$Arch
            fi
            export SHLIB_PATH
            ;;
        ibm_rs)
            if [ "$LIBPATH" != "" ]; then
                LIBPATH=$TMW_ROOT/extern/lib/$Arch:$LIBPATH:/usr/lib:/lib
            else
                LIBPATH=$TMW_ROOT/extern/lib/$Arch:/usr/lib:/lib
            fi
            export LIBPATH
            ;;
        sgi64)
            if [ "$LD_LIBRARY64_PATH" != "" ]; then
                LD_LIBRARY64_PATH=$TMW_ROOT/extern/lib/$Arch:$LD_LIBRARY64_PATH
            else
                LD_LIBRARY64_PATH=$TMW_ROOT/extern/lib/$Arch
            fi
            export LD_LIBRARY64_PATH
            ;;
    esac
#
#   Link stage
#
    if [ "$cfiles" = "1" ]; then
        libs="$libs $CLIBS"
    fi
    libetc="$objs $libs"
#
# determine whether to optimize or debug
#
    if [ "$debug" != "1" ]; then
        LDFLAGS="$LDOPTIMFLAGS $LDFLAGS"
    elif [ "$optimize" = "1" ]; then
        LDFLAGS="$LDDEBUGFLAGS $LDOPTIMFLAGS $LDFLAGS"
    else
        LDFLAGS="$LDDEBUGFLAGS $LDFLAGS"
    fi

    if [ "$linkarg" = "shared" ]; then
        case "$Arch" in
            alpha | sgi | sgi64)
                if [ "$TEMP" != "" ]; then
                    SO_LOCATIONS=$TEMP/so_locations$$
                    LDFLAGS="$LDFLAGS -update_registry $SO_LOCATIONS"
                fi
                ;;
            sol2)
        #
        # The mechanism for defining which symbols to export or hide is
        # the ld -Wmapfile option.  For Solaris 2.4 this requires patch
        # 102303-05.
        #
                patched=`showrev -p | grep -c '102303-05'`
                osversion=`uname -r`
                if [ "$osversion" = '5.4' ]; then
                    if [ ! "$patched" = '1' ]; then
                        describe solaris_linker_patch >&2
                        cleanup
                        exit 1
                    fi
                fi
                ;;
        esac
    fi

    if [ "$verbose" = "1" -o "$no_execute" = "true" ]; then
        describe link_stage
    fi
    if [ "$no_execute" != "true" ]; then 
        
        eval "$LD $LDFLAGS $ld_flags -o $outname $libetc"; 
    fi
    if [ $? -ne 0 ]; then
        describe failed_link >&2
        cleanup
        exit 1
    fi
  }
# end link ()
#
#****************************************************************************
#
# Main routine
#
#
# Determine what is set in the environment
# 
    MATLABenv="$MATLAB"
    AUTOMOUNT_MAPenv="$AUTOMOUNT_MAP"
#
#  Initialize some variables
#
    TMW_ROOT=|>MATLAB<|
    AUTOMOUNT_MAP=|>AUTOMOUNT_MAP<|
    SOURCE_DIR="search"
    OPTIONS_FILE="mbuildopts.sh"
#
# If MATLABenv is not empty ALWAYS use that for TWM_ROOT.
#
    if [ "$MATLABenv" != "" -a "$MATLABenv" != "$TMW_ROOT" ]; then
        TMW_ROOT="$MATLABenv"
    fi
#
# If AUTOMOUNT_MAPenv is not empty ALWAYS use that for AUTOMOUNT_MAP
#
    if [ "$AUTOMOUNT_MAPenv" != "" ]; then
        AUTOMOUNT_MAP="$AUTOMOUNT_MAPenv"
    fi
#
    if [ "$AUTOMOUNT_MAP" != "" ]; then
#----------------------------------------------------------------------------
            TMW_ROOT=`echo $TMW_ROOT $AUTOMOUNT_MAP | awk '
                {if (substr($1,1,length($2)) == $2)
                     if (NF == 4)                               # a -> b
                         print $NF substr($1,length($2) + 1)
                     else                                       # a ->
                         print substr($1,length($2) + 1)
                 else
                     print $1}'`
#----------------------------------------------------------------------------
    fi
#
    stat="OK"
    Arch='Undetermined'
    ARCH=
#
# Set up the linker-independent (LI_) and linker-specific export file names
    LI_EXPFILE="/tmp/$$tmp_export_list"
    EXPFILE="/tmp/$$processed_export_list"
    INTERMEDIATE="$INTERMEDIATE $LI_EXPFILE $EXPFILE"

    linkarg="unspecified"
    exports_file_seen=0

    SO_LOCATIONS=so_locations

    arg_count=$#
    while [ "$stat" = "OK" -a  $# -gt 0 ]; do
#
# Parse input arguments.  The routine may need the next two arguments,
# as in -f optionsfile and -o mbuildfilename.
#
        case "$1" in
            -c)
                compile_only=1
                ;;
            -D*)                           # Compiler flags.
                lhs=`expr "$1" : '\(-D[a-zA-Z0-9_]*\).*'`
                mid=`expr "$1" : '-D[a-zA-Z0-9_]*\([=\#]\).*$'`
                rhs=`expr "$1" : '-D[a-zA-Z0-9_]*[=\#]\(.*\)$'`
                
                if [ "$mid" != "" ]; then
                    mid="="
                fi

                cc_flags="$cc_flags $lhs$mid$rhs"
                fc_flags="$fc_flags $lhs$mid$rhs"
                ;;
            -[UI]*)                        # Compiler flags.
                cc_flags="$cc_flags $1"
                fc_flags="$fc_flags $1"
                ;;
            -f)
                if [ -f "$2" ]; then
                    OPTIONS_FILE="$2"
                    SOURCE_DIR='none'
                else
#                   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '    Error: An invalid options file name was specified:' >&2
    echo "           $2 is not a normal file or does not exist." >&2
    echo '' >&2
                    cleanup
                    exit 1
#                   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                fi
                shift
                ;;
            -[g]*)                          # Use debugging flags.
                debug=1
                ;;
            -h | -help | -\? )              # -help: Help option.
                describe "help"
		cleanup
		exit 0
                ;;
            -inline)
                cc_flags="$cc_flags -DARRAY_ACCESS_INLINING"
                ;;
            -lang)                          # -lang c or -lang cpp
	        lang=$2
                case "$lang" in
                    c)
                         ;;
                  cpp)
                         ;;
                    *)
			 describe "lang"
                         cleanup
                         exit 1
                         ;;
                esac 
		shift
		;;
            -link)                          # undocumented/grandfathered option
		linkarg=$2                  # -link exe or -link shared
                case "$linkarg" in
                  exe)
                        ;;
                  shared)
                        ;;
                  *)
                        describe "link"
                        cleanup
                        exit 1
                        ;;
                esac

		shift
		;;
            -l*)
                libs="$libs $1"
                ;;
            -L*)                            # -Ldirectory: search path
                ld_flags="$ld_flags $1"
                ;;
            -n)                             # output name
                no_execute="true"
                ;;
            -no_mwsglm)                     # suppress default linking with 
                                            # libmwsglm - undocumented
                no_mwsglm="true"
                ;;
            -no_mmfile)                     # suppress default linking with 
                                            # libmmfile - undocumented
                no_mmfile="true"
                ;;
            -outdir)                        # output directory
                OUTDIR=$2
                shift
                ;;
            -output)                        # output name
                outname=$2
                shift
                ;;
            -O)                             # Use optimization flags.
                optimize=1
                ;;
            -setup)
		if [ $arg_count -ne 2 -a $arg_count -ne 1 ]; then
		    describe usage >&2
                    cleanup
		    exit 1
		else
		    setup_options_file $2
                    cleanup
		    exit 0
		fi
                ;;
            -v)
                verbose=1
                ;;
            -*)
                check_archlist argument=$1 noprint
                if [ "$ARCH" = "" ]; then
                    stat="$1 not a valid option."
                fi
                ;;
            TMW_ROOT[=\#]*)
                mlrhs=`expr "$1" : '[a-zA-Z0-9_]*[=\#]\(.*\)$'`
                TMW_ROOT="`eval echo $mlrhs`"
                ;;
            *[=\#]*)
                lhs=`expr "$1" : '\([a-zA-Z0-9_]*\)[=\#].*'`
                rhs=`expr "$1" : '[a-zA-Z0-9_]*[=\#]\(.*\)$'`
                echo $lhs='"'$rhs'"' >> /tmp/$$a
                INTERMEDIATE="$INTERMEDIATE /tmp/$$a"
                ;;
            *.c)                              # C source file
                cfiles=1
                files="$files $1"
                ;;
            *.C | *.cc | *.cpp | *.cxx)       # C++ source file.
                cppfiles=1
                files="$files $1"
                ;;
            *.o)                              # object files
                files="$files $1"
                ;;
	    *.exports)       
                # Note that the first regular expression below contains
                # a tab character.
                awk '$0 !~ /^[	 ]*$/ && $0 !~ /^[#*]/ { print; }' "$1" >> $LI_EXPFILE 
                exports_file_seen=1
		;;
            *)                                # other files
                libs="$libs $1"
                ;;
        esac
    shift
    done

    if [ "$linkarg" = "unspecified" ]; then
        if [ $exports_file_seen = 1 ]; then
            linkarg="shared"
        else
            linkarg="exe"
        fi
    fi
#

# Handle -lang switch here
    if [ "$lang" = "c" ]; then
        cppfiles=""
    elif [ "$lang" = "cpp" ]; then
        cppfiles=1
    fi

    error_check                         # Check calling syntax errors

#
# It is now safe to use functions, since we have parsed all of the
# input arguments.  (The use of functions corrupts $# and $* on
# HP-UX 9.0x systems.)
#
    if [ ! "$OPTIONS_FILE" ]; then      # If no -f optionsfile was used
        describe no_options_file
        cleanup
	exit 1
    elif [ "$SOURCE_DIR" = "search" ]; then
        find_options_file $OPTIONS_FILE
    fi
#

    . $OPTIONS_FILE                     # Source file to determine $TMW_ROOT
    
    get_arch                            # Determine architecture
#
    get_ext                             # Determine appropriate extension
    get_name $files                     # Determine result name
#
    if [ "$ffiles" = "1" ]; then
        COMPILER='$FC'
    else
        COMPILER='$CC'
    fi
#
    . $OPTIONS_FILE                     # Source options file

#
# Switch to C++ compiler if any C++ files passed to mbuild
#
    if [ "$cppfiles" = "1" ]; then
	COMPILER="$CPP"
        CC="$CPP"
        CFLAGS="$CPPFLAGS"
        CDEBUGFLAGS="$CPPDEBUGFLAGS"
        COPTIMFLAGS="$CPPOPTIMFLAGS"
        CLIBS="$CPPLIBS"
        LDFLAGS="$CPPLDFLAGS"
    elif [ "$linkarg" = "shared" ]; then
        if [ "$SHLMAKEDEF" = "" ]; then
            describe cant_make_shl >&2
            cleanup
            exit 1
        fi
        CFLAGS="$SHLCFLAGS"
        LD="$SHLLD"
        LDFLAGS="$SHLLDFLAGS"
    fi

# This must come after the switch to C++.
    
    if [ "$no_mmfile" = "true" ]; then
        CLIBS=`echo $CLIBS | sed -e 's/-lmmfile//g'`
    fi
    if [ "$no_mwsglm" = "true" ]; then
        CLIBS=`echo $CLIBS | sed -e 's/-lmwsglm//g'`
    fi

    eval_assignments                    # Evaluate VAR=value arguments

    if [ "$verbose" = "1" ]; then
        describe final_options
    fi
#
    if [ "$files" = "" ]; then
        stat="no file names given."
        describe status >&2
        describe usage >&2
        cleanup
        exit 1
    fi
#
# From this point on, we need to put traps in each function.  The IBM
# resets traps on entry to each function, so we need to safeguard
# any functions we call after compiling.  This includes compile(),
# link(), and cleanup().
#
    set $files
    for file in $*
    do
        compile $file                   # Process each file in list
    done
#
    if [ "$compile_only" != "1" ]; then
        if [ "$linkarg" = "shared" ]; then
            makedef
        fi
        link                            # Perform linking
        if [ "$SGL" =  "1" ]; then
	    if [ "$OUTDIR" = "" ]; then
		OUTDIR='.'
	    fi
	    if [ ! -d $OUTDIR/bin ]; then
	        mkdir $OUTDIR/bin
	    fi
	    if [ ! -f $OUTDIR/bin/FigureMenuBar.fig ]; then
	       cp $TMW_ROOT/extern/include/FigureMenuBar.fig  $OUTDIR/bin/
	    fi
	    if [ ! -f $OUTDIR/bin/FigureToolBar.fig ]; then
	       cp $TMW_ROOT/extern/include/FigureToolBar.fig  $OUTDIR/bin/
	    fi
	    if [ ! -f $OUTDIR/bin/Matlab ]; then
	       cp $TMW_ROOT/X11/app-defaults/Matlab  $OUTDIR/bin/
	    fi
	    if [ "$Arch" = "hpux" -o "$Arch" = "hp700" ]; then
	       if [ ! -d $OUTDIR/bin/$Arch ]; then
	           mkdir $OUTDIR/bin/$Arch
	       fi
	       if [ ! -f $OUTDIR/bin/$Arch/glren.sl ]; then
	           cp $TMW_ROOT/bin/$Arch/glren.sl  $OUTDIR/bin/$Arch/
	       fi
	    fi
        fi
    fi
#
    cleanup
    exit 0
#
#****************************************************************************
