#! /bin/sh
#
#  Name:
#     cmex    compilation program for MATLAB C language MEX files
#     
#  Usage:
#     cmex  [ -c -debug -Dname[=def] -flibs -g -Ipathname -llibrary
#	      -Ldir -O[level] -Uname -v3.5 -v name=[def] CASE=value ]
#	      sourcefile ... [ objectfile ] ... [ library ] ...
#
#   Description:
#     "cmex" will compile and link MEX source files into a relocatable
#     executable image.  This image is only executable from within
#     MATLAB.  The resulting file will have a ".mex###" extension, where
#     ### will be one of of the following to reflect the architecture of the
#     machine:
#
#       sun4, SunOS 4.x - 4
#	sun4, SunOS 5.x - sol
#       hp700 - hp7
#       ibm_rs - rs6
#       sgi - sg (sg64 for R8000)
#       dec_risc - ds
#       hp300 - hp3
#	alpha - axp
#	lnx86 - lx
#
#     The first file name given (less any file name extension) will be the
#     name of the resulting MEX file.  Additional source, object, or
#     library files can be given to satisfy external references.  Both C
#     and Fortran source files can be specified when building a MEX file.
#
#     The behavior of this script is affected in two ways: a startup script
#     called .mexrc.sh which is sourced if it exists and command line options.
#
#     The template startup script can be found in matlab/bin/.mexrc.sh. The
#     first occurrence of the file .mexrc.sh is sourced from the following
#     directory list: . (current), $HOME (home), matlab/bin. For more
#     details see the README.mex file in the matlab/bin directory.
#
#     The default values assigned in the body of this script for the
#     documented variables that can be changed in .mexrc.sh can be viewed
#     by typing cmex or fmex without ANY arguments.
#
#     The options are passed on to the C/Fortran compiler and linker.
#     Note, the default options do not include the optimizer flag.  The -O
#     option must be specified to generate optimized code.  Different compilers
#     interpret the -O[level] option differently.  See the man page for
#     the compiler for the definition of "level" if any.
#
#     If MATLAB detects a file with a ".mex" extension in the search path
#     it will load it before a corresponding M-file in the same directory.
#     Therefore it is recommended that MEX-files be installed in the same
#     directory that the M-file is (or would be if it existed).
#
#     Further evaluation is done to most of the options below. This means
#     that if the argument part of the option is placed in single quotes,
#     variable evaluation is postponed until after all options are considered.
#     For example, if the option -L'$MATLAB/extern/lib/sun4' is used,
#     $MATLAB will be evaluated inside this script at the appropriate time.
#     The user does not need to know the value of $MATLAB.
#
#  Options:
#
#     -c
#           Compile only.  Creates an object file but not a mex file.
#     -debug
#           Creates a special stand-alone executable image that reads its
#           inputs from a MAT-file rather than from the MATLAB command
#           line. Since it it a stand-alone image, you can use a standard
#           debugger on it.
#     -Dname=[def]
#	    Define a symbol name to the C preprocessor "cpp(1)".  Equivalent
#	    to a #define directive in the source.
#     -flibs
#           Include the standard system Fortran libraries when linking
#           the MEX file.  This is useful when some of the object files
#           needed to satisfy external references for the MEX image (i.e.
#           Fortran subroutines) were previously compiled.
#     -g
#           Produce additional symbol table information for debugging.
#     -Ipathname
#	    Add "pathname" to the list of directories in which to search for
#	    #include files with relative filenames (not beginning with slash
#	    /).  The preprocessor first searches for #include files in the
#           directory containing "sourcefile", then in directories named
#           with -I options (if any), and finally, in system wide
#           directories such as /usr/include.
#     -llibrary
#	    Link with object library "library" (for "ld(1)").
#     -Ldirectory
#	    Add "directory" to the list of directories containing
#	    object-library routines (for linking using "ld(1)").
#     -mips2
#           Generate the mex file using the mips2 instruction set (SGI only)
#     -O[level]
#	    Optimize the object code.  See the man page for the compiler
#	    for the definition of "level" if any.
#     -Uname
#	    Remove any initial definition of the "cpp(1)" symbol "name".
#	    (Inverse of the -D option.)
#     -v3.5
#	    Compile MEX files developed under version 3.5 or earlier.
#	    Use fmex if any Fortran source or object files were developed
#	    under version 3.5 or earlier.
#     -v
#           Prints the values for important internal variables AFTER
#	    .mexrc.sh is sourced and ALL 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=[def]
#           Define a variable. The variable can be a string enclosed in
#           quotes. Be careful that the string cannot contain any interior
#           DOUBLE quotes. It overrides any variable already defined in
#           the script either by a default value, being set in the
#           .mexrc.sh file, or passed through the environment.
#
#           Note: If you need to fine tune the order of the libraries use
#                 the LIBS variable. This can be tricky.
#     CASE=value
#	    Used to select which case to take in .mexrc.sh for complicated
#	    mex file applications and bugs.
#
#  Examples:
#     The following command will compile "vdpol.c" into "vdpol.mex4" (when
#     run on a Sun-4) using the optimizer option.
#
#	cmex  -O  vdpol.c
#
#     The resulting MEX-File should be installed in a directory in your
#     normal search path as defined by MATLABPATH.  Since the resulting
#     MEX-File is compiled code it will execute much faster than a cor-
#     responding M-file.		
#
#  Files:
#     .mexrc.sh,$HOME/.mexrc.sh,          Mex startup file that is source from
#     matlab/bin/.mexrc.sh		  the first file in the list. It
#                                         allows the user to set the values
#                                         for important directories, files,
#                                         and environment variables. See
#					  matlab/bin/.mexrc.sh for a template.
#     matlab/extern/include/mex.h	  Header file for MEX files.
#     matlab/extern/include/cmex.h	  Header file for 3.5 and earlier
#					  MEX files.
#     matlab/extern/lib/`arch`/libmex.a	  Library supplied if needed to link
#					  MEX objects, where `arch` is
#					  replaced by the architecture i.e.
#                                         "sun4". Used only on platforms that
#                                         do not use shared libraries.
#     matlab/extern/lib/ibm_rs/exp.ibm_rs Text file containing a list of
#                                         symbols exported by MATLAB. Needed
#                                         for linking mex files on the
#                                         IBM/RS 6000.
#
#  See Also:
#     fmex(1L)
#     MATLAB User's Manual.
#
#  Copyright (c) 1986-94 by The MathWorks, Inc.
#  $Revision: 1.112 $  $Date: 1995/09/14 17:19:50 $
#__________________________________________________________________________
#
    abort='rm -f $compiled_files $obj_file > /dev/null 2>&1; \
	  echo "" >&2; \
	  echo "    ${command}:  interrupted." >&2; \
          echo "" >&2'
