#! /bin/sh

# This program is granted to the public domain

# 2003-01-03 Paul Kienzle <pkienzle@users.sf.net>
# * eliminate sed --- use direct string interpolation for variables
# * define both the C and fortran names for mexFunction in the oct-file.
# 2001-06-20 Paul Kienzle <pkienzle@users.sf.net>
# * eliminate $(arg:0:1) since it is not available in all sh versions
# 2001-09-20 Paul Kienzle <pkienzle@users.sf.net>
# * use config-like syntax to set the name of mkoctfile and the path to mex

test $# -lt 1 && echo usage: mex -options file.c && exit 1

first=""
for arg in $*; do
    case "$arg" in -c) compileonly=1 ;; -*) ;; *) first="$arg"; break ;; esac
done

if test -z "$first" ; then
   mkoctfile -DHAVE_OCTAVE_21 -v $*
   exit
fi

if test -n "$compileonly" ; then
   set -x
   mkoctfile -DHAVE_OCTAVE_21 -v -I/usr/lib/octave/2.1.57/site/oct/i386-pc-linux-gnu/octave-forge $*
   exit
elif grep -iq mexfunction $first ; then
   echo building $first
else
   echo $first does not contain mexfunction
   exit 1
fi

# default the name of the octave function from the first filename
name=${first%%.*}
ext=${first#*.}
#echo $name . $ext

case "$ext" in
  f*|F*)
    invoke=Fortran_mex
    otherfn=mexFunction
  ;;
  *)
    invoke=C_mex
    otherfn="F77_FUNC(mexfunction,MEXFUNCTION)"
  ;;
esac

cat <<EOF > mex_$name.cc
#include <octave/oct.h>

extern "C" {
  // mex.cc names both mexFunction (c) and MEXFUNCTION (Fortran)
  // but the mex file only defines one of them, so define the other
  // here just to keep the linker happy, but don't ever call it.
  void $otherfn() {}
  const char *mexFunctionName = "$name";
} ;

DEFUN_DLD($name, args, nargout, "\
$name not directly documented. Try the following:\n\
   type(file_in_loadpath('$name.m'))\n\
")
{
  octave_value_list $invoke(const octave_value_list &, const int);
  return $invoke(args, nargout);
}
EOF

if test -f "mex.o" ; then
  MEXPATH=.
else
  MEXPATH="/usr/lib/octave/2.1.57/site/oct/i386-pc-linux-gnu/octave-forge"
fi

set -x
mkoctfile -DHAVE_OCTAVE_21 -v -o $name.oct mex_$name.cc $MEXPATH/mex.o -I$MEXPATH $*
