#!/bin/bash

# some hopefully reasonable defaults
MAKEDEPEND="gcc -MM"
MAKEDEPENDOPTS=""
SRCDIR="`dirname $0`"
EXT_SRC_HEADER=h
EXT_SRC_C=c
EXT_SRC_CPP=cpp
EXT_SRC_SWIG=i
EXT_SRC_SWIG=_wrap.cxx
EXT_INP_SWIG=i
EXT_IF_SWIG=.py
EXT_OBJ_SWIG=_wrap.cxx.o
PRE_LIB_SWIG=_
EXT_LIB_SWIG=so
EXT_DOXY=.doxy
EXT_SWIG_DOXY=_doxygen.i
SWIGFLAGS=""
SWIG=swig
DOXYGEN=doxygen
PYTHON=python
KERNELNAME=`uname`
MACHINE=`uname -m | tr ' ' '-'`
EXT_OBJ_CPP=cpp.o
EXT_OBJ_C=c.o

#the defaults are
_readline=auto
_matlab=no
_mindy=auto
_R=no
_python=no
_octave=no
if [ -e classifier/svm/SVM_light.cpp ]; then
  _svm_light=yes
  _gpl=no
else
  _svm_light=no
  _gpl=yes
fi
_cplex=auto
_doxygen=auto
_wtiming=no
_logcache=no
_shortrealkernelcache=yes
_treemem=yes
_logsumarray=no
_hmmparallel=no
_largefile=yes
_doxygen=auto
_swig=no 
_lapack=auto
_bigstates=yes
_hmmcache=yes
_debug=no
_hmmdebug=no
_pathdebug=no
_profile=no
_prefix="/usr/local"
_destdir="/"
_bindir=""
_datadir=""
_mandir=""
_confdir=""
_libdir=""
_incdir=""
_pydir=""
_octdir=""
_inc_extra=""
_ld_extra=""
_optimizing=""
_interface=""
test -z "$INCLUDES" || _inc_extra="-I`echo $INCLUDES | sed 's,:, -I,g'`"
test -z "$LIBS" || _ld_extra="-L`echo $LIBS | sed 's,:, -L,g'`"

# these ones will be autodetected
CONFIGURE_OPTIONS="configure options $@"
GDB=gdb
MAKE=make
COMP_OPTS="-g -Wall -O9 -fexpensive-optimizations -frerun-cse-after-loop -fcse-follow-jumps -finline-functions -fschedule-insns2 -fthread-jumps -fforce-addr -fstrength-reduce -unroll-loops"
COMP_NOOPTS="-g -Wall -O2"
COMPFLAGS_C=
COMPFLAGS_CPP=
test "$CFLAGS" && COMPFLAGS_C="$COMPFLAGS_C $CFLAGS"
test "$CXXFLAGS" && COMPFLAGS_CPP="$COMPFLAGS_CPP $CXXFLAGS"
INCLUDES=-I${SRCDIR}
LINK=c++
LINKFLAGS=
POSTLINKFLAGS=
DEFINES=
TARGET="shogun"

# stuff needed for autodetections (definitely needs cleanup)
TMPLOG="configure.log"
TMPMAK="./configure-$RANDOM-$$-makefile"
TMPC="./configure-$RANDOM-$$.c"
TMPCPP="./configure-$RANDOM-$$.cpp"
TMPO="./configure-$RANDOM-$$.o"
TMPS="./configure-$RANDOM-$$.S"
TMPSS="./configure-$RANDOM-$$.s"

# Check how echo works in this /bin/sh
case `echo -n` in
  -n)	_echo_n=	_echo_c='\c'	;;	# SysV echo
  *)	_echo_n='-n '	_echo_c=	;;	# BSD echo
esac

# Check how to call 'head' and 'tail'. Newer versions spit out warnings
# if used as 'head -1' instead of 'head -n 1', but older versions don't
# know about '-n'.
if test "`(echo line1 ; echo line2) | head -1 2>/dev/null`" = "line1" ; then
  _head() { head -$1 2>/dev/null ; }
else
  _head() { head -n $1 2>/dev/null ; }
fi
if test "`(echo line1 ; echo line2) | tail -1 2>/dev/null`" = "line2" ; then
  _tail() { tail -$1 2>/dev/null ; }
else
  _tail() { tail -n $1 2>/dev/null ; }
fi

# OS name
system_name=`( uname -s ) 2>&1`
# OS test booleans functions
issystem() {
  echo $system_name | tr A-Z a-z | grep -q "`echo $1 | tr A-Z a-z`"
}
linux()   { issystem "Linux"   ; return "$?" ; }
sunos()   { issystem "SunOS"   ; return "$?" ; }
hpux()    { issystem "HP-UX"   ; return "$?" ; }
irix()    { issystem "IRIX"    ; return "$?" ; }
aix()     { issystem "AIX"     ; return "$?" ; }
cygwin()  { issystem "CYGWIN" ; return "$?" ; }
interix() { issystem "Interix" ; return "$?" ; }
freebsd() { issystem "FreeBSD" ; return "$?" ; }
netbsd()  { issystem "NetBSD"  ; return "$?" ; }
bsdos()   { issystem "BSD/OS"  ; return "$?" ; }
openbsd() { issystem "OpenBSD" ; return "$?" ; }
bsd()     { freebsd || netbsd || bsdos || openbsd ; return "$?" ; }
qnx()     { issystem "QNX"     ; return "$?" ; }
darwin()  { issystem "Darwin"  ; return "$?" ; }
gnu()     { issystem "GNU"     ; return "$?" ; }
osf1()     { issystem "OSF1"    ; return "$?" ; }
mingw32() { issystem "MINGW32" ; return "$?" ; }
morphos() { issystem "MorphOS" ; return "$?" ; }
win32()   { cygwin || mingw32  ; return "$?" ; }
beos()    { issystem "BEOS"    ; return "$?" ; }

set_default_cc()
{
	if sunos
	then
		COMP_C=cc
		COMP_CPP=CC
	else
		COMP_C=cc
		COMP_CPP=c++
	fi
	test "$CC" && COMP_C="$CC"
	test "$CXX" && COMP_CPP="$CXX"
}

detect_cc()
{
	echocheck "C Compiler"
cat > $TMPC << EOF
int main(void) { return 0; }
EOF
	if sunos
	then
		for COMP_C in "$COMP_C"
		do
			if cc_check
			then
				cc_vendor=sun
				cc_found=yes
				cc_version=`cc -V 2>&1 | head -n 1 | cut -f 2 -d ':'`
			fi
		done
	else
	for COMP_C in "$COMP_C" gcc gcc-4.1 gcc-4.0 gcc-3.4 gcc-3.3 gcc-3.2 gcc-3.1 gcc3 gcc-3.0
	do
		if cc_check
		then
			cc_vendor=gnu
			cc_name=`$COMP_C -v 2>&1 | _tail 1 | cut -d ' ' -f 1`
			cc_version=`$COMP_C -dumpversion 2>&1`
			if test "$?" -gt 0; then
				cc_version="not found"
			fi
			case $cc_version in
				'')
				cc_version="v. ?.??, bad"
				;;
				2.95.[2-9]|2.95.[2-9][-.]*|[3-4].*)
				_cc_major=`echo $cc_version | cut -d '.' -f 1`
				_cc_minor=`echo $cc_version | cut -d '.' -f 2`
				_cc_mini=`echo $cc_version | cut -d '.' -f 3`
				cc_version="$cc_version, ok"
				cc_found=yes
				break
				;;
				'not found')
				cc_found=no
				;;
				*)
				cc_version="$cc_version, bad"
				;;
			esac
		fi
	done
	fi

	if test "$cc_found" = yes
	then
		echores "$cc_version"
	else
		die "no C compiler detected - cannot do anything"
	fi

	#cygwins gcc is buggy - so disable -O9 optimizations
	if cygwin || test "$_cpudetection" = no ; then
		COMP_OPTS=$COMP_NOOPTS;
	fi

	echocheck "C Compiler flags"
	for opt in `echo $COMP_OPTS`
	do
		cc_check $opt && COMPFLAGS_C="$COMPFLAGS_C $opt"
	done
	echores "$COMPFLAGS_C"

	echocheck "C++ Compiler"
	if sunos
	then
		for COMP_CPP in "$COMP_CPP"
		do
			if cc_check
			then
				cxx_found=yes
				cxx_version=`cc -V 2>&1 | head -n 1 | cut -f 2 -d ':'`
			fi
		done
	else
	for COMP_CPP in "$COMP_CPP" cxx CC g++ g++-4.1 g++-4.0 g++-3.4 g++-3.3 g++-3.2 g++-3.1 g++3 g++-3.0
	do
		if cxx_check
		then
			cxx_vendor=gnu
			cxx_name=`$COMP_CPP -v 2>&1 | _tail 1 | cut -d ' ' -f 1`
			cxx_version=`$COMP_CPP -dumpversion 2>&1`
			if test "$?" -gt 0; then
				cxx_version="not found"
			fi
			case $cxx_version in
				'')
				cxx_version="v. ?.??, bad"
				;;
				2.95.[2-9]|2.95.[2-9][-.]*|[3-4].*)
				_cxx_major=`echo $cxx_version | cut -d '.' -f 1`
				_cxx_minor=`echo $cxx_version | cut -d '.' -f 2`
				_cxx_mini=`echo $cxx_version | cut -d '.' -f 3`
				cxx_version="$cxx_version, ok"
				cxx_found=yes
				break
				;;
				'not found')
				cxx_found=no
				;;
				*)
				cxx_version="$cxx_version, bad"
				;;
			esac
		fi
	done
	fi

	if test "$cxx_found" = yes
	then
		echores "$cxx_version"
	else
		die "no C++ compiler detected - cannot do anything"
	fi

	echocheck "C++ Compiler flags"
	for opt in `echo $COMP_OPTS`
	do
		cxx_check $opt && COMPFLAGS_CPP="$COMPFLAGS_CPP $opt"
	done
	echores "$COMPFLAGS_CPP"

	#as our code is C++ use CPP compiler for linking
	LINK=$COMP_CPP
}

check_python()
{
	echocheck "Python"
	if $PYTHON -V >/dev/null 2>&1
	then
		echores "`$PYTHON -V 2>&1 | grep Python | cut -f 2 -d ' '`"
	else
		echores "python not detected (required)"
	fi
}

check_makedepend()
{
	echocheck "makedepend"

cat > $TMPC << EOF
int main(void) { return 0; }
EOF
	if $MAKEDEPEND $TMPC >/dev/null 2>&1
	then
		echores "$MAKEDEPEND"
	elif makedepend -f - $TMPC >/dev/null 2>&1
	then
		MAKEDEPEND=makedepend
		MAKEDEPENDOPTS="-f -"
		echores "$MAKEDEPEND"
	else
		echores "no"
		die "neither gcc nor makedepend found, but required to proceed. please install gcc or xutils-dev"
	fi
}

check_doxygen()
{
	echocheck "Doxygen"

	if test "$_doxygen" = yes || test "$_doxygen" = auto
	then
		if doxygen --version 2>&1 >/dev/null 2>&1
		then
			echores "`doxygen --version`"
			_doxygen=yes
		else
			if test "$_doxygen" = yes
			then
				die "doxygen not detected"
			else
				echores "doxygen not detected, for documentation please install"
			fi
		fi
	else
		echores "disabled"
	fi
}

check_make()
{
	echocheck "GNU Make"

	if make --version 2>&1 | grep GNU >/dev/null 2>&1
	then
		echores "`make --version | grep GNU`"
		MAKE=make
	else
		if gmake --version 2>&1 | grep GNU >/dev/null 2>&1
		then
			echores "`gmake --version | grep GNU`"
			MAKE=gmake
		else
			echores "non GNU Make detected expect trouble (try running GNU make manually in case of trouble)"
		fi
	fi
}

cc_check() {
  echo >> "$TMPLOG"
  cat "$TMPC" >> "$TMPLOG"
  echo >> "$TMPLOG"
  echo "$COMP_C $INCLUDES $COMPFLAGS_C $TMPC -o $TMPO $LINKFLAGS $@" >> "$TMPLOG"
  rm -f "$TMPO"
  ( "$COMP_C" $INCLUDES $COMPFLAGS_C "$TMPC" -o "$TMPO" $LINKFLAGS "$@" ) >> "$TMPLOG" 2>&1
  TMP="$?"
  if test -f "$TMPO"
  then
	  echo >> "$TMPLOG"
	  echo "ldd $TMPO" >> "$TMPLOG"
	  ( ldd "$TMPO" ) >> "$TMPLOG" 2>&1
  else
	  echo "no object file created" >> "$TMPLOG"
  fi
	  echo >> "$TMPLOG"
  return "$TMP"
}

cxx_check() {
  echo >> "$TMPLOG"
  cat "$TMPC" >> "$TMPLOG"
  echo >> "$TMPLOG"
  echo "$COMP_CPP $INCLUDES $COMPFLAGS_CPP $TMPC -o $TMPO $LINKFLAGS $@" >> "$TMPLOG"
  rm -f "$TMPO"
  ( "$COMP_CPP" $INCLUDES $COMPFLAGS_CPP "$TMPC" -o "$TMPO" $LINKFLAGS "$@" ) >> "$TMPLOG" 2>&1
  TMP="$?"
  if test -f "$TMPO"
  then
	  echo >> "$TMPLOG"
	  echo "ldd $TMPO" >> "$TMPLOG"
	  ( ldd "$TMPO" ) >> "$TMPLOG" 2>&1
  else
	  echo "no object file created" >> "$TMPLOG"
  fi
	  echo >> "$TMPLOG"
  return "$TMP"
}