#
    trap "eval $abort; exit 1" 1 2 3 15
#
#**************************************************************************
# Determine the path of the MATLAB root directory - always one directory
# up from the path to this command.
#**************************************************************************
#
    filename=$0
#
# Now it is either a file or a link to a file.
#
    cpath=`pwd`
#
# Follow up to 8 links before giving up. Same as BSD 4.3
#
    n=1
    maxlinks=8
    while [ $n -le $maxlinks ]
    do
#
# Get directory correctly!
#
	newdir=`echo "$filename" | awk '
                        { tail = $0
                          np = index (tail, "/")
                          while ( np != 0 ) {
                             tail = substr (tail, np + 1, length (tail) - np)
                             if (tail == "" ) break
                             np = index (tail, "/")
                          }
                          head = substr ($0, 1, length ($0) - length (tail))
                          if ( tail == "." || tail == "..")
                             print $0
                          else
                             print head
                        }'`
	if [ ! "$newdir" ]; then
	    newdir="."
	fi
	(cd $newdir) > /dev/null 2>&1
	if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 1: We could not determine the path of the'
    echo '                  MATLAB root directory.'
    echo ''
    echo "                  original command path = $0"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    exit 1
	fi
	cd $newdir
#
# Need the function pwd - not the built in one
#
	newdir=`/bin/pwd`
