#! /bin/sh
#
#  Name:
#     fmex    compilation program for MATLAB Fortran language MEX files
#     
#  Usage:
#     fmex  [ -debug -Dname[=def] -g -Ipathname -llibrary -Ldir -O[level]
#	      -Uname -v3.5 -v name=[def] CASE=value ] sourcefile ...
#             [ objectfile ] ...  [ library ] ...
#
#  Description:
#     "fmex" 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
#
#     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 Fortran/C compiler and linker.
#     The -D, -I, and -U options are useful with Fortran compilers that
#     first pass the source file through the C preprocessor "cpp(1)". Most
#     Berkeley UNIX "f77" Fortran compilers will do this if the file exten-
#     sion is `.F' instead of `.f'.  See the man page for your Fortran com-
#     piler for more information.
#
#     Note, the default options do not include the optimizer flag. The -O
#     option must be specified to generate optimized code.  Different com-
#     pilers 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 install 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:
#
#     -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.
#     -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.
#     -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 "yprime.f" into "yprime.mex4" (when
#     on a Sun-4) using the optimizer option.
#
#	fmex  -O  yprime.f yprimefg.f
#
#     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/`arch`/fmex35.o   Object file containing the main
#					  entry point for 3.5 and earlier
#					  mex files.
#     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:
#     cmex(1L)
#     MATLAB User's Manual.
#
#  Copyright (c) 1986-93 by The MathWorks, Inc.
#  $Revision: 1.82 $  $Date: 1995/01/23 14:02:46 $
#__________________________________________________________________________
#
    abort='rm -f $compiled_files $obj_file /tmp/$$a > /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.82 $  $Date: 1995/01/23 14:02:46 $"
    RCSREVISION=`echo "$RCSHEADER" | awk '{ print $2 }'`
#
    USAGE1="${command} [ -debug -Dname[=def] -g -Ipathname -llibrary -Ldir"
    USAGE2="     -Uname -v3.5 -v name=[def] CASE=value ] sourcefile ..."
    USAGE3="     [ 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_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_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_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
# later by architecture.
#
    CFLAGS_REQUIRED=
    CFLAGS_DB_REQUIRED=
    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=
#
# 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"
#
	    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'
#
	    LDFLAGS='-s -G'
            LDFLAGS_DB='-G'
            LD_FCLIBS='-lM77 -lF77 -lm'
#
            CFLAGS_REQUIRED='-G'
            FFLAGS_REQUIRED='-G'
	    ;;
	alpha)
	    processor='ALPHA'
	    mex_ext='mexaxp'
#
	    LDFLAGS_DB='-shared -hidden -exported_symbol mexFunction -exported_symbol mexfunction_ -exported_symbol usrfcn_'
	    LDFLAGS="-s $LDFLAGS_DB"
            LD_FCLIBS='-lUfor -lfor -lFutil -lm -lots -lc'
#
	    CFLAGS_REQUIRED="-shared $CFLAGS_REQUIRED"
	    FFLAGS_REQUIRED='-shared'
	    ;;
	hp700)
	    processor='PA-RISC'
	    mex_ext='mexhp7'
#
            LDFLAGS_DB='-b +e mexfunction +e mexFunction +e usrfcn'
	    LDFLAGS="-s $LDFLAGS_DB"
#
            CFLAGS_REQUIRED=+z
            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
            FFLAGS_REQUIRED=+z
	    ;;
	ibm_rs)
	    processor='RS6000'
	    mex_ext='mexrs6'
#
	    LD='f77'
	    LDFLAGS_DB="-bI:$MEX_LIB_DIR/exp.ibm_rs -bM:SRE -e mexFunction"
            LDFLAGS="-s $LDFLAGS_DB"
	    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 [ "$LD_FCLIBSset" = "FALSE" ]; then
	        if [ -d /usr/lib/cmplrs ]; then
	            latest=`(cd /usr/lib/cmplrs; ls -d1 fort 2>/dev/null)`
	            if [ "$latest" != "" ]; then	# new compiler
		        LD_FCLIBS='-lfor -lutil -lUfor -li -lots -lm'
	    	        LD_FCLIBS="-L/usr/lib/cmplrs/$latest $LD_FCLIBS"
	            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
#
		            LD_FCLIBS='-lU77 -lI77 -lF77 -lI77 -lF77 -lm'
	    	            LD_FCLIBS="-L/usr/lib/cmplrs/$latest $LD_FCLIBS"
		        else
			    LD_FCLIBS=
		        fi
	            fi
	         else
	            LD_FCLIBS=
	         fi
	     fi
#-----------------------------------------------------------------------------
	    LDFLAGS_DB='-e mex_entry_pt -d -r -u mex_entry_pt'
            LDFLAGS="-x $LDFLAGS_DB"
	    LD_FCLIBS="$LD_FCLIBS -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_FCLIBS        = $LD_FCLIBS"                  >&2
    echo '----------------------------------------------------------------' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        fi
#
    cc_flags=""
    f77_flags=""
    ld_flags=""
#
    mex_file=""
    compiled_files=""
    obj_libs=""
    libs=""
    files=""
    debug=""
    stand_alone_debug=""
#
#
# Parse the arguments
#
    stat="OK"
    while [ "$stat" = "OK" -a  $# -gt 0 ]; do
	case "$1" in
            -debug)
                stand_alone_debug=1
                ;;
	    -help)			    # -help: Help option.
		stat=""
		;;
	    -[DIOU]*)			    # Compiler flags.
		cc_flags="$cc_flags $1"
                f77_flags="$f77_flags $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_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
	if [ "$FC" = "$LD" ]; then
             LD="`eval echo $FC_SOURCED`"
	fi
	FC="`eval echo $FC_SOURCED`"
    fi
    if [ "$FFLAGSset" = "TRUE" ]; then
	FFLAGS="`eval echo $FFLAGS_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_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