tmp_run() {
  "$TMPO" >> "$TMPLOG" 2>&1
}

# Display error message, flushes tempfile, exit
die () {
  echo
  echo "Error: $@" >&2
  echo >&2
  rm -f "$TMPO" "$TMPC" "$TMPS" "$TMPCPP"
  echo "Check "$TMPLOG" if you do not understand why it failed."
  exit 1
}

# OS test booleans functions
issystem() {
  test "`echo $system_name | tr A-Z a-z`" = "`echo $1 | tr A-Z a-z`"
}
linux()   { issystem "Linux"   ; return "$?" ; }
sunos()   { issystem "SunOS"   ; return "$?" ; }
hpux()    { issystem "HP-UX"   ; return "$?" ; }
irix()    { issystem "IRIX"    ; return "$?" ; }
aix()     { issystem "AIX"     ; return "$?" ; }
cygwin()  { issystem "CYGWIN"  ; return "$?" ; }
freebsd() { issystem "FreeBSD" ; return "$?" ; }
netbsd()  { issystem "NetBSD"  ; return "$?" ; }
bsdos()   { issystem "BSD/OS"  ; return "$?" ; }
openbsd() { issystem "OpenBSD" ; return "$?" ; }
bsd()     { freebsd || netbsd || bsdos || openbsd ; return "$?" ; }
qnx()     { issystem "QNX"     ; return "$?" ; }
darwin()  { issystem "Darwin"  ; return "$?" ; }
gnu()     { issystem "GNU"     ; return "$?" ; }
osf1()     { issystem "OSF1"    ; return "$?" ; }
mingw32() { issystem "MINGW32" ; return "$?" ; }
morphos() { issystem "MorphOS" ; return "$?" ; }
win32()   { cygwin || mingw32  ; return "$?" ; }
beos()    { issystem "BEOS"    ; return "$?" ; }

# arch test boolean functions
# x86/x86pc is used by QNX
x86() {
  case "$host_arch" in
    i[3-9]86|x86|x86pc|k5|k6|k6-2|k6-3|pentium*|athlon*|i586-i686) return 0 ;;
    *) return 1 ;;
  esac
}

x86_64() {
  case "$host_arch" in
    x86_64) return 0 ;;
    *) return 1 ;;
  esac
}

ppc() {
  case "$host_arch" in
    ppc) return 0;;
    *) return 1;;
  esac
}

alpha() {
  case "$host_arch" in
    alpha) return 0;;
    *) return 1;;
  esac
}

# not boolean test: implement the posix shell "!" operator for a
# non-posix /bin/sh.
#   usage:  not {command}
# returns exit status "success" when the execution of "command"
# fails.
not() {
  eval "$@"
  test $? -ne 0
}

# Use this before starting a check
echocheck() {
  echo "============ Checking for $@ ============" >> "$TMPLOG"
  echo ${_echo_n} "Checking for $@ ... ${_echo_c}"
}

# Use this to echo the results of a check
echores() {
  echo "Result is: $@" >> "$TMPLOG"
  echo "##########################################" >> "$TMPLOG"
  echo "" >> "$TMPLOG"
  echo "$@"
}

mangle_homedir_tilde() {
	if test `echo "$1" | cut -c 1` = '~'
	then
		echo "$1" | sed -e "s#\~#$HOME#g"
	else
		echo "$1"
	fi
}

for parm in "$@" ; do
  if test "$parm" = "--help" || test "$parm" = "-help" || test "$parm" = "-h" ; then
    cat << EOF

Usage: $0 [OPTIONS]...

Configuration:
  --interface=INTERFACE         configure shogun for interface
                                cmdline, python-modular, python, r, r-modular
								octave, octave-modular, matlab or libshogun
  -h, -help, --help             display this help and exit

Installation directories:
  --destdir=DIR                 use this as the root dir to install shogun to [/]
  --prefix=DIR                  use this prefix for installing shogun [/usr/local]
  --bindir=DIR                  use this prefix for installing shogun binary
                                [PREFIX/bin]
  --datadir=DIR                 use this prefix for installing machine independent
                                data files (fonts, skins) [PREFIX/share/shogun]
  --mandir=DIR                  use this prefix for installing manpages [PREFIX/man]
  --confdir=DIR                 use this prefix for installing configuration files
                                [same as datadir]
  --libdir=DIR                  use this prefix for object code libraries [PREFIX/lib]
  --incdir=DIR                  use this prefix for include files [PREFIX/include]
  --pydir=DIR                   use this prefix for python files [PREFIX/auto-detected]
  --octdir=DIR                  use this prefix for octave files [PREFIX/auto-detected]
  --rdir=DIR                    use this prefix for r files [PREFIX/auto-detected]

Optional features:
  --enable-mindy                enable mindy library support (for more efficient n-gram, word-in-a-bag kernel implementations) [auto]
  --enable-readline    	        enable readline in cmdline interface [auto]
  --enable-w-timing    	        enable code using W timing  [disabled]
  --enable-logcache             enable log (1+exp(x)) log cache (is much faster but less accurate) [disabled]
  --enable-shortrealkernelcache enable kernelcache to use 4-byte-floating-point values instead of 8-byte-doubles [enabled]
  --enable-logsum-array         enable log sum array supposed to be a bit more accurate [disabled]
  --enable-hmm-parallel         enable parallel structures in hmm training. shogun will then run as many threads as the machine has (much faster) [disabled]

  --disable-treemem             disable more efficient treemem support and use malloc's for each node instead [enabled]
  --disable-largefile           disable large file support (64bit file acces routines) [enabled]
  --disable-lapack    	        disable lapack (fast blas and lapack math routines) and use built in ones (slower!) [auto]
  --disable-cplex    	        disable code using CPLEX  [auto]
  --disable-bigstates	        disable big (16bit) state [enabled]
  --disable-hmmcache 	        disable HMM cache [enabled]
  --disable-svm-light 	        disable building of SVM-light and thus result in pure GPLv3 code [enabled]

Miscellaneous options:
  --disable-doxygen             disable documentation generation via doxygen for python-modular interface [enabled]
  --disable-cpudetection        disable cpu flags detection and corresponding optimization options [enabled]
  --enable-debug                enable debugging [disabled]
  --enable-path-debug	        enable viterbi path debugging [disabled]
  --enable-profile              compile profiling information into shogun [disable]
  --enable-static               build a statically linked binary. Set further linking
                                options with --enable-static="-lslang -lncurses"
  --python=python               use this python executable [python]
  --cc=COMPILER                 use this C compiler to build shogun [gcc]
  --cxx=COMPILER                use this C++ compiler to build shogun [g++]
  --cflags=OPTIONS              use these C compiler options
  --cxxflags=OPTIONS            use these C++ compiler options
  --target=PLATFORM             target platform (i386-linux, arm-linux, etc)
  --install-path=PATH           the path to a custom install program (useful if
                                your OS uses a GNU-incompatible install utility by
                                default and you want to point to the GNU version)
  --includes=DIR                include DIR when searching for includes
  --libs=DIR                    include DIR when searching for libraries on linking
EOF
    exit 0
  fi
done # for parm in ...

# remove stale log
rm -f "$TMPLOG"

# 1st pass checking for vital options
_install=install
_ranlib=ranlib
test "$CC" && COMP_C="$CC"
test "$CXX" && COMP_CPP="$CXX"
_as=auto
_cpudetection=yes