#
	newbase=`expr //$filename : '.*/\(.*\)' \| $filename`
        lscmd=`ls -l $newbase 2>/dev/null`
	if [ ! "$lscmd" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 2: Could not determine the path of the'
    echo '                  MATLAB root directory.'
    echo ''
    echo "                  original command path = $filename"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    exit 1
	fi
#
# Check for link portably
#
	if [ `expr "$lscmd" : '.*->.*'` -ne 0 ]; then
	    filename=`echo "$lscmd" | awk '{ print $NF }'`
	else
#
# It's a file
#
	    dir="$newdir"
	    command="$newbase"
#
	    cd $dir/..
	    MATLAB=`/bin/pwd`; export MATLAB
	    break
	fi
        n=`expr $n + 1`
    done
    if [ $n -gt $maxlinks ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo 'Internal error 3: More than $maxlinks links in path to'
    echo "                  this script. That's too many!"
    echo ''
    echo "                  original command path = $filename"
    echo "                  current  command path = $filename"
    echo ''
    echo '                  Please contact:'
    echo '' 
    echo '                      MathWorks Technical Support'
    echo ''
    echo '                  for further assistance.'
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	exit 1
    fi
#	
    cd $cpath
#
#**************************************************************************
#
    RCSHEADER="$Revision: 1.112 $  $Date: 1995/09/14 17:19:50 $"
    RCSREVISION=`echo "$RCSHEADER" | awk '{ print $2 }'`
#
    USAGE1="${command} [ -debug -Dname[=def] -flibs -g -Ipathname -llibrary -Ldir"
    USAGE2="     -O[level] -Uname -v3.5 -v name=[dev] CASE=value ]" 
    USAGE3="     sourcefile ... [ objectfile ] ...  [ library ] ..."
#
    MEX_UTIL_DIRdefault=$MATLAB/install
#
#--------------------------------------------------------------------------
#
# Scan the arguments for CASE=value only.
#
    arglist=`eval echo $*`
    casecmd=`expr "$arglist" : '.*[ 	]*\(CASE=[^ 	]*\).*'`
    if [ "$casecmd" != "" ]; then
	eval $casecmd
    fi
#
#--------------------------------------------------------------------------
#
# Source file .mexrc.sh and get values for the following local variables
# 
#       MATLAB                  (MATLAB root directory)
#       CC                      (C compiler)
#       CFLAGS                  (C compiler options)
#       FC                      (Fortran 77 compiler)
#       FFLAGS                  (Fortran 77 options)
#       LD_CCLIBS               (Libraries for linking with C objects only)
#       LD_FCLIBS               (Libraries for linking Fortran objects)
#
# The following are supported but undocumented.
#
#       LD                      (Linker command)
#       LDFLAGS                 (Linker options)
#       MEX_INCLUDE_DIR         (Mex include directory)
#       MEX_LIB_DIR             (Mex library directory)
#	LIBS			(Override libraries for linking objects)
#
# A null value means use the default value in this script.
#
# The search order for .mexrc.sh is:
#
#	.		(current directory)
#	$HOME		(users home directory)
#	$MATLAB/bin	(MATLAB bin directory)
#
    MATLABeval=$MATLAB
    if [ -f .mexrc.sh ]; then
	SOURCED_DIR='.'
	SOURCED_DIReval=`pwd`
	. $cpath/.mexrc.sh
    elif [ -f $HOME/.mexrc.sh ]; then
	SOURCED_DIR='$HOME'
	SOURCED_DIReval=$HOME
	. $HOME/.mexrc.sh
    elif [ -f $MATLAB/bin/.mexrc.sh ]; then
#
# NOTE: At this point we will use the MATLAB determined earlier to
#	source the file. After that the value in that file if not
#	null will be used.
#
	SOURCED_DIR='$MATLAB/bin'
	SOURCED_DIReval=$MATLAB/bin
	. $MATLAB/bin/.mexrc.sh
    else
	SOURCED_DIR=
	MEX_UTIL_DIR=$MEX_UTIL_DIRdefault
#
        . $MEX_UTIL_DIR/arch.sh
    fi
    if [ "$Arch" = "unknown" ]; then
	if [ "$SOURCED_DIR" = "" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '    Sorry! We could not determine the machine architecture for your' >&2
    echo '           host. Please contact:' >&2
    echo '' >&2
    echo '               MathWorks Technical Support' >&2
    echo '' >&2
    echo '           for further assistance.' >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    trap ""
            exit 1
	else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '    Sorry! We could not determine the machine architecture for your' >&2
    echo '           host. A .mexrc.sh file was sourced from directory:' >&2
    echo '' >&2
    echo "               $SOURCED_DIR" >&2
    echo ''
    echo '           You MUST start with the default .mexrc.sh found in' >&2
    echo '' >&2
    echo '               $MATLAB/bin' >&2
    echo '' >&2
    echo '           It makes the call that determines the machine' >&2
    echo '           architecture. Please read the README.mex file found in' >&2
    echo '' >&2
    echo '               $MATLAB/bin' >&2
    echo '' >&2
    echo '           for more details.' >&2
    echo '' >&2
    echo "           Here" >&2
    echo '' >&2
    echo "               MATLAB = $MATLAB" >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    trap ""
            exit 1
        fi
    fi
#
    MATLABset="FALSE"
    CCset="FALSE"
    CFLAGSset="FALSE"
    FCset="FALSE"
    FFLAGSset="FALSE"
    LDset="FALSE"
    LDFLAGSset="FALSE"
    LD_CCLIBSset="FALSE"
    LD_FCLIBSset="FALSE"
    LIBSset="FALSE"
#
    if [ "$MATLAB" != "" ]; then 
	MATLABset="TRUE"
    else
	MATLAB=$MATLABeval
    fi
#
    if [ "$CC" != "" ]; then
	CCset="TRUE"
	CC_SOURCED="$CC"
    fi
#
    if [ "$CFLAGS" != "" ]; then
	CFLAGSset="TRUE"
	CFLAGS_SOURCED="$CFLAGS"
    fi
#
    if [ "$FC" != "" ]; then
	FCset="TRUE"
	FC_SOURCED="$FC"
    fi
#
    if [ "$FFLAGS" != "" ]; then
	FFLAGSset="TRUE"
	FFLAGS_SOURCED="$FFLAGS"
    fi
#
    if [ "$LD_CCLIBS" != "" ]; then
        LD_CCLIBSset="TRUE"
	LD_CCLIBS_SOURCED="$LD_CCLIBS"
    fi
#
    if [ "$LD_FCLIBS" != "" ]; then
        LD_FCLIBSset="TRUE"
	LD_FCLIBS_SOURCED="$LD_FCLIBS"
    fi
#
    if [ "$LIBS" != "" ]; then
        LIBSset="TRUE"
	LIBS_SOURCED="$LIBS"
    fi
#
# Not intended for MATLAB users
#
    if [ "$LD" != "" ]; then
	LDset="TRUE"
	LD_SOURCED="$LD"
    fi
#
    if [ "$LDFLAGS" != "" ]; then
        LDFLAGSset="TRUE"
	LDFLAGS_SOURCED="$LDFLAGS"
    fi
#
    if [ "$MEX_INCLUDE_DIR" = "" ]; then
        MEX_INCLUDE_DIR=$MATLAB/extern/include
    fi
#
    if [ "$MEX_LIB_DIR" = "" ]; then
        MEX_LIB_DIR=$MATLAB/extern/lib/$Arch
    fi
#
#--------------------------------------------------------------------------
#
    mex_lib=libmex.a
    mex_db=mexdb.o
    mat_lib=libmat.a
#
    mex_35=fmex35.o
#
# Initialize little used set of parameters. Set them only where needed
# latter by architecture.
#
    CFLAGS_REQUIRED="-DMATLAB_MEX_FILE"
    CFLAGS_DB_REQUIRED="-DMATLAB_MEX_FILE"
    if [ -d $MATLAB/simulink ]; then
        CFLAGS_REQUIRED="$CFLAGS_REQUIRED -I$MATLAB/simulink/include"
        CFLAGS_DB_REQUIRED="$CFLAGS_DB_REQUIRED -I$MATLAB/simulink/include"
    fi
    if [ -d $MATLAB/codegen ]; then
        CFLAGS_REQUIRED="$CFLAGS_REQUIRED -I$MATLAB/codegen/external/common"
        CFLAGS_DB_REQUIRED="$CFLAGS_DB_REQUIRED -I$MATLAB/codegen/external/common"
    fi
    FFLAGS_REQUIRED=
    FFLAGS_DB_REQUIRED=
    LD_FILES_FC_REQUIRED=
    LD_FILES_FC_OLDSTYLE_REQUIRED=
#
# Set defaults
#
    CC='cc'
    CFLAGS=
    CFLAGS_DB='-g'
    FC='f77'
    FFLAGS=
    FFLAGS_DB='-g'
    LD='ld'
    LD_CCLIBS=
    LD_FCLIBS=
    LIBS=
    MEXLIBS=
    MEXLIBS_FC_OLDSTYLE=
    use_cc=""
#
# Set parameters specific to architecture
#
    case "$Arch" in
	sun4)
	    processor='SPARC'
	    mex_ext='mex4'
#
# Do not define entry point for sun4
#
	    LDFLAGS_DB='-d -r -u _mex_entry_pt -u _mexFunction'
	    LDFLAGS="-x $LDFLAGS_DB"
            LD_CCLIBS='-lm'
            LD_FCLIBS='-lm'
#
	    MEXLIBS='$MEX_LIB_DIR/$mex_lib'
	    MEXLIBS_FC_OLDSTYLE='$MEX_LIB_DIR/$mex_35 $MEX_LIB_DIR/$mex_lib'
#
	    ;;
	sol2)
	    processor='SPARC'
	    mex_ext='mexsol'
#
	    CC='cc -G'
	    LD='$CC'
	    LDFLAGS_DB=""
	    LDFLAGS='-s'
            LD_CCLIBS='-lm'
            LD_FCLIBS='-lm'
#
	    ;;
	lnx86)
	    processor='lnx86'
	    mex_ext='mexlx'
