#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
# 
# Description: configure.in
#   Autonconf produce a ./configure from this file
#   that's used to discover various programs/dependencies
#   usage: autoconf
#
# Authors: paul_c alex_joni jepler
# License: GPL Version 2
# System: Linux
#    
# Copyright (c) 2004 All rights reserved.
#
# Last change:
# This file is released under GPL, refer to docs/README for details
#
# This file is adapted to replace the old ./configure script
# therefor it includes parts of that script

##############################################################################
# Section 1                                                                  #
# Autoconf initialisation                                                    #
##############################################################################

AC_PREREQ(2.53)
AC_INIT(EMC2, m4_normalize(esyscmd([cat ../VERSION])), emc-developers@lists.sourceforge.net)
AC_CONFIG_SRCDIR(emc/motion/motion.c)
if test "$srcdir" != "."; then
    AC_MSG_ERROR([Building outside of srcdir is not supported])
fi

AC_MSG_CHECKING(build toplevel)
BUILD_TOPLEVEL="$(cd ..; pwd -P)"
AC_MSG_RESULT($BUILD_TOPLEVEL)

AC_CONFIG_HEADER(config.h)

# Support some of the standard configure options for directories
AC_PREFIX_DEFAULT(run-in-place)

AC_MSG_CHECKING(installation prefix)
if test "x$prefix" = "xNONE"; then
  RUN_IN_PLACE=yes
  AC_MSG_RESULT(run in place)
  prefix=${BUILD_TOPLEVEL}
else
  RUN_IN_PLACE=no
  AC_MSG_RESULT($prefix)
fi
AC_SUBST(AUTODIRS)

# EMC2 internationalisation package name:
PACKAGE="emc2"
AC_SUBST([PACKAGE])

if test -f ../VERSION; then
    EMC2VERSION="$(cat ../VERSION)"
else
    EMC2VERSION="Undetermined"
fi
AC_SUBST([EMC2VERSION])

##############################################################################
# Section 2                                                                  #
# RealTime checking (either RTAI, or RT-Linux)                               #
# Subsection 2.1 - arguments to ./configure (--with-realtime)                #
# Subsection 2.2 - if none specified above, RTDIR needs to be found by search#
# Subsection 2.3 - RTS(RT-script) is found, it gets queried for values       #
##############################################################################

AC_MSG_CHECKING(for RT dir)

# set up some default values
RTDIR=""
RTNAME=""
RTAI=""
RTLINUX=""
RTLINUXPRO=""
RTPREFIX=""
KERNELDIR=""
RTFLAGS=""

RTAI3_MOD=""
RTAI_MOD=""
RTL_MOD=""

##############################################################################
# Subsection 2.1                                                             #
# Check for arguments to ./configure                                         #
# accept --with-realtime=<path> from commandline                             #
##############################################################################

AC_ARG_ENABLE(simulator,
    [  --enable-simulator      Run as a pure userspace program],
    [
        case "$enableval" in
            Y*|y*)
                SIMULATOR=yes
                RTS=simulator
                BUILD_SYS=sim
                MODEXT=.so
                MODULE_DIR=${prefix}/lib/emc2/modules
                AC_MSG_RESULT([configuring for simulator])
            ;;
            *)
                SIMULATOR=no
        esac
    ],
    [
        SIMULATOR=no
    ])
AC_SUBST(SIMULATOR)

AC_ARG_WITH(realtime,
    [  --with-realtime=<path to realtime>     Path where RTAI or RTlinux is installed],
    [   case "$withval" in
	"" | y | ye | yes | n | no)
	    AC_MSG_ERROR([You must supply a path for --with-rtai.]) ;;
	*)
		case "$SIMULATOR" in
		yes) AC_MSG_ERROR([--with-realtime and --enable-simulator are mutually exclusive]) ;;
		*) RTDIR="$withval" ;;
		esac
	;;
        esac])

##############################################################################
# Subsection 2.2                                                             #
# 1. If a RT has been specified by the user it needs to be checked for       #
# validity. That is done by checking default locations for a certain script  #
# (similar to 2)                                                             #
#                                                                            #
# 2. If no RT has been specified explicitely by the user, one has to be      #
# found by search. In order to do that the following code will search for a  #
# RT-specific script:                                                        #
# rtlinux-config for RTLinux                                                 #
# realtime-config for RTAI 24.1.x                                            #
# rtai-config for RTAI 3.x                                                   #
##############################################################################

#at this point if RTDIR is empty, we need to find RT ourselves
if test $SIMULATOR = yes; then
  RTS=sim
  AC_PATH_PROG(PTH_CONFIG,pth-config,"")
  if test "$PTH_CONFIG" = ""; then
    AC_MSG_ERROR([GNU PTH library is required: get it with apt-get install libpth-dev])
  fi
else
  if test -z "$RTDIR"; then
    DIRS="/usr/realtime-`uname -r` /usr/realtime /usr/realtime* /usr /usr/src/rtai*"
  else
    DIRS="$RTDIR"
  fi
  for location in $DIRS; do
    for subdir in . scripts bin; do
      for signature in rtai rtl realtime; do
	candidate=$location/$subdir/$signature-config
	if test -z "$RTS" -a -e $candidate; then
	  RTS=$candidate
	fi
      done
    done
 done
 if test -z "$RTS"; then
    AC_MSG_ERROR([RT not found.  Specify:
	--with-realtime=<path>
or use
	--enable-simulator
to build without a realtime system.])
  fi
  AC_MSG_RESULT([Using $RTS as the RT signature])
fi


##############################################################################
# Subsection 2.3                                                             #
# we have the RT-script now, it's time to query it for some values           #
# it can provide us with default values such as CC, CFLAGS, etc              #
# see each case for more details                                             #
##############################################################################

RTARCH=`uname -m | sed s/i.86/i386/`
case $RTS in
*/rtai-config)
    RTNAME=rtai-3.0
    RTPREFIX=rtai
    RTAI=3
    RTDIR=`$RTS --prefix`
    RTDIR=$(cd $RTDIR ; pwd -P )
    RTFLAGS=`$RTS --module-cflags`
    RTFLAGS="$RTFLAGS -DRTAI=3"
    KERNELDIR=`$RTS --linux-dir`
    RTARCH=`$RTS --arch`
;;
*/realtime-config)
# For RTAI-24.1x $RTS = realtime-config
# Options and their return values for realtime-config
#	 Option		Returns
#	--prefix	Path to the rtai installation (usually /usr/realtime), not the original source tree. - USE WITH CAUTION
#	--version	Should return the version number - Appears to return 0.0.0 for most 24.1.x releases.
#	--cc		The compiler used for the C sources - Not necessarily the default cc
#	--cflags	Flags used to compile the realtime modules with.
#	--cflags-fp	Flags to use when compiling realtime modules with floating point math.
#	--dump		Dumps the .buildvars to screen - Grep for linuxdir
    RTNAME=rtai
    RTPREFIX=rtai
    RTAI=1

    # any other rtai-24.1.x system
    TEMP=`$RTS --prefix`
    if (test -d $TEMP) ; then
        RTDIR=$(cd $TEMP ; pwd -P )
    else
        RTDIR=${RTS%%/scripts/realtime-config}
    fi
    RTFLAGS=`$RTS --cflags-fp | head -n 1`
    RTFLAGS="$RTFLAGS -DRTAI=1"
    KERNELDIR=$($RTS --dump | grep -i linuxdir | awk -F'[[ ="]]+' '{print $2}')