for ac_option do
  case "$ac_option" in
  --interface=*)
	_interface=`echo $ac_option | cut -d '=' -f 2`
	;;
  --target=*)
    _target=`echo $ac_option | cut -d '=' -f 2`
	;;
  --python=*)
    PYTHON=`echo $ac_option | cut -d '=' -f 2`
    ;;
  --cc=*)
    COMP_C=`echo $ac_option | cut -d '=' -f 2`
    ;;
  --cxx=*)
    COMP_CPP=`echo $ac_option | cut -d '=' -f 2`
    ;;
  --cflags=*)
    COMPFLAGS_C=`echo $ac_option | cut -d '=' -f 2` ;
    ;;
  --cxxflags=*)
    COMPFLAGS_CPP=`echo $ac_option | cut -d '=' -f 2` ;
    ;;
  --as=*)
    _as=`echo $ac_option | cut -d '=' -f 2`
    ;;
  --enable-static)
    _ld_static='-static'
    ;;
  --disable-static)
    _ld_static=''
    ;;
  --enable-static=*)
    _ld_static="-static `echo $ac_option | cut -d '=' -f 2`"
    ;;
  --includes=*)
    _inc_extra="-I`echo $ac_option | cut -d '=' -f 2 | sed 's,:, -I,g'` $_inc_extra"
	INCLUDES="$_inc_extra $INCLUDES "
    ;;
  --libs=*)
    _ld_extra="-L`echo $ac_option | cut -d '=' -f 2 | sed 's,:, -L,g'` $_ld_extra"
	LINKFLAGS="$_ld_extra $LINKFLAGS "
    ;;
  --install-path=*)
    _install=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2 | sed 's/\/$//'`/install")
    ;;
  --disable-mindy)		_mindy=no	;;
  --enable-mindy)		_mindy=yes	;;
  --disable-svm-light)	_svm_light=no;	_gpl=yes;;
  --enable-svm-light)	_svm_light=yes; _gpl=no;;
  --disable-readline)	_readline=no	;;
  --enable-readline)	_readline=yes	;;
  --disable-w-timing)	_wtiming=no	;;
  --enable-w-timing)	_wtiming=yes	;;
  --disable-logcache)	_logcache=no	;;
  --enable-logcache)	_logcache=yes	;;
  --disable-shortrealkernelcache)	_shortrealkernelcache=no	;;
  --enable-shortrealkernelcache)	_shortrealkernelcache=yes	;;
  --disable-treemem)	_treemem=no  ;;
  --enable-treemem)		_treemem=yes ;;
  --disable-logsum-array)_logsumarray=no	;;
  --enable-logsum-array)_logsumarray=yes	;;
  --disable-hmm-parallel)	_hmmparallel=no	;;
  --enable-hmm-parallel)	_hmmparallel=yes	;;
  --disable-largefile)	_largefile=no	;;
  --enable-largefile)	_largefile=yes	;;
  --enable-swig-python)	_swig=yes ; _python=yes	;;
  --disable-swig-python)_swig=no ; _python=no ;;
  --enable-doxygen)		_doxygen=yes ;;
  --disable-doxygen)	_doxygen=no ;;
  --disable-lapack)		_lapack=no	;;
  --enable-lapack)		_lapack=yes	;;
  --disable-cplex)		_cplex=no	;;
  --enable-cplex)		_cplex=yes	;;
  --disable-doxygen)	_doxygen=no	;;
  --enable-doxygen)		_doxygen=yes	;;
  --disable-bigstates)	_bigstates=no	;;
  --enable-bigstates)	_bigstates=yes	;;
  --disable-hmmcache)	_hmmcache=no	;;
  --enable-hmmcache)	_hmmcache=yes	;;
  --disable-debug) 		_debug=no ;;
  --enable-debug) 		_debug=yes ;;
  --disable-hmm-debug) 	_hmmdebug=no ;;
  --enable-hmm-debug)   _hmmdebug=yes ;;
  --disable-path-debug)	_pathdebug=no ;;
  --enable-path-debug)  _pathdebug=yes ;;
  --disable-profile) 	_profile=no ;;
  --enable-profile) 	_profile=yes ;;
  --disable-cpudetection) 	_cpudetection=no ;;
  --enable-cpudetection) 	_cpudetection=yes ;;
  --destdir=*)
    _destdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --prefix=*)
    _prefix=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --bindir=*)
    _bindir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --datadir=*)
    _datadir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --mandir=*)
    _mandir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --confdir=*)
    _confdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --libdir=*)
    _libdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --incdir=*)
    _incdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --pydir=*)
    _pydir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
	;;
  --octdir=*)
    _octdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;
  --rdir=*)
    _rdir=$(mangle_homedir_tilde "`echo $ac_option | cut -d '=' -f 2`")
    ;;

  *)
    die "Unknown parameter: $ac_option"
    ;;
  esac
done

if test -z "$_interface"; then
	cat <<EOF
Please specify interface using

    ./configure --interface=INTERFACE,
see ./configure --help for supported interfaces
EOF
	die "no interface specified"
fi

if test "$_interface" = "cmdline"; then
	echo "Enabling cmdline interface"
	_cmdline=yes
	_swig=no
elif test "$_interface" = "python-modular"; then
	echo "Enabling modular python interface"
	_python=yes
	_swig=yes
elif test "$_interface" = "python"; then
	echo "Enabling python interface"
	_python=yes
	_swig=no
elif test "$_interface" = "r"; then
	echo "Enabling R interface"
	_R=yes
	_swig=no
elif test "$_interface" = "r-modular"; then
	echo "Enabling modular R interface"
	_R=yes
	_swig=yes
elif test "$_interface" = "octave"; then
	echo "Enabling Octave interface"
	_octave=yes
	_swig=no
elif test "$_interface" = "octave-modular"; then
	echo "Enabling modular Octave interface"
	_octave=yes
	_swig=yes
elif test "$_interface" = "matlab"; then
	_matlab=yes
	echo "Enabling Matlab(tm) interface"
	_swig=no
elif test "$_interface" = "libshogun"; then
	echo "Enabling library interface"
	_swig=no
else
	die "unknown interface, see ./configure --help for supported interfaces"
fi

#set install dirs
test -z "$_bindir" && _bindir="$_prefix/bin"
test -z "$_datadir" && _datadir="$_prefix/share/shogun"
test -z "$_mandir" && _mandir="$_prefix/man"
test -z "$_confdir" && _confdir="$_prefix/etc/shogun"
test -z "$_libdir" && _libdir="$_prefix/lib"
test -z "$_incdir" && _incdir="$_prefix/include"
test -z "$_pydir" && _pydir="`$PYTHON -c 'import sys; print \"python\"+sys.version[0:3]'`/site-packages"

determine_system_name()
{
	# Determine our OS name and CPU architecture
	if test -z "$_target" ; then
	  # OS name
	  system_name=`( uname -s ) 2>&1`
	  case "$system_name" in
	  Linux|FreeBSD|NetBSD|BSD/OS|OpenBSD|SunOS|QNX|Darwin|GNU|OSF1|BeOS|MorphOS|AIX)
		;;
	  IRIX*)
		system_name=IRIX
		;;
	  HP-UX*)
		system_name=HP-UX
		;;
	  [cC][yY][gG][wW][iI][nN]*)
		system_name=CYGWIN
		;;
	  Interix)
		system_name=INTERIX
		;;
	  *)
		system_name="$system_name-UNKNOWN"
		;;
	  esac


	  # host's CPU/instruction set
	   host_arch=`( uname -p ) 2>&1`
	   case "$host_arch" in
	   i386|sparc|ppc|alpha|arm|mips)
		 ;;
	   powerpc) # Darwin returns 'powerpc'
		 host_arch=ppc
		 ;;
	   *) # uname -p on Linux returns 'unknown' for the processor type,
		  # OpenBSD returns 'Intel Pentium/MMX ("Genuine Intel" 586-class)'

		  # Maybe uname -m (machine hardware name) returns something we
		  # recognize.

		  # x86/x86pc is used by QNX
		  case "`( uname -m ) 2>&1`" in
		  i[3-9]86*|x86|x86pc|k5|k6|k6_2|k6_3|k6-2|k6-3|pentium*|athlon*|i586_i686|i586-i686|BePC) host_arch=i386 ;;
		  ia64) host_arch=ia64 ;;
		  x86_64|amd64)
			if [ -n "`$COMP_C -dumpmachine | sed -n '/^x86_64-/p;/^amd64-/p'`" -a \
				 -z "`echo $COMPFLAGS_C | grep -- -m32`"  ]; then
			  host_arch=x86_64
			else
			  host_arch=i386
			fi
		  ;;
		  macppc|ppc|ppc64) host_arch=ppc ;;
		  alpha) host_arch=alpha ;;
		  sparc) host_arch=sparc ;;
		  sparc64) host_arch=sparc64 ;;
		  parisc*|hppa*|9000*) host_arch=hppa ;;
		  arm*|zaurus|cats) host_arch=arm ;;
		  s390) host_arch=s390 ;;
		  s390x) host_arch=s390x ;;
		  mips) host_arch=mips ;;
		  vax) host_arch=vax ;;
		  m68|m68k) host_arch=m68 ;;
		  *) host_arch=UNKNOWN ;;
		esac
		;;
	  esac
	else
	  system_name=`echo $_target | cut -d '-' -f 2`
	  case "`echo $system_name | tr A-Z a-z`" in
		linux) system_name=Linux ;;
		freebsd) system_name=FreeBSD ;;
		netbsd) system_name=NetBSD ;;
		bsd/os) system_name=BSD/OS ;;
		openbsd) system_name=OpenBSD ;;
		sunos) system_name=SunOS ;;
		qnx) system_name=QNX ;;
		morphos) system_name=MorphOS ;;
		mingw32msvc) system_name=MINGW32 ;;
	  esac
	  # We need to convert underscores so that values like k6-2 and pentium-mmx can be passed
	  host_arch=`echo $_target | cut -d '-' -f 1 | tr '_' '-'`
	fi

	OS="`echo $system_name | tr 'a-z-' 'A-Z_'`"
	echo "Detected Operating System: $system_name"
	echo "Detected Host Architecture: $host_arch"
}

determine_march_mtune()
{

# XXX: this should be ok..
_cpuinfo="echo"
# Cygwin has /proc/cpuinfo, but only supports Intel CPUs
# FIXME: Remove the cygwin check once AMD CPUs are supported
if test -r /proc/cpuinfo && not cygwin; then
  # Linux with /proc mounted, extract CPU information from it
  _cpuinfo="cat /proc/cpuinfo"
elif test -r /compat/linux/proc/cpuinfo && not x86 ; then
  # FreeBSD with Linux emulation /proc mounted,
  # extract CPU information from it
  _cpuinfo="cat /compat/linux/proc/cpuinfo"
elif darwin && not x86 ; then
  # use hostinfo on Darwin
  _cpuinfo="hostinfo"
elif aix; then
  # use 'lsattr' on AIX
  _cpuinfo="lsattr -E -l proc0 -a type"
elif x86; then
  # all other OSes try to extract CPU information from a small helper
  # program .cpuinfo
cat >.cpuinfo.c <<EOF
/* small utility to extract CPU information
   Used by configure to set CPU optimization levels on some operating
   systems where /proc/cpuinfo is non-existent or unreliable. */

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#if defined(__MINGW32__) && (__MINGW32_MAJOR_VERSION <= 3) && (__MINGW32_MINOR_VERSION < 10)
#include <sys/timeb.h>
void gettimeofday(struct timeval* t,void* timezone) {
  struct timeb timebuffer;
  ftime( &timebuffer );
  t->tv_sec=timebuffer.time;
  t->tv_usec=1000*timebuffer.millitm;
}
#endif
#ifdef __MINGW32__
#define MISSING_USLEEP
#define sleep(t) _sleep(1000*t);
#endif

#ifdef __BEOS__
#define usleep(t) snooze(t)
#endif

#ifdef M_UNIX
typedef long long int64_t;
#define MISSING_USLEEP
#else
#include <inttypes.h>
#endif

#ifdef __INTERIX
#include <stdint.h>
#endif

typedef struct cpuid_regs {
  unsigned int eax;
  unsigned int ebx;
  unsigned int ecx;
  unsigned int edx;
} cpuid_regs_t;

static cpuid_regs_t
cpuid(int func) {
  cpuid_regs_t regs;
#define CPUID   ".byte 0x0f, 0xa2; "
#ifdef __x86_64__
  asm("mov %%rbx, %%rsi\n\t"
#else
  asm("mov %%ebx, %%esi\n\t" 
#endif
      CPUID"\n\t"
#ifdef __x86_64__
      "xchg %%rsi, %%rbx\n\t"
#else
      "xchg %%esi, %%ebx\n\t"
#endif
      : "=a" (regs.eax), "=S" (regs.ebx), "=c" (regs.ecx), "=d" (regs.edx)
      : "0" (func));
  return regs;
}


static int64_t
rdtsc(void)
{
  uint64_t i;
#define RDTSC   ".byte 0x0f, 0x31; "
  asm volatile (RDTSC : "=A"(i) : );
  return i;
}

static const char*
brandname(int i)
{
  const static char* brandmap[] = {
    NULL,
    "Intel(R) Celeron(R) processor",
    "Intel(R) Pentium(R) III processor",
    "Intel(R) Pentium(R) III Xeon(tm) processor",
    "Intel(R) Pentium(R) III processor",
    NULL,
    "Mobile Intel(R) Pentium(R) III processor-M",
    "Mobile Intel(R) Celeron(R) processor"
  };

  if (i >= sizeof(brandmap))
    return NULL;
  else
    return brandmap[i];
}

static void
store32(char *d, unsigned int v)
{
  d[0] =  v        & 0xff;
  d[1] = (v >>  8) & 0xff;
  d[2] = (v >> 16) & 0xff;
  d[3] = (v >> 24) & 0xff;
}


int
main(int argc, char **argv)
{
  cpuid_regs_t regs, regs_ext;
  char idstr[13];
  unsigned max_cpuid;
  unsigned max_ext_cpuid;
  unsigned int amd_flags;
  unsigned int amd_flags2;
  const char *model_name = NULL;
  int i;
  char processor_name[49];

  regs = cpuid(0);
  max_cpuid = regs.eax;
  /* printf("%d CPUID function codes\n", max_cpuid+1); */

  store32(idstr+0, regs.ebx);
  store32(idstr+4, regs.edx);
  store32(idstr+8, regs.ecx);
  idstr[12] = 0;
  printf("vendor_id\t: %s\n", idstr); 

  regs_ext = cpuid((1<<31) + 0);
  max_ext_cpuid = regs_ext.eax;
  if (max_ext_cpuid >= (1<<31) + 1) {
    regs_ext = cpuid((1<<31) + 1);
    amd_flags = regs_ext.edx;
    amd_flags2 = regs_ext.ecx;

    if (max_ext_cpuid >= (1<<31) + 4) {
      for (i = 2; i <= 4; i++) {
        regs_ext = cpuid((1<<31) + i);
        store32(processor_name + (i-2)*16, regs_ext.eax);
        store32(processor_name + (i-2)*16 + 4, regs_ext.ebx);
        store32(processor_name + (i-2)*16 + 8, regs_ext.ecx);
        store32(processor_name + (i-2)*16 + 12, regs_ext.edx);
      }
      processor_name[48] = 0;
      model_name = processor_name;
    }
  } else {
    amd_flags = 0;
    amd_flags2 = 0;
  }

  if (max_cpuid >= 1) {
    static struct {
      int bit;
      char *desc;;
      char *description;
    } cap[] = {
      { 0,  "fpu",   "Floating-point unit on-chip" },
      { 1,  "vme",   "Virtual Mode Enhancements" },
      { 2,  "de",    "Debugging Extension" },
      { 3,  "pse",   "Page Size Extension" },
      { 4,  "tsc",   "Time Stamp Counter" },
      { 5,  "msr",   "Pentium Processor MSR" },
      { 6,  "pae",   "Physical Address Extension" },
      { 7,  "mce",   "Machine Check Exception" },
      { 8,  "cx8",   "CMPXCHG8B Instruction Supported" },
      { 9,  "apic",  "On-chip APIC Hardware Enabled" },
      { 11, "sep",   "SYSENTER and SYSEXIT" },
      { 12, "mtrr",  "Memory Type Range Registers" },
      { 13, "pge",   "PTE Global Bit" },
      { 14, "mca",   "Machine Check Architecture" },
      { 15, "cmov",  "Conditional Move/Compare Instruction" },
      { 16, "pat",   "Page Attribute Table" },
      { 17, "pse36", "Page Size Extension 36-bit" },
      { 18, "pn",    "Processor Serial Number" },
      { 19, "cflsh", "CFLUSH instruction" },
      { 21, "dts",   "Debug Store" },
      { 22, "acpi",  "Thermal Monitor and Clock Ctrl" },
      { 23, "mmx",   "MMX Technology" },
      { 24, "fxsr",  "FXSAVE/FXRSTOR" },
      { 25, "sse",   "SSE Extensions" },
      { 26, "sse2",  "SSE2 Extensions" },
      { 27, "ss",    "Self Snoop" },
      { 28, "ht",    "Multi-threading" },
      { 29, "tm",    "Therm. Monitor" },
      { 30, "ia64",  "IA-64 Processor" },
      { 31, "pbe",   "Pend. Brk. EN." },
      { -1 }
    };
    static struct {
      int bit;
      char *desc;
      char *description;
    } cap2[] = {
      { 0, "pni", "SSE3 Extensions" },
      { 3, "monitor", "MONITOR/MWAIT" },
      { 4, "ds_cpl", "CPL Qualified Debug Store" },
      { 5, "vmx", "Virtual Machine Extensions" },
      { 7, "est", "Enhanced Intel SpeedStep Technology" },
      { 8, "tm2", "Thermal Monitor 2" },
      { 10, "cid", "L1 Context ID" },
      { 13, "cx16", "CMPXCHG16B Available" },
      { 14, "xtpr", "xTPR Disable" }, 
      { -1 }
    };
    static struct {
      int bit;
      char *desc;;
      char *description;
    } cap_amd[] = {
      { 11, "syscall", "SYSCALL and SYSRET" },
      { 19, "mp", "MP Capable" },
      { 20, "nx", "No-Execute Page Protection" },
      { 22, "mmxext","MMX Technology (AMD Extensions)" },
      { 25, "fxsr_opt", "Fast FXSAVE/FXRSTOR" },
      { 27, "rdtscp", "RDTSCP Instruction" },
      { 29, "lm", "Long Mode Capable" },
      { 30, "3dnowext","3DNow! Extensions" },
      { 31, "3dnow", "3DNow!" },
      { -1 }
    };
    static struct {
      int bit;
      char *desc;
      char *description;
    } cap_amd2[] = {
      { 0, "lahf_lm", "LAHF/SAHF Supported in 64-bit Mode" },
      { 1, "cmp_legacy", "Chip Multi-Core" },
      { 2, "svm", "Secure Virtual Machine" },
      { 4, "cr8legacy", "CR8 Available in Legacy Mode" },
      { -1 }
    };
    unsigned int family, model, stepping;

    regs = cpuid(1);
    family = (regs.eax >> 8) & 0xf;
    model = (regs.eax >> 4) & 0xf;
    stepping = regs.eax & 0xf;

    if (family == 0xf)
    {
      family += (regs.eax >> 20) & 0xff;
      model += ((regs.eax >> 16) & 0xf) << 4;
    }

    printf("cpu family\t: %d\n"
           "model\t\t: %d\n"
           "stepping\t: %d\n" ,
           family,
           model,
           stepping);

    if (strstr(idstr, "Intel") && !model_name) {
      if (family == 6 && model == 0xb && stepping == 1)
        model_name = "Intel (R) Celeron (R) processor";
      else
        model_name = brandname(regs.ebx & 0xf);
    }   

    printf("flags\t\t:");
    for (i = 0; cap[i].bit >= 0; i++) {
      if (regs.edx & (1 << cap[i].bit)) {
        printf(" %s", cap[i].desc);
      }
    }
    for (i = 0; cap2[i].bit >= 0; i++) {
      if (regs.ecx & (1 << cap2[i].bit)) {
        printf(" %s", cap2[i].desc);
      }
    }
    /* k6_mtrr is supported by some AMD K6-2/K6-III CPUs but
       it is not indicated by a CPUID feature bit, so we
       have to check the family, model and stepping instead. */
    if (strstr(idstr, "AMD") &&
        family == 5 && 
        (model >= 9 || model == 8 && stepping >= 8))
      printf(" %s", "k6_mtrr");
    /* similar for cyrix_arr. */
    if (strstr(idstr, "Cyrix") &&
        (family == 5 && model < 4 || family == 6))
      printf(" %s", "cyrix_arr");
    /* as well as centaur_mcr. */
    if (strstr(idstr, "Centaur") &&
        family == 5)
      printf(" %s", "centaur_mcr");
 
    for (i = 0; cap_amd[i].bit >= 0; i++) {
      if (amd_flags & (1 << cap_amd[i].bit)) {
        printf(" %s", cap_amd[i].desc);
      }
    }
    for (i = 0; cap_amd2[i].bit >= 0; i++) {
      if (amd_flags2 & (1 << cap_amd2[i].bit)) {
        printf(" %s", cap_amd2[i].desc);
      }
    }
    printf("\n");

    if (regs.edx & (1 << 4)) {
      int64_t tsc_start, tsc_end;
      struct timeval tv_start, tv_end;
      int usec_delay;

      tsc_start = rdtsc();
      gettimeofday(&tv_start, NULL);
#ifdef  MISSING_USLEEP
      sleep(1);
#else
      usleep(100000);
#endif
      tsc_end = rdtsc();
      gettimeofday(&tv_end, NULL);

      usec_delay = 1000000 * (tv_end.tv_sec - tv_start.tv_sec)
        + (tv_end.tv_usec - tv_start.tv_usec);

      printf("cpu MHz\t\t: %.3f\n", 
             (double)(tsc_end-tsc_start) / usec_delay);
    }
  }

  printf("model name\t: ");
  if (model_name)
    printf("%s\n", model_name);
  else
    printf("Unknown %s CPU\n", idstr); 
}
EOF

		$COMP_C -o .cpuinfo .cpuinfo.c
		_cpuinfo="./.cpuinfo"
	fi

if x86 || x86_64 ; then
  # gather more CPU information
  pname=`$_cpuinfo | grep 'model name' | cut -d ':' -f 2 | _head 1`
  pvendor=`$_cpuinfo | grep 'vendor_id' | cut -d ':' -f 2  | cut -d ' ' -f 2 | _head 1`
  pfamily=`$_cpuinfo | grep 'cpu family' | cut -d ':' -f 2 | cut -d ' ' -f 2 | _head 1`
  pmodel=`$_cpuinfo | grep -v 'model name' | grep 'model' | cut -d ':' -f 2 | cut -d ' ' -f 2 | _head 1`
  pstepping=`$_cpuinfo | grep 'stepping' | cut -d ':' -f 2 | cut -d ' ' -f 2 | _head 1`

  exts=`$_cpuinfo | egrep 'features|flags' | cut -d ':' -f 2 | _head 1`

  pparam=`echo $exts | sed -e s/k6_mtrr/mtrr/ -e s/cyrix_arr/mtrr/ -e s/centaur_mcr/mtrr/ \
                           -e s/xmm/sse/ -e s/kni/sse/`

  for ext in $pparam ; do
    eval _$ext=auto && eval _$ext=yes
  done

  # SSE implies MMX2, but not all SSE processors report the mmxext CPU flag.
  test $_sse = yes && _mmxext=yes

  echocheck "CPU vendor"
  echores "$pvendor ($pfamily:$pmodel:$pstepping)"

  echocheck "CPU type"
  echores "$pname"
fi

case "$host_arch" in
  i[3-9]86|x86|x86pc|k5|k6|k6-2|k6-3|pentium*|athlon*|i586-i686)
  _def_arch="#define ARCH_X86 1"
  _target_arch="TARGET_ARCH_X86 = yes"

  case "$pvendor" in
  AuthenticAMD)
    case "$pfamily" in
    3) proc=i386 iproc=386 ;;
    4) proc=i486 iproc=486 ;;
    5) iproc=586       # LGB: models are: K5/SSA5 K5 K5 K5 ? ? K6 K6 K6-2 K6-3
	# K6 model 13 are the K6-2+ and K6-III+, only differing in cache size.
	if test "$pmodel" -eq 9 -o "$pmodel" -eq 13; then
		proc=k6-3
	elif test "$pmodel" -ge 8; then
		proc=k6-2
	elif test "$pmodel" -ge 6; then
		proc=k6
	else
		proc=i586
	fi
	;;
    6) iproc=686
	# It's a bit difficult to determine the correct type of Family 6
	# AMD CPUs just from their signature. Instead, we check directly
	# whether it supports SSE.
	if test "$_sse" = yes; then
		# gcc treats athlon-xp, athlon-4 and athlon-mp similarly.
		proc=athlon-xp
	else
		# Again, gcc treats athlon and athlon-tbird similarly.
		proc=athlon
	fi
	;;
    15) iproc=686
    	# k8 cpu-type only supported in gcc >= 3.4.0, but that will be
    	# caught and remedied in the optimization tests below.
    	proc=k8
    	;;

    *) proc=k8 iproc=686 ;;
    esac
    ;;
  GenuineIntel)
    case "$pfamily" in
    3) proc=i386 iproc=386 ;;
    4) proc=i486 iproc=486 ;;
    5) iproc=586
	if test "$pmodel" -eq 4 || test "$pmodel" -eq 8; then
		proc=pentium-mmx # 4 is desktop, 8 is mobile
	else
		proc=i586
	fi
	;;
    6) iproc=686
	if test "$pmodel" -eq 9 -o "$pmodel" -ge 13; then
		proc=pentium-m
	elif test "$pmodel" -ge 7; then
		proc=pentium3
	elif test "$pmodel" -ge 3; then
		proc=pentium2
	else
		proc=i686
	fi
	;;
    15) iproc=686
	# A nocona in 32-bit mode has no more capabilities than a prescott.
	if test "$pmodel" -ge 3; then
		proc=prescott
	else
		proc=pentium4
	fi
	;;
    *) proc=prescott iproc=686 ;;
    esac
    ;;
  CentaurHauls)
    case "$pfamily" in
    5) iproc=586
	if test "$pmodel" -ge 8; then
		proc=winchip2
	elif test "$pmodel" -ge 4; then
		proc=winchip-c6
	else
		proc=i586
	fi
	;;
    6) iproc=686
	if test "$pmodel" -ge 9; then
		proc=c3-2
	else
		proc=c3
		iproc=586
	fi
	;;
    *) proc=i686 iproc=i686 ;;
    esac
    ;;
  unknown)
    case "$pfamily" in
    3) proc=i386 iproc=386 ;;
    4) proc=i486 iproc=486 ;;
    *) proc=i586 iproc=586 ;;
    esac
    ;;
  *)
    proc=i586 iproc=586 ;;
  esac

    # check that gcc supports our CPU, if not, fall back to earlier ones
    # LGB: check -mcpu and -march swithing step by step with enabling
    # to fall back till 386.

    # gcc >= 3.4.0  doesn't support -mcpu, we have to use -mtune instead

    if [ "$cc_vendor" = "gnu" ] && ([ "$_cc_major" -gt 3 ] || ( [ "$_cc_major" = 3 ] && [ "$_cc_minor" -ge 4 ])) ; then
	cpuopt=-mtune
    else
	cpuopt=-mcpu
    fi

    echocheck "GCC & CPU optimization abilities"
cat > $TMPC << EOF
int main(void) { return 0; }
EOF
  if test "$_cpudetection" = no ; then
	cc_check -march=native && proc=native
    if test "$proc" = "k8" -o "$proc" = "opteron" \
		-o "$proc" = "athlon64" -o "$proc" = "athlon-fx" ; then
      cc_check -march=$proc $cpuopt=$proc || proc=athlon-xp
    fi
    if test "$proc" = "athlon-xp" || test "$proc" = "athlon-4" \
		|| test "$proc" = "athlon-tbird"; then
      cc_check -march=$proc $cpuopt=$proc || proc=athlon
    fi
    if test "$proc" = "k6-3" || test "$proc" = "k6-2"; then
      cc_check -march=$proc $cpuopt=$proc  || proc=k6
    fi
    if test "$proc" = "k6" || test "$proc" = "c3"; then
      if not cc_check -march=$proc $cpuopt=$proc; then
        if cc_check -march=i586 $cpuopt=i686; then
          proc=i586-i686
        else 
          proc=i586
	fi
      fi
    fi
    if test "$proc" = "pentium4" || test "$proc" = "pentium-m" || test "$proc" = "pentium3" || test "$proc" = "pentium2" || test "$proc" = "athlon" || test "$proc" = "c3-2" || test "$proc" = "geode"; then
      cc_check -march=$proc $cpuopt=$proc  || proc=i686
    fi
    if test "$proc" = "i686" || test "$proc" = "pentium-mmx" || test "$proc" = "winchip-c6" || test "$proc" = "winchip2"; then
      cc_check -march=$proc $cpuopt=$proc  || proc=i586
    fi
    if test "$proc" = "i586"; then
      cc_check -march=$proc $cpuopt=$proc  || proc=i486
    fi
    if test "$proc" = "i486" ; then
      cc_check -march=$proc $cpuopt=$proc  || proc=i386
    fi
    if test "$proc" = "i386" ; then
      cc_check -march=$proc $cpuopt=$proc  || proc=error
    fi
    if test "$proc" = "error" ; then
        echores "CPU optimization disabled. CPU not recognized or your compiler is too old."
      _mcpu=""
      _march=""
    elif test "$proc" = "i586-i686"; then
      _march="-march=i586"
      _mcpu="$cpuopt=i686"
    else
      _march="-march=$proc"
      _mcpu="$cpuopt=$proc"
    fi
  else # if test "$_cpudetection" = no
    # i686 is probably the most common CPU - optimize for it
    _mcpu="$cpuopt=i686"
    # at least i486 required, for bswap instruction
    _march="-march=i486"
    cc_check $_mcpu || _mcpu=""
    cc_check $_march $_mcpu || _march=""
  fi

    ## Gabucino : --target takes effect here (hopefully...) by overwriting
    ##             autodetected mcpu/march parameters
    if test "$_target" ; then
      # TODO: it may be a good idea to check GCC and fall back in all cases
      if test "$host_arch" = "i586-i686"; then
        _march="-march=i586"
        _mcpu="$cpuopt=i686"
      else      
        _march="-march=$host_arch"
        _mcpu="$cpuopt=$host_arch"
      fi
    
      proc="$host_arch"

      case "$proc" in
        i386) iproc=386 ;;
        i486) iproc=486 ;;
        i586|k5|k6|k6-2|k6-3|pentium|pentium-mmx) iproc=586 ;;
        i686|athlon*|pentium*) iproc=686 ;;
        *) iproc=586 ;;
      esac
    fi

    echores "$proc"
    ;;

  ia64)
    _def_arch='#define ARCH_IA64 1'
    _target_arch='TARGET_ARCH_IA64 = yes'
    iproc='ia64'
    proc=''
    _march=''
    _mcpu=''
    ;;

  x86_64|amd64)
    _def_arch='#define ARCH_X86_64 1'
    _target_arch='TARGET_ARCH_X86_64 = yes'
    iproc='x86_64'

    # gcc >= 3.4.0  doesn't support -mcpu, we have to use -mtune instead
    if test "$cc_vendor" = "gnu" && test "$_cc_major" -gt 3 -o "$_cc_major" -eq 3 -a "$_cc_minor" -ge 4 ; then
	cpuopt=-mtune
    else
	cpuopt=-mcpu
    fi
    case "$pvendor" in
    AuthenticAMD)
      proc=k8;;
    GenuineIntel)
      # 64-bit prescotts exist, but as far as GCC is concerned they have the
      # same capabilities as a nocona.
      proc=nocona;;
    *)
      proc=error;;
    esac

    echocheck "GCC & CPU optimization abilities"
cat > $TMPC << EOF
int main(void) { return 0; }
EOF
    # This is a stripped-down version of the i386 fallback.
    if test "$_cpudetection" = no ; then
      # --- AMD processors ---
      if test "$proc" = "k8" -o "$proc" = "opteron" -o "$proc" = "athlon64" -o "$proc" = "athlon-fx" ; then
        cc_check -march=$proc $cpuopt=$proc || proc=athlon-xp
      fi
      # This will fail if gcc version < 3.3, which is ok because earlier
      # versions don't really support 64-bit on amd64.
      # Is this a valid assumption? -Corey
      if test "$proc" = "athlon-xp" || test "$proc" = "athlon-4" ; then
        cc_check -march=$proc $cpuopt=$proc || proc=error
      fi
      # --- Intel processors ---
      if test "$proc" = "nocona" || test "$proc" = "prescott" ; then
        cc_check -march=$proc $cpuopt=$proc || proc=pentium4
      fi
      if test "$proc" = "pentium4" || test "$proc" = "pentium4m" ; then
        cc_check -march=$proc $cpuopt=$proc || proc=error
      fi

      _march="-march=$proc"
      _mcpu="$cpuopt=$proc"
      if test "$proc" = "error" ; then
        echores "CPU optimization disabled. CPU not recognized or your compiler is too old."
        _mcpu=""
        _march=""
      fi
    else
      _march=""
      _mcpu=""
    fi
    
    echores "$proc"
    ;;

  sparc)
    _def_arch='#define ARCH_SPARC 1'
    _target_arch='TARGET_ARCH_SPARC = yes'
    iproc='sparc'
    if sunos ; then
	echocheck "CPU type"
	karch=`uname -m`
	case "`echo $karch`" in
	    sun4) proc=v7 ;;
	    sun4c) proc=v7 ;; 
	    sun4d) proc=v8 ;;
	    sun4m) proc=v8 ;;
	    sun4u) proc=v9 _vis='yes' _def_vis='#define HAVE_VIS = yes' ;;
	    sun4v) proc=v9 ;;
	    *) proc=v8 ;;
	esac
	echores "$proc"
    else
	proc=v8
    fi
    _march=''
    _mcpu="-mcpu=$proc"
    ;;

  sparc64)
    _def_arch='#define ARCH_SPARC 1'
    _target_arch='TARGET_ARCH_SPARC = yes'
    _vis='yes'
    _def_vis='#define HAVE_VIS = yes'
    iproc='sparc'
    proc='v9'
    _march=''
    _mcpu="-mcpu=$proc"
    ;;

  arm|armv4l|armv5tel)
    _def_arch='#define ARCH_ARMV4L 1'
    _target_arch='TARGET_ARCH_ARMV4L = yes'
    iproc='arm'
    proc=''
    _march=''
    _mcpu=''
    ;;

  ppc)
    _def_arch='#define ARCH_POWERPC 1'
    _def_dcbzl='#define NO_DCBZL 1'
    _target_arch='TARGET_ARCH_POWERPC = yes'
    iproc='ppc'
    proc=''
    _march=''
    _mcpu=''
    _altivec=no

    echocheck "CPU type"
    case $system_name in
      Linux)
	proc=`$_cpuinfo | grep 'cpu' | cut -d ':' -f 2 | cut -d ',' -f 1 | cut -b 2- | _head 1`
	if test -n "`$_cpuinfo | grep altivec`"; then
	    _altivec=yes
	fi
        ;;
      Darwin)
	proc=`$_cpuinfo | grep "Processor type" | cut -f 3 -d ' ' | sed 's/ppc//'`
	if [ `sysctl -n hw.vectorunit` -eq 1 -o \
	    "`sysctl -n hw.optional.altivec 2> /dev/null`" = "1" ]; then
	    _altivec=yes
	fi
        ;;
      NetBSD)
        # only gcc 3.4 works reliably with AltiVec code under NetBSD
	case $cc_version in
	    2*|3.0*|3.1*|3.2*|3.3*)
		;;
	    *)
		if [ `sysctl -n machdep.altivec` -eq 1 ]; then
		    _altivec=yes
		fi
		;;
	esac
        ;;
      AIX)
	proc=`$_cpuinfo | grep 'type' | cut -f 2 -d ' ' | sed 's/PowerPC_//'`
	;;
    esac
    if test "$_altivec" = yes; then
        echores "$proc altivec"
    else
        echores "$proc"
    fi

    echocheck "GCC & CPU optimization abilities"

    if test -n "$proc"; then
        case "$proc" in
	    601) _march='-mcpu=601' _mcpu='-mtune=601' ;;
	    603) _march='-mcpu=603' _mcpu='-mtune=603' ;;
	    603e|603ev) _march='-mcpu=603e' _mcpu='-mtune=603e' ;;
	    604|604e|604r|604ev) _march='-mcpu=604' _mcpu='-mtune=604' ;;
	    740|740/750|745/755) _march='-mcpu=740' _mcpu='-mtune=740' ;;
	    750|750CX) _march='-mcpu=750' _mcpu='-mtune=750' ;;
	    POWER)  _march='-mcpu=power'  _mcpu='-mtune=power'  ;;
	    POWER2) _march='-mcpu=power2' _mcpu='-mtune=power2' ;;
	    POWER3) _march='-mcpu=power3' _mcpu='-mtune=power3' ;;
    	    *) ;;
        esac
	# gcc 3.1(.1) and up supports 7400 and 7450
	if test "$_cc_major" -ge "3" && test "$_cc_minor" -ge "1" || test "$_cc_major" -ge "4"; then
	    case "$proc" in
		7400*|7410*) _march='-mcpu=7400' _mcpu='-mtune=7400' ;;
		7447*|7450*|7455*) _march='-mcpu=7450' _mcpu='-mtune=7450' ;;
    		*) ;;
    	    esac
	fi
	# gcc 3.2 and up supports 970
	if test "$_cc_major" -ge "3" && test "$_cc_minor" -ge "3" || test "$_cc_major" -ge "4"; then
	    case "$proc" in
		970*|PPC970*) _march='-mcpu=970' _mcpu='-mtune=970'
                      _def_dcbzl='#undef NO_DCBZL' ;;
    		*) ;;
    	    esac
	fi
	# gcc 3.3 and up supports POWER4
	if test "$_cc_major" -ge "3" && test "$_cc_minor" -ge "3" || test "$_cc_major" -ge "4"; then
	    case "$proc" in
		POWER4) _march='-mcpu=power4' _mcpu='-mtune=power4' ;;
		*) ;;
	    esac
	fi
	# gcc 4.0 and up supports POWER5
	if test "$_cc_major" -ge "4"; then
	    case "$proc" in
		POWER5) _march='-mcpu=power5' _mcpu='-mtune=power5' ;;
		*) ;;
	    esac
	fi
    fi

	echores "none"
    ;;

  alpha)
    _def_arch='#define ARCH_ALPHA 1'
    _target_arch='TARGET_ARCH_ALPHA = yes'
    iproc='alpha'
    _march=''
    
    echocheck "CPU type"
    cat > $TMPC << EOF
int main() {
    unsigned long ver, mask;
    asm ("implver %0" : "=r" (ver));
    asm ("amask %1, %0" : "=r" (mask) : "r" (-1));
    printf("%ld-%x\n", ver, ~mask);
    return 0;
}
EOF
    $COMP_C -o "$TMPO" "$TMPC"
    case `"$TMPO"` in

        0-0)    proc="ev4";   cpu_understands_mvi="0";;
        1-0)    proc="ev5";   cpu_understands_mvi="0";;
        1-1)    proc="ev56";  cpu_understands_mvi="0";; 
        1-101)  proc="pca56"; cpu_understands_mvi="1";;
        2-303)  proc="ev6";   cpu_understands_mvi="1";;
        2-307)  proc="ev67";  cpu_understands_mvi="1";;
        2-1307) proc="ev68";  cpu_understands_mvi="1";;
    esac
    echores "$proc"
    
    echocheck "GCC & CPU optimization abilities"
    if test "$proc" = "ev68" ; then
      cc_check -mcpu=$proc || proc=ev67
    fi
    if test "$proc" = "ev67" ; then
      cc_check -mcpu=$proc || proc=ev6
    fi
    _mcpu="-mcpu=$proc"
    echores "$proc"
    
    echocheck "MVI instruction support in GCC"
    if test "$_cc_major" -ge "3" && test "$cpu_understands_mvi" = "1" ; then
        _def_gcc_mvi_support="#define CAN_COMPILE_ALPHA_MVI 1"
	echores "yes"
    else
	_def_gcc_mvi_support="#undef CAN_COMPILE_ALPHA_MVI"
	echores "no, GCC = `$COMP_C -dumpversion 2>&1` (must be >= 3), CPU = $proc (must be pca56 or later)"
    fi
    ;;

  mips)
    _def_arch='#define ARCH_SGI_MIPS 1'
    _target_arch='TARGET_ARCH_SGI_MIPS = yes'
    iproc='sgi-mips'
    proc=''
    _march=''
    _mcpu=''

    if irix ; then
	echocheck "CPU type"
	proc=`hinv -c processor | grep CPU | cut -d " " -f3`
	case "`echo $proc`" in
	    R3000) _march='-mips1' _mcpu='-mtune=r2000' ;;
	    R4000) _march='-mips3' _mcpu='-mtune=r4000' ;;
	    R4400) _march='-mips3' _mcpu='-mtune=r4400' ;;
	    R4600) _march='-mips3' _mcpu='-mtune=r4600' ;;
	    R5000) _march='-mips4' _mcpu='-mtune=r5000' ;;
	    R8000|R10000|R12000|R14000|R16000) _march='-mips4' _mcpu='-mtune=r8000' ;;
	esac
        echores "$proc"
    fi

    ;;

  hppa)
    _def_arch='#define ARCH_PA_RISC 1'
    _target_arch='TARGET_ARCH_PA_RISC = yes'
    iproc='PA-RISC'
    proc=''
    _march=''
    _mcpu=''
    ;;

  s390)
    _def_arch='#define ARCH_S390 1'
    _target_arch='TARGET_ARCH_S390 = yes'
    iproc='390'
    proc=''
    _march=''
    _mcpu=''
    ;;

  s390x)
    _def_arch='#define ARCH_S390X 1'
    _target_arch='TARGET_ARCH_S390X = yes'
    iproc='390x'
    proc=''
    _march=''
    _mcpu=''
    ;;

  vax)
    _def_arch='#define ARCH_VAX 1'
    _target_arch='TARGET_ARCH_VAX = yes'
    iproc='vax'
    proc=''
    _march=''
    _mcpu=''
	;;
  m68)
    _def_arch='#define ARCH_M68K 1'
    _target_arch='TARGET_ARCH_M68K = yes'
    iproc=''
    proc=''
    _march=''
    _mcpu=''
    ;;

  *)
    echo "The architecture of your CPU ($host_arch) is not supported by this configure script"
    echo "It seems nobody has ported SHOGUN to your OS or CPU type yet."
    die "unsupported architecture $host_arch"
    ;;
esac # case "$host_arch" in

if test "$_cpudetection" = yes ; then
  if x86; then
    _mmx=yes
    _3dnow=yes
    _3dnowext=yes
    _mmxext=yes
    _sse=yes
    _sse2=yes
    _sse3=yes
    _mtrr=yes
  fi
  if ppc; then
    _altivec=yes
  fi
fi

if x86 || x86_64 && test "$_cpudetection" = no ; then
  extcheck() {
    if test "$1" = yes ; then
      echocheck "compiler and kernel support of $2"
      cat > $TMPC <<EOF
#include <signal.h>
void catch() { exit(1); }
int main(void){
  signal(SIGILL, catch);
  __asm__ __volatile__ ("$3":::"memory");return(0);
}
EOF

      if cc_check "-m$2" && tmp_run ; then
        echores "yes"
		_optimizing="$_optimizing -m$2"
        return 0
      else
        echores "failed"
	return 1
      fi
    fi
    return 0
  }

  extcheck $_mmx "mmx" "emms" || _mmx=no
  extcheck $_3dnow "3dnow" "femms" || _3dnow=no
  extcheck $_sse "sse" "xorps %%xmm0, %%xmm0" || _sse=no _gcc3_ext="$_gcc3_ext -mno-sse"
  extcheck $_sse2 "sse2" "xorpd %%xmm0, %%xmm0" || _sse2=no _gcc3_ext="$_gcc3_ext -mno-sse2"
  extcheck $_pni "sse3" "addsubpd %%xmm0, %%xmm1" || _sse3=no _gcc3_ext="$_gcc3_ext -mno-sse3"

  if test "$_gcc3_ext" != ""; then
    # if we had to disable sse/sse2 because the active kernel does not
    # support this instruction set extension, we also have to tell
    # gcc3 to not generate sse/sse2 instructions for normal C code
    cat > $TMPC << EOF
int main(void) { return 0; }
EOF
    cc_check $_march $_gcc3_ext && _march="$_march $_gcc3_ext"
  fi

fi


# intrinsics headers for use with FFmpeg
if test "$_sse" = yes ; then
  echocheck "xmmintrin.h"
  cat > $TMPC << EOF
#include <xmmintrin.h>
int main() { _mm_sfence(); return 0; }
EOF
  _builtin_vector=no
  cc_check -msse && _builtin_vector=yes
  if test "$_builtin_vector" = yes ; then
    _def_builtin_vector='#define HAVE_BUILTIN_VECTOR 1'
  else
    _def_builtin_vector='#undef HAVE_BUILTIN_VECTOR'
  fi
  echores "$_builtin_vector"
fi

if test "$_3dnow" = yes ; then
  echocheck "mm3dnow.h"
  cat > $TMPC << EOF
#include <mm3dnow.h>
int main() { _m_femms(); return 0; }
EOF
  _mm3dnow=no
  cc_check -m3dnow && _mm3dnow=yes
  if test "$_mm3dnow" = yes ; then
    _def_mm3dnow='#define HAVE_MM3DNOW 1'
  else
    _def_mm3dnow='#undef HAVE_MM3DNOW'
  fi
  echores "$_mm3dnow"
fi

  DEFINES="$DEFINES -D$OS"

  if test "$_cpudetection" = yes
  then
	  COMPFLAGS_C="$COMPFLAGS_C $_march $_mcpu"
	  COMPFLAGS_CPP="$COMPFLAGS_CPP $_march $_mcpu"
  fi

  if test "$_profile" = yes
  then
	  COMPFLAGS_CPP="$COMPFLAGS_CPP -pg"
	  COMPFLAGS_C="$COMPFLAGS_CPP -pg"
	  LINKFLAGS="$LINKFLAGS -pg"
  fi

}

set_opts()
{
	if darwin
	then
		if test "$_matlab" = yes
		then
			true #nop	
		elif test "$_R" = yes
		then
			true #nop	
		else
			LINKFLAGS="$LINKFLAGS -undefined error"
		fi
	elif interix
	then
		COMPFLAGS_C="$COMPFLAGS_C -D_ALL_SOURCE -D_REENTRANT"
		COMPFLAGS_CPP="$COMPFLAGS_CPP -D_ALL_SOURCE -D_REENTRANT"
	elif sunos
	then
		true #nop
	else
		LINKFLAGS="$LINKFLAGS -Xlinker --no-undefined"
	fi

cat > $TMPC << EOF
#include <math.h>
int main(void) { return 0; }
EOF
	echocheck "Math support (-lm)"
	if cc_check -lm
	then
		LINKFLAGS="$LINKFLAGS -lm"
		echores "yes"
	else
		echores "no"
		die "could not find math library (libm)"
	fi

cat > $TMPC << EOF
#include <math.h>
int main(int argc, char** argv)
{
	long double a=::powl((long double) argc, (long double) argc);
	return (int) a;
}
EOF
	echocheck "Math powl() support"
	if cxx_check -lm
	then
		HAVE_POWL='#define HAVE_POWL 1'
		DEFINES="$DEFINES -DHAVE_POWL"
		echores "yes"
	else
		echores "no - resorting to pow()"
	fi

cat > $TMPC << EOF
#include <math.h>
int main(int argc, char** argv)
{
	long double a=::sqrtl((long double) argc);
	return (int) a;
}
EOF
	echocheck "Math sqrtl() support"
	if cxx_check -lm
	then
		HAVE_SQRTL='#define HAVE_SQRTL 1'
		DEFINES="$DEFINES -DHAVE_SQRTL"
		echores "yes"
	else
		echores "no - resorting to sqrt()"
	fi

cat > $TMPC << EOF
#include <math.h>
int main(int argc, char** argv)
{
	double a=::log2((double) argc);
	return (int) a;
}
EOF
	echocheck "Math log2() support"
	if cxx_check -lm
	then
		HAVE_LOG2='#define HAVE_LOG2 1'
		DEFINES="$DEFINES -DHAVE_LOG2"
		echores "yes"
	else
		echores "no - resorting to emulation()"
	fi

cat > $TMPC << EOF
#include <pthread.h>
int main(void) { return 0; }
EOF
	echocheck "Posix threads support"
	_pthread=no

	for pthr in -pthread -lpthread
	do
		if cc_check $pthr
		then
			COMPFLAGS_C="$COMPFLAGS_C $pthr"
			COMPFLAGS_CPP="$COMPFLAGS_CPP $pthr"
			LINKFLAGS="$LINKFLAGS $pthr"
			_pthread=yes
			break
		fi
	done

	if test "$_pthread" = yes
	then
		echores "yes"
	else
		echores "no"
		die "no posix threading support found (libpthread)"
	fi

	if test "$_R" != yes -a "$_python" != yes -a "$_matlab" != yes -a "$_octave" != yes
	then
		if test "$_readline" = yes || test "$_readline" = auto;
		then
cat > $TMPC << EOF
#include <readline/readline.h>
int main(void) { return 0; }
EOF
			echocheck "Readline support"
			if cc_check -lreadline >/dev/null 2>&1
			then
				HAVE_READLINE='#define HAVE_READLINE 1'
				DEFINES="$DEFINES -DHAVE_READLINE"
				LINKFLAGS="$LINKFLAGS -lreadline"
				echores "yes"
			else
				echores "no"
			fi
		fi
	fi

	if test "$_mindy" = yes || test "$_mindy" = auto
	then
cat > $TMPC << EOF
#include <mindy.h>
int main(void) { return 0; }
EOF
		echocheck "Mindy support"
		if cc_check -lmindy
		then
			HAVE_MINDY='#define HAVE_MINDY 1'
			DEFINES="$DEFINES -DHAVE_MINDY"
			LINKFLAGS="$LINKFLAGS -lmindy"
			echores "yes"
		else
			echores "no - never mind"
		fi
	fi

	if test "$_lapack" = yes || test "$_lapack" = auto
	then
cat > $TMPC << EOF
#include <cblas.h>
void dpotrf(char uplo, int n, double *a, int lda, int *info);

int main(int argc, char** argv)
{ 
	char uplo = 'U';
	int info=0;
	int skip=argc;
	int n=argc; double* a=0; double* v1=0; double* v2=0;
	int lda=1;
	dpotrf(uplo, n, a, lda, &info);
	int r = cblas_ddot(n, v1, skip, v2, skip);
	return 0;
}
EOF
		echocheck "AMD ACML support"
		if cc_check -lacml -lcblas -lgfortran
		then
			echores "yes"
			HAVE_ACML='#define HAVE_ACML 1'
			HAVE_LAPACK='#define HAVE_LAPACK 1'
			DEFINES="$DEFINES -DHAVE_ACML -DHAVE_LAPACK"
			LINKFLAGS="$LINKFLAGS -lacml -lcblas -lgfortran"
		else
			echores "no"

cat > $TMPC << EOF
#include <mkl_cblas.h>
void dpotrf(char* uplo, int* n, double* a, int* lda, int* info);

int main(int argc, char** argv)
{ 
	char uplo = 'U';
	int info=0;
	int skip=argc;
	int n=argc; double* a=0; double* v1=0; double* v2=0;
	int lda=1;
	dpotrf(&uplo, &n, a, &lda, &info);
	int r = cblas_ddot(n, v1, skip, v2, skip);
	return 0;
}
EOF
			echocheck "Intel MKL support"
			if cc_check -lmkl -lguide -lmkl_lapack64
			then
				echores "yes"
				HAVE_MKL='#define HAVE_MKL 1'
				HAVE_LAPACK='#define HAVE_LAPACK 1'
				DEFINES="$DEFINES -DHAVE_MKL -DHAVE_LAPACK"
				LINKFLAGS="$LINKFLAGS -lmkl -lguide -lmkl_lapack64"
			else
				echores "no"

cat > $TMPC << EOF
#include <cblas.h>
#include <clapack.h>

int main(int argc, char** argv)
{ 
	int skip=argc;
	int n=argc; double* a=0; double* v1=0; double* v2=0;
	int result=clapack_dpotrf(CblasRowMajor, CblasUpper, n, a, n);
	int r = cblas_ddot(n, v1, skip, v2, skip);
	return 0;
}
EOF
				echocheck "Atlas support"
				if cc_check -llapack_atlas -llapack -lcblas
				then
					echores "yes"
					HAVE_ATLAS='#define HAVE_ATLAS 1'
					HAVE_LAPACK='#define HAVE_LAPACK 1'
					DEFINES="$DEFINES -DHAVE_ATLAS -DHAVE_LAPACK"
					LINKFLAGS="$LINKFLAGS -llapack_atlas -llapack -lcblas"
				else
					if cc_check -latlas -llapack -lcblas
					then
						echores "yes"
						HAVE_ATLAS='#define HAVE_ATLAS 1'
						HAVE_LAPACK='#define HAVE_LAPACK 1'
						DEFINES="$DEFINES -DHAVE_ATLAS -DHAVE_LAPACK"
						LINKFLAGS="$LINKFLAGS -latlas -llapack -lcblas"
					else
						echores "no"
					fi

cat > $TMPC << EOF
#include <cblas.h>
int dpotrf_(char* uplo, int* n, double* a, int* lda, int* info);
int main(int argc, char** argv)
{ 
	char uplo = 'U';
	int info=0;
	int skip=argc;
	int n=argc; double* a=0; double* v1=0; double* v2=0;
	dpotrf_(uplo, &n, a, 1, &info);
	int r = cblas_ddot(n, v1, skip, v2, skip);
	return 0;
}
EOF
					echocheck "Vanilla lapack and blas support"
					if cc_check -llapack -lcblas
					then
						echores "yes"
						HAVE_LAPACK='#define HAVE_LAPACK 1'
						DEFINES="$DEFINES -DHAVE_LAPACK -DHAVE_LAPACK"
						LINKFLAGS="$LINKFLAGS -llapack -lcblas"
					else
						if cc_check -llapack -lblas
						then
							echores "yes"
							HAVE_LAPACK='#define HAVE_LAPACK 1'
							DEFINES="$DEFINES -DHAVE_LAPACK -DHAVE_LAPACK"
							LINKFLAGS="$LINKFLAGS -llapack -lblas"
						else
							echores "no"
						fi
					fi
				fi
			fi
		fi
	fi

	if test "$_matlab" = yes
	then
		if win32
		then
			echocheck "Matlab"
			matlab.exe /nosplash /minimize /r "fid=fopen('matlab_version.txt','wb');fprintf(fid,version);fclose(fid);quit"
			if test -f matlab_version.txt
			then
				echores `cat matlab_version.txt`
				matlab.exe /nosplash /minimize /r "system('env > matlab_path.txt');quit"
				MATLAB_DIR=`grep '^_=' matlab_path.txt | cut -c 3- | sed 's#/bin/win32/matlab.exe##'`
				MATLAB_SRCDIR="$MATLAB_DIR/extern/src"
				MATLAB_INCDIR="$MATLAB_DIR/extern/include"
				MATLAB_LIBDIR="$MATLAB_DIR/extern/lib"
				MATLAB_BINDIR="$MATLAB_DIR/bin"
			else
				echores "no"
				die "could not find matlab in path / matlab crashed"
			fi

		else
			echocheck "Matlab"
			if matlab -nodisplay -r 'version;quit' >/dev/null 2>&1
			then
				 echores "`matlab -nodisplay -r \"sprintf('ver:%s',version),quit\" | grep '^ver:' | cut -f '2-' -d ':'`"
				 MATLAB_DIR=`echo "unix('env');quit" | matlab -nodisplay | grep '^MATLAB=' | cut -c 8-`
				 MATLAB_SRCDIR="$MATLAB_DIR/extern/src"
				 MATLAB_INCDIR="$MATLAB_DIR/extern/include"
				 MATLAB_LIBDIR="$MATLAB_DIR/extern/lib"
				 MATLAB_BINDIR="$MATLAB_DIR/bin"
			else
				echores "no"
				die "could not find matlab in path / matlab crashed"
			fi
		fi

		HAVE_MATLAB='#define HAVE_MATLAB 1'
		DEFINES="$DEFINES -DHAVE_MATLAB"

		if osf1
		then
			COMPFLAGS_C="-DMATLAB_MEX_FILE$COMPFLAGS_C -shared -ieee -std1"
			COMPFLAGS_CPP="-DMATLAB_MEX_FILE $COMPFLAGS_CPP -shared -ieee -std1"
			LINKFLAGS="$LINKFLAGS -shared -Wl,-expect_unresolved,'*',-hidden,-exported_symbol,mexFunction,-exported_symbol,mexVersion,-exported_symbol,'__*' -L$MATLAB_BINDIR/alpha -lmx -lmex -lmat"
			INCLUDES="$INCLUDES -I$MATLAB_INCDIR -I$MATLAB_SRCDIR"
			TARGET="sg.mexaxp"
		elif darwin
		then
		    INCLUDES="$INCLUDES -I$MATLAB_INCDIR -I$MATLAB_SRCDIR"
			if ppc
			then
				LINKFLAGS="$LINKFLAGS -bundle -Wl,-flat_namespace -undefined suppress -Wl,-exported_symbols_list,$MATLAB_LIBDIR/mac/mexFunction.map -L$MATLAB_BINDIR/mac -lmx -lmex -lmat"
				TARGET="sg.mexmac"
			elif x86
			then
				DEFINES="$DEFINES -DMX_COMPAT_32"
				COMPFLAGS_C="$COMPFLAGS_CPP -DMX_COMPAT_32"
				COMPFLAGS_CPP="$COMPFLAGS_CPP -DMX_COMPAT_32"
				LINKFLAGS="$LINKFLAGS -bundle -Wl,-flat_namespace -undefined suppress -Wl,-exported_symbols_list,$MATLAB_LIBDIR/maci/mexFunction.map -L$MATLAB_BINDIR/maci -lmx -lmex -lmat"
				TARGET="sg.mexmaci"
			else
				die "non supported matlab architecture"
			fi
		elif linux
		then
			if x86_64
			then
				COMPFLAGS_C="$COMPFLAGS_C -fPIC -fno-omit-frame-pointer -ansi -D_GNU_SOURCE"
				COMPFLAGS_CPP="$COMPFLAGS_CPP -fPIC -fno-omit-frame-pointer -ansi -D_GNU_SOURCE"
				LINKFLAGS="$LINKFLAGS -shared -Wl,--version-script,$MATLAB_LIBDIR/glnxa64/mexFunction.map -Wl,--rpath-link,$MATLAB_BINDIR/glnxa64 -L$MATLAB_BINDIR/glnxa64 -lmx -lmex -lmat"
				INCLUDES="$INCLUDES -I$MATLAB_INCDIR -I$MATLAB_SRCDIR"
				TARGET="sg.mexa64"
			elif x86
			then
				LINKFLAGS="$LINKFLAGS -shared -Wl,--version-script,$MATLAB_LIBDIR/glnx86/mexFunction.map -Wl,--rpath-link,$MATLAB_LIBDIR/glnx86 -L$MATLAB_BINDIR/glnx86 -lmx -lmex -lmat"
				INCLUDES="$INCLUDES -I$MATLAB_INCDIR -I$MATLAB_SRCDIR"
				TARGET="sg.mexglx"
			else
				die "matlab only supports x86_84 and x86 linux architectures"
			fi
		elif sunos
		then
				COMPFLAGS_C="$COMPFLAGS_C -KPIC -dalign -xlibmieee -D__EXTENSIONS__ -D_POSIX_C_SOURCE=199506L -mt -xs -g -xO3 -xlibmil"

				COMPFLAGS_CPP="$COMPFLAGS_CPP -KPIC -dalign -xlibmieee -D__EXTENSIONS__ -D_POSIX_C_SOURCE=199506L -mt -library=stlport4,Crun -xs -g -xO3 -xlibmil"
				LINKFLAGS="$LINKFLAGS -G -mt -M$MATLAB_LIBDIR/sol64/mexFunction.map -L$MATLAB_BINDIR/sol64 -lmx -lmex -lmat"
				INCLUDES="$INCLUDES -I$MATLAB_INCDIR -I$MATLAB_SRCDIR"
				TARGET="sg.mexs64"
		elif cygwin
		then