#
	    CC='gcc-elf'
	    LD='$CC'
	    LDFLAGS_DB="-shared -rdynamic"
	    LDFLAGS="$LDFLAGS_DB"
            LD_CCLIBS='-lm'
            LD_FCLIBS='-lm'
#
	    ;;
	alpha)
	    processor='ALPHA'
	    mex_ext='mexaxp'
#
	    LDFLAGS_DB='-shared -hidden -exported_symbol mexFunction -exported_symbol mexfunction_ -exported_symbol usrfcn_'
	    LDFLAGS="-s $LDFLAGS_DB"
            LD_CCLIBS='-lm -lc'
            LD_FCLIBS='-lm -lc'
#
	    CFLAGS_REQUIRED="-ieee_with_no_inexact $CFLAGS_REQUIRED"
	    FFLAGS_REQUIRED='-ieee_with_no_inexact'
	    ;;
	hp700)
	    processor='PA-RISC'
	    mex_ext='mexhp7'
#
            LDFLAGS_DB='-b +e mexfunction +e mexFunction +e usrfcn'
	    LDFLAGS="-s $LDFLAGS_DB"
#
	    CC='cc +z'
	    CFLAGS_REQUIRED="-D_HPUX_SOURCE $CFLAGS_REQUIRED"
	    FFLAGS_REQUIRED=+z
	    ;;
	hp300)
	    processor='680x0'
	    mex_ext='mexhp3'
#
            LDFLAGS_DB='-b +e _mexfunction +e _mexFunction +e _usrfcn'
	    LDFLAGS="-s $LDFLAGS_DB"
#
	    CFLAGS_REQUIRED="+z -D_HPUX_SOURCE $CFLAGS_REQUIRED"
	    FFLAGS_REQUIRED=+z
	    ;;
	ibm_rs)
	    processor='RS6000'
	    mex_ext='mexrs6'
#
	    LD='cc'
	    LDFLAGS_DB="-bI:$MEX_LIB_DIR/exp.ibm_rs -bM:SRE -e mexFunction"
            LDFLAGS="-s $LDFLAGS_DB"
	    LD_CCLIBS='-lm'
	    LD_FCLIBS='-lm'
#
            LD_FILES_FC_REQUIRED='$MEX_LIB_DIR/fmex1.o'
            LD_FILES_FC_OLDSTYLE_REQUIRED='$MEX_LIB_DIR/fmex35.o'
	    ;;
	sgi)
            if [ "`/bin/uname`" = "IRIX64" ]; then
                processor='R8000'
                mex_ext='mexsg64'