#"
    KERNELDIR=$(cd $KERNELDIR ; pwd -P )
;;
*/rtl-config)
# For RTLinux-3.? $RTS = rtl-config
# Options and their return values for rtl-config
#	 Option		Returns
#	--prefix	Path to the RTLinux installation (usually /usr/rtlinux-{rtlVersion}), not the original source tree.
#	--rtlVersion	Version number of the installed RTLinux (e.g. 3.0)
#	--cc		The compiler used for the C sources - Not necessarily the default cc
#	--cflags	Flags used to compile the realtime modules with - It is a good idea to use these !
#	--linux		Path to the source directory of the patched kernel.
#	--module_dir	Path to the directory where the RTLinux modules are installed
#	--modules	A list of the available realtime modules.
    RTPREFIX=rtl
    RTDIR=`$RTS --prefix`
    RTDIR=$(cd $RTDIR ; pwd -P )
    RTFLAGS=`$RTS --cflags`
    KERNELDIR=`$RTS --linux`
;;
sim)
    RTPREFIX=sim
    RTDIR=$(pwd -P)
    RTFLAGS=-DSIMULATOR
esac

if test $RTS != sim; then
    AC_MSG_CHECKING([for location of kernel headers])
    AC_ARG_WITH(kernel-headers,
	[  --with-kernel-headers=<directory>       Location for kernel headers],
	[
	    KERNELDIR="$withval"
	    AC_MSG_RESULT(using specified value: $KERNELDIR)
	],[
	    AC_MSG_RESULT(using value from RTS: $KERNELDIR)
	])
fi

AC_SUBST([RTNAME])
AC_SUBST([RTAI])
AC_SUBST([RTLINUX])
AC_SUBST([RTLINUXPRO])
AC_SUBST([RTPREFIX])
AC_SUBST([KERNELDIR])
AC_SUBST([RTFLAGS])
AC_SUBST([RTDIR])
AC_SUBST([RTARCH])

if test $RTPREFIX = sim; then
    AC_DEFINE(RTAPI_SIM, [], [Realtime system is simulated])
elif test $RTPREFIX = rtai; then
    AC_DEFINE(RTAPI_RTAI, [], [Realtime system is RTAI])
elif test $RTPREFIX = rtl; then
    AC_DEFINE(RTAPI_RTL, [], [Realtime system is RTL])
fi


EMC2_HOME=`(cd .. ; pwd)`
AC_SUBST([EMC2_HOME])

##############################################################################
# Section 3                                                                  #
# aditional checking                                                         #
# Subsection 3.1 - checking for a CC (we must use the same one used for RT)  #
# Subsection 3.2 - check for the kernel version, with RT patches             #
# Subsection 3.3 - check the moduledir where modules can get installed       #
# Subsection 3.4 - check for GTK                                             #
# Subsection 3.5 - check for utility programs needed to build and run EMC    #
##############################################################################


##############################################################################
# Subsection 3.1 - checking for a CC (we must use the same one used for RT)  #
# Check CC version - (P.C.) We need to verify the compiler is the same one   #
# used for the realtime extensions... Hence the need to find the RT signature# 
# first.                                                                     #
# $RTS --cc should return the C compiler used - Verify this is acceptable.   #
# if version is gcc-2.96 check for alternative                               #
##############################################################################
AC_MSG_CHECKING([for cc version])