cat >mexFunction.map <<EOF
MEX {
_mexFunction;
_mexVersion;
};
EOF
			COMPFLAGS_C="$COMPFLAGS_C -mno-cygwin -DMATLAB_MEX_FILE"
			COMPFLAGS_CPP="$COMPFLAGS_CPP -mno-cygwin -DMATLAB_MEX_FILE"
			LINKFLAGS="$LINKFLAGS -shared -mno-cygwin -Wl,--version-script,mexFunction.map -Wl,--rpath-link,$MATLAB_LIBDIR/win32 -L$MATLAB_BINDIR/win32 -lmx -lmex -lmat"
			INCLUDES="$INCLUDES -I$MATLAB_INCDIR"
			TARGET="sg.dll"
		else
			die "non supported matlab architecture"
		fi

		echocheck "Matlab developer support (-lmx -lmex -lmat)"
cat > $TMPC << EOF
#include <mex.h>
#include <mexversion.c>
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{

}

int main(void) { return 0; }
EOF
		if cc_check
		then
			echores "yes"
		else
			echores "no"
			die "could not find matlab developer files (e.g. mex.h)"
		fi
	fi

	if test "$_octave" = yes
	then
		echocheck "Octave"
		if echo version | octave >/dev/null 2>&1
		then
			VERSION="`echo version | octave | grep ans | cut -f 3- -d ' '`"
			if [ `echo "$VERSION" | cut -f 1 -d '.'` -ge 3 ]
			then
				echores "$VERSION"
			else
				die "$VERSION - too old, at least octave version 3.0 required"
			fi
		else
			echores "no"
			die "could not find octave in path / octave crashed"
		fi

		echocheck "octave-config"
		if test -n "`octave-config -p OCTLIBDIR`" && test -n "`octave-config -p OCTINCLUDEDIR`" && test -n "`octave-config -p INCLUDEDIR`"
		then
			test -n "$_octdir" || _octdir=`octave-config --print LOCALAPIOCTFILEDIR`
			echores "yes"
		else
			echores "no"
			die "could not find octave-config in path / octave-config crashed"
		fi

