#! /bin/sh

# This program is granted to the public domain

# 2001-06-20 Paul Kienzle <pkienzle@users.sf.net>
# * eliminate $(arg:0:1) since it is not available in all bash 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

if test $# -lt 1 ; then
    echo usage: mex -options file.c
fi

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

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

if grep -iq mexfunction $first ; then
   echo building $first
else
   echo $first does not contain mexfunction
   exit 1
fi

name=${first%%.*}
ext=${first#*.}
#echo $name . $ext

sedopt="-es/NAME/$name/"
if test ${ext:0:1} = "f" || test ${ext:0:1} = 'F' ; then
  sedopt="$sedopt -es/C_mex/Fortran_mex/"
fi
#echo "$sedopt"

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

extern "C" {
  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 C_mex(const octave_value_list &, const int);
  return C_mex(args, nargout);
}
EOF

set -x
mkoctfile -DHAVE_OCTAVE_21 -v -o $name mex_$name.cc /usr/lib/octave/2.1.35/site/oct/sparc-unknown-linux-gnu/octave-forge/mex.o -I/usr/lib/octave/2.1.35/site/oct/sparc-unknown-linux-gnu/octave-forge $*