#
                LDFLAGS_DB='-shared -U -Bsymbolic'
	        LDFLAGS="-s $LDFLAGS_DB"
	    else
	        processor='R4000'
	        mex_ext='mexsg'
#
                LDFLAGS_DB='-shared -U -B symbolic'
	        LDFLAGS="-s $LDFLAGS_DB"
	    fi
	    ;;
	dec_risc)
	    processor='MIPS'
	    mex_ext='mexds'
#
#-----------------------------------------------------------------------------
#
# 1. Look in /usr/lib/cmplrs.
# 2. Old compiler: (FORTRAN for RISC) use latest "f77*" library.
# 3. New compiler: (DEC Fortran for ULTRIX RISC) use "fort" library.
# 4. If both exist use New compiler.
#
	    if [ "$FC_CCLIBSset" = "FALSE" ]; then
	        if [ -d /usr/lib/cmplrs ]; then
	            latest=`(cd /usr/lib/cmplrs; ls -d1 fort 2>/dev/null)`
	            if [ "$latest" != "" ]; then	# new compiler
		        FC_CCLIBS='-lfor -lutil -lUfor -li -lots -lm'
	    	        FC_CCLIBS="-L/usr/lib/cmplrs/$latest $FC_CCLIBS"
	            else			# old compiler
	                latest=`(cd /usr/lib/cmplrs; ls -d1 f77* 2>/dev/null \
			        | sort | awk '{x = $1}; END {print x}')`
		        if [ "$latest" != "" ]; then
#
# This order was from a real customer - MK-C
#
		            FC_CCLIBS='-lU77 -lI77 -lF77 -lm'
	    	            FC_CCLIBS="-L/usr/lib/cmplrs/$latest $FC_CCLIBS"
		        else
			    FC_CCLIBS=
		        fi
	            fi
	         else
	            FC_CCLIBS=
	         fi
	     fi
#-----------------------------------------------------------------------------
	    LDFLAGS_DB='-e mex_entry_pt -d -r -u mex_entry_pt'
            LDFLAGS="-x $LDFLAGS_DB"
	    LD_CCLIBS='-lm -lc'
	    LD_FCLIBS="$FC_CCLIBS -lc"
#
	    MEXLIBS='$MEX_LIB_DIR/$mex_lib'
	    MEXLIBS_FC_OLDSTYLE='$MEX_LIB_DIR/$mex_35 $MEX_LIB_DIR/$mex_lib'
#
	    ;;
	*)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    ${command}:  machine architecture '$Arch' not supported." >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    trap ""
	    exit 1
	    ;;
    esac
#
	if [ $# -eq 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '----------------------------------------------------------------' >&2
    echo '      Default values for . . . (see matlab/bin/README.mex)'	    >&2
    echo '----------------------------------------------------------------' >&2
    echo "->    MATLAB           = $MATLABeval"                 >&2
    echo "->    CC               = $CC"                         >&2
    echo "->    CFLAGS           = $CFLAGS"                     >&2
    echo "->    FC               = $FC"                         >&2
    echo "->    FFLAGS           = $FFLAGS"                     >&2
    echo "->    LD_CCLIBS        = $LD_CCLIBS"                  >&2
    echo "->    LD_FCLIBS        = $LD_FCLIBS"                  >&2
    echo '----------------------------------------------------------------' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	fi
#
    cc_flags=""
    includes=""
    f77_flags=""
    ld_flags=""
#
    mex_file=""
    compiled_files=""
    obj_libs=""
    libs=""
    files=""
    debug=""
    stand_alone_debug=""
    compile_only=""
#
# Parse the arguments
#
    stat="OK"
    while [ "$stat" = "OK" -a  $# -gt 0 ]; do
	case "$1" in
            -c)
                compile_only=1
		;;
            -debug)
                stand_alone_debug=1
                ;;
	    -help)			    # -help: Help option.
		stat=""
		;;
	    -flibs)			    # -flibs: Fortran libs.
		fortran=1
		;;
	    -[DOU]*)			    # Compiler flags.
                cc_flags="$cc_flags $1"
                f77_flags="$f77_flags $1"
 		;;
	    -I*)			    # Inlcude paths.
                includes="$includes $1"
                f77_flags="$includes $1"
 		;;
	    -[g]*)			    # Compiler flags.
		debug=1
		cc_flags="$cc_flags $CFLAGS_DB"
		f77_flags="$f77_flags $FFLAGS_DB"
		LDFLAGS=$LDFLAGS_DB
 		;;
	    -L*)			    # -Ldirectory: search path
		cc_flags="$cc_flags $1"
                f77_flags="$f77_flags $1"
		ld_flags="$ld_flags $1"
		;;
	    -l*)
		libs="$libs $1"
		;;
            -v3.5)
                oldstyle=1
                cc_flags="$cc_flags -DOLDSTYLE"
		;;
            -v)
                verbose=1
                ;;
	    -o)				    # mexfile name - undocumented
	        mex_file=$2
		shift
		;;
            -mips2)
		if [ "$Arch" = "sgi" ]; then
			cc_flags="$cc_flags $1"
			f77_flags="$f77_flags $1"
			ld_flags="$ld_flags -L/usr/lib/mips2"
		fi
		;;
            -*)
                stat="$1 not a valid option."
                ;;
            *=*)
                lhs=`expr "$1" : '\([a-zA-Z0-9_]*\)=.*'`
                rhs=`expr "$1" : '[a-zA-Z0-9_]*=\(.*\)$'`
                echo $lhs='"'$rhs'"' >> /tmp/$$a
                ;;
	    *)
		files="$files $1" 	    # file names
		;;
	esac
	shift
    done #while
