#!/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 Compiler-generated shared libraries into a stand-alone
#    executable or shared library.
#  
#    The first filename given (less any file name extension) will be the
#    name of the resulting executable. You can give additional source,
#    object, or library files to satisfy external references. You can
#    specifiy either C or C++ source files when building executables. In
#    addition, you can specify both C and C++ source files at the same
#    time as long as the C files are C++ compatible, and you specify the
#    -lang cpp option (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
#        Compiler.
#    -lang <language>
#        Specify compiler language. <language> can be c or cpp. By
#        default, MBUILD determines which compiler (C or C++) to use by
#        inspecting the source file's extension. This option overrides
#        that default.
#    -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 an 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 a
#        default for future invocations of MBUILD by placing it in
#        "<UserProfile>\Application Data\MathWorks\MATLAB\<rel_version>"
#        (for Windows) or $HOME/.matlab/<rel_version> (for UNIX). 
#        <rel_version> is the base release version, such as R14. When this
#        option is specified, no other command line input is accepted.
#    -U<name>
#        Remove any initial definition of the C preprocessor symbol
#        <name>. (This is the 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. This option
#        is 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:
#
#    -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 filename and location, then
#      MBUILD searches for an options file named compopts.bat in the
#      current directory, and then the directory
#      "<UserProfile>\Application Data\MathWorks\MATLAB\<rel_version>".
#      <rel_version> is the base release version, such as R14. You can
#      override any variable specified in the options file at the command
#      line by using the <name>#<value> command-line argument. If <value>
#      has spaces in it, then it should be 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 filename and location,
#      then MBUILD searches for an options file named mbuildopts.sh in the
#      the current directory (.), then $HOME/.matlab/<rel_version>, and
#      then $MATLAB/bin. <rel_version> is the base release version, such
#      as R14. You can override any variable specified in the options file
#      at the command line by using the <name>=<def> command-line
#      argument. If <def> has spaces in it, then it should be 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:
#
#      This 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
#
#      This 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 Compiler User's Guide
#
# Copyright 1984-2004 The MathWorks, Inc.
# $Revision: 1.50.4.12 $  $Date: 2004/12/22 19:52:40 $
#____________________________________________________________________________
#
    arg0_=$0
    tmpbase=/tmp/mbuild.$LOGNAME.$$

    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-2004 The MathWorks, Inc.
# $Revision: 1.9.4.4 $  $Date: 2004/07/08 01:06:10 $
#----------------------------------------------------------------------------
#
    ARCH_LIST='sol2 hpux glnx86 glnxi64 glnxa64 mac'
#=======================================================================
# 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) ==============================
#
#========================== version.sh (start) ============================
#
# usage:        version [-b]
#
# abstract:     This POSIX Shell script function returns the MATLAB
#               release version. Any bad options are ignored without
#		warning.
#
#		The version is assumed to be of the form:
#
#		    R<integer>[<noninteger>]
#
#               options:
#
#		b       - return just R<integer> or the base version.
#
# note(s):      1. This file is always imbedded in another script
#
# Copyright 1992-2003 The MathWorks, Inc.
# $Revision: 1.1.6.2 $  $Date: 2004/07/08 01:06:11 $
#----------------------------------------------------------------------------
#
version () {
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ver='R14'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if [ $# -eq 1 ]; then
        if [ "$1" = '-b' ]; then
            expr "$ver" : '\(R[0-9]*\).*$'
	    return $?
        fi
    fi
    echo "$ver"
    return 0
}
#========================== version.sh (end) ==============================
    REL_VERSION=`version -b`
#
#============================================================================
#  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
    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 Compiler-generated shared libraries into a stand-alone
  executable or shared library.
  
  The first filename given (less any file name extension) will be the
  name of the resulting executable. You can give additional source,
  object, or library files to satisfy external references. You can
  specifiy either C or C++ source files when building executables. In
  addition, you can specify both C and C++ source files at the same
  time as long as the C files are C++ compatible, and you specify the
  -lang cpp option (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
      Compiler.
  -lang <language>
      Specify compiler language. <language> can be c or cpp. By
      default, MBUILD determines which compiler (C or C++) to use by
      inspecting the source file's extension. This option overrides
      that default.
  -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 an 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 a
      default for future invocations of MBUILD by placing it in
      "<UserProfile>\Application Data\MathWorks\MATLAB\<rel_version>"
      (for Windows) or $HOME/.matlab/<rel_version> (for UNIX). 
      <rel_version> is the base release version, such as R14. When this
      option is specified, no other command line input is accepted.
  -U<name>
      Remove any initial definition of the C preprocessor symbol
      <name>. (This is the 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. This option
      is 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 UNIX platforms:

  -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 UNIX:
    The options file is written as a UNIX shell script. If the -f
    option is not used to specify the options filename and location,
    then MBUILD searches for an options file named mbuildopts.sh in the
    the current directory (.), then $HOME/.matlab/<rel_version>, and
    then $MATLAB/bin. <rel_version> is the base release version, such
    as R14. You can override any variable specified in the options file
    at the command line by using the <name>=<def> command-line
    argument. If <def> has spaces in it, then it should be 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:

    This 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

    This 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 Compiler User's Guide

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 Compiler 
    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 ''
            ;;
        postlink_stage)
    echo "-> $POSTLINK_CMDS"
    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/<rel_version>/<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/$REL_VERSION/$1 ]; then
        SOURCE_DIR='$HOME/.matlab/$REL_VERSION'
        SOURCE_DIReval=$HOME/.matlab/$REL_VERSION
        OPTIONS_FILE="$HOME/.matlab/$REL_VERSION/$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_sl_ext () {
#
#   Determine extension for shared library file
#
    case "$Arch" in
        hpux)
            sl_ext='.sl'
            ;;
        mac)
            sl_ext='.dylib'
            ;;
	*)
	    sl_ext='.so'
	    ;;
    esac
  }