#
    LIBS="`eval echo $LIBS`"
    cc_flags="`eval echo $cc_flags`"
    f77_flags="`eval echo $f77_flags`"
    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_DB              = $CFLAGS_DB"         >&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_DB              = $FFLAGS_DB"         >&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_FCLIBS                 = $LD_FCLIBS"       	>&2
    echo "->    mex/mat libraries:"                     	>&2
	        if [ "$oldstyle" = "1" ]; then
    echo "         MEXLIBS_FC_OLDSTYLE    = `eval echo $MEXLIBS_FC_OLDSTYLE`" >&2
		else
    echo "         MEXLIBS                = `eval echo $MEXLIBS`"     	     >&2
		fi
            if [ "$LIBS" != "" ]; then
    echo "->    LIBS                  = $LIBS"                   >&2
            fi
        fi
    echo '----------------------------------------------------------------' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# 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
#
# 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
	$FC -g -o $mex_file -I$MEX_INCLUDE_DIR $fflags $f77_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
    echo '' >&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
                [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 -I$MEX_INCLUDE_DIR $cflags $cc_flags $file" >&2
      echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    fi
#
                    $CC -c -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}$" \| //$file : ".*/\(.*\)"`.i
                    	for_file=`expr "//$file" : ".*/\(.*\)\.${ext}$" \| //$file : ".*/\(.*\)"`.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
		    if [ "$Arch" = "ibm_rs" -a "$ext" = "F" ]; then
			rm -f $for_file
		    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 [ "$compiled_files" != ""  -o  "$obj_libs" != "" ]; then
	default_libs="$LD_FCLIBS"
	if [ "$oldstyle" = "1" ]; then
	    ld_flags="$ld_flags `eval echo $LD_FILES_FC_OLDSTYLE_REQUIRED`"
    	    mex_libs="`eval echo $MEXLIBS_FC_OLDSTYLE`"
	else
	    ld_flags="$ld_flags `eval echo $LD_FILES_FC_REQUIRED`"
	    mex_libs="`eval echo $MEXLIBS`"
	fi
#
        if [ "$LIBS" != "" ]; then
	    ldcmd="$LD $LDFLAGS $ld_flags -o $mex_file.$mex_ext $compiled_files $LIBS"
	elif [ $Arch = "sol2" ]; then
	    ldcmd=`$FC -dryrun $LDFLAGS $ld_flags -o $mex_file.$mex_ext $compiled_files $obj_libs $mex_libs $libs $default_libs 2>&1 | awk ' /.*###.*/ { next }
			{ for (i = 1; i <= NF; i = i + 1 )
		              if ( $i == "-z") {
				  j = i + 1
				  if ( $j == "text" )
			  	      i = i + 1 # skip current and next arg
				  else
			  	      line = line " " $i # append current arg
			      }
		      	      else
			  	   line = line " " $i # append current arg
		  	  print line }'`
        elif [ $Arch = "sun4" ]; then
	    dryrunopts='-dryrun -Bstatic'
#
# format: ld_cmd . . . -u _MAIN_ . . . -o a.out . . . -e start . . .
#		 . . . */crt0.o . . . 
#
#	  remove the '-u _MAIN_', '-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
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    	    	$FC $dryrunopts -o $mex_file.$mex_ext $compiled_files $obj_libs $mex_libs $libs $default_libs 1>&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
    echo '################################################################' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    fi
	    ldcmd=`$FC $dryrunopts -o $mex_file.$mex_ext $compiled_files $obj_libs $mex_libs $libs $default_libs 2>&1 | awk ' /.*###.*/ { next }
			{ for (i = 1; i <= NF; i = i + 1 )
		              if ( $i == "-e" )
			          i = i + 1	# skip current and next arg
		              else if ( $i == "-u") {
				  j = i + 1
				  if ( $j == "_MAIN_" )
			  	      i = i + 1 # skip current and next arg
				  else
			  	      line = line " " $i # append current arg
			      }
		      	      else if (index($i, "crt0.o") != 0)
			  	   continue	# skip current arg
		      	      else
			  	   line = line " " $i # append current arg
		  	  print line }'`
#
# separate the ld_cmd and the rest of the command
#
            if [ "$LDchanged" != "TRUE" ]; then
                LD=`echo $ldcmd | awk '{print $1}'`
            fi
    	    ldcmd="`echo $ldcmd | awk '{ i = index($0,$2); print substr($0,i) }'`"
	    ldcmd="$LD $LDFLAGS $ld_flags $ldcmd" 
	elif [ $Arch = "alpha" ]; then
	    ldcmd="$LDFLAGS $ld_flags -o $mex_file.$mex_ext $compiled_files $obj_libs $mex_libs $libs $default_libs"
	else
	    ldcmd="$LD $LDFLAGS $ld_flags -o $mex_file.$mex_ext $compiled_files $obj_libs $mex_libs $libs $default_libs"
	fi
        if [ "$verbose" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            if [ $Arch = "alpha" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "-> $LD -expect_unresolved '*' $ldcmd"
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo "-> $ldcmd" >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	    fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo '' >&2
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	fi
	case "$Arch" in
	    alpha)
	        $LD -expect_unresolved '*' $ldcmd
	        rm -f so_locations > /dev/null 2>&1
		;;
	    sgi)
                $ldcmd
	        rm -f so_locations > /dev/null 2>&1
		;;
	    *)
                $ldcmd
		;;
	esac
    fi
#
    if [ "$Arch" = "sol2" -a "$debug" = "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 ""
        exi 1
    else
        exit 0
    fi