# The compiler MUST match the one used to compile the realtime modules if the
# kernel level code is to function correctly. But if the kernel has been
# compiled with gcc-2.96, it is unlikely to ever work !
# However realtime-config doesn't seem to have such an option
if (test ${RTS##*/} = rtai-config ) ; then
  RTSCC=`$RTS --cc`
  AC_MSG_RESULT(found $RTSCC in rtai-config)
elif (test ${RTS##*/} = rtl-config ) ; then
  RTSCC=`$RTS --cc`
  AC_MSG_RESULT(found $RTSCC in rtl-config)
else
  AC_MSG_RESULT(not specified)
fi

AC_PROG_CC([$RTSCC gcc])
AC_PROG_CPP()

if test -z "$CC"; then
  AC_MSG_ERROR([no acceptable cc found])
elif ! test `$CC -dumpversion | cut -d '.' -f 1` -gt 2 ; then
  AC_MSG_ERROR([Compilers older than gcc 3.x are no longer supported])
fi

AC_MSG_CHECKING([for usability of rdtscll from asm/msr.h])
AC_TRY_LINK(
    [
#include <asm/msr.h>
#include <stdio.h>
void use_rdtscll(void) { long long tsc; rdtscll(tsc); }
],
    [],
    [
        MSR_H_USABLE=yes
        AC_DEFINE([MSR_H_USABLE], [], [Define to 1 if asm/msr.h is usable and defines rdtscll])
    ], [MSR_H_USABLE=no])
AC_MSG_RESULT($MSR_H_USABLE)

CFLAGS_save=$CFLAGS
if ! test -z "$KERNELDIR"; then
	CFLAGS="$CFLAGS -I$KERNELDIR/include"
fi
AC_MSG_CHECKING([for usability of linux/joystick.h])
AC_TRY_LINK(
    [
#include <inttypes.h>
#include <linux/joystick.h>
    ],
    [],
    [JOYSTICK_H_USABLE=yes],
    [JOYSTICK_H_USABLE=no])
AC_MSG_RESULT($JOYSTICK_H_USABLE)
AC_SUBST([JOYSTICK_H_USABLE])
CFLAGS=$CFLAGS_save

##############################################################################
# Subsection 3.2 - check for the kernel version, with RT patches             #
#----------------------------------------------------------------------------#
# Check with the version.h to find the uts-kernel version.                   #
# This should be a more reliable way of determining the kernel that          #
# is being used to compile against - `uname -r` only returns the             #
# running kernel version which is may not be the one the code is             #
# compiled against.                                                          #
##############################################################################

if test $RTS '!=' sim; then
AC_CHECK_HEADERS([$KERNELDIR/include/linux/version.h],[],[AC_MSG_ERROR([version.h not found - Is the kernel headers package installed ?])])

# Unfortunately, many distributions (redhat, mandrake) have #defines
# inside version.h, so a simple cat|grep|cut test won't work... But then again,
# RH & Mandrake kernels are notorious for their use of patches that break
# the RT patching - Both RTAI and RTLinux strongly recommend using
# a virgin source from kernel.org.

# Get the kernel version from version.h
AC_MSG_CHECKING([for kernel version string])

if test -e $KERNELDIR/include/linux/utsrelease.h; then
    VERSION_FILE=$KERNELDIR/include/linux/utsrelease.h
else
    VERSION_FILE=$KERNELDIR/include/linux/version.h
fi
KERNEL_VERS=`$CC -E -dM ${VERSION_FILE} | grep UTS | cut -d '"' -f 2`

if test -z "$KERNEL_VERS"; then 
    AC_MSG_ERROR(Kernel version string not found)
fi

AC_MSG_RESULT([$KERNEL_VERS])
AC_SUBST([KERNEL_VERS])

# Do a quick test for module extension..
AC_MSG_CHECKING([for kernel module extension])
MODEXT=`$RTS --module-ext 2>/dev/null` || MODEXT=".o"
if test "x" = "x$MODEXT"; then
    MODEXT=".o"
fi
AC_MSG_RESULT([$MODEXT])

# This check should see if kbuild is or isn't used
AC_MSG_CHECKING([kernel build system])
# FIXME FIXME FIXME
# right now it will assume based on the kernel module extension
EXT_RTFLAGS=""
BUILD_SYS="normal"

if test "x$MODEXT" = "x.ko" ; then
    BUILD_SYS="kbuild"
else
    EXT_RTFLAGS="-DEXPORT_SYMTAB"
fi

AC_ARG_WITH(kbuild,
    [  --with-kbuild=<y/n>                     Specify if your kernel uses kbuild or not],
    [
        case "$withval" in
        "" | y | ye | yes )
	    BUILD_SYS="kbuild"
          ;;
        n | no )
	    BUILD_SYS="normal"
          ;;
        esac
    ])
AC_MSG_RESULT([$BUILD_SYS])
fi
AC_SUBST([MODEXT])
AC_DEFINE_UNQUOTED([MODULE_EXT], "$MODEXT", [Extension for realtime modules])
AC_SUBST([BUILD_SYS])
AC_SUBST([EXT_RTFLAGS])

##############################################################################
# Subsection 3.3 - check the moduledir where modules can get installed       #
#                                                                            #
# Provides the user the possibility to specify (--with-module-dir=<path>)    #
# If not specified default inside /lib/modules/${KERNEL_VERS}/               #
# to the location where a RT-module gets found (mbuff.o or rtai_shm.o)       #
# (maybe the default should be /lib/modules/$KERNEL_VERS/extra if it exists? #
##############################################################################

# Create a module-dir option, similar to rtai's...
AC_MSG_CHECKING([for module installation directory])

AC_ARG_WITH(module-dir,
    [  --with-module-dir=<module-dir>          Installation directory for kernel modules],
    [
        case "$withval" in
        "" | y | ye | yes | n | no)
            AC_MSG_ERROR([You must supply a path for --with-module-dir.])
          ;;
        esac
        MODULE_DIR="$withval"
    ])


# if not specified, ask the realtime config script where the directory is
# if the config script returns an error, set MODULE_DIR to nothing
if test "x" = "x$MODULE_DIR" ; then
  MODULE_DIR=`$RTS --module-dir 2>/dev/null`
  if ! test -d $MODULE_DIR ; then
    AC_MSG_ERROR([$RTS --module-dir did not specify an existing directory.  You must use specify it using --with-module-dir=...])
  fi
fi
    
if test "$RUN_IN_PLACE" = "yes"; then
    RIP_MODULE_DIR="${BUILD_TOPLEVEL}/rtlib"
    AC_MSG_RESULT([configuring for run-in-place])
    prefix=${BUILD_TOPLEVEL}
    DEFAULT_NMLFILE=${prefix}/configs/common/emc.nml
    DEFAULT_TOOLTABLE=${prefix}/configs/sim/sim.tbl
    AC_MSG_RESULT([$RIP_MODULE_DIR])
else
    RUN_IN_PLACE=no
    EMC2_HOME=$prefix
    DEFAULT_NMLFILE=${prefix}/share/emc/emc.nml
    AC_MSG_RESULT([$MODULE_DIR])
fi

AC_ARG_ENABLE(run-in-place,
    [  --enable-run-in-place   A deprecated flag
                          (instead, configure without specifying --prefix)],
    [
        if ! test -z "$enableval"; then
            AC_MSG_WARN([--enable-run-in-place will be removed soon.
Configure without specifying --prefix to get a run-in-place build.])
        fi
    ])

AC_SUBST([MODULE_DIR])
AC_SUBST([RIP_MODULE_DIR])
AC_SUBST([RUN_IN_PLACE])
AC_SUBST([DEFAULT_NMLFILE])
AC_DEFINE_UNQUOTED([EMC2_DEFAULT_NMLFILE], "$DEFAULT_NMLFILE", [Default nml file])
AC_DEFINE_UNQUOTED([EMC2_DEFAULT_TOOLTABLE], "$DEFAULT_TOOLTABLE", [Default nml file])

##############################################################################
# Subsection 3.4 - define default dirs, these get used in a lot of places    #
# we decide based on RIP or install where stuff goes                         #
##############################################################################

fe () {
    # Fully expand argument.  Example:
    # ${datadir} -> ${datarootdir} -> ${prefix}/share -> /usr/local
    case "$1" in
    *\$*) eval fe \""$1"\" ;;
    *) echo "$1" ;;
    esac
}

if test "xyes" = "x$RUN_IN_PLACE"; then
    EMC2_BIN_DIR=$EMC2_HOME/bin
    EMC2_TCL_DIR=$EMC2_HOME/tcl
    EMC2_TCL_LIB_DIR=$EMC2_HOME/tcl
    EMC2_LANG_DIR=$EMC2_HOME/src/objects
    EMC2_PO_DIR=$EMC2_HOME/share/locale
    EMC2_HELP_DIR=$EMC2_HOME/docs/help
    EMC2_RTLIB_DIR=$EMC2_HOME/rtlib
    EMC2_CONFIG_PATH="~/emc2/configs:$EMC2_HOME/configs"
    EMC2_NCFILES_DIR=$EMC2_HOME/nc_files
    REALTIME=$EMC2_HOME/scripts/realtime
    EMC2_IMAGE_DIR=$EMC2_HOME
else
    EMC2_HOME=${prefix}
    EMC2_BIN_DIR=${prefix}/bin
    EMC2_TCL_DIR=${prefix}/share/emc/tcl
    EMC2_TCL_LIB_DIR=${prefix}/lib/emc/tcl
    EMC2_LANG_DIR=${prefix}/share/emc/tcl/msgs
    EMC2_PO_DIR=${prefix}/share
    EMC2_HELP_DIR=${prefix}/share/doc/emc2
    case $MODULE_DIR in
        */emc2*) EMC2_RTLIB_DIR=$MODULE_DIR ;;
	*) EMC2_RTLIB_DIR=$MODULE_DIR/emc2
    esac
    EMC2_CONFIG_PATH="~/emc2/configs:/usr/local/etc/emc2/configs:"$(eval echo $EMC2_HELP_DIR)"/examples/sample-configs"
    EMC2_NCFILES_DIR=${prefix}/share/emc/ncfiles
    REALTIME=/etc/init.d/realtime
    EMC2_IMAGE_DIR=$(fe "$datadir")/emc
fi

AC_DEFINE_UNQUOTED([EMC2_HOME], "$EMC2_HOME", [Prefix or RIP directory])
AC_DEFINE_UNQUOTED([EMC2_BIN_DIR], "$EMC2_BIN_DIR", [Directory for binaries])
AC_DEFINE_UNQUOTED([EMC2_TCL_DIR], "$EMC2_TCL_DIR", [Directory for tcl scripts])
AC_DEFINE_UNQUOTED([EMC2_HELP_DIR], "$EMC2_HELP_DIR", [Directory for help files])
AC_DEFINE_UNQUOTED([EMC2_RTLIB_DIR], "$EMC2_RTLIB_DIR", [Directory of realtime system])
AC_DEFINE_UNQUOTED([EMC2_LANG_DIR], "$EMC2_LANG_DIR", [Directory for tcl translation files])
AC_DEFINE_UNQUOTED([EMC2_PO_DIR], "$EMC2_PO_DIR", [Directory for po/mo translation files])
AC_DEFINE_UNQUOTED([EMC2_CONFIG_DIR], "$EMC2_CONFIG_DIR", [Directory for configuration files])
AC_DEFINE_UNQUOTED([EMC2_NCFILES_DIR], "$EMC2_NCFILES_DIR", [Directory for nc files])
AC_DEFINE_UNQUOTED([EMC2_IMAGE_DIR], "$EMC2_IMAGE_DIR", [Directory for images])
AC_SUBST([EMC2_BIN_DIR])
AC_SUBST([EMC2_TCL_DIR])
AC_SUBST([EMC2_TCL_LIB_DIR])
AC_SUBST([EMC2_HELP_DIR])
AC_SUBST([EMC2_RTLIB_DIR])
AC_SUBST([EMC2_LANG_DIR])
AC_SUBST([EMC2_CONFIG_PATH])
AC_SUBST([EMC2_NCFILES_DIR])
AC_SUBST([REALTIME])
AC_SUBST([EMC2_IMAGE_DIR])