cat > $TMPC << EOF

#include <octave/config.h>

#include <octave/defun-dld.h>
#include <octave/error.h>
#include <octave/oct-obj.h>
#include <octave/pager.h>
#include <octave/symtab.h>
#include <octave/variables.h>

DEFUN_DLD (sg, prhs, nlhs, "shogun.")
{
	int nrhs = prhs.length();
	octave_value_list plhs;
}
EOF
		EXT_IF_SWIG='stop'
		PRE_LIB_SWIG=
		EXT_LIB_SWIG=oct
		SWIGFLAGS="-w473 -c++ -octave"
		HAVE_OCTAVE='#define HAVE_OCTAVE 1'
		DEFINES="$DEFINES -DHAVE_OCTAVE"

		if darwin
		then
			LINKFLAGS="-bundle -Wl,-flat_namespace -L`octave-config -p OCTLIBDIR` -loctinterp -loctave -lcruft $LINKFLAGS"
		else
			OCTLIBDIR=`octave-config -p OCTLIBDIR`
			LINKFLAGS="-shared -L $OCTLIBDIR -loctinterp -loctave -lcruft $LINKFLAGS"
		fi
		TARGET="sg.oct"
		INCLUDES="$INCLUDES -I`octave-config -p OCTINCLUDEDIR` -I`octave-config -p INCLUDEDIR`"
		COMPFLAGS_CPP="$COMPFLAGS_CPP -fPIC"
		COMPFLAGS_C="$COMPFLAGS_C -fPIC"

		echocheck "Octave Developer Files"
		if LD_LIBRARY_PATH=`octave-config -p OCTLIBDIR` cxx_check
		then
			echores "yes"
		else
			echores "no"
			die "octave developer files missing"
		fi
	fi

	if test "$_python" = yes
	then
		echocheck "Python numpy support"
		if $PYTHON -c "import sys; import numpy" >/dev/null 2>&1
		then
			if [ `$PYTHON -c 'import numpy; print numpy.__version__' | cut -c 1` -gt 0 ]
			then
				echores "`$PYTHON -c 'import numpy; print numpy.__version__'`"
			else
				echores "`$PYTHON -c 'import numpy; print numpy.__version__'`... too old version 1.0 or later required"
				die "python numpy outdated"
			fi
		else
			echores "no"
			die "python numpy package missing"
		fi

		EXT_IF_SWIG='.py'
		HAVE_PYTHON='#define HAVE_PYTHON 1'
		DEFINES="$DEFINES -DHAVE_PYTHON"
		test -n "$_pyinclude" && _pyinclude="-I$_pyinclude"
		test -n "$_pyinclude" || _pyinclude=`$PYTHON -c "import numpy; import sys; print '-I'+sys.prefix+'/include/python'+sys.version[0:3]+' -I'+numpy.get_include()"`
		_pylibpath=""
		#test -n "$_pylibpath" && _pylibpath="-I$_pylibpath"
		#test -n "$_pylibpath" || _pylibpath=`$PYTHON -c "import sys; print '-L'+sys.exec_prefix+'/lib/python'+sys.version[0:3]+'/config'"`
		test -n "$_pylibs" || _pylibs=`$PYTHON -c "import sys; print 'python'+sys.version[0:3]"`
		INCLUDES="$_pyinclude $INCLUDES"
		COMPFLAGS_CPP="-fno-strict-aliasing -fPIC $COMPFLAGS_CPP"
		COMPFLAGS_C="-fno-strict-aliasing -fPIC $COMPFLAGS_C"
		if darwin
		then
			LINKFLAGS="$_pylibpath -l$_pylibs -ldl -bundle -Wl,-flat_namespace $LINKFLAGS"
			POSTLINKFLAGS="$_pylibpath -l$_pylibs -ldl -bundle -Wl,-flat_namespace $POSTLINKFLAGS"
		else
			LINKFLAGS="-shared $_pylibpath -l$_pylibs $LINKFLAGS"
			POSTLINKFLAGS="-shared $_pylibpath -l$_pylibs $POSTLINKFLAGS"
		fi

		if win32
		then
			TARGET="sg.dll"
		else
			TARGET="sg.so"
		fi