# end get_sl_ext ()
#****************************************************************************
#
  get_ext () {
#
#   Determine extension for shared library file
#
    if [ "$linkarg" = "shared" ]; then
        mbuild_ext=$sl_ext
    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 1984-2003 The MathWorks, Inc.
#  $Revision: 1.16.4.3 $  $Date: 2004/04/25 21:30:59 $
#____________________________________________________________________________
#
#****************************************************************************
#


setup_describe () {

SCRIPT_NAME=`basename $arg0_`

cat << EOF

    Using the '$SCRIPT_NAME -setup' command selects an options file that is
    placed in ~/.matlab/$REL_VERSION 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/$REL_VERSION.

    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/<rel_version> for the user, if it doesn't already exist.
    # <rel_version> is the base release version like R14.
    #
    if [ ! -d $HOME/.matlab/$REL_VERSION ]; then
        echo
        echo $HOME/.matlab/$REL_VERSION does not exist. It will be created.
        echo
	mkdir -p $HOME/.matlab/$REL_VERSION
    fi

    if [ -d $HOME/.matlab/$REL_VERSION/$DEFAULT_OPTIONS_FILE ]; then
        echo "$HOME/.matlab/$REL_VERSION/$DEFAULT_OPTIONS_FILE is a directory. Please remove it."
        exit 1
    fi
    if [ -f $HOME/.matlab/$REL_VERSION/$DEFAULT_OPTIONS_FILE ]; then
        echo "Overwrite $HOME/.matlab/$REL_VERSION/$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/$REL_VERSION/$DEFAULT_OPTIONS_FILE
    fi
    echo
    echo "$FOUND_FILE is being copied to "
    echo "$HOME/.matlab/$REL_VERSION/$DEFAULT_OPTIONS_FILE"
    echo
    cp $FOUND_FILE $HOME/.matlab/$REL_VERSION/$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-2004 The MathWorks, Inc.
# $Revision: 1.17.4.5 $  $Date: 2004/07/08 01:06:09 $
#----------------------------------------------------------------------------
#
#=======================================================================
# 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)
		    case "`/bin/uname -m`" in
		    i*86)
			ARCH="glnx86"
			;;
		    ia64)
			ARCH="glnxi64"
			;;
		    x86_64)
			ARCH="glnxa64"
			;;
		    esac
		    ;;
# Usually uname lives in /usr/bin on the Mac, but sometimes people 
# have links in /bin that link uname to /usr/bin.  Because of this
# Mac needs to be listed in the checks for both /bin/uname and /usr/bin/uname
	        Darwin)					# Mac OS X
                    ARCH="mac"
                    ;;
	        *)
		    :
	            ;;
	    esac
	elif [ -f /usr/bin/uname ]; then
   	    case "`/usr/bin/uname`" in
	        Darwin)					# Mac OS X
                    ARCH="mac"
                    ;;
            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=$tmpbase.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 tested 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