##############################################################################
# Subsection 3.5 - check for GTK                                             #
# FIXME: allow it to be enabled or disabled command line                     #
##############################################################################

AC_MSG_CHECKING([for glib])
if pkg-config glib-2.0 >/dev/null 2>&1; then
  GLIB_VER=`pkg-config glib-2.0 --modversion`
  AC_MSG_RESULT(yes - $GLIB_VER)
  GLIB_CFLAGS=`pkg-config glib-2.0 --cflags`
  GLIB_LIBS=`pkg-config glib-2.0 --libs`
else
  AC_MSG_ERROR(no -- required until somebody makes modbus optional)
fi

AC_MSG_CHECKING([for GTK 2.4.0 or above])
if pkg-config gtk+-2.0 --atleast-version 2.4.0 >/dev/null 2>&1; then
  GTK_VER=`pkg-config gtk+-2.0 --modversion`
  AC_MSG_RESULT(yes - $GTK_VER)
  GTK_CFLAGS=`pkg-config gtk+-2.0 --cflags`
  GTK_LIBS=`pkg-config gtk+-2.0 --libs`
  AC_MSG_CHECKING(for libgnomeprintui-2.2)
  if pkg-config --exists libgnomeprintui-2.2; then
    AC_MSG_RESULT(yes)
    GTK_CFLAGS="$GTK_CFLAGS `pkg-config --cflags libgnomeprintui-2.2`"
    GTK_LIBS="$GTK_LIBS `pkg-config --libs libgnomeprintui-2.2`"
    HAVE_GNOMEPRINT=yes
  else
    AC_MSG_RESULT(no -- printing from classicladder will not be possible)
    HAVE_GNOMEPRINT= 
  fi
else
  AC_MSG_WARN([GTK2 not found, some utilities (halscope, classicladder) will not be built])
fi
AC_SUBST(HAVE_GNOMEPRINT)
AC_SUBST(GTK_VER)
AC_SUBST(GTK_LIBS)
AC_SUBST(GTK_CFLAGS)
AC_SUBST(GLIB_LIBS)
AC_SUBST(GLIB_CFLAGS)

##############################################################################
# Subsection 3.6 - check for utility programs needed to build and run EMC    #
#                                                                            #
# Check for all the utility programs we need to build and install emc        #
# as well as those we use in the emc scripts...                              #
##############################################################################

SPATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin
AC_PROG_CXX
AC_PROG_MAKE_SET
AC_PROG_RANLIB
AC_PATH_PROG(AR,ar)
AC_PATH_PROG(GREP, grep)
AC_PATH_PROG(INSTALL, install)
AC_PATH_PROG(SED, sed)
AC_PATH_PROG(PS, ps)
AC_PATH_PROG(KILL, kill)
AC_PATH_PROG(WHOAMI, whoami)
AC_PATH_PROG(AWK, awk)
AC_PATH_PROG(INSMOD, insmod, $SPATH)
AC_PATH_PROG(RMMOD, rmmod, "", $SPATH)
AC_PATH_PROG(LSMOD, lsmod, "", $SPATH)
AC_PATH_PROG(PIDOF, pidof, "", $SPATH)
AC_PATH_PROG(IPCS, ipcs, "")
AC_PATH_PROG(FUSER, fuser, "", $SPATH)
AC_PATH_PROG(MANDB, mandb, "")

AC_ARG_WITH(rmmod,
    [  --with-rmmod=</path/rmmod>              rmmod variant],
    [
	case "$withval" in
	"" | y | ye | yes)
	    AC_MSG_ERROR([You must supply an argument to --with-rmmod.])
	  ;;
	n | no | none)
	    RMMOD=""
	  ;;
	*)
	    RMMOD="$withval"
	esac
    ],
    [
            RMMOD="$EMC2_BIN_DIR/emc_module_helper remove"
    ])

AC_ARG_WITH(insmod,
    [  --with-insmod=</path/insmod>            insmod variant],
    [
	case "$withval" in
	"" | y | ye | yes)
	    AC_MSG_ERROR([You must supply an argument to --with-insmod.])
	  ;;
	n | no | none)
	    INSMOD=""
	  ;;
	*)
	    INSMOD="$withval"
	esac
    ],
    [
            INSMOD="$EMC2_BIN_DIR/emc_module_helper insert"
    ])

##############################################################################
# Subsection 3.7 - check for programs needed to build documentation          #
#                                                                            #
# Check for LyX and other programs we need to build and install docs.        #
# (Optional, if not present, just don't build the docs.)                     #
##############################################################################

AC_ARG_WITH(python,
    [  --with-python=<path>                    Specify the Python interpreter],
    [
        PYTHON=$withval
    ],[
        PYTHON=python
    ])
AC_PATH_PROG(PYTHON,$PYTHON,"none")
if test $PYTHON = "none"
then
    AC_MSG_ERROR([python not found])
fi

AC_MSG_CHECKING([whether to build documentation])
AC_ARG_ENABLE(build-documentation,
    [  --enable-build-documentation[=format]   Build documentation.
              Format may be "pdf" or "html" if only one format is desired.],
    [
        case "$enableval" in
        Y*|y*|html,pdf|pdf,html)
            BUILD_DOCS=yes
            BUILD_DOCS_PDF=yes
            BUILD_DOCS_HTML=yes
            AC_MSG_RESULT([PDF and HTML requested])
        ;;
        html)
            BUILD_DOCS=yes
            BUILD_DOCS_PDF=no
            BUILD_DOCS_HTML=yes
            AC_MSG_RESULT([HTML requested])
	;;
        pdf)
            BUILD_DOCS=yes
            BUILD_DOCS_PDF=yes
            BUILD_DOCS_HTML=no
            AC_MSG_RESULT([PDF requested])
	;;
        *)
            BUILD_DOCS=no
            AC_MSG_RESULT([no])
        ;;
    esac
    ],
    [
        BUILD_DOCS=no
        AC_MSG_RESULT([no])
    ])