cat > $TMPC << EOF
#include <Python.h>
#include <stdlib.h>
#include <numpy/arrayobject.h>

PyMODINIT_FUNC initsg(void)
{
	double* array=(double*) malloc(10*sizeof(double));
	npy_intp* dims=(npy_intp*) malloc(sizeof(npy_int));
	dims[0]=10;
	Py_Initialize();
	PyObject* outArray = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, (void*)array);
}

PyMODINIT_FUNC initsg(void);
EOF
		echocheck "Python/Python Numpy Developer Files"
		if cc_check
		then
			echores "yes"
			SWIGFLAGS="-w473 -c++ -python"
		else
			# add -ldl and -lutil for some self compiled python versions as
			# they for some reason are not automgically pulled in
			LINKFLAGS="-lutil -ldl $LINKFLAGS"
			POSTLINKFLAGS="-lutil -ldl $POSTLINKFLAGS"
			if cc_check
			then
				echores "yes"
				SWIGFLAGS="-w473 -c++ -python"
			else
				echores "no"
				die "python/numpy developer files missing"
			fi
		fi
	fi

	if test "$_R" = yes
	then
		echocheck "R"
		if ( echo 'version; quit()' | R --no-save ) >/dev/null 2>&1 
		then
			echores "`echo 'version; quit()' | R  --no-save 2>&1 | grep version\.string | cut -f 4 -d ' '`"
			test -n "$_rdir" || _rdir=`echo '.libPaths()[1]' | R --no-save 2>/dev/null | grep '^\[1\]' | cut -f 2 -d '"'`
			PRE_LIB_SWIG=
			EXT_IF_SWIG='.R'
		else
			echores "no"
			die "cannot find R executable in path"
		fi

		HAVE_R='#define HAVE_R 1'
		DEFINES="$DEFINES -DHAVE_R"

		if win32
		then
			RPATH=$(cygpath -u $(cygpath -d "`which R | sed 's#/bin/R##'`"))
			TARGET="sg.dll"
			COMPFLAGS_C="$COMPFLAGS_C -mno-cygwin"
			COMPFLAGS_CPP="$COMPFLAGS_CPP -mno-cygwin"
			INCLUDES="$INCLUDES -I$RPATH/include"
			LINKFLAGS="$LINKFLAGS -L$RPATH/bin -lR -shared -mno-cygwin"
		else
			TARGET="sg.so"
			#unset makeflags as R uses -w and that leads to screwed up R CMD config --ldflags
			unset MAKEFLAGS MFLAGS
			COMPFLAGS_C="$COMPFLAGS_C `R CMD config CPICFLAGS`"
			COMPFLAGS_CPP="$COMPFLAGS_CPP `R CMD config CXXPICFLAGS`"
			INCLUDES="$INCLUDES `R CMD config --cppflags`"
			LINKFLAGS="$LINKFLAGS `R CMD config --ldflags` `R CMD config DYLIB_LDFLAGS`"
		fi


