dnl--------------------------------------------------------------------
dnl
dnl Hugs98 configure script template. Process this file with autoconf to
dnl produce a configure script.
dnl
dnl--------------------------------------------------------------------

AC_INIT(../hugs.c)
AC_CONFIG_HEADER(../config.h ../options.h)

dnl--------------------------------------------------------------------
dnl Choose host(/target/build) platform
dnl--------------------------------------------------------------------

dnl Guess host/target/build platform(s) if necessary.
AC_CANONICAL_SYSTEM

# "$host" defaults to "$target"
if test "x$host" = xNONE ; then
    host=$target
fi

dnl ** canonicalize platform names
BuildPlatform=`/bin/sh $srcdir/config.sub $build` || exit 1
HostPlatform=`/bin/sh $srcdir/config.sub $host` || exit 1
TargetPlatform=`/bin/sh $srcdir/config.sub $target` || exit 1

if test x"$TargetPlatform" != x"$HostPlatform" ; then
    echo "Hugs98 does not yet support differing host/target (i.e., cross-compiling)"
    exit 1
fi

host_cpu=`echo $HostPlatform | sed 's/-.*//'`
host_os=[`echo $HostPlatform | sed 's/^\([^-]*\)-\([^-]*\)-\([^-]*\).*/\3/'`]
target_cpu=`echo $TargetPlatform | sed 's/-.*//'`
target_os=[`echo $TargetPlatform | sed 's/^\([^-]*\)-\([^-]*\)-\([^-]*\).*/\3/'`]
build_cpu=`echo $BuildPlatform | sed 's/-.*//'`
build_os=[`echo $BuildPlatform | sed 's/^\([^-]*\)-\([^-]*\)-\([^-]*\).*/\3/'`]

# canonicalize the target OS (approximately as fptools does)
case $target_os in
aix*) target_os=aix ;;
cygwin*) target_os=cygwin32 ;;
darwin*) target_os=darwin ;;
freebsd2*) target_os=freebsd2 ;;
freebsd*) target_os=freebsd ;;
hpux*) target_os=hpux ;;
irix*) target_os=irix ;;
linuxaout*) target_os=linuxaout ;;
linux*) target_os=linux ;;
mingw32*) target_os=mingw32 ;;
netbsd*) target_os=netbsd ;;
openbsd*) target_os=openbsd ;;
osf[12]*) target_os=osf1 ;;
osf*) target_os=osf3 ;;
solaris2*) target_os=solaris2 ;;
sunos4*) target_os=sunos4 ;;
ultrix*) target_os=ultrix ;;
esac
host_os="$target_os"	# hack: we can't cross-compile
build_os="$target_os"	# hack: we can't cross-compile

AC_DEFINE_UNQUOTED(HOST_ARCH, "$host_cpu")
AC_DEFINE_UNQUOTED(HOST_OS, "$host_os")

# ToDo: We should probably use AS_TR_CPP here, but this changes case, too, and
# I'm a bit reluctant to do this without closer inspection of the Hugs code.
fp_tr_cpp="sed s%[[^_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]]%_%g"

HostPlatform_CPP=`echo $HostPlatform | $fp_tr_cpp`
AC_SUBST([HostPlatform], [$HostPlatform_CPP])

TargetPlatform_CPP=`echo $TargetPlatform | $fp_tr_cpp`
AC_SUBST([TargetPlatform], [$TargetPlatform_CPP])

BuildPlatform_CPP=`echo $BuildPlatform | $fp_tr_cpp`
AC_SUBST([BuildPlatform], [$BuildPlatform_CPP])

HostOS_CPP=`echo $host_os | $fp_tr_cpp`
AC_SUBST([HostOS], [$HostOS_CPP])

HostArch_CPP=`echo $host_cpu | $fp_tr_cpp`
AC_SUBST([HostArch], [$HostArch_CPP])

TargetOS_CPP=`echo $target_os | $fp_tr_cpp`
AC_SUBST([TargetOS], [$TargetOS_CPP])

TargetArch_CPP=`echo $target_cpu | $fp_tr_cpp`
AC_SUBST([TargetArch], [$TargetArch_CPP])

BuildOS_CPP=`echo $build_os | $fp_tr_cpp`
AC_SUBST([BuildOS], [$BuildOS_CPP])

BuildArch_CPP=`echo $build_cpu | $fp_tr_cpp`
AC_SUBST([BuildArch], [$BuildArch_CPP])

dnl--------------------------------------------------------------------
dnl
dnl Check Configuration options
dnl
dnl--------------------------------------------------------------------

AC_ARG_ENABLE(path-canonicalization,
  AC_HELP_STRING([--enable-path-canonicalization],
                 [enable filepath canonicalization]),
  AC_DEFINE([PATH_CANONICALIZATION], [1],
    [Define to 1 if you want filenames to be converted to normal form
     by: (a) replacing relative pathnames with absolute pathnames and
     eliminating .. and . where possible. (b) converting to lower case
     (only in case-insensitive filesystems)]))

AC_ARG_WITH(preprocessor,
  AC_HELP_STRING([--with-preprocessor],
                 [use a preprocessor]),
  AC_DEFINE([USE_PREPROCESSOR], [1],
    [Define to 1 if you want to run Haskell code through a
     preprocessor. Note that there's the import chasing mechanism will
     not spot any CPP includes so you must :load (not :reload) if you
     change any (non-Haskell) configurations files.]))

AC_ARG_ENABLE(timer,
  AC_HELP_STRING([--enable-timer],
                 [enable evaluation timing]))

AC_ARG_ENABLE(profiling,
  AC_HELP_STRING([--enable-profiling],
                 [enable heap profiler]),
  AC_DEFINE([PROFILING], [1],
    [Define to 1 if heap profiling should be used.]))