# Programs required for building all documentation
if ( test "$BUILD_DOCS" = "yes" ) ; then
    if ( test "none" = "$PYTHON" ) ; then
        AC_MSG_ERROR([no python, documentation cannot be built])
    fi

    AC_PATH_PROG(LYX,lyx,"none")
    if ( test "none" = "$LYX" ) ; then
	AC_PATH_PROG(LYXQT,lyx-qt,"none")
	if ( test "none" != "$LYXQT" ) ; then
	    LYX=$LYXQT
	fi
    fi
    if ( test "none" = "$LYX" ) ; then
	AC_MSG_ERROR([no LyX, documentation cannot be built])
    fi

    AC_MSG_CHECKING([for LyX version])
    set -- `$LYX --version 2>&1 | grep ^LyX` ; LYX_VER=$2
    AC_MSG_RESULT([$LYX_VER])
    set -- `echo $LYX_VER | sed 's/\./ /g'`
    if test $1 -lt 1 -o \( $1 -eq 1 -a $2 -lt 5 \) -o \( $1 -eq 1 -a $2 -eq 5 -a $3 -lt 3 \); then
	AC_MSG_ERROR([LyX version less than 1.5.3, documentation cannot be built])
    fi
    if test $1 -gt 1 -o \( $1 -eq 1 -a $2 -gt 5 \); then
	    AC_MSG_WARN([LyX documentation should only be edited with LyX version 1.5.x])
    fi
    AC_PATH_PROG(CONVERT,convert,"none")
    if ( test "none" = "$CONVERT" ) ; then
	AC_MSG_ERROR([no convert, documentation cannot be built])
    fi

    AC_PATH_PROG(GS,gs,"none")
    if ( test "none" = "$GS" ) ; then
	AC_MSG_ERROR([no gs, documentation cannot be built])
    fi
fi

# Programs required only for building the PDF documentation
if ( test "$BUILD_DOCS_PDF" = "yes" ) ; then
    AC_PATH_PROG(PDFLATEX,pdflatex,"none")
    if ( test "none" = "$PDFLATEX" ) ; then
	AC_MSG_ERROR([no pdflatex, PDF documentation cannot be built])
    fi

    AC_PATH_PROG(EPSTOPDF,epstopdf,"none")
    if ( test "none" = "$EPSTOPDF" ) ; then
	AC_MSG_ERROR([no epstopdf, PDF documentation cannot be built])
    fi
fi

# Programs required only for building the HTML documentation
if ( test "$BUILD_DOCS_HTML" = "yes" ) ; then
    AC_PATH_PROG(XSLTPROC,xsltproc,"none")
    if ( test "none" = "$XSLTPROC" ) ; then
	AC_MSG_ERROR([no xsltproc, HTML documentation cannot be built])
    fi

    AC_PATH_PROG(DVIPNG,dvipng,"none")
    if ( test "none" = "$DVIPNG" ) ; then
	AC_MSG_ERROR([no dvipng, HTML documentation cannot be built])
    fi

    AC_MSG_CHECKING([for HTML support in groff])
    if ! groff -Thtml < /dev/null > /dev/null 2>&1 ; then
        AC_MSG_ERROR([no groff -Thtml, HTML documentation cannot be built])
    else
        AC_MSG_RESULT(yes)
    fi
fi
AC_SUBST(BUILD_DOCS)
AC_SUBST(BUILD_DOCS_PDF)
AC_SUBST(BUILD_DOCS_HTML)

#############################################################################
# Section 4 - Check for math support                                         #
#                                                                            #
# Because some of the realtime kernel modules use floating point math        #
# which is not supported by standard kernel calls, we need to link to        #
# libm. RTAI provides a loadable module derived from uclibc (a minimal       #
# glibc implimentaion for embedded systems). Alternatively, we can link      #
# to dietlibc - Most distros package this as diet or dietlibc. Debian        #
# splits the headers and static libs into dietlibc-dev..                     #
# If neither of the two preferred options are available, then the default    #
# GNU glibc math library will have to be used. This will cause problems      #
# if certain functions found in libc.so are not stubbed, hence the following #
# tests and linking to mathstubs.o at a later stage.                         #
##############################################################################

if test "$SIMULATOR" != "yes"
then
AC_MSG_CHECKING([for kernel math support])
USE_LIBM=""
USE_RTLIBM=""
USE_STUBS=""
MATHLIB=""
MATHINC=""