#
    if [ $# -eq 0 -a "$files" = "" -a "$stat" = "OK" ]; then
        stat="no file name given."
    fi
#
# Determine the final values for the following variables
#
#	MATLAB			(MATLAB root directory)
#	CC                      (C compiler)
#	CFLAGS			(C compiler options)
#       FC                      (Fortran 77 compiler)
#	FFLAGS			(Fortran 77 options)
#	LD			(Linker command)
#	LDFLAGS			(Linker options)
#       LD_CCLIBS               (Libraries for ld(1) with C objects only)
#       LD_FCLIBS               (Libraries for ld(1) that include Fortran 77
#				 objects)
#	LIBS			(Override libraries for linking objects)
#
    if [ "$CCset" = "TRUE" ]; then
	CC="`eval echo $CC_SOURCED`"
    fi
    if [ "$CFLAGSset" = "TRUE" ]; then
	CFLAGS="`eval echo $CFLAGS_SOURCED`"
    fi
    if [ "$FCset" = "TRUE" ]; then
	FC="`eval echo $FC_SOURCED`"
    fi
    if [ "$FFLAGSset" = "TRUE" ]; then
	FFLAGS="`eval echo $FFLAGS_SOURCED`"
    fi
    if [ "$CCLIBSset" = "TRUE" ]; then
	CCLIBS="`eval echo $CCLIBS_SOURCED`"
    fi
    if [ "$FC_CCLIBSset" = "TRUE" ]; then
	FC_CCLIBS="`eval echo $FC_CCLIBS_SOURCED`"
    fi
    if [ "$LDset" = "TRUE" ]; then
	LDchanged="TRUE"
	LD="`eval echo $LD_SOURCED`"
    fi
    if [ "$LDFLAGSset" = "TRUE" ]; then
	LDFLAGS="`eval echo $LDFLAGS_SOURCED`"
    fi
    if [ "$LD_CCLIBSset" = "TRUE" ]; then
	LD_CCLIBS="`eval echo $LD_CCLIBS_SOURCED`"
    fi
    if [ "$LD_FCLIBSset" = "TRUE" ]; then
	LD_FCLIBS="`eval echo $LD_FCLIBS_SOURCED`"
    fi
    if [ "$LIBSset" = "TRUE" ]; then
	LIBS="`eval echo $LIBS_SOURCED`"
    fi
#
    LDsave="$LD"
    LD=
#
# Source the file of argument variables, name=[def]
#
    if [ -f /tmp/$$a ]; then
	. /tmp/$$a
	rm -f /tmp/$$a
    fi
#
    if [ "$LD" != "" ]; then
	LDchanged="TRUE"
    else
	LD="$LDsave"
    fi
#
# Be sure that LD is fully evaluated to handle cases like CC=LD. 
#
    LD="`eval echo $LD`"
#
    LIBS="`eval echo $LIBS`"
    cc_flags="`eval echo $cc_flags`"
    f77_flags="`eval echo $f77_flags`"
    includes="`eval echo $includes`"
    ld_flags="`eval echo $ld_flags`"
#
    if [ "$verbose" = "1" ]; then
#
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '----------------------------------------------------------------' >&2
	if [ "$SOURCED_DIR" != "" ]; then
    echo "->    .mexrc.sh sourced from directory (DIR = $SOURCED_DIR)" >&2
    echo "->    DIR                   = $SOURCED_DIReval" >&2
	else
    echo "->    .mexrc.sh not found." >&2
	fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	if [ "$MATLABset" = "TRUE" ]; then
    echo "->    MATLAB                = $MATLAB" >&2
	else
    echo "->    MATLAB                = $MATLABeval" >&2
	fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "->    CC                    = $CC"               	>&2
    echo "->    CC flags:"					>&2
    echo "         CFLAGS_REQUIRED    = $CFLAGS_REQUIRED"  	>&2
    echo "         CFLAGS             = $CFLAGS"		>&2
    echo "         arguments          = $cc_flags"		>&2
    echo "->    FC                    = $FC"             	>&2
    echo "->    FC flags:"                             		>&2
    echo "         FFLAGS_REQUIRED    = $FFLAGS_REQUIRED" 	>&2
    echo "         FFLAGS             = $FFLAGS"          	>&2
    echo "         arguments          = $f77_flags"       	>&2
    echo "->    LD                    = $LD"              	>&2
    echo "->    Link flags:"                           		>&2
    echo "         LDFLAGS            = $LDFLAGS" 		>&2
    echo "         arguments          = $ld_flags"        	>&2
    echo "->    LD_CCLIBS             = $LD_CCLIBS"        	>&2
    echo "->    LD_FCLIBS             = $LD_FCLIBS"       	>&2
    echo "->    mex/mat libraries:"                     	>&2
    echo "         MEXLIBS            = `eval echo $MEXLIBS`"   >&2
	    if [ "$LIBS" != "" ]; then
    echo "->    LIBS                  = $LIBS"                  >&2
	    fi
    echo '----------------------------------------------------------------' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    fi
#
# Check for errors
#
    if [ "$stat" != "OK" ]; then                        # An error occurred.
        if [ "$stat" != "" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "" >&2
    echo "    ${command}:  $stat" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   echo "" >&2
   echo "    Usage:  $USAGE1" >&2                      # echo command usage.
   echo "            $USAGE2" >&2
   echo "            $USAGE3" >&2
   echo "" >&2
   echo "    RCS revision #: $RCSREVISION" >&2         # RCS revision number.
   echo "" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	trap ""
        exit 1
    fi
#
# If oldstyle is in effect and fortran modules or objects are on the list
# then do not proceed. Issue message informing user to use fmex.
#
    for file in $files
    do
	if [ ! -f $file ]; then
	    continue
	else
	    ext=`expr "$file" : '\.*[^.].*\.\([^.]*\)$'`
	    case "$ext" in
		[Ff])			# Fortran source file.
		    fortran="1"
		    ;;
		*)
		    ;;
	    esac
	fi
    done
    if [ "$oldstyle" = "1" -a "$fortran" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   echo '' >&2
   echo '    Sorry! Please use fmex . . .' >&2
   echo '' >&2
   echo '    cmex cannot handle the -v3.5 option with some of your files' >&2
   echo '    being fortran (source or objects) . . .' >&2
   echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	trap ""
        exit 1
    fi
#
# Main loop
#
    set $files
#
# Get the extension to help determine the mex-file name
#
    ext=`expr "$1" : '\.*[^.].*\.\([^.]*\)$'`
#
# mex_file=`basename $1 ".$ext"`
#
	if [ "$mex_file" = "" ]; then
    	mex_file=`expr "//$1" : ".*/\(.*\)\.${ext}$" \| "//$1" : ".*/\(.*\)"`
	fi
#
    if [ "$stand_alone_debug" = "1" ]; then
	$CC -g -o $mex_file $includes -I$MEX_INCLUDE_DIR $cflags $cc_flags $files $MEX_LIB_DIR/mexdb.o $MEX_LIB_DIR/libmat.a -lm
	exit 0
    fi
#
    cflags="$CFLAGS_REQUIRED $CFLAGS"
    fflags="$FFLAGS_REQUIRED $FFLAGS"
#
    for file in $*
    do
	if [ ! -f "$file" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    ${command}:  $file not a normal file or does not exist." >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	else
#
# Extensions: sun4/dec_risc/ibm_rs  - .c .f .F .o .a
#	      hp700/hp300          - .c .f .F .o .a .sl
#	      sgi/sol2/alpha       - .c .f .F .o .a .so[.[0-9]+]*
#
            ext=`expr "$file" : '\.*[^.].*\.\([^.]*\)$'`
	    if [ "$ext" = "" ]; then
	        ext=`expr "$file" : '\.*[^.].*\.\(so\)[.0-9]*$'`
	    fi
	    case "$ext" in
		[Ff])			# Fortran source file.
		    fortran="1";;
	    esac
#
	    case "$ext" in
                [c])                    # C source file.