AC_ARG_ENABLE(stack-dumps,
  AC_HELP_STRING([--enable-stack-dumps],
                 [enable stack dump on stack overflow]),
  AC_DEFINE([GIMME_STACK_DUMPS], [1],
    [If you get really desperate to understand why your Hugs programs
     keep crashing or running out of stack, you might like to set this
     flag and recompile Hugs. When you hit a stack error, it will print
     out a list of all the objects currently under evaluation. The
     information isn't perfect and can be pretty hard to understand but
     it's better than a poke in the eye with a blunt stick. This is a
     very experimental feature!]))

AC_ARG_WITH(nmake,
  AC_HELP_STRING([--with-nmake],
                 [produce nmake compatible Makefile]),
  [RM="del";CP="copy"])

AC_ARG_ENABLE(large-banner,
  AC_HELP_STRING([--disable-large-banner],
                 [disable multiline startup banner]),
  AC_DEFINE([SMALL_BANNER], [1],
    [Define to 1 if you want the small startup banner.]))

AC_ARG_WITH(gui,
  AC_HELP_STRING([--with-gui],
                 [build Hugs for Windows GUI]))

AC_ARG_ENABLE(internal-prims,
  AC_HELP_STRING([--enable-internal-prims],
                 [experimental primitives to access Hugs' innards]),
  [AC_DEFINE([INTERNAL_PRIMS], [1],
    [Define to 1 if you want to use the primitives which let you examine
     Hugs internals.])
   AC_DEFINE([BYTECODE_PRIMS], [1],
     [Define to 1 if you want to use the primitives which let you
      examine Hugs bytecodes (requires INTERNAL_PRIMS).])])

AC_ARG_ENABLE(debug,
  AC_HELP_STRING([--enable-debug],
                 [include C debugging information (for debugging use)]),
  [AC_DEFINE([DEBUG_CODE], [1],
     [Define to 1 if debugging generated bytecodes or the bytecode
      interpreter])
   AC_DEFINE([DEBUG_PRINTER], [1],
     [Define if you want to use a low-level printer from within a
      debugger])])

AC_ARG_ENABLE(tag-checks,
  AC_HELP_STRING([--enable-tag-checks],
                 [runtime tag checking (for debugging use)]),
  AC_DEFINE([CHECK_TAGS], [1],
    [Define to 1 if you want to perform runtime tag-checks as an
     internal consistency check. This makes Hugs run very slowly - but is
     very effective at detecting and locating subtle bugs.]))

AC_ARG_ENABLE(lint,
  AC_HELP_STRING([--enable-lint],
                 [enable "lint" flags (for debugging use)]))

AC_ARG_ENABLE(only98,
  AC_HELP_STRING([--enable-only98],
                 [make Hugs Haskell 98 only]),
  AC_DEFINE([HASKELL_98_ONLY], [1], [Define to 1 to omit Hugs extensions]))

AC_ARG_WITH(pthreads,
  AC_HELP_STRING([--with-pthreads],
                 [build Hugs using pthreads C library]),
  [AC_DEFINE([DONT_PANIC], [1],
     [In a plain Hugs system, most signals (SIGBUS, SIGTERM, etc)
      indicate some kind of error in Hugs - or maybe a stack
      overflow. Rather than just crash, Hugs catches these errors and
      returns to the main loop. It does this by calling a function
      "panic" which longjmp's back to the main loop. If you're developing
      a GreenCard library, this may not be the right behaviour - it's
      better if Hugs leaves them for your debugger to catch rather than
      trapping them and "panicing".])])

AC_ARG_WITH(fptools,
  AC_HELP_STRING([--with-fptools=<dir>],
                 [location of fptools directory to get libraries from]),
  [FPTOOLS="$withval"], [FPTOOLS=../../fptools])

AC_ARG_ENABLE(ffi,
  AC_HELP_STRING([--enable-ffi],
                 [include modules that use the FFI]),
  , [enable_ffi=autodetect])

AC_ARG_ENABLE(hopengl,
  AC_HELP_STRING([--enable-hopengl],
                 [[include HOpenGL, a Haskell binding for OpenGL/GLUT.
                          On Mac OS X, use --enable-hopengl=x11 to use X11
                          instead of the "native" libraries]]),
  , [enable_hopengl=no])

AC_SUBST(FPTOOLS)

AC_MSG_CHECKING([directory $FPTOOLS])
if test -d "$FPTOOLS/hslibs" && test -d "$FPTOOLS/libraries"
then AC_MSG_RESULT([looks ok])
else AC_MSG_RESULT(failed)
     AC_MSG_ERROR([
The argument to --with-fptools must be a directory containing copies of
hslibs and libraries from the Haskell CVS repository.])
fi
FPTOOLS=`cd $FPTOOLS; pwd`

dnl win32: Canonicalize FPTOOLS
case $host_os in
  cygwin*|mingw*) FPTOOLS=`cygpath -w $FPTOOLS | sed -e 's@\\\\@/@g'`;;
esac

dnl--------------------------------------------------------------------
dnl
dnl Check for programs
dnl
dnl--------------------------------------------------------------------

dnl ToDo: if we have YACC, insert parser.c: parser.y in Makefile
AC_PROG_YACC
if test "`basename ${YACC}`x" = "byaccx"; then
   echo "Found 'byacc', but the Hugs98 parser is incompatible with it."
   echo "You need to install 'bison' and re-run the configure script."
   exit 1;
fi;

: ${CFLAGS=-g}
OPTFLAGS="-O2"

AC_PROG_CC
AC_PROG_CPP
AC_PROG_GCC_TRADITIONAL

if test "$with_pthreads" = yes; then
   ACX_PTHREAD
   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
   LIBS="$PTHREAD_LIBS $LIBS"
   CC="$PTHREAD_CC"
fi

dnl  The following patch avoids the outburst of (benign) error messages during 
dnl  compilation of machine.c under MacOS X/Darwin, as well as some linker 
dnl  warnings caused by the default two-level namespace introduced in version 10.1
dnl
case $HostPlatform in
  *-*-darwin*)
     CFLAGS="$CFLAGS -no-cpp-precomp"
     LDFLAGS="$LDFLAGS -flat_namespace"
     ;;
  # As suggested by James B. White III (Trey) <whitejbiii@ornl.gov> (for
  # AIX 4.3.3 & XL C 5.0.2 at least, may need to tweak the pattern match
  # below some to avoid upsetting other AIX versions).
  *-*-aix*) 
     optcflags="-qalloca"
     CFLAGS_save="$CFLAGS"
     CFLAGS="$CFLAGS $optcflags"
     AC_MSG_CHECKING([whether $CC accepts $optcflags])
     AC_LANG_C
     AC_TRY_LINK([],[int main(){return(0);}],[optok=yes],[optok=no])
     if test "$optok" = "yes"; then
	# lump the recognition of -qalloca together with -qmaxmem=-1 and -bmaxdata..
        CFLAGS="$CFLAGS_save $optcflags"
	LDFLAGS="$LDFLAGS -bmaxdata:0x70000000"; 
	OPTFLAGS="-O -qmaxmem=-1"
        AC_MSG_RESULT([yes])
     else
        CFLAGS="$CFLAGS_save"
	AC_MSG_RESULT([no])
     fi
     ;;
  *-*-cygwin*)
     EXE='.exe'
     ;;
  *-*-mingw*)
     EXE='.exe'
     ;;
  *) ;;