cat > $TMPC << EOF
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include <Rdefines.h>

static SEXP sg_helper(SEXP args)
{
	SEXP result=NEW_LOGICAL(args);
	return result;
}
EOF
		echocheck "R Developer Files"
		if cc_check
		then
			echores "yes"
			SWIGFLAGS="-w473 -c++ -r"
		else
			echores "no"
			die "cannot find R developer files"
		fi
	fi

	if test "$_cplex" = yes || test "$_cplex" = auto
	then
cat > $TMPC << EOF
#include <ilcplex/cplex.h>
int main (int argc, char **argv)
{
	int status = argc;
	CPXENVptr     env = NULL;
	env = CPXopenCPLEX (&status);
	status = CPXcloseCPLEX (&env);
	return status;
}
EOF
		echocheck "CPLEX support"
		if echo quit | cplex >/dev/null 2>&1
		then
			CPLEXVER=`echo quit | cplex 2>&1 | grep ^ILOG | cut -d ' ' -f 3 | tr -d ','`
			if [ -z "$CPLEXVER" ]
			then
				echores "no"
			else
				echores "$CPLEXVER"

				echocheck "CPLEX developer files"
				CPLEXLINKFLAGS="-lcplex"
				CPLEXINCLUDES=""

				if linux
				then
					CPLEXVER=`echo $CPLEXVER | cut -f 1 -d '.'``echo $CPLEXVER | cut -f 2 -d '.' | cut -c 1`
					CPLEXPATH=`env | grep ^ILOG_LICENSE_FILE | cut -f 2 -d '=' | sed 's/ilog.*$/ilog/'`/cplex$CPLEXVER
					if x86
					then
						for cpx_path in "$CPLEXPATH/lib/i86_linux2_glibc2.3_gcc3.2/static_pic" \
							"$CPLEXPATH/lib/x86_RHEL3.0_3.2/static_pic" \
							"$CPLEXPATH/lib/x86_rhel4.0_3.4/static_pic" \
							"$CPLEXPATH/lib/x86_debian4.0_4.1/static_pic" \
							"$CPLEXPATH/lib/x86_sles9.0_3.3/static_pic"
						do
							if test -d $cpx_path
							then
								CPLEXLINKFLAGS="-L$cpx_path -lcplex"
								CPLEXINCLUDES="-I$CPLEXPATH/include"
								break
							fi
						done
					elif x86_64
					then
						for cpx_path in "$CPLEXPATH/lib/x86-64_RHEL3.0_3.2/static_pic" \
							"$CPLEXPATH/lib/x86-64_rhel4.0_3.4/static_pic" \
							"$CPLEXPATH/lib/x86-64_debian4.0_4.1/static_pic" \
							"$CPLEXPATH/lib/x86-64_sles9.0_3.3/static_pic"
						do
							if test -d $cpx_path
							then
								CPLEXLINKFLAGS="-L$cpx_path -lcplex"
								CPLEXINCLUDES="-I$CPLEXPATH/include"
								break
							fi
						done
					fi

					if cc_check $CPLEXINCLUDES $CPLEXLINKFLAGS
					then
						echores "yes"
						USE_CPLEX='#define USE_CPLEX 1'
						DEFINES="$DEFINES -DUSE_CPLEX"
						INCLUDES="$INCLUDES $CPLEXINCLUDES"
						LINKFLAGS="$LINKFLAGS $CPLEXLINKFLAGS"
						POSTLINKFLAGS="$POSTLINKFLAGS $CPLEXLINKFLAGS"
					else
						echores "no"
					fi
				else
					die "non supported CPLEX architecture"
				fi
			fi
		else
			echores "no"
		fi
	fi

	if test "$_wtiming" = yes
	then
		USE_W_TIMING='#define USE_W_TIMING 1'
		DEFINES="$DEFINES -DUSE_W_TIMING"
	fi

	if test "$_largefile" = yes
	then
		HAVE_LARGEFILE='#define HAVE_LARGEFILE 1'
		DEFINES="$DEFINES -DHAVE_LARGEFILE"
	fi


	if test "$_swig" = yes
	then
		echocheck "SWIG"
		if ${SWIG} -version >/dev/null 2>&1
		then
			if [ `${SWIG} -version 2>&1 | grep Version | cut -f 3 -d ' ' | cut -f 2 -d '.'` -ge 4 ] || \
				[ `${SWIG} -version 2>&1 | grep Version | cut -f 3 -d ' ' | cut -f 3 -d '.'` -ge 29 ]
			then
				echores "`${SWIG} -version 2>&1 | grep Version | cut -f 3 -d ' '`"
			else
				echores "`${SWIG} -version 2>&1 | grep Version | cut -f 3 -d ' '` ... too old version 1.3.29 or later required"
				die "swig outdated"
			fi
		else
			echores "no"
			die "cannot find swig executable in path"
		fi

		HAVE_SWIG='#define HAVE_SWIG 1'
		DEFINES="$DEFINES -DHAVE_SWIG"

		USE_SWIG='yes'

		if cygwin
		then
			EXT_LIB_SWIG=dll
			POSTLINKFLAGS=$LINKFLAGS
		fi
	else
		USE_SWIG='no'
	fi

	if test "$USE_SWIG" = 'yes'
	then
		if test "$_doxygen" = yes
		then
			HAVE_DOXYGEN='#define HAVE_DOXYGEN 1'
			DEFINES="$DEFINES -DHAVE_DOXYGEN"

			USE_DOXYGEN='yes'
		else
			USE_DOXYGEN='no'
		fi
	fi

	if test "$_logcache" = yes
	then
		USE_LOGCACHE='#define USE_LOGCACHE 1'
		DEFINES="$DEFINES -DUSE_LOGCACHE"
	fi

	if test "$_shortrealkernelcache" = yes
	then
		USE_SHORTREAL_KERNELCACHE='#define USE_SHORTREAL_KERNELCACHE 1'
		DEFINES="$DEFINES -DUSE_SHORTREAL_KERNELCACHE"
	fi

	if test "$_treemem" = yes
	then
		USE_TREEMEM='#define USE_TREEMEM 1'
		DEFINES="$DEFINES -DUSE_TREEMEM"
	fi

	if test "$_logsumarray" = yes
	then
		USE_LOGSUMARRAY='#define USE_LOGSUMARRAY 1'
		DEFINES="$DEFINES -DUSE_LOGSUMARRAY"
	fi

	if test "$_hmmparallel" = yes
	then
		USE_HMMPARALLELSTRUCTURES='#define USE_HMMPARALLELSTRUCTURES 1'
		DEFINES="$DEFINES -DUSE_HMMPARALLELSTRUCTURES"
		USE_HMMPARALLEL='#define USE_HMMPARALLEL 1'
		DEFINES="$DEFINES -DUSE_HMMPARALLEL"
	fi

	if test "$_bigstates" = yes
	then
		USE_BIGSTATES='#define USE_BIGSTATES 1'
		DEFINES="$DEFINES -DUSE_BIGSTATES"
	fi

	if test "$_hmmcache" = yes
	then
		USE_HMMCACHE='#define USE_HMMCACHE 1'
		DEFINES="$DEFINES -DUSE_HMMCACHE"
	fi

	if test "$_debug" = yes
	then
		_hmmdebug=yes
		_pathdebug=yes
	fi

	if test "$_hmmdebug" = yes
	then
		USE_HMMDEBUG='#define USE_HMMDEBUG 1'
		DEFINES="$DEFINES -DUSE_HMMDEBUG"
		TARGET="shogun-debug"
	fi

	if test "$_pathdebug" = yes
	then
		USE_PATHDEBUG='#define USE_PATHDEBUG 1'
		DEFINES="$DEFINES -DUSE_PATHDEBUG"
		TARGET="shogun-debug"
	fi

	if test "$_svm_light" = yes
	then
		USE_SVMLIGHT='#define USE_SVMLIGHT 1'
		DEFINES="$DEFINES -DUSE_SVMLIGHT"
		GPL=""
	else
		GPL='#define GPL 1'
		DEFINES="$DEFINES -DGPL"
	fi

	if test "$_interface" = libshogun
	then
		TARGET=libshogun.so
		POSTLINKFLAGS="$POSTLINKFLAGS -shared -fPIC"
	fi

	if test "$_cmdline" = yes
	then
		HAVE_CMDLINE='#define HAVE_CMDLINE 1'
		DEFINES="$DEFINES -DHAVE_CMDLINE"
	fi
}