#we need to make sure that $RTS has a --module-dir option
#only rtai-config has, well rtlinux-config has a --module_dir and lacks the rtai_* modules
if (test ${RTS##*/} = rtai-config ) ; then
    if (test -r $($RTS --module-dir)/rtai_math${MODEXT} ) ; then
       USE_RTLIBM=1
    fi
fi

if (test -r $RTDIR/modules/rtai_libm${MODEXT} ) || (test $USE_RTLIBM) || (test -r /lib/modules/${KERNEL_VERS}/rtai/rtai_libm${MODEXT}) ; then
    # Found a suitable kernel module..
    MATHLIB=
    USE_RTLIBM=1
    AC_MSG_RESULT([ok, using RTAI's libm kernel module])
# Note: need to search /lib/modules/$KERNEL_VER for the math modules..
#       or `$RTS --module-dir`...
else
    AC_MSG_RESULT([no])
    AC_MSG_CHECKING([for a suitable libm])
    rm -f tests/mathtest.o tests/mathtest 2>/dev/null
    # compile a sample first.
    $CC -c tests/mathtest.c $RTFLAGS -o tests/mathtest.o 2>/dev/null
    
    DIET_DIR=$(find /usr/lib -maxdepth 2 -name diet* | head -n1)
    if (test "$DIET_DIR" != "" ) ; then
        # Run a test to see if it will work...
        ld -r -static tests/mathtest.o -o tests/mathtest -L$DIET_DIR/lib-i386 -lm 2>/dev/null
        if (test "$(nm -u tests/mathtest | grep -v ende)" = "" ) ; then
            AC_MSG_RESULT([diet lib OK to use.])
            USE_DIET=1
            MATHLIB="-L$DIET_DIR/lib-i386 -lm"
            MATHINC="-I$DIET_DIR/include"
        fi
    fi
    if (test "$USE_DIET" = "" ) ; then
        # Test the standard libm
    rm -f tests/mathtest 2>/dev/null
    ld -r -static tests/mathtest.o -o tests/mathtest -L/usr/lib -lm 2>/dev/null
        if ! nm -u tests/mathtest ; then
            AC_MSG_RESULT([libm OK to use.])
            USE_LIBM=1
            MATHLIB="-L/usr/lib -lm"
        else
            # We need to link to mathstubs if we are to use the glibc libm
            AC_MSG_WARN([Using glibc libm with mathstubs.
			If unresolved symbols are reported when loading kernel modules
			please file a bug report.])
            USE_LIBM=1
	    USE_STUBS=1
            MATHLIB="-L/usr/lib -lm"
        fi
    fi
    rm -f tests/mathtest.o tests/mathtest 2>/dev/null
fi

AC_SUBST([USE_LIBM])
AC_SUBST([USE_STUBS])
AC_SUBST([USE_RTLIBM])
AC_SUBST([MATHINC])
AC_SUBST([MATHLIB])

# Export substitution symbols for module loading
AC_SUBST([RTAI3_MOD])
AC_SUBST([RTAI_MOD])
AC_SUBST([RTL_MOD])

for m in adeos rtai_hal rtai_ksched rtai_fifos rtai_shm rtai_sem rtai_math \
        rtai rt_mem_mgr rtai_sched rtai_libm \
        rtl mbuff rtl_time rtl_sched rtl_posixio rtl_fifo; do
    AC_MSG_CHECKING([for $m])
    TMP=$(find $MODULE_DIR -name $m$MODEXT)
    if test -z "$TMP"; then
        TMP=$(find /lib/modules/$KERNEL_VERS -name $m$MODEXT)
    fi
    eval MODPATH_$m=${TMP/$KERNEL_VERS/\\\$\\\(uname\\\ -r\\\)}
    AC_MSG_RESULT([${TMP:-not found}])
done

AC_SUBST(MODPATH_adeos)
AC_SUBST(MODPATH_rtai_hal)
AC_SUBST(MODPATH_rtai_ksched)
AC_SUBST(MODPATH_rtai_fifos)
AC_SUBST(MODPATH_rtai_shm)
AC_SUBST(MODPATH_rtai_sem)
AC_SUBST(MODPATH_rtai_math)
AC_SUBST(MODPATH_adeos)
AC_SUBST(MODPATH_rtai)
AC_SUBST(MODPATH_rt_mem_mgr)
AC_SUBST(MODPATH_rtai_sched)
AC_SUBST(MODPATH_rtai_shm)
AC_SUBST(MODPATH_rtai_libm)
AC_SUBST(MODPATH_rtl)
AC_SUBST(MODPATH_mbuff)
AC_SUBST(MODPATH_rtl_time)
AC_SUBST(MODPATH_rtl_sched)
AC_SUBST(MODPATH_rtl_posixio)
AC_SUBST(MODPATH_rtl_fifo)
fi

# Checks for header files.

##############################################################################
# Section 4.1 - Important headers, functions and gloabl defines.             #
#                                                                            #
##############################################################################

# This section gets inserted in to config.h.in when autoheader is run.
# Global and common defines should be here rather than duplicated in
# multiple places. Keep screwball constructs out of this, and it can
# be used in both kernel space and user space.
AH_TOP([/********************************************************************
* Description: config.h
*
*	Common defines used in many emc2 source files.
*       To add to this file, edit Section 4.1 in configure.in
*       and then run autoheader.
*
* Author: Autogenerated by autoheader
* License: LGPL Version 2
* System: Linux
*    
* Copyright (c) 2004 All rights reserved.
********************************************************************/
#ifndef EMC2_CONFIG_H
#define EMC2_CONFIG_H

/* LINELEN is used throughout for buffer sizes, length of file name strings,
   etc. Let's just have one instead of a multitude of defines all the same. */
#define LINELEN 255
/* Used in a number of places for sprintf() buffers. */
#define BUFFERLEN 80

#define MM_PER_INCH 25.4
#define INCH_PER_MM (1.0/25.4)
])

AH_VERBATIM([_GNU_SOURCE],
[/* Enable GNU extensions on systems that have them.  */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
])

AC_HEADER_STDC
AC_HEADER_SYS_WAIT
AC_CHECK_FUNCS(semtimedop)
LDFLAGS_hold=$LDFLAGS
LDFLAGS="$LDFLAGS -lm"
AC_CHECK_FUNCS(sincos)
AC_CHECK_FUNCS(__sincos)
LDFLAGS=$LDFLAGS_hold

AH_BOTTOM(#endif
)

##############################################################################
# Section 5 - Check for tcl/tk support                                       #
#                                                                            #
# Test for tcl/tk headers fails if they are not in /usr/include              #
# so testing is done by finding tclConfig.sh and tkConfig.sh                 #
# if the search fails the traditional check is done                          #
##############################################################################
AC_MSG_CHECKING([for tcl])

AC_ARG_WITH(tclConfig,
    [  --with-tclConfig=<path>                 Specify the path to tclConfig],
    [
        TCLCONFIG=$withval
    ],[
        TCLCONFIG=
    ])

# if not specified, search for tclConfig.sh
if (test "x$TCLCONFIG" = "x"); then
    TCLCONFIG=$(find /usr/lib* -maxdepth 2 -name tclConfig.sh | head -n1)
    if (test "x$TCLCONFIG" = "x"); then
	TCLCONFIG=$(find /usr/local/lib* -maxdepth 2 -name tclConfig.sh | head -n1)
    fi
fi

if (test "x$TCLCONFIG" = "x"); then
   AC_MSG_RESULT([tclConfig.sh not found, trying tcl.h and libs.
		  If it doesn't work try running ./configure --with-tclConfig=<path to tclConfig.sh>])
   AC_CHECK_HEADERS([tcl.h])
   AC_SEARCH_LIBS(Tcl_Init,[tcl tcl8.1 tcl8.2 tcl8.3 tcl8.4 tcl8.5],[],[AC_MSG_ERROR([tcl lib not found])])
else
# tclConfig.sh found,
# extracting vars
   AC_MSG_RESULT([$TCLCONFIG found])
   . "$TCLCONFIG"
   TCL_CFLAGS="$TCL_INCLUDE_SPEC -DUSE_TCL_STUBS"
   TCL_LIBS="$TCL_STUB_LIB_SPEC"
fi

AC_MSG_CHECKING([for tk])

AC_ARG_WITH(tkConfig,
    [  --with-tkConfig=<path>                  Specify the path to tkConfig],
    [
        TKCONFIG=$withval
    ],[
        TKCONFIG=
    ])

# if not specified, search for tclConfig.sh
if test -z "$TKCONFIG"; then
    TKCONFIG=$(dirname $TCLCONFIG)/tkConfig.sh
    if ! test -f $TKCONFIG; then unset TKCONFIG; fi
fi
if (test "x$TKCONFIG" = "x"); then
    # search for tkConfig.sh
    TKCONFIG=$(find /usr/lib -maxdepth 2 -name tkConfig.sh | head -n1)
    if (test "x$TKCONFIG" = "x"); then
	TKCONFIG=$(find /usr/local/lib -maxdepth 2 -name tkConfig.sh | head -n1)
    fi
fi

if (test "x$TKCONFIG" = "x"); then
   AC_MSG_RESULT([tkConfig.sh not found, trying tk.h and libs.
		  If it doesn't work try running ./configure --with-tkConfig=<path to tkConfig.sh>])
   AC_CHECK_HEADERS([tk.h])
   AC_SEARCH_LIBS(Tk_Init,[tk tk80 tk8.0 tk8.1 tk8.2 tk8.3 tk8.4 tk8.5],[],[AC_MSG_ERROR([tk lib not found])])
else
# tkConfig.sh found,
# extracting vars
   AC_MSG_RESULT([$TKCONFIG found])
   . "$TKCONFIG"
   TK_CFLAGS="$TK_INCLUDE_SPEC $TK_XINCLUDES" 
   TK_LIBS="$TK_LIBS $TK_LIB_SPEC"
fi

if ! test -z "$TCL_VERSION" && ! test -z "$TK_VERSION" && ! test "$TCL_VERSION" = "$TK_VERSION" ; then
    AC_MSG_ERROR([Tcl and Tk versions must be the same, but configure found
Tcl $TCL_VERSION and Tk $TK_VERSION.  You can use --with-tkConfig= and --with-tclConfig=
to override the autodetected versions.])
fi

if test -f $TCL_EXEC_PREFIX/bin/wish$TCL_VERSION; then
    WISH=$TCL_EXEC_PREFIX/bin/wish$TCL_VERSION
elif test -f $TCL_EXEC_PREFIX/bin/wish; then
    WISH=$TCL_EXEC_PREFIX/bin/wish
else
    WISH=wish
fi

if test -f $TCL_EXEC_PREFIX/bin/tclsh$TCL_VERSION; then
    TCLSH=$TCL_EXEC_PREFIX/bin/tclsh$TCL_VERSION
elif test -f $TCL_EXEC_PREFIX/bin/tclsh; then
    TCLSH=$TCL_EXEC_PREFIX/bin/tclsh
else
    TCLSH=tclsh
fi

AC_MSG_CHECKING([for BWidget using $TCLSH])
if (unset DISPLAY; echo ["catch { package require bwidget }; exit [expr [lsearch [package names] BWidget] == -1]"] | $TCLSH); then
    AC_MSG_RESULT([found])
else
    AC_MSG_ERROR([not found])
fi

AC_SUBST([TCL_DBGX])
AC_SUBST([TK_DBGX])
AC_SUBST([TCL_CFLAGS])
AC_SUBST([TK_CFLAGS])
AC_SUBST([TCL_LIBS])
AC_SUBST([TK_LIBS])
AC_SUBST([WISH])
AC_SUBST([TCLSH])

##############################################################################
# Section 6 - Miscelaneous support                                           #
#                                                                            #
# Subsection 6.1. - provides DATE to output it to the generated files        #
# Subsection 6.2. - user option to convince make to be quiet during make     #
##############################################################################

# provides DATE in order to output it to the generated files
DATE=$(date)
AC_SUBST([DATE])
AC_PATH_XTRA
#X_CFLAGS gets set
#X_LIBS and X_EXTRA_LIBS likewise

AC_SUBST([X_LIBS])
AC_SUBST([X_CFLAGS])

# check for Xaw, that is needed for emc2/src/emc/usr_intf/xemc.cc

if test "$have_x" = "yes"; then
CFLAGS_hold=$CFLAGS
LDFLAGS_hold=$LDFLAGS
CFLAGS="$CFLAGS $X_CFLAGS"
LDFLAGS="$LDFLAGS $X_PRE_LIBS $X_LIBS"

AC_CHECK_HEADERS(X11/Xaw/XawInit.h,
	    [HAVE_XAW=yes],
	    [HAVE_XAW=no],
	    [[#include <X11/Intrinsic.h>
	    ]])

AC_CHECK_LIB(Xaw, XawDialogGetValueString,
	    [],
	    [HAVE_XAW=no])
CFLAGS=$CFLAGS_hold
LDFLAGS=$LDFLAGS_hold
fi

if test "x$HAVE_XAW" = "xno"; then
    AC_MSG_WARN(Xaw lib missing, you won't be able to build/run xemc. try installing it with 'apt-get install libxaw7-dev')
else    
    XAW_LIBS="$X_PRE_LIBS $X_LIBS -lX11 -lXaw"
fi
AC_SUBST([HAVE_XAW])
AC_SUBST([XAW_LIBS])

#clean out LIBS, or else all future tests will check with -lXaw (which fails on odd systems)
temp_LIBS=$LIBS
LIBS=

# check for readline.h and friends, optional for halcmd
AC_CHECK_HEADERS(readline/readline.h, [HAVE_READLINE=yes], [HAVE_READLINE=no])
AC_CHECK_HEADERS(readline/history.h, [], [HAVE_READLINE=no])

echo "Trying readline without -ltermcap"
AC_CHECK_LIB(readline, readline, [HAVE_READLINE_NOTERMCAP=yes], [])
unset ac_cv_lib_readline_readline
echo "Trying readline with -ltermcap"
AC_CHECK_LIB(readline, readline, [HAVE_READLINE_TERMCAP=yes], [], -ltermcap)
unset ac_cv_lib_readline_readline

if test "x$HAVE_READLINE_NOTERMCAP" = "xyes"; then
    echo "Readline does not require -ltermcap"
    READLINE_LIBS="-lreadline"
elif test "x$HAVE_READLINE_TERMCAP" = "xyes"; then
    echo "Readline requires -ltermcap"
    READLINE_LIBS="-lreadline -ltermcap"
else
    HAVE_READLINE=no
fi

if test "x$HAVE_READLINE" = "xyes"; then
    AC_DEFINE([HAVE_READLINE], [], [Define to 1 if you have the 'readline' library (-lreadline) and required headers])
else
    AC_MSG_ERROR([Required library 'readline' missing.])
fi
AC_SUBST([HAVE_READLINE])
AC_SUBST([READLINE_LIBS])


#check for ncurses.h needed for emc2/src/emc/usr_intf/keystick.cc

AC_CHECK_HEADERS(ncurses.h,
	    [HAVE_NCURSES=yes],
	    [HAVE_NCURSES=no])

AC_CHECK_LIB(ncurses, initscr,
	    [],
	    [HAVE_NCURSES=no])

if test "x$HAVE_NCURSES" = "xno"; then
    AC_MSG_WARN(ncurses lib missing, you won't be ablet o build/run keystick. try installing it with 'apt-get install libncurses-dev')
else    
    NCURSES_LIBS="-lncurses"
fi
AC_SUBST([HAVE_NCURSES])
AC_SUBST([NCURSES_LIBS])


##############################################################################
# Section 7 - Language support                                               #
#                                                                            #
# i18n Language support:                                                     #
# see http://cvs.gnome.org/viewcvs/intltool/doc/I18N-HOWTO?rev=1.3           #
##############################################################################

# if you don't have nls tools, allow a way out!

AC_ARG_ENABLE(nls,
              [  --disable-nls           don't use NLS],
              USE_NLS=no, USE_NLS=yes)
AC_SUBST(USE_NLS)

if test "$USE_NLS" = "yes"; then
  AC_CHECK_HEADERS(locale.h)
  AC_CHECK_FUNCS(setlocale)
  AC_SUBST(HAVE_LOCALE_H)  

# Add languages here when they are translated.
# Grep the LINGUAS file.
  LANGUAGES=""
  AC_SUBST(LANGUAGES)  
  AC_CHECK_HEADERS(libintl.h)
  AC_CHECK_LIB(intl,gettext)
  AC_SUBST(HAVE_LIBINTL_H)  
  AC_SUBST(HAVE_LIBINTL)

# The default locale directory is /usr/share/locale - This is generally fixed
# by the distribution....
  dnl Handle localedir
  LOCALEDIR='/usr/share/locale'
  AC_ARG_WITH(locale-dir,
  [  --with-locale-dir=DIR   Location of the locale file(s)
                          [DATADIR/locale]],[
    if test x$withval = xyes; then
      AC_MSG_WARN(Usage is: --with-locale-dir=basedir)
    else
      if test x$withval = xno; then
        AC_MSG_WARN(Usage is: --with-locale-dir=basedir)
      else
        LOCALEDIR=$withval
      fi
    fi
  ])
  AC_SUBST(LOCALEDIR)
fi

#restore LIBS
LIBS="$X_LIBS $temp_LIBS"

AC_PATH_PROG(XGETTEXT,xgettext,none)
XGETTEXT_TCL_WORKS=no
if test "$XGETTEXT" != "none"; then
   AC_MSG_CHECKING(for xgettext tcl bug)
   set -- $(xgettext --version | head -1)
   version=$4
   set -- $(echo $4 | tr . " ")
   if test ${1-0} -gt 0 -o \( ${1-0} -eq 0 -a \( ${2-0} -gt 14 -o \( ${2-0} -eq 14 -a ${3-0} -ge 5 \) \) \)
   then
	XGETTEXT_TCL_WORKS=yes
	AC_MSG_RESULT(xgettext version $version OK)
    else
	AC_MSG_RESULT(xgettext version $version buggy -- need at least 0.14.5)
        AC_MSG_ERROR(install xgettext 0.14.5 or above)
   fi
fi
AC_SUBST(XGETTEXT)

AC_PATH_PROG(MSGFMT,msgfmt,none)
if test "$MSGFMT" != "none"; then
    AC_MSG_CHECKING(for --tcl support in msgfmt)
    if $MSGFMT --tcl -l de -d /tmp /dev/null > /dev/null 2>&1; then
        AC_MSG_RESULT(yes)
    else
        AC_MSG_ERROR(install xgettext 0.14.5 or above)
    fi
fi
AC_SUBST(MSGFMT)

AC_MSG_CHECKING(for Python support)
AC_ARG_ENABLE(python,
    [  --disable-python        Disable the parts of emc2 that depend on Python],
    [
	case "$enableval" in
	Y*|y*)
	    BUILD_PYTHON=yes ;;
	*)
	    BUILD_PYTHON=no ;;
	esac
    ],
    [BUILD_PYTHON=yes])

AC_MSG_RESULT($BUILD_PYTHON)

if test "$BUILD_PYTHON" = "yes"; then
    if test "$PYTHON" = "none"; then
	AC_MSG_ERROR([Python missing.  Install it or specify --disable-python to skip the parts of emc2 that depend on Python])
    fi

    AC_MSG_CHECKING([python version])
    if ! $PYTHON -c 'import sys;raise SystemExit,sys.hexversion<0x2040000'
    then
	AC_MSG_ERROR(Python version too old (2.4 or newer required))
    fi
    AC_MSG_RESULT(OK)

    AC_MSG_CHECKING([match between tk and Tkinter versions])
	
    PYTHON_TK_VERSION="`$PYTHON -c 'import _tkinter; print _tkinter.TK_VERSION'`"
    PYTHON_TCL_VERSION="`$PYTHON -c 'import _tkinter; print _tkinter.TCL_VERSION'`"

    if test "$PYTHON_TCL_VERSION" != "$TCL_VERSION"; then
	AC_MSG_RESULT([TCL mismatch: $TCL_VERSION vs $PYTHON_TCL_VERSION])
	AC_MSG_ERROR([Python requires use of Tcl $PYTHON_TCL_VERSION and Tk $PYTHON_TK_VERSION.
Install this version and specify --with-tclConfig and --with-tkConfig if necessary])
    fi
    if test "$PYTHON_TK_VERSION" != "$TK_VERSION"; then
	AC_MSG_RESULT([Tk mismatch: $TK_VERSION vs $PYTHON_TK_VERSION])
	AC_MSG_ERROR(["Python requires use of Tk $TK_VERSION.  Install this version and specify --with-tkConfig if necessary"])
    fi
    AC_MSG_RESULT([$PYTHON_TK_VERSION])

    AC_MSG_CHECKING(location of Python header files)
    INCLUDEPY=`$PYTHON -c 'import distutils.sysconfig; print distutils.sysconfig.get_config_vars().get("INCLUDEPY")'`
    AC_MSG_RESULT($INCLUDEPY)

    AC_CHECK_HEADER($INCLUDEPY/Python.h,[],
	[AC_MSG_ERROR([Required header Python.h missing.  Install it, or specify --disable-python to skip the parts of emc2 that depend on Python])])

    AC_MSG_CHECKING(for site-package location)
    SITEPY=`$PYTHON -c 'import distutils.sysconfig; print distutils.sysconfig.get_python_lib()'`
    AC_MSG_RESULT($SITEPY)

    AC_CHECK_HEADERS(GL/gl.h GL/glu.h,[],[AC_MSG_ERROR([Required OpenGL header missing.  Install it, or specify --disable-python to skip the parts of emc2 that depend on Python])])

    AC_CHECK_LIB(GL, glBegin, [], [AC_MSG_ERROR([Required GL library missing.  Install it, or specify --disable-python to skip the parts of emc2 that depend on Python])])

    AC_MSG_CHECKING(for working GLU quadrics)
    AC_TRY_COMPILE([
#include <GL/gl.h>
#include <GL/glu.h>
],
	[GLUquadric *q;],
	[AC_MSG_RESULT(yes)],[
		AC_MSG_ERROR([Required GLU library missing.  Install it or specify --disable-python to skip the parts of emc2 that depend on Python])]
	
    )
fi

AC_SUBST([BUILD_PYTHON])
AC_SUBST([INCLUDEPY])
AC_SUBST([SITEPY])


##############################################################################
# files that get created by ./configure                                      #
##############################################################################
#AC_CONFIG_FILES([../configs/rtapi.conf ../configs/emc.conf ../configs/hal.conf config.h])
AC_CONFIG_FILES([../scripts/rtapi.conf])
AC_CONFIG_FILES([../docs/man/man1/emc.1])
AC_CONFIG_FILES([../scripts/emc], [chmod +x ../scripts/emc])
AC_CONFIG_FILES([../scripts/halrun], [chmod +x ../scripts/halrun])
AC_CONFIG_FILES([../scripts/emc-environment], [chmod +x ../scripts/emc-environment])
AC_CONFIG_FILES([../scripts/haltcl], [chmod +x ../scripts/haltcl])
AC_CONFIG_FILES([../scripts/realtime], [chmod +x ../scripts/realtime])
AC_CONFIG_FILES(Makefile.inc)
AC_CONFIG_FILES(Makefile.modinc)
AC_CONFIG_FILES(../tcl/emc.tcl)
AC_CONFIG_FILES(../lib/python/nf.py)
AC_CONFIG_FILES([../scripts/emcmkdesktop], [chmod +x ../scripts/emcmkdesktop])
AC_OUTPUT()

##############################################################################
# message to the user what to do next, after a succesfull ./configure        #
##############################################################################
bold () {
    if tty > /dev/null 2>&1 && type -path tput > /dev/null 2>&1;
    then
        tput smso
    fi
}

offbold () {
    if tty > /dev/null 2>&1 && type -path tput > /dev/null 2>&1;
    then
        tput rmso
    fi
}

echo ""
echo ""
echo "######################################################################"
echo "#                  EMC2 - Enhanced Machine Controller                #"
echo "######################################################################"
echo "#                                                                    #"
echo "#   EMC2 is a software system for computer control of machine tools, #"
echo "#   such as milling machines. EMC2 is released under the GPL.        #"
echo "#   Check out http://www.linuxcnc.org/ for more details.             #"
echo "#                                                                    #"
echo "#                                                                    #"
echo "#   It seems that ./configure completed successfully.                #"
if test $SIMULATOR = yes; then
echo "#   However, the configuration is for a simulator only, no RT        #"
echo "#   capabilities will be used. In this mode no control of hardware   #"
echo "#   is possible. Drivers won't be built.                             #"
else
echo "#   This means that RT is properly installed                         #"
fi
echo "#   If things don't work check config.log for errors & warnings      #"
echo "#                                                                    #"

if test "xyes" = "x$RUN_IN_PLACE"; then
echo "#   Next compile by typing                                           #"
echo "#         make                                                       #"
if test $SIMULATOR != yes; then
echo "#         sudo make setuid                                           #"
fi
echo "#                                                                    #"
echo "#   Before running the software, set the emc environment:            #"
echo "#         . (top dir)/scripts/emc-environment                        #"
else
bold
echo "#   warning: If you already have an installed emc2, this will        #"
echo "#         replace an existing installation.  If you have installed   #"
echo "#         an emc2 package, this will damage the package.             #"
offbold
echo "#   hint: To test a self-built version of emc without damaging       #"
echo "#         the package version, use                                   #"
echo "#             ./configure --enable-run-in-place                      #"
echo "#                                                                    #"
echo "#   Next compile by typing                                           #"
echo "#         make                                                       #"
echo "#   then install it by typing                                        #"
echo "#         sudo make install                                          #"
fi
echo "#                                                                    #"
echo "#   To run the software type                                         #"
echo "#         emc                                                        #"
echo "#                                                                    #"
echo "######################################################################"
echo ""
echo ""