esac

if test "x$CP" != "xcopy"; then
# Only check for RM&CP if they haven't been overridden already (cf. --with-nmake)
AC_PATH_PROG(RM,rm)
RM="$RM -f"
AC_PATH_PROG(CP,cp)
fi

AC_CHECK_PROG(LD,ld,ld)

AC_CHECK_PROGS(PERL,perl)  dnl should test for perl5
AC_PROG_MAKE_SET
AC_CHECK_PROG(have_hp2ps,hp2ps,1,0)
if test "$have_hp2ps" = "1"; then
AC_DEFINE(HAVE_HP2PS,1)
fi
AC_CHECK_PROGS(DOCBOOK2HTML,[docbook2html db2html],[])
AC_CHECK_PROGS(DOCBOOK2DVI,[docbook2dvi db2dvi],[])
AC_CHECK_PROGS(DOCBOOK2PDF,[docbook2pdf db2pdf],[])
AC_CHECK_PROGS(DOCBOOK2PS,[docbook2ps db2ps],[])

dnl Look for right versions of 'find' and 'sort' (win32 only, really.)
FP_PROG_FIND
FP_PROG_SORT

dnl AC_PROG_INSTALL

dnl POSIX systems prefer "diff -C 1"; SunOS4 prefers "diff -c1".
AC_PROG_DIFF

dnl If you can run configure, you certainly have /bin/sh
AC_DEFINE(HAVE_BIN_SH)

dnl--------------------------------------------------------------------
dnl 
dnl Check for libraries
dnl
dnl--------------------------------------------------------------------


AC_CHECK_LIB_NOWARN(dl, dlopen)
AC_CHECK_LIB_NOWARN(dld, shl_load)
AC_CHECK_LIB_NOWARN(m, atan)
AC_PATH_XTRA

dnl Should we use the "native" (= Quartz) Opengl on MacOS X or the X11 one?
UseQuartzOpenGL=NO
case $HostPlatform in
  *-*-darwin*)
     if test x"$enable_hopengl" != x"x11"; then
       AC_DEFINE(USE_QUARTZ_OPENGL)
       UseQuartzOpenGL=YES
     fi
     ;;
  *) ;;
esac

if test x"$enable_hopengl" != x"no"; then
  FPTOOLS_HAVE_OPENGL
fi

dnl--------------------------------------------------------------------
dnl
dnl Check for header files
dnl
dnl--------------------------------------------------------------------

AC_HEADER_STDC
dnl checks for sys/wait.h
AC_HEADER_SYS_WAIT
AC_CHECK_HEADERS(
  stdarg.h stdlib.h unistd.h assert.h ctype.h string.h limits.h \
  fcntl.h sgtty.h termio.h termios.h signal.h \
  arpa/inet.h \
  netdb.h netinet/tcp.h \
  sys/stat.h sys/types.h sys/ioctl.h sys/resource.h sys/param.h \
  sys/socket.h sys/timers.h sys/uio.h sys/un.h sys/utsname.h \
  console.h pascal.h Files.h errno.h stat.h nlist.h ftw.h direct.h \
  grp.h pwd.h \
  dirent.h utime.h vfork.h
  )

AC_HEADER_TIME
AC_CHECK_HEADERS(time.h sys/time.h sys/timeb.h sys/times.h)

dnl One of these two is used to obtain floating point parameters
AC_CHECK_HEADERS(float.h values.h)

dnl DOS include files
AC_CHECK_HEADERS(dos.h conio.h io.h std.h) 

dnl Windows include files
AC_CHECK_HEADERS(windows.h winsock.h)

dnl dynamic loading include files
if test "$target" = windows; then
  dynamic_loading=yes
else
  dynamic_loading=no
fi
AC_CHECK_HEADERS(dlfcn.h dl.h mach-o/dyld.h, [dynamic_loading=yes])
if test "$enable_ffi" = autodetect; then
  enable_ffi="$dynamic_loading"
fi

AC_SUBST(FFI_LIBRARIES)
if test "$enable_ffi" = yes; then
  FFI_LIBRARIES=ffi_libraries
else
  FFI_LIBRARIES=
fi

