dnl Try to link a test program with already determined PYTHON2_INCLUDES and
dnl PYTHON2_LDFLAGS (by whatever means necessary).
dnl $1 = action on success
dnl $2 = action on failure

AC_DEFUN([GWY_PYTHON2_TRY_LINK],
[ac_save_CPPFLAGS="$CPPFLAGS"
ac_save_LIBS="$LIBS"
CPPFLAGS="$LIBS $PYTHON2_INCLUDES"
LIBS="$LIBS $PYTHON2_LDFLAGS"
AC_MSG_CHECKING([if we can link a test Python2 program])
AC_LANG_PUSH([C])
AC_LINK_IFELSE([
AC_LANG_PROGRAM([[#include <Python.h>]],
                [[Py_Initialize();]])
],dnl
[AC_MSG_RESULT([yes])
$1],dnl
[AC_MSG_RESULT([no])
$2])
AC_LANG_POP([C])
CPPFLAGS="$ac_save_CPPFLAGS"
LIBS="$ac_save_LIBS"
])

dnl Find flags for with-Python compilation and linking.
dnl   Originally suggested by wichert.
dnl   Rewritten by Yeti.  Also added the pkg-config method.
dnl $1 = list of Python versions to try
dnl $2 = action on success
dnl $3 = action on failure
AC_DEFUN([GWY_PYTHON2_DEVEL],
[have_libpython2_pkg=no
if test "x$1" != x; then
  for version in $1 ; do
    AC_PATH_TOOL([PYTHON2_CONFIG], [python$version-config])
    if test "x$PYTHON2_CONFIG" != x; then
      PYTHON2_VERSION=$version
      break
    fi
    PKG_CHECK_MODULES([PYTHON2],[python-$version],[have_libpython2_pkg=yes],[:])
    if test $have_libpython2_pkg != no; then
      PYTHON2_VERSION=$version
      break
    fi
  done
else
  AC_PATH_TOOL([PYTHON2_CONFIG], [python-config])
  if test "x$PYTHON2_CONFIG" != x; then
    PYTHON2_VERSION=$(python2 -c "import sys;print '.'.join(map(str, sys.version_info@<:@:2@:>@))")
  fi
fi

if test "x$PYTHON2_CONFIG" != x; then
  if test "x$PYTHON2_INCLUDES" = x; then
    PYTHON2_INCLUDES="$("$PYTHON2_CONFIG" --includes)"
  fi
  if test "x$PYTHON2_LDFLAGS" = x; then
    PYTHON2_LDFLAGS="$("$PYTHON2_CONFIG" --ldflags)"
  fi
  GWY_PYTHON2_TRY_LINK([],[PYTHON2_CONFIG=])
fi

if test $have_libpython2_pkg != no; then
  if test "x$PYTHON2_INCLUDES" = x; then
    PYTHON2_INCLUDES="$PYTHON2_CFLAGS"
  fi
  if test "x$PYTHON2_LDFLAGS" = x; then
    PYTHON2_LDFLAGS="$PYTHON2_LIBS"
  fi
  GWY_PYTHON2_TRY_LINK([],[have_libpython2_pkg=no])
fi

if test $have_libpython2_pkg != no -o "x$PYTHON2_CONFIG" != x; then
  $2
  :
else
  PYTHON2_INCLUDES=
  PYTHON2_LDFLAGS=
  $3
fi

AC_SUBST([PYTHON2_VERSION])
AC_SUBST([PYTHON2_INCLUDES])
AC_SUBST([PYTHON2_LDFLAGS])
])