#write the actual config

write_dot_config()
{

#enable additional warnings / -Wfloat-equal -W
if test "$_cc_major" -ge "3" 2>/dev/null ; then
	COMPFLAGS_C=`echo "$COMPFLAGS_C" | sed -e 's/\(-Wall\)/\1 -Wno-unused-parameter -Wformat -Wformat-security -Wimplicit -Wparentheses -Wshadow/'`
	COMPFLAGS_SWIG_CPP=`echo "$COMPFLAGS_CPP" | sed -e 's/-Wall//'`
	COMPFLAGS_CPP=`echo "$COMPFLAGS_CPP" | sed -e 's/\(-Wall\)/\1 -Wno-unused-parameter -Wformat -Wformat-security -Wimplicit -Wparentheses -Wshadow/'`
fi

cat > "$SRCDIR/.config" <<EOF
INTERFACE		= ${_interface}
MAKE 			= ${MAKE}
MAKEDEPEND		= ${MAKEDEPEND}
MAKEDEPENDOPTS	= ${MAKEDEPENDOPTS}
SWIG 			= ${SWIG}
PYTHON 			= ${PYTHON}
DOXYGEN 		= ${DOXYGEN}
USE_SWIG 		= ${USE_SWIG}
USE_DOXYGEN 	= ${USE_DOXYGEN}
SWIGFLAGS		= ${SWIGFLAGS}
EXT_INP_SWIG	= ${EXT_INP_SWIG}
EXT_IF_SWIG		= ${EXT_IF_SWIG}
EXT_SRC_SWIG	= ${EXT_SRC_SWIG}
EXT_OBJ_SWIG	= ${EXT_OBJ_SWIG}
PRE_LIB_SWIG	= ${PRE_LIB_SWIG}
EXT_LIB_SWIG	= ${EXT_LIB_SWIG}
EXT_SRC_HEADER	= ${EXT_SRC_HEADER}
EXT_SRC_C 		= ${EXT_SRC_C}
EXT_SRC_CPP 	= ${EXT_SRC_CPP}
EXT_SRC_SWIG	= ${EXT_SRC_SWIG}
KERNELNAME  	= ${KERNELNAME}
MACHINE  		= ${MACHINE}
TARGET			= ${TARGET}
EXT_OBJ_CPP 	= ${EXT_OBJ_CPP}
EXT_OBJ_C   	= ${EXT_OBJ_C}
EXT_SRC_CPP 	= ${EXT_SRC_CPP}
EXT_SRC_C   	= ${EXT_SRC_C}
EXT_DOXY        = ${EXT_DOXY}
EXT_SWIG_DOXY  	= ${EXT_SWIG_DOXY}
GDB				= ${GDB}
COMP_C			= ${COMP_C}
COMP_CPP		= ${COMP_CPP}
DEFINES			=${DEFINES}
COMPFLAGS_C		= ${COMPFLAGS_C}
COMPFLAGS_CPP	= ${COMPFLAGS_CPP}
COMPFLAGS_SWIG_CPP	= ${COMPFLAGS_SWIG_CPP}
INCLUDES		= ${INCLUDES}
LINK			= ${LINK}
LINKFLAGS 		= ${LINKFLAGS}
POSTLINKFLAGS	= ${POSTLINKFLAGS}
PREFIX			= ${_prefix}
DESTDIR			= ${_destdir}
BINDIR			= ${_bindir}
DATADIR			= ${_datadir}
MANDIR			= ${_mandir}
CONFDIR			= ${_confdir}
INCDIR			= ${_incdir}
LIBDIR			= ${_libdir}
PYDIR			= ${_libdir}/${_pydir}
OCTDIR			= ${_octdir}
RDIR			= ${_rdir}
EOF
}

svmlight_warn_license()
{
	if test "$_svm_light" = yes
	then
		cat <<EOF

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WARNING: SHOGUN is built using SVMlight which was written
by Thorsten Joachims and uses a different non GPL compatible license.
To build a fully GPL'd SHOGUN use 

./configure --disable-svm-light

The SVMlight license can be found in LICENSE.SVMlight.  In case
you do not know or cannot agree to the licensing terms expressed in
LICENSE.SVMlight press ctrl+c to abort configure now.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

EOF
		sleep 1
	fi
}

write_config_h()
{
cat >"$SRCDIR/lib/config.h" <<EOF
$HAVE_READLINE
$HAVE_MINDY
$HAVE_PYTHON
$HAVE_MATLAB
$HAVE_R
$HAVE_OCTAVE
$HAVE_CMDLINE
$HAVE_LARGEFILE
$HAVE_SWIG
$HAVE_DOXYGEN
$HAVE_LAPACK
$HAVE_ATLAS
$HAVE_ACML
$HAVE_MKL
$HAVE_POWL
$HAVE_SQRTL
$HAVE_LOG2
$USE_LOGCACHE
$USE_SHORTREAL_KERNELCACHE
$USE_TREEMEM
$USE_LOGSUMARRAY
$USE_HMMPARALLELSTRUCTURES
$USE_HMMPARALLEL
$USE_SVMPARALLEL
$USE_BIGOBS
$USE_BIGSTATES
$USE_HMMCACHE
$USE_KERNELCACHE
$USE_DEBUG
$USE_HMMDEBUG
$USE_PATHDEBUG
$USE_SVMLIGHT
$GPL
$USE_CPLEX
$USE_W_TIMING
#define $OS 1
#define CONFIGURE_OPTIONS "$CONFIGURE_OPTIONS"
#define MACHINE "$MACHINE"
#define TARGET "$TARGET"
#define COMPFLAGS_C	"$COMPFLAGS_C"
#define COMPFLAGS_CPP "$COMPFLAGS_CPP"
#define LINKFLAGS "$LINKFLAGS"
EOF
}

type_buildinfo()
{
	cat <<EOF

SHOGUN was configured for $_interface interface with the following 
$CONFIGURE_OPTIONS

type "make" now to compile

EOF
}

clean_up()
{
	rm -f "$TMPC" "$TMPCPP" "$TMPO" "$TMPS" "$TMPSS"
}

set_default_cc
determine_system_name
detect_cc
check_makedepend
check_python
check_make
check_doxygen
determine_march_mtune
set_opts
svmlight_warn_license
write_dot_config
write_config_h
clean_up
type_buildinfo
