if test "$needs_ncurses" = no; then
  CURSESCPPFLAGS=
  LDCURSESLIB=
  CURSESDEP=
else
  #
  # Check for ncurses.
  #
  have_ncurses=no
  HAVE_NCURSES_CURSES_H=no

  EXTRA_NCURSES_INCLUDE=
  EXTRA_NCURSES_LIBDIR=

  if test "$with_system_ncurses" = yes; then
    if test "x$with_ncurses_libdir" != x; then
      EXTRA_NCURSES_LIBDIR="-L$with_ncurses_libdir"
    fi
    if test "x$with_ncurses_include" != x; then
      EXTRA_NCURSES_INCLUDE="-I$with_ncurses_include"
    fi
  fi

  OLD_LDFLAGS=$LDFLAGS
  OLD_CPP=$CPP
  OLD_LIBS=$LIBS

  LDFLAGS="$LDFLAGS $EXTRA_NCURSES_LIBDIR"
  CPP="$CPP $EXTRA_NCURSES_INCLUDE"

  CURSESCPPFLAGS=
  if test "$try_ncurses" = yes; then
    AC_CHECK_LIB(ncurses, wresize, have_ncurses=yes, have_ncurses=no)
    if test "${have_ncurses}" = "yes" ; then
      AC_DEFINE(HAVE_NCURSES)
      if (
        AC_CHECK_HEADERS(ncurses/curses.h, HAVE_NCURSES_CURSES_H=yes, HAVE_NCURSES_CURSES_H=no)
        test $HAVE_NCURSES_CURSES_H = yes && exit 0
        exit 1
      )
      then
        HAVE_NCURSES_CURSES_H=yes
      else
        HAVE_NCURSES_CURSES_H=no
      fi

      if (
        AC_CHECK_HEADERS(ncurses.h, HAVE_NCURSES_H=yes, HAVE_NCURSES_H=no)
        test $HAVE_NCURSES_H = yes && exit 0
        exit 1
      )
      then
        HAVE_NCURSES_H=yes
      else
        HAVE_NCURSES_H=no
      fi

      if test "${HAVE_NCURSES_CURSES_H}" = no && test "${HAVE_NCURSES_H}" = no; then
        # Try again, and check for the bogus ncurses/ include bug.
        # (i.e. ncurses/curses.h bogusly includes <unctrl.h> instead of
        # <ncurses/unctrl.h>)
        AC_MSG_RESULT(Trying again with -I/usr/include/ncurses...)
        OLD_CPP="${CPP}"
        CPP="${CPP} -I/usr/include/ncurses"
        if (
          AC_CHECK_HEADERS(ncurses/curses.h, HAVE_NCURSES_CURSES_H=yes, HAVE_NCURSES_CURSES_H=no)
          test $HAVE_NCURSES_CURSES_H = yes && exit 0
          exit 1
        )
        then
          HAVE_NCURSES_CURSES_H=yes
        else
          HAVE_NCURSES_CURSES_H=no
        fi
        
        if test "${HAVE_NCURSES_CURSES_H}" = "yes" ; then
          CURSESCPPFLAGS=-I/usr/include/ncurses
          AC_MSG_RESULT([    Your system has the bogus ncurses include bug.])
        else
          CPP="${OLD_CPP}"
        fi
      fi
    fi
  fi

  LDFLAGS=$OLD_LDFLAGS
  CPP=$OLD_CPP
  LIBS=$OLD_LIBS

  if test "${have_ncurses}" = yes  && { test "${HAVE_NCURSES_CURSES_H}" = yes || test "${HAVE_NCURSES_H}" = yes; }; then
    LDCURSESLIB="$EXTRA_NCURSES_LIBDIR -lncurses"
    CURSESDEP=
    CURSESCPPFLAGS="$CURSESCPPFLAGS $EXTRA_NCURSES_INCLUDE"
    using_system_ncurses=yes
  else
    CURSESCPPFLAGS='-I$(NCURSESDIR)/include -I$(NCURSESSRCDIR)/include'
    LDCURSESLIB='$(NCURSESDIR)/lib/libncurses.a'
    CURSESDEP='$(NCURSESDIR)/lib/libncurses.a'
    using_system_ncurses=no
  fi
fi

AC_SUBST(CURSESCPPFLAGS)
AC_SUBST(LDCURSESLIB)
AC_SUBST(CURSESDEP)