#		   hpux:    uname -r          -> token(1)(3:end)
#                  glnx86:  /lib/libc.so.6    -> messy parsing to yield token 
#                  glnxi86: (fixed until more experience)
#		   glnxa86: /lib/libc.so.6    -> messy parsing to yield token
#		   mac:     uname -r	      -> token(1)
#
#               3. This requires at least the System V Bourne Shell since
#                  internal functions are used.
#
#               4. 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.
#
#               5. Assume that this routine is called using the
#                  unused temporary file defined by
#
#                     $temp_file
#
#               6. The calling routine will exit if the variable,
#                  oscheck_status, is set as follows:            
#
#                      oscheck_status=1
#
#               7. Also, any cleanup associated with of an interrupt
#                  will be handled by the calling routine.
#
#               8. Set oscheck_debug=1 to check for the consistency 
#                  of the data. Set oscheck_debug=0 for shipping.
#
# Copyright 1996-2004 The MathWorks, Inc.
# $Revision: 1.20.4.5 $  $Date: 2004/08/13 23:14:29 $
#----------------------------------------------------------------------------
#
    oscheck_status=0
#
#                   arch   OSprefix minimum_ver release_ver future_ver
#
    oslist="        sol2    SunOS    5.8         5.8         -"
    oslist="$oslist hpux    HP-UX    11.00       11.00       -"
    oslist="$oslist glnx86  glibc    2.2.0       2.2.5       -"
    oslist="$oslist glnxi64 glibc    2.2.4       2.2.4       -"
    oslist="$oslist glnxa64 glibc    2.3.2       2.3.2       -"
    oslist="$oslist mac     Darwin   7.2.0       7.2.0       -"
#
    if [ -f /bin/uname ]; then
        case $Arch in
            glnx86)
#
# Note: R13 used 'uname -r'. If you use ver below, we shipped with 2.1.2
#
# This may be run on either glnx86 or glnxa64. Note that things are OK
# since release_ver on glnx86 <= glnxa64.
#
# Example: first line from executing /lib/libc.so.6
# glnx86:  GNU C Library stable release version 2.2.5, by Roland McGrath et al.
# glnxa64: GNU C Library stable release version 2.3.2 (20030827), by Roland McGrath et al.
#
                ver=`/lib/libc.so.6 | head -n 1 | sed -e "s/^[^0-9]*//" -e "s/[ ,].*$//"`
                ;;
            glnxi64)
#
# We do not have a lot of experience yet on how things will look across multiple
# vendors. So we will pick a fixed version for now.
#
# 1. Red Hat version: ver=`/lib/libc.so.6.1 | head -n 1 | sed -e "s/^[^0-9]*//" -e "s/,.*$//"`
#
                ver=2.2.4
                ;;
            glnxa64)