dnl Checks for:
dnl   farcalloc (in bcc), 
dnl   valloc (in sunos, solaris, mips, amiga, next, minix, ultrix)
AC_CHECK_HEADER(alloc.h,[AC_CHECK_FUNCS(farcalloc)])
if test "${ac_cv_header_stdlib_h+set}" = set ||
   test "${ac_cv_header_unistd_h+set}" = set; then
  AC_CHECK_FUNCS(valloc)
fi

dnl ** check for POSIX regex
HavePosixRegex=NO
AC_CHECK_HEADERS(regex.h,[AC_CHECK_FUNC(regcomp, [HavePosixRegex=YES])])
AC_SUBST(HavePosixRegex)

dnl check for OpenGL include files
if test x"$enable_hopengl" != x"no"; then
  fp_save_cppflags="$CPPFLAGS"
  CPPFLAGS="$CPPFLAGS $X_CFLAGS"
  if test "$UseQuartzOpenGL" = YES ; then
    AC_CHECK_HEADERS(OpenGL/gl.h)
  else
    AC_CHECK_HEADERS(GL/gl.h)
  fi
  CPPFLAGS="$fp_save_cppflags"
fi

dnl --------------------------------------------------
dnl * test for netinet/in.h and in_addr_t
dnl --------------------------------------------------
AC_CHECK_HEADERS(netinet/in.h,
 [AC_MSG_CHECKING(for in_addr_t in netinet/in.h)
 AC_EGREP_HEADER(in_addr_t, netinet/in.h,
  [AC_DEFINE(HAVE_IN_ADDR_T) AC_MSG_RESULT(yes)],
  [AC_MSG_RESULT(no)])])

dnl used by System.Posix.Signals
dnl --------------------------------------------------
AC_MSG_CHECKING([for SIGPOLL])
AC_EGREP_CPP(we_have_sigpoll,
[#include <signal.h>
#ifdef SIGPOLL
we_have_sigpoll
#endif
], AC_DEFINE([HAVE_SIGPOLL], [1], [Define to 1 if you have the sigpoll function.]) haveSIGPOLL=yes, haveSIGPOLL=no)
AC_MSG_RESULT([$haveSIGPOLL])

dnl--------------------------------------------------------------------
dnl
dnl Check for types 
dnl
dnl--------------------------------------------------------------------

dnl ** do we have long longs?
FPTOOLS_C_LONG_LONG

dnl ** check what fields struct msghdr contains
FPTOOLS_MSGHDR_MSG_ACCRIGHTS
FPTOOLS_MSGHDR_MSG_CONTROL

dnl ** what are the sizes of various types
AC_CHECK_SIZEOF(char,               1)
AC_CHECK_SIZEOF(double,             8)
AC_CHECK_SIZEOF(float,              4)
AC_CHECK_SIZEOF(int,                4)
AC_CHECK_SIZEOF(long,               4)
if test "$fptools_cv_have_long_long" = yes; then
AC_CHECK_SIZEOF(long long,          8)
fi
AC_CHECK_SIZEOF(short,              2)
AC_CHECK_SIZEOF(unsigned char,      1)
AC_CHECK_SIZEOF(unsigned int,       4)
AC_CHECK_SIZEOF(unsigned long,      4)
if test "$fptools_cv_have_long_long" = yes; then
AC_CHECK_SIZEOF(unsigned long long, 8)
fi
AC_CHECK_SIZEOF(unsigned short,     2)
AC_CHECK_SIZEOF(void *,             4)

dnl ** what are alignment constraints on various types
FP_CHECK_ALIGNMENT(char)
FP_CHECK_ALIGNMENT(double)
FP_CHECK_ALIGNMENT(float)
FP_CHECK_ALIGNMENT(int)
FP_CHECK_ALIGNMENT(long)
if test "$fptools_cv_have_long_long" = yes; then
FP_CHECK_ALIGNMENT(long long)
fi
FP_CHECK_ALIGNMENT(short)
FP_CHECK_ALIGNMENT(unsigned char)
FP_CHECK_ALIGNMENT(unsigned int)
FP_CHECK_ALIGNMENT(unsigned long)
if test "$fptools_cv_have_long_long" = yes; then
FP_CHECK_ALIGNMENT(unsigned long long)
fi
FP_CHECK_ALIGNMENT(unsigned short)
FP_CHECK_ALIGNMENT(void *)

dnl ** map standard C types and ISO types to Haskell types
FPTOOLS_CHECK_HTYPE(char)
FPTOOLS_CHECK_HTYPE(signed char)
FPTOOLS_CHECK_HTYPE(unsigned char)
FPTOOLS_CHECK_HTYPE(short)
FPTOOLS_CHECK_HTYPE(unsigned short)
FPTOOLS_CHECK_HTYPE(int)
FPTOOLS_CHECK_HTYPE(unsigned int)
FPTOOLS_CHECK_HTYPE(long)
FPTOOLS_CHECK_HTYPE(unsigned long)
if test "$fptools_cv_have_long_long" = yes; then
FPTOOLS_CHECK_HTYPE(long long)
FPTOOLS_CHECK_HTYPE(unsigned long long)
fi
FPTOOLS_CHECK_HTYPE(float)
FPTOOLS_CHECK_HTYPE(double)
FPTOOLS_CHECK_HTYPE(ptrdiff_t)
FPTOOLS_CHECK_HTYPE(size_t)
FPTOOLS_CHECK_HTYPE(wchar_t)
dnl Int32 is a HACK for non-ISO C compilers
FPTOOLS_CHECK_HTYPE(sig_atomic_t, Int32)
FPTOOLS_CHECK_HTYPE(clock_t)
FPTOOLS_CHECK_HTYPE(time_t)
FPTOOLS_CHECK_HTYPE(dev_t, Word32)
FPTOOLS_CHECK_HTYPE(ino_t)
FPTOOLS_CHECK_HTYPE(mode_t)
FPTOOLS_CHECK_HTYPE(off_t)
FPTOOLS_CHECK_HTYPE(pid_t)
FPTOOLS_CHECK_HTYPE(gid_t)
FPTOOLS_CHECK_HTYPE(uid_t)
FPTOOLS_CHECK_HTYPE(cc_t)
FPTOOLS_CHECK_HTYPE(speed_t)
FPTOOLS_CHECK_HTYPE(tcflag_t)
FPTOOLS_CHECK_HTYPE(nlink_t)
FPTOOLS_CHECK_HTYPE(ssize_t)
FPTOOLS_CHECK_HTYPE(rlim_t)

