dnl Process this file with autoconf to produce a configure script.
AC_INIT(pycaml_ml.c)

dnl Checks for programs.

dnl Checks for libraries.
dnl Replace `main' with a function in -lpython:
AC_CHECK_LIB(python, main)

dnl Checks for header files.
AC_CHECK_HEADERS(unistd.h)

dnl Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST

dnl Checks for library functions.
AC_HEADER_STDC

dnl ********************
dnl Check for Python. 
dnl ********************

AM_PATH_PYTHON()

dnl Find Python executable
AC_PATH_PROGS(PYPACKAGE, python)

dnl Extract the version using Python, check against 1.5+

changequote(<<, >>)
PY_PREFIX=`$PYPACKAGE getprefix.py`
PY_VERSION=`$PYPACKAGE getversion.py`
changequote([, ])

if test `echo $PY_VERSION | tr -d .` -lt 15; then
echo "Sorry, you need to have Python 1.5+ installed - update your version!"
    AC_MSG_ERROR([*** Python 1.5 or better required])
fi

dnl Find the Python.h header file

AC_MSG_CHECKING(for Python header files)
changequote(<<, >>)
PY_INCLUDE=`$PYPACKAGE -c 'import sys ; print "%s/include/python%s" % (sys.prefix, sys.version[:3])'`
changequote([, ])

if test -r "$PY_INCLUDE/Python.h"; then
   PY_CFLAGS="-I$PY_INCLUDE"
else
   AC_MSG_ERROR([Could not find Python.h in $PY_INCLUDE])
fi
AC_MSG_RESULT(found)

dnl Find the Python library

AC_MSG_CHECKING(for Python library)
PYLIB=""
changequote(<<, >>)
PY_PREFIX=`$PYPACKAGE -c 'import sys; print sys.prefix'`
PYLIBVER=`$PYPACKAGE -c 'import sys; print sys.version[:3]'`
changequote([, ])

py_paths="$PY_PREFIX/lib/python$PYLIBVER/config $PYPREFIX/lib"
py_suffix="$PYLIBVER.so $PYLIBVER.a .so .a"
   
dnl Try for specific version first, then the generic version, then panic

for ppath in $py_paths ; do
    if test -r "$ppath/libpython$PYLIBVER.so" -o \
	    -r "$ppath/libpython$PYLIBVER.a"; then
        PYLIB="-cclib -L$ppath -cclib -lpython$PYLIBVER"
        break
    fi

    if test -r "$ppath/libpython.so" -o \
            -r "$ppath/libpython.a"; then
        PYLIB="-cclib -L$ppath -cclib -lpython"
    break
    fi
done

if test "x$PYLIB" != x ; then
    PY_LIBS="$PYLIB $PY_LIBS"
    AC_MSG_RESULT(found)
else
    AC_MSG_ERROR([*** Python library not found])
fi

dnl Get the libraries that python depends on

AC_PATH_PROG(haveldd, ldd)
AC_MSG_CHECKING(for Python's dependencies)

if test x$haveldd != x ; then
    changequote(<<, >>)
    py_deps=`ldd $PYPACKAGE | sed 's/\( *lib\([^\/]*\)\.so.*=.*$\)/-cclib\ \"-l\2\"/p; d'`
    for py_lib in $py_deps ; do
        if test "$py_lib" != "-lm" && test "$py_lib" != "-lc" ; then
            PY_DEPS="$PY_DEPS $py_lib"
        fi
    done
      changequote([, ])
fi

dnl only GNU ld seems to know -E flag

if $LD -v 2>&1 </dev/null | egrep '(GNU|with BFD)' 1>&5; then
    PY_LIBS="-Wl,-E $PY_LIBS $PY_DEPS"
else
    PY_LIBS="$PY_LIBS $PY_DEPS"
fi

export PY_LIBS
export PY_VERSION
export PY_PREFIX

AC_SUBST(PY_LIBS)
AC_SUBST(PY_VERSION)
AC_SUBST(PY_PREFIX)

AC_OUTPUT(Makefile)