#
# Example: first line from executing /lib64/libc.so.6
# glnxa64: GNU C Library stable release version 2.3.2 (20030827), by Roland McGrath et al.
#
                ver=`/lib64/libc.so.6 | head -n 1 | sed -e "s/^[^0-9]*//" -e "s/[ ,].*$//"`
                ;;
            sol2)
                ver=`/bin/uname -r`
                ;;
            hpux)  # Remove the leading capital letter and period
                ver=`/bin/uname -r | awk '{print substr($1,3)}'`
                ;;
	    Darwin)					# Mac OS X
        	ver=`/usr/bin/uname -r | awk '{print $1}'`
                ;;
            *)
		ver=`/bin/uname -r | awk '{print $1}'`
                ;;
        esac
    elif [ -f /usr/bin/uname ]; then
        case "`/usr/bin/uname`" in
	    Darwin)					# Mac OS X
                ver=`/usr/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 version\n", arch, ver
printf "         %s %-10s - MATLAB built using this version\n", arch, rver
print "----------------------------------------------------------------------------"
          }
          else if (errmode == 2) {
print " "   
print "----------------------------------------------------------------------------"
printf "Warning: %s %-10s - Your version\n", arch, ver
printf "         %s %-10s - MATLAB built using this version\n", arch, rver
print "----------------------------------------------------------------------------"
          }
          else if (errmode == 3) {
print " "   
print "----------------------------------------------------------------------------"
printf "Warning: %s %-10s - Unqualified version\n", arch, ver
printf "         %s %-10s - MATLAB built using this version\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 version\n", arch, mver
printf "       %s %-10s - MATLAB built using this version\n", arch, rver
printf "       %s %-10s - Maximum supported version\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 configuration APPEARS to be too OLD to run this MATLAB program!'
echo '----------------------------------------------------------------------------'
#---------------------------------------------------------------------------
                    ;;
                'Unqualified')
#---------------------------------------------------------------------------
echo '-> Your configuration 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 $tmpbase.a ]; then
        . $tmpbase.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 ()
#
#****************************************************************************
#
 get_precompile () {
#
# Use the architecture to determine if environment variables need to be set/unset 
# in any way

     if [ "$Arch" = "hpux" ]; then 
	 precompile="unset LD_PRELOAD;"
     fi
}
# end get_precompile ()
#
#****************************************************************************
#
  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
#
    get_precompile $precompile

    if [ "$no_execute" != "true" ]; then eval "$precompile $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
#
#   Link stage
#
    if [ "$cfiles" = "1" ]; then
        libs="$CLIBS $libs"
    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
             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=/data/matlabr14sp2
    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 [ `uname` = "Darwin" ]; then
	privatemap=`expr "$TMW_ROOT" : '/private/*'`
	if [ "$privatemap" = "9" ]; then
   	   # If $TMW_ROOT starts with /private/ assume it needs to have
  	   # AUTOMOUNT_MAP set.
   	   AUTOMOUNT_MAP='/private ->'
	fi
    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

    linkhg="false"

    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"
                ;;
            -nohg)                          # suppress default linking with
                linkhg="false"              # libmwsgl 
                ;;                          
            -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'"' >> $tmpbase.a
                INTERMEDIATE="$INTERMEDIATE $tmpbase.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_sl_ext                          # determine architecture's shared library extension
    get_ext                             # Determine appropriate extension
    get_sl_ext                          # determine architecture's shared library extension
    get_name $files                     # Determine result name
#
    if [ "$ffiles" = "1" ]; then
        COMPILER='$FC'
    else
        COMPILER='$CC'
    fi
#
#   Check for existence of Graphics Library
#   Set $linkhg accordingly, so that mbuildopts.sh can use it in determining
#   default settings.
#
    if [ ! -f "$TMW_ROOT/extern/lib/$Arch/libmwsgl$sl_ext" ]; then
        linkhg="false"                  # if libmwsgl not installed, then
                                        # assume Graphics Library not 
                                        # installed. So don't link against it.
    fi

    . $OPTIONS_FILE                     # Source options file

#
# Fix variables for compile step: consider C++ files and shared link step
#
    if [ "$cppfiles" = "1" ]; then
        COMPILER="$CXX"
        CC="$CXX"
        if [ "$linkarg" = "shared" ]; then
           CFLAGS="$SHLCXXFLAGS"		# This is new with R14
        else
           CFLAGS="$CXXFLAGS"
        fi
        CDEBUGFLAGS="$CXXDEBUGFLAGS"
        COPTIMFLAGS="$CXXOPTIMFLAGS"
        CLIBS="$CXXLIBS"
# Adding condition for use of -fPIC: support for glnxa64 
     else 
	if [ "$linkarg" = "shared" ]; then 
	    CFLAGS="$SHLCFLAGS"
	fi
     fi
#
# Fix variables for link step: consider shared link step
#
     if [ "$linkarg" = "shared" ]; then
        if [ "$SHLMAKEDEF" = "" ]; then
            describe cant_make_shl >&2
            cleanup
            exit 1
        fi
        LD="$SHLLD"
        if [ "$cppfiles" = "1" ]; then
          LDFLAGS="$SHLCXXLDFLAGS"		# This is new with R14
        else
          LDFLAGS="$SHLLDFLAGS"
        fi
        POSTLINK_CMDS="$SHLPOSTLINK_CMDS"
      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 [ "$linkhg" = "true" ]; 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" ]; 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

        # Perform any POSTLINK_CMDS; ":" is the empty/null command which
        # we initialize POSTLINK_CMDS to in order to allow for concatenation
        # of multiple postlink commands such as 
        #
        # POSTLINK_CMDS='$POSTLINK_CMDS;my_command'
        #
        # if POSTLINK_CMDS were initially empty in the above command, the 
        # result would be ";my_command" which isn't legal.
        if [ "$POSTLINK_CMDS" != ":" -a "$POSTLINK_CMDS" != "" ]; then
            if [ "$verbose" = "1" -o "$no_execute" = "true" ]; then
                describe postlink_stage
            fi
            if [ "$no_execute" != "true" ]; then 
                eval "$POSTLINK_CMDS"; 
            fi
        fi
    fi
#
    cleanup
    exit 0
#
#****************************************************************************