#
# obj_file=`basename $file .$ext`.o
#
                    obj_file=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$file : ".*/\(.*\)"`.o
                    if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      echo '' >&2
      echo "-> $CC -c $includes -I$MEX_INCLUDE_DIR $cflags $cc_flags $file" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    fi
#
                    $CC -c $includes -I$MEX_INCLUDE_DIR $cflags $cc_flags $file
                    if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    ${command}: compile of '$file' failed." >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        		trap "rm -f $compiled_files $obj_file > /dev/null 2>&1" 1
                        exit 1
                    fi
                    compiled_files="$compiled_files $obj_file"
                    ;;
                [Ff])                   # Fortran source file.
#
# obj_file=`basename $file .$ext`.o
#
                    obj_file=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$file : ".*/\(.*\)"`.o
                    if [ "$Arch" = "ibm_rs" -a "$ext" = "F" ]; then
                        pp_file=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$fil
e : ".*/\(.*\)"`.i
                        for_file=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$fi
le : ".*/\(.*\)"`.f
                        if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      echo '' >&2
      echo "-> $CC -P -I$MEX_INCLUDE_DIR $fflags $file" >&2
      echo "-> mv $pp_file $for_file"
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                        fi
                        $CC -P -I$MEX_INCLUDE_DIR $file
                        mv $pp_file $for_file
                        file=$for_file
                    fi
                    if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      echo '' >&2
      echo "-> $FC -c -I$MEX_INCLUDE_DIR $fflags $f77_flags $file" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    fi
#
                    $FC -c -I$MEX_INCLUDE_DIR $fflags $f77_flags $file
                    if [ $? -ne 0 ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    ${command}: compile of '$file' failed." >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			trap "rm -f $compiled_files $obj_file > /dev/null 2>&1" 1
                        exit 1
                    fi
                    compiled_files="$compiled_files $obj_file"
                    ;;
		[ao])
		    obj_libs="$obj_libs $file"
		    ;;

		*)
		    case "$Arch" in
		        sun4|dec_risc|ibm_rs)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    $file must have a .c, .f, .F, .o, or .a extension." >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			    ;;
		        hp700|hp300)
			    if [ "$ext" = "sl" ]; then
		         	obj_libs="$obj_libs $file"
			    else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    $file must have a .c, .f, .F, .o, .a, or .sl extension." >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			    fi
			    ;;
		        sgi|sol2|alpha)
			    if [ "$ext" = "so" ]; then
		         	obj_libs="$obj_libs $file"
			    else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    $file must have a .c, .f, .F, .o, .a, or .so* extension." >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			    fi
			    ;;
			*)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "    $file must have a .c, .f, .F, .o, or .a extension." >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			    ;;
		    esac
		    ;;
	    esac
	fi
    done #for