dnl ** Map OpenGL data types to Haskell types
if test x"$enable_hopengl" != x"no"; then
FPTOOLS_CHECK_HTYPE(GLboolean)
FPTOOLS_CHECK_HTYPE(GLbyte)
FPTOOLS_CHECK_HTYPE(GLubyte)
FPTOOLS_CHECK_HTYPE(GLshort)
FPTOOLS_CHECK_HTYPE(GLushort)
FPTOOLS_CHECK_HTYPE(GLint)
FPTOOLS_CHECK_HTYPE(GLuint)
FPTOOLS_CHECK_HTYPE(GLsizei)
FPTOOLS_CHECK_HTYPE(GLenum)
FPTOOLS_CHECK_HTYPE(GLbitfield)
FPTOOLS_CHECK_HTYPE(GLfloat)
FPTOOLS_CHECK_HTYPE(GLclampf)
FPTOOLS_CHECK_HTYPE(GLdouble)
FPTOOLS_CHECK_HTYPE(GLclampd)
fi

FP_CHECK_CONSTS([E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EADV EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBADRPC EBUSY ECHILD ECOMM ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDIRTY EDOM EDQUOT EEXIST EFAULT EFBIG EFTYPE EHOSTDOWN EHOSTUNREACH EIDRM EILSEQ EINPROGRESS EINTR EINVAL EIO EISCONN EISDIR ELOOP EMFILE EMLINK EMSGSIZE EMULTIHOP ENAMETOOLONG ENETDOWN ENETRESET ENETUNREACH ENFILE ENOBUFS ENODATA ENODEV ENOENT ENOEXEC ENOLCK ENOLINK ENOMEM ENOMSG ENONET ENOPROTOOPT ENOSPC ENOSR ENOSTR ENOSYS ENOTBLK ENOTCONN ENOTDIR ENOTEMPTY ENOTSOCK ENOTTY ENXIO EOPNOTSUPP EPERM EPFNOSUPPORT EPIPE EPROCLIM EPROCUNAVAIL EPROGMISMATCH EPROGUNAVAIL EPROTO EPROTONOSUPPORT EPROTOTYPE ERANGE EREMCHG EREMOTE EROFS ERPCMISMATCH ERREMOTE ESHUTDOWN ESOCKTNOSUPPORT ESPIPE ESRCH ESRMNT ESTALE ETIME ETIMEDOUT ETOOMANYREFS ETXTBSY EUSERS EWOULDBLOCK EXDEV], [#include <stdio.h>
#include <errno.h>])

FP_CHECK_CONST([O_BINARY], [#include <fcntl.h>], [0])

dnl--------------------------------------------------------------------
dnl
dnl Check for library functions.
dnl
dnl--------------------------------------------------------------------


dnl Old: AC_CHECK_FUNCS(WinExec GetModuleFileName)       dnl Windows
dnl Doesn't work because the linker can't see the functions if
dnl you omit the #include <windows.h>.  (I've no idea why not...)

AC_TRY_LINK_NOWARN(,[
#if HAVE_WINDOWS_H
#include <windows.h>
#endif
main() { 
  WinExec("",0);
  exit(0);
}
],
[have_winexec=1],
[have_winexec=0])
if test "$have_winexec" = "1"; then
AC_DEFINE(HAVE_WINEXEC)
fi

AC_TRY_LINK_NOWARN(,[
#if HAVE_WINDOWS_H
#include <windows.h>
#endif
main() { 
  char* dir;
  GetModuleFileName((HMODULE)0,dir,0);
  exit(0);
}
],
[have_getmodulefilename=1],
[have_getmodulefilename=0])
if test "$have_getmodulefilename" = "1"; then
AC_DEFINE(HAVE_GETMODULEFILENAME)
fi

AC_CHECK_FUNCS(strcasecmp _stricmp stricmp strcmpi)
AC_CHECK_FUNCS(strcmp)
AC_CHECK_FUNCS(rindex)
AC_CHECK_FUNCS(strrchr)
AC_CHECK_FUNCS(canonicalize_file_name realpath _fullpath)  
AC_CHECK_FUNCS(PBHSetVolSync macsystem)  
AC_CHECK_FUNCS(fgetpos fsetpos fseek ftell)
AC_CHECK_FUNCS(vsnprintf _vsnprintf)
AC_CHECK_FUNCS(snprintf  _snprintf )  
AC_CHECK_FUNCS(popen     _popen )  
AC_CHECK_FUNCS(pclose    _pclose )  
AC_CHECK_FUNCS(setenv unsetenv)
AC_CHECK_FUNCS(sigprocmask)  
AC_CHECK_FUNCS(getrusage)
AC_CHECK_FUNCS(times)
AC_CHECK_FUNCS(isatty)
AC_CHECK_FUNCS(fstat lstat)
AC_CHECK_FUNCS(select)
AC_CHECK_FUNCS(getclock)
AC_CHECK_FUNCS(gettimeofday)
AC_CHECK_FUNCS(ftime)
AC_CHECK_FUNCS(time)
AC_CHECK_FUNCS(localtime)
AC_CHECK_FUNCS(gmtime)
AC_CHECK_FUNCS(mktime)
AC_CHECK_FUNCS(readdir_r)
AC_CHECK_FUNCS(dup)

dnl--------------------------------------------------------------------
dnl
dnl Timezonery
dnl
dnl--------------------------------------------------------------------

AC_STRUCT_TIMEZONE
FPTOOLS_HAVE_TIMEZONE
FPTOOLS_HAVE_ALTZONE

dnl This always fails unless you also #include <windows.h>
dnl AC_CHECK_FUNCS(GetModuleFileName GetModuleFileNameA)      dnl Windows

dnl Probably Macintosh specific
dnl AC_CHECK_FUNCS(getfinfo)

AC_FUNC_ALLOCA   dnl Also sets STACK_DIRECTION

dnl Visual C++ doesn't have alloca, does have _alloca macro
AC_CACHE_CHECK(for _alloca, ac_cv_c__alloca,
[AC_TRY_LINK([
#include <malloc.h>
int test1() {
    return _alloca(42);
}
],
[int i;], 
ac_cv_c__alloca=yes,
ac_cv_c__alloca=no)])
if test "$ac_cv_c__alloca" = yes; then
AC_DEFINE(HAVE__ALLOCA)
fi

dnl Library functions used in C interface Foreign/test.ss (non-essential)

AC_CHECK_FUNCS(stime poly)

dnl--------------------------------------------------------------------
dnl
dnl Check for typedefs, structures, and compiler characteristics
dnl
dnl--------------------------------------------------------------------


AC_C_CONST               dnl can we use "const"?
AC_C_PROTOTYPES          dnl can we use function prototypes?
AC_C_JMPBUF_ARRAY        dnl can we take address of jmpbufs?
AC_C_LABELS_AS_VALUES    dnl can we use gcc's "labels as values" feature?

dnl AC_C_CHAR_UNSIGNED   dnl We can test for signed/unsigned chars - but don't use it

AC_STRUCT_TM

dnl We don't test for this because Borland C uses a typedef to define size_t
dnl but puts it in stdio.h - this conflicts with defining it in config.h
dnl AC_TYPE_SIZE_T

dnl Foo: assumes we can use prototypes.
dnl On BCC, signal handlers have type "int(void)", elsewhere its "void(int)".
dnl AC_CACHE_CHECK([type of signal handlers], ac_cv_type_signal_handler,
dnl [AC_TRY_COMPILE([#include <sys/types.h>
dnl #include <signal.h>
dnl #ifdef signal
dnl #undef signal
dnl #endif
dnl void (*signal (int, void (*)(int)))(int);
dnl ],
dnl [int i;], 
dnl ac_cv_type_signal_handler=void_int,
dnl ac_cv_type_signal_handler=int_void)])
dnl if test "$ac_cv_type_signal_handler" = void_int; then
dnl AC_DEFINE(VOID_INT_SIGNALS)
dnl fi

dnl On BCC, signal handlers have type "int(void)", elsewhere its "void(int)".
AC_TYPE_SIGNAL
if test "$ac_cv_type_signal" = void; then
AC_DEFINE(VOID_INT_SIGNALS)
fi


dnl--------------------------------------------------------------------
dnl 
dnl Readline - based on the feature testing that the GHC fptools/ configure
dnl            script performs.
dnl
dnl--------------------------------------------------------------------
AC_CHECK_LIB(ncurses, tputs, HaveLibTermcap=YES; LibTermcap=ncurses,
  AC_CHECK_LIB(termcap, tputs, HaveLibTermcap=YES; LibTermcap=termcap,
    AC_CHECK_LIB(curses, tputs, HaveLibTermcap=YES; LibTermcap=curses,
      HaveLibTermcap=NO)))
if test $HaveLibTermcap = YES ; then
    LIBS="-l$LibTermcap $LIBS"
fi

AC_CHECK_LIB(readline, readline, HaveLibReadline=YES; LibReadline=readline,
  AC_CHECK_LIB(editline, readline, HaveLibReadline=YES; LibReadline=editline,
    HaveLibReadline=NO))
if test $HaveLibTermcap = YES && test $HaveLibReadline = YES ; then
    LIBS="-l$LibReadline $LIBS"
    AC_DEFINE([USE_READLINE], [1],
      [Define to 1 if a command line editor is available and should be
       used. There are two choices of command line editor that can be
       used with Hugs: GNU readline and editline (from comp.sources.misc,
       vol 31, issue 71)])
fi

dnl--------------------------------------------------------------------
dnl
dnl Profiling
dnl
dnl--------------------------------------------------------------------
if test "$enable_profiling" = yes; then
    if test "$have_hp2ps" = "0"; then
        AC_MSG_WARN(
[hp2ps (heap profile display program) not available 
(not ignoring --enable-profiling)])
    fi
fi

dnl--------------------------------------------------------------------
dnl
dnl Timer
dnl
dnl--------------------------------------------------------------------
WANT_TIMER=0
if test "$enable_timer" = yes; then
    if test "$ac_cv_header_time_h" = yes; then
        WANT_TIMER=1
    elif test "$ac_cv_header_sys_time_h" = yes &&
	 test "$ac_cv_header_sys_resource_h" = yes; then
        WANT_TIMER=1
    else
        AC_MSG_WARN(
[neither <time.h> nor (<sys/time.h> and <sys/resource.h>) is available
(ignoring --enable-timer)])
    fi
fi
AC_DEFINE_UNQUOTED([WANT_TIMER], [$WANT_TIMER],
   [Define if you want to time every evaluation. Timing is included in
    the Hugs distribution for the purpose of benchmarking the Hugs
    interpreter, comparing its performance across a variety of different
    machines, and with other systems for similar languages. It would be
    somewhat foolish to try to use the timings produced in this way for
    any other purpose.  In particular, using timings to compare the
    performance of different versions of an algorithm is likely to give
    very misleading results.  The current implementation of Hugs as an
    interpreter, without any significant optimizations, means that there
    are much more significant overheads than can be accounted for by
    small variations in Hugs code.])

dnl These flags are gcc specific.  
dnl They detecting many common programming errors but can get fooled
dnl by perfectly safe code so we usually turn them off.
dnl We don't use -Wstrict-prototypes because some definitions in 
dnl storage.h tickle this flag and can't be rewritten the 'correct' way
dnl without generating a warning/error from Microsoft's compiler.
GCC_LINT_FLAGS="-Wall \
  -Wpointer-arith -Wbad-function-cast -Wcast-qual \
  -Wmissing-prototypes \
  -Wmissing-declarations -Wnested-externs \
  -Wno-parentheses \
  "

dnl--------------------------------------------------------------------
dnl
dnl Debugging flags (assumed to be mutually exclusive with optimisation)
dnl
dnl--------------------------------------------------------------------
if test "$enable_debug" = yes; then
    OPTFLAGS=""
else
    DEBUGFLAGS=""
    LDDEBUGFLAGS=""
fi
AC_SUBST(OPTFLAGS)
AC_SUBST(DEBUGFLAGS)
AC_SUBST(LDDEBUGFLAGS)

dnl--------------------------------------------------------------------
dnl
dnl Figure out sizes of objects and decide which version of Hugs to build
dnl
dnl--------------------------------------------------------------------

AC_CHECK_SIZEOF(int,4)
AC_CHECK_SIZEOF(float,4)
AC_CHECK_SIZEOF(double,8)
AC_CHECK_SIZEOF(int*,4)

if test "$ac_cv_sizeof_int" -eq "2"; then
    AC_DEFINE([SMALL_HUGS], [1],
      [Define to 1 for 16 bit operation on a limited memory PC.])
else
    dnl ToDo: test for virtual memory - if you have it, LARGE_HUGS is cool
    dnl also: provide a way to override default
    if test 0 -eq 1; then
        echo "building regular hugs"
        AC_DEFINE([REGULAR_HUGS], [1],
          [Define to 1 for 32 bit operation using largish default table sizes.])
    else
        echo "building large hugs"
        AC_DEFINE([LARGE_HUGS], [1],
          [Define to 1 for 32 bit operation using larger default table sizes.])
    fi
fi


dnl--------------------------------------------------------------------
dnl
dnl Figure out how to do dynamic linking.
dnl
dnl It is fairly easy to do the dynamic loading: that is fairly well 
dnl documented and only depends on the target platform.
dnl 
dnl It is also fairly easy to decide whether or not to add a leading 
dnl underscore to symbol names when doing symbol lookup.
dnl
dnl But it is bloody hard to figure out how to _build_ a file which can be
dnl dynamically loaded because it varies with both the platform and the
dnl choice of linker.  So we use a rather crude approach: we try every
dnl set of linking commands that anyone suggests will work.
dnl
dnl At the time of writing, I have no idea which of these tests will work.
dnl I don't want to add flags that are obviously silly but I want to
dnl record what is worth trying.  So, for now, I'm going to leave all
dnl the untested ones commented out.  As platforms are found which need
dnl those flags, we'll uncomment each line (and maybe even record which
dnl platforms those are).
dnl
dnl--------------------------------------------------------------------

dnl Try the MS Visual C flags
HUGS_TRY_DYNLINK([/LD])
HUGS_TRY_DYNLINK([/LD /ML /nologo])

dnl Try the win32 way
HUGS_TRY_DYNLINK([-shared])

dnl Try the gcc flags
HUGS_TRY_DYNLINK([-shared -fPIC])

dnl Try the MacOS X flags
HUGS_TRY_DYNLINK(-bundle)

dnl Try the MacOS X flags
HUGS_TRY_DYNLINK([-bundle -lc])        

dnl Try the gcc flags
dnl HUGS_TRY_DYNLINK([-shared -nostdlib])

dnl Some other gcc flags
HUGS_TRY_DYNLINK(-r)

dnl Some other gcc flags
dnl HUGS_TRY_DYNLINK(-rdynamic)

dnl Try the SunOS flags
dnl HUGS_TRY_DYNLINK(-G)

dnl Try the HPUX flags
dnl HUGS_TRY_DYNLINK([-Aa +z])             

AC_DEFINE_UNQUOTED(MKDLL_CMD,
  ["${CC-cc} $CFLAGS $CPPFLAGS $LDFLAGS $ac_cv_dll_flags"])
if test "$ac_cv_leading_underscore" = "yes"; then
AC_DEFINE(LEADING_UNDERSCORE)
fi

dnl--------------------------------------------------------------------
dnl
dnl Lint flags
dnl (placed after DLL stuff, so not included in MKDLL_CMD)
dnl
dnl--------------------------------------------------------------------
if test "$enable_lint" = yes; then
    if test "$CC" = "gcc"; then
        LINT_FLAGS="$GCC_LINT_FLAGS"
#    elif test "$CC" = "bcc32"; then
#        LINT_FLAGS="$BCC32_LINT_FLAGS"
    else
        AC_MSG_WARN(dnl
[lint flags only defined for gcc (at present)
(ignoring --enable-lint)])
    fi

    CFLAGS="$CFLAGS $LINT_FLAGS"
    dnl AC_MSG_WARN(using lint $CFLAGS)
fi

dnl--------------------------------------------------------------------
dnl
dnl Architecture specific substitutions
dnl The default values can be overridden by environment variables when
dnl the configure script is called
dnl
dnl--------------------------------------------------------------------

dnl When building a Windows script, $target will be set to "windows".

if test "x$target" = "xwindows"; then
    EXE=".exe"          
    OBJ=".obj"          
    DLL=".dll"          
    DLL_ENDING="-dll"   
    DEV_NULL="nul"
    HUGSPATH=".;{Hugs}\\\\libraries;{Hugs}\\\\oldlib;{Hugs}\\\\lib\\\\win32"
    HUGSSUFFIXES=".hs;.lhs"
    MkInstall="../MkNull.in"
elif test "x$target" = "xdos"; then
    # Just the same as for Windows but excludes win32 from Path
    EXE=".exe"          
    OBJ=".obj"          
    DLL=".dll"          
    DLL_ENDING="-dll"   
    DEV_NULL="nul"
    hugsdir_deflt='${libdir}\\hugs'
    HUGSPATH=".;{Hugs}\\\\libraries;{Hugs}\\\\oldlib"
    HUGSSUFFIXES=".hs;.lhs"
    MkInstall="../MkNull.in"
else
    hugsdir_deflt='${libdir}/hugs'
    HUGSPATH=".:{Hugs}/libraries:{Hugs}/oldlib"
    HUGSSUFFIXES=".hs:.lhs"
    MkInstall="../MkInstal.in"
fi
AC_SUBST(HUGSPATH)
AC_SUBST(HUGSSUFFIXES)
AC_DEFINE_UNQUOTED([HUGSSUFFIXES], ["$HUGSSUFFIXES"],
  [The list of suffixes used by Haskell source files, separated either
   by colons (Unix) or semicolons (Macintosh, Windows, DOS). This value
   can be overridden using the -S flag.])

if test "x$prefix" = xNONE; then
    prefix="$ac_default_prefix"
fi

AC_SUBST_DEF(hugsdir,"$hugsdir_deflt")

test "x$prefix"      = xNONE && prefix=$ac_default_prefix
test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'

dnl This is the only way I could find to perform the substitutions
dnl in hugsdir.  Sigh.
HUGSDIR=`sh -c "prefix=$prefix; exec_prefix=$exec_prefix; libdir=$libdir; datadir=$datadir; echo $hugsdir"`
AC_DEFINE_UNQUOTED([HUGSDIR], ["$HUGSDIR"],
  [The directory name which is substituted for the string "{Hugs}" in a
   path variable. This normally points to where the Hugs libraries are
   installed - ie so that the file HUGSDIR/lib/Prelude.hs exists. Typical
   values are: "/usr/local/lib/hugs", "/usr/homes/JFHaskell/hugs",
   "..". This value is ignored on Windows and Macintosh versions since it
   is assumed that the binary is installed in HUGSDIR. This value cannot
   be overridden from the command line or by using environment
   variables. This isn't quite as limiting as you'd think since you can
   always choose _not_ to use the {Hugs} variable - however, it's
   obviously _nicer_ to have it set correctly.])
AC_SUBST(HUGSDIR)
BINDIR=`sh -c "prefix=$prefix; exec_prefix=$exec_prefix; echo $bindir"`
AC_SUBST(BINDIR)

AC_SUBST_DEF(EXE,"")
AC_SUBST_DEF(OBJ,".o")
AC_SUBST_DEF(DLL,".so")
AC_SUBST_DEF(DLL_ENDING,"-so")
AC_SUBST_DEF(DEV_NULL,"/dev/null")
AC_SUBST_DEF(RM,"/bin/rm -f")
AC_SUBST_DEF(CP,"/bin/cp")

AC_SUBST_FILE(MkInstall)
MkDepend=../MkDepend.in
AC_SUBST_FILE(MkDepend)  

AC_DEFINE_UNQUOTED([HUGSPATH], ["${HUGSPATH}"],
  [Define this as the default setting of HUGSPATH. Value may contain
   string "{Hugs}" (for which we will substitute the value of HUGSDIR)
   and should be either colon-separated (Unix) or semicolon-separated
   (Macintosh, Windows, DOS). Escape characters in the path string are
   interpreted according to normal Haskell conventions. This value can be
   overridden from the command line by setting the HUGSFLAGS environment
   variable or by storing an appropriate value for HUGSFLAGS in the
   registry (Win32 only).  In all cases, use a string of the form
   -P"...".])

dnl--------------------------------------------------------------------
dnl
dnl Figure out whether we can build the GUI
dnl (done last because -W flags messes everything else up)
dnl
dnl--------------------------------------------------------------------

HUGS_FOR_WINDOWS=0
if test "x$with_gui" = xyes; then
  if test "x$target" = "xwindows"; then
    LDFLAGS="$LDFLAGS -W"
    WOBJECTS="win-text.obj"
    STRIP="brc32 hugs32.rc hugs.exe -w32"
    RC_FILES="hugs32.rc"
    HUGS_FOR_WINDOWS=1
  elif test "x$target" = "xdos"; then
    WOBJECTS="win-text.obj"
    STRIP="brc hugs16.rc hugs.exe"
    RC_FILES="hugs16.rc"
    HUGS_FOR_WINDOWS=1
  else
    AC_MSG_WARN(
[not building Hugs GUI because this isn't a DOS machine
    ])
  fi
fi
AC_DEFINE_UNQUOTED([HUGS_FOR_WINDOWS], [$HUGS_FOR_WINDOWS],
  [Define to 1 if you want to use the "Hugs for Windows" GUI. (Windows
   3.1 and compatibles only)])
AC_SUBST_DEF(WOBJECTS,"")
AC_SUBST_DEF(RC_FILES,"")
AC_SUBST_DEF(STRIP,"")

dnl--------------------------------------------------------------------
dnl
dnl Generate output files
dnl
dnl--------------------------------------------------------------------

TESTSCRIPT=""
if test -f ../../tests/config.in ; then
 TESTSCRIPT=../../tests/config
fi

AC_OUTPUT(../Makefile ../platform.h \
	../../docs/Makefile ../../docs/users_guide/Makefile \
	../../docs/hugs.1 $TESTSCRIPT hugs-package)

echo ''
echo '************************************************'
echo '*** NOW DO: cd .. ; make ; make install'
echo '************************************************'
exit 0

dnl End of configure.in