#
    if [ "$compile_only" = "" -a "$compiled_files" != ""  -o  "$obj_libs" != "" ]; then
#
#  Determine which libraries to include
#
	if [ "$fortran" = "1" ]; then
	    default_libs="$LD_FCLIBS"
	else
	    default_libs="$LD_CCLIBS"
	fi
#
	mex_libs="`eval echo $MEXLIBS`"
#
        if [ "$LIBS" != "" ]; then
	    libetc="$compiled_files $LIBS"
	elif [ $Arch = "sun4" -o $Arch = "dec_risc" ]; then
    	    base=`expr "//$CC" : ".*/\(.*\)"`
    	    if [ "$base" = "gcc" -o "$base" = "g++" ]; then
		dryrunopts="-v -static -o $mex_file.$mex_ext"
    	    elif [ $Arch = "sun4" ]; then
		dryrunopts='-dryrun -Bstatic'
	    else
		dryrunopts='-v'
    	    fi
#
# format: ld_cmd . . . -o a.out . . . -e start . . . */crt0.o . . . 
#
#	  remove the '-o a.out', '-e start' and '*/crt0.o' token sets
#
            if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '################################################################' >&2
    echo "-> output of 'dryrun' to help determine libraries for linking:" >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    		$CC $dryrunopts $compiled_files $obj_libs $mex_libs $libs $default_libs 1>&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '################################################################' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            fi
	    libetc=`$CC $dryrunopts $compiled_files $obj_libs $mex_libs $libs $default_libs 2>&1 | awk '
	 /.*Reading specs.*/ { next }
	 /.*gcc version.*/ { next }
	 /^ld.so:.*/  { next }
	 /.*ld.so:.*/ { next }
	 /^ld:.*/  { exit }
	 /.*ld:.*/ { exit }
	 /.*collect2:.*/ { exit }
	 /.*###.*/ { next }
	 /^\/lib\/crt0\.o.*/ { next }
			{ for (i = 1; i <= NF; i = i + 1 )
		              if ( $i == "-e" )
			  	   i = i + 1	# skip current and next argument
		              else if ( $i == "-o" )
			  	   i = i + 1	# skip current and next argument
		      	      else if (index($i, "crt0.o") != 0)
			  	   continue	# skip current argument
		      	      else
			  	   line = line " " $i # append current argument
		  	  print line }'`
#
# separate the ld_cmd and the rest of the command
#
	    if [ "$LDchanged" != "TRUE" ]; then
	        LD=`echo $libetc | awk '{print $1}'`
	    fi
    	    libetc="`echo $libetc | awk '{ i = index($0,$2); print substr($0,i) }'`"
	else
    	    libetc="$compiled_files $obj_libs $mex_libs $libs $default_libs"
	fi
        if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    if [ "$Arch" = "alpha" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "-> $LD $LDFLAGS -expect_unresolved '*' $ld_flags -o $mex_file.$mex_ext" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "-> $LD $LDFLAGS $ld_flags -o $mex_file.$mex_ext" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "      $libetc" >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	fi
	case "$Arch" in
	    alpha)
                $LD $LDFLAGS -expect_unresolved '*' $ld_flags -o $mex_file.$mex_ext $libetc
	        rm -f so_locations > /dev/null 2>&1
		;;
	    sgi)
                $LD $LDFLAGS $ld_flags -o $mex_file.$mex_ext $libetc
	        rm -f so_locations > /dev/null 2>&1
		;;
	    *)
                $LD $LDFLAGS $ld_flags -o $mex_file.$mex_ext $libetc
		;;
	esac
    fi
#
    if [ "$Arch" = "sol2" -a "$debug" = "1" -o "$compile_only" = "1" ]; then
        :
    else
        rm -f $compiled_files $obj_file > /dev/null 2>&1
    fi
    if [ \( "$Arch" = "hp700" -o "$Arch" = "hp300" \) -a "$debug" = "1" ]; then
        if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo "-> mv $mex_file.$mex_ext $mex_file.sl" >&2
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        fi
        mv $mex_file.$mex_ext $mex_file.sl
    fi
#
# Check for errors
#
    if [ "$stat" != "OK" ]; then			# An error occurred.
        if [ "$stat" != "" ]; then
            echo "" >&2
            echo "${command}:  $stat" >&2
        fi
        echo "" >&2
        echo "Usage:  $USAGE1" >&2                      # echo command usage.
        echo "        $USAGE2" >&2
        echo "        $USAGE3" >&2
        echo "" >&2
        echo "RCS revision #: $RCSREVISION" >&2         # RCS revision number.
        echo "" >&2
	trap ""
	exit 1
    else
	exit 0
    fi
