#!/bin/sh
#
# configure -- custom configure script for the ScummVM tools.
#
# ScummVM Tools is the legal property of its developers, whose names
# are too numerous to list here. Please refer to the COPYRIGHT
# file distributed with this source distribution.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Save the current environment variables for next runs
SAVED_CONFIGFLAGS=$@
SAVED_LDFLAGS=$LDFLAGS
SAVED_PKG_CONFIG_LIBDIR=${PKG_CONFIG_LIBDIR:-unset}
SAVED_CXX=$CXX
SAVED_CXXFLAGS=$CXXFLAGS
SAVED_CPPFLAGS=$CPPFLAGS
SAVED_ASFLAGS=$ASFLAGS
SAVED_WINDRESFLAGS=$WINDRESFLAGS

# Use environment vars if set
CXXFLAGS="$CXXFLAGS $CPPFLAGS"

# Backslashes into forward slashes:
# The following OS/2 specific code is performed to deal with handling of backslashes by ksh.
# Borrowed from the Sane configure script

if test "$ac_emxsupport" != "no" -a "$ac_emxsupport" != "NO"; then
	ac_save_IFS="$IFS"
	IFS="\\"
	ac_TEMP_PATH=
	for ac_dir in $PATH; do
		IFS=$ac_save_IFS
		if test -z "$ac_TEMP_PATH"; then
			ac_TEMP_PATH="$ac_dir"
		else
			ac_TEMP_PATH="$ac_TEMP_PATH/$ac_dir"
		fi
	done
	PATH="$ac_TEMP_PATH"
	export PATH
	unset ac_TEMP_PATH
fi

set_var() {
	eval ${1}='${2}'
}

get_var() {
	eval echo \$${1}
}

_srcdir=`dirname $0`

#
# Default settings
#
# Default lib behavior yes/no/auto
_vorbis=auto
_tremor=auto
_flac=auto
_mad=auto
_zlib=auto
_png=auto
_freetype2=auto
_wxwidgets=auto
_iconv=auto
_boost=auto
_endian=unknown
_need_memalign=no
# Default option behavior yes/no
_debug_build=auto
_release_build=auto
_verbose_build=no
_enable_prof=no
_use_cxx11=yes
# Default commands
_ranlib=ranlib
_strip=strip
_ar="ar cru"
_as="as"
_windres=windres
_pkgconfig=pkg-config
_wxconfig=wx-config
_wxpath="$PATH"
_prefix=/usr/local
_wxincludes=""
_wxlibs=""
_wxstaticlibs=""
_freetypeconfig=freetype-config
_freetype_found="false"
_freetypepath="$PATH"
_staticlibpath=""
_xcodetoolspath=""
_amigaospath="install"
_morphospath="PROGDIR:"
# For cross compiling
_host=""
_host_cpu=""
_host_vendor=""
_host_os=""
_host_alias=""

# Use temp files in the build directory
TMPO=./scummvm-tools-conf
TMPC=${TMPO}.cpp
TMPLOG=config.log

cc_check_no_clean() {
	echo >> "$TMPLOG"
	cat "$TMPC" >> "$TMPLOG"
	echo >> "$TMPLOG"
	echo "$CXX $LDFLAGS $CXXFLAGS $TMPC -o $TMPO$HOSTEXEEXT $@" >> "$TMPLOG"
	rm -f "$TMPO$HOSTEXEEXT"
	( $CXX $LDFLAGS $CXXFLAGS "$TMPC" -o "$TMPO$HOSTEXEEXT" "$@" ) >> "$TMPLOG" 2>&1
	TMPR="$?"
	echo "return code: $TMPR" >> "$TMPLOG"
	echo >> "$TMPLOG"
	return "$TMPR"
}

cc_check_clean() {
	rm -rf $TMPC $TMPO $TMPO.o $TMPO.dSYM $TMPO$HOSTEXEEXT "$@"
}

cc_check() {
	cc_check_no_clean "$@"
	TMPR="$?"
	cc_check_clean
	return "$TMPR"
}

cc_check_define() {
cat > $TMPC << EOF
int main(void) {
	#ifndef $1
	syntax error
	#endif
	return 0;
}
EOF
	cc_check -c
	return $?
}

gcc_get_define() {
	echo "" | $CXX -dM -E - | fgrep "$1" | head -n1 | cut -d ' ' -f 3-
}

#
# Function to provide echo -n for bourne shells that don't have it
#
echo_n() {
	printf "$@"
}

echocheck() {
	echo_n "Checking for $@... "
}

# Add a line of data to config.mk.
add_line_to_config_mk() {
	_config_mk_data="$_config_mk_data"'
'"$1"
}

# Add a line of data to config.h.
add_line_to_config_h() {
	_config_h_data="$_config_h_data"'
'"$1"
}

# Conditionally add a line of data to config.h. Takes two parameters:
# The first one can be set to 'no' to "comment out" the line, i.e.
# make it ineffective, use 'yes' otherwise.
# The second param is the line to insert.
add_to_config_h_if_yes() {
	if test "$1" = yes ; then
		add_line_to_config_h "$2"
	else
		add_line_to_config_h "/* $2 */"
	fi
}

# Conditionally add a line of data to config.mk. Takes two parameters:
# The first one can be set to 'no' to "comment out" the line, i.e.
# make it ineffective, use 'yes' otherwise.
# The second param is the line to insert.
add_to_config_mk_if_yes() {
	if test "$1" = yes ; then
		add_line_to_config_mk "$2"
	else
		add_line_to_config_mk "# $2"
	fi
}

# Conditionally add a '#define' line to config.h. Takes two parameters:
# The first one can be set to 'yes' or 'no'. If 'yes' is used, then
# the line "#define $2" is added to config.h, otherwise "#undef $2".
define_in_config_h_if_yes() {
	if test "$1" = yes ; then
		add_line_to_config_h "#define $2"
	else
		add_line_to_config_h "#undef $2"
	fi
}

# Conditionally add definitions to config.h and config.mk. Takes two parameters:
# The first one can be set to 'yes' or 'no'. If 'yes' is used, then
# the line "#define $2" is added to config.h and "$2 = 1" to config.mk.
# Otherwise "#undef $2" is added to config.h and "# $2 = 1" to config.mk
define_in_config_if_yes() {
	if test "$1" = yes ; then
		add_line_to_config_h "#define $2"
		add_line_to_config_mk "$2 = 1"
	else
		add_line_to_config_h "#undef $2"
		add_line_to_config_mk "# $2 = 1"
	fi
}

#
# Determine wx-config
#
# TODO: small bit of code to test wxWidgets usability
find_wxconfig() {
	echo_n "Looking for wx-config... "
	wxconfigs="$_wxconfig:wxgtk2-2.8-config"
	_wxconfig=

	IFS="${IFS=   }"; ac_save_ifs="$IFS"; IFS="$SEPARATOR"
	for path_dir in $_wxpath; do
		#reset separator to parse wxconfigs
		IFS=":"
		for wxconfig in $wxconfigs; do
			if test -f "$path_dir/$wxconfig" ; then
				_wxconfig="$path_dir/$wxconfig"
				echo $_wxconfig
				# Save the prefix
				_wxpath=$path_dir
				if test `basename $path_dir` = bin ; then
					_wxpath=`dirname $path_dir`
				fi
				# break at first wx-config found in path
				break 2
			fi
		done
	done

	IFS="$ac_save_ifs"

	if test -z "$_wxconfig"; then
		echo "none found!"
	fi
}

#
# Determine freetype-config
#
find_freetypeconfig() {
	echo_n "Looking for freetype-config... "
	freetypeconfigs="$_freetypeconfig"
	_freetypeconfig=

	IFS="${IFS=   }"; ac_save_ifs="$IFS"; IFS="$SEPARATOR"
	for path_dir in $_freetypepath; do
		#reset separator to parse freetypeconfigs
		IFS=":"
		for freetypeconfig in $freetypeconfigs; do
			if test -f "$path_dir/$freetypeconfig" ; then
				_freetypeconfig="$path_dir/$freetypeconfig"
				echo $_freetypeconfig
				# Save the prefix
				_freetypepath=$path_dir
				if test `basename $path_dir` = bin ; then
					_freetypepath=`dirname $path_dir`
				fi
				# break at first freetype-config found in path
				break 2
			fi
		done
	done

	IFS="$ac_save_ifs"

	if test -z "$_freetypeconfig"; then
		echo "none found!"
	fi
}

#
# Determine extension used for executables
#
get_system_exe_extension() {
	case $1 in
	riscos)
		_exeext=",e1f"
		;;
	dreamcast | ds | gamecube | n64 | ps2 | psp | wii)
		_exeext=".elf"
		;;
	gph-linux)
		_exeext=".gph"
		;;
	mingw* | *os2-emx | wince)
		_exeext=".exe"
		;;
	*)
		_exeext=""
		;;
	esac
}

#
# Generic options functions
#

# Show the configure help line for an option
option_help() {
	tmpopt=`echo $1 | sed 's/_/-/g'`
	option=`echo "--${tmpopt}                       " | sed "s/\(.\{23\}\).*/\1/"`
	echo "  ${option}  ${2}"
}

# Show an error about an unknown option
option_error() {
	echo "error: unrecognized option: $ac_option
Try \`$0 --help' for more information." >&2
	exit 1
}


#
# Greet user
#
echo "Running ScummVM Tools configure..."
echo "Configure run on" `date` > $TMPLOG

#
# Check any parameters we received
#

for parm in "$@" ; do
	if test "$parm" = "--help" || test "$parm" = "-help" || test "$parm" = "-h" ; then
		cat << EOF

Usage: $0 [OPTIONS]...

Configuration:
  -h, --help             display this help and exit

Installation directories:
  --prefix=DIR           use this prefix for installing the ScummVM Tools [/usr/local]
  --bindir=DIR           directory to install the tool binaries in [PREFIX/bin]
  --datadir=DIR          directory to install the GUI tool media files in [PREFIX/share]
  --mandir=DIR           directory to install the manpage in [PREFIX/share/man]
  --libdir=DIR           directory to install the plugins in [PREFIX/lib]

Special configuration feature:
  --host=HOST             cross-compile to target HOST (arm-linux, ...)

Optional Features:
  --disable-c++11          disable building as C++11 when the compiler allows that
  --disable-debug          disable building with debugging symbols
  --enable-Werror          treat warnings as errors
  --enable-profiling       enable profiling
  --enable-verbose-build   enable regular echoing of commands during build
                           process

Optional Libraries:
  --with-ogg-prefix=DIR    Prefix where libogg is installed (optional)
  --with-vorbis-prefix=DIR Prefix where libvorbis is installed (optional)
  --disable-vorbis         disable Ogg Vorbis support [autodetect]

  --with-tremor-prefix=DIR Prefix where tremor is installed (optional)
  --disable-tremor         disable tremor support [autodetect]

  --with-mad-prefix=DIR    Prefix where libmad is installed (optional)
  --disable-mad            disable libmad (MP3) support [autodetect]

  --with-flac-prefix=DIR   Prefix where libFLAC is installed (optional)
  --disable-flac           disable FLAC support [autodetect]

  --with-zlib-prefix=DIR   Prefix where zlib is installed (optional)
  --disable-zlib           disable zlib (compression) support [autodetect]

  --with-png-prefix=DIR    Prefix where libpng is installed (optional)
  --disable-png            disable libpng (compression) support [autodetect]

  --with-freetype2-prefix=DIR  prefix where the freetype-config script is
                               installed (optional)
  --disable-freetype2      disable freetype2 TTF library usage [autodetect]

  --with-wx-prefix=DIR     Prefix where wxwidgets is installed (optional)
  --disable-wxwidgets      disable wxwidgets (GUI) support [autodetect]

  --disable-iconv          disable iconv (Japanese font) support [autodetect]

  --with-boost-prefix=DIR  Prefix where Boost is installed (optional)
  --disable-boost          disable Boost support [autodetect]

Some influential environment variables:
  LDFLAGS            linker flags, e.g. -L<lib dir> if you have libraries in a
                     nonstandard directory <lib dir>
  CXX                C++ compiler command
  CXXFLAGS           C++ compiler flags
  CONFIGURE_NO_HOST  Ignore the cross-compile target set by the --host= option
  CPPFLAGS           C++ preprocessor flags, e.g. -I<include dir> if you have
                     headers in a nonstandard directory <include dir>
  PKG_CONFIG_LIBDIR  list of directories where pkg-config ‘.pc’ files are
                     looked up

EOF
		exit 0
	fi
done # for parm in ...

for ac_option in $@; do
	case "$ac_option" in
	# Silently ignore options valid for Autotools configure.
	--build=*)                                ;;
	--exec-prefix=*)                          ;;
	--program-prefix=*)                       ;;
	--sbindir=*)                              ;;
	--sysconfdir=*)                           ;;
	--includedir=*)                           ;;
	--libexecdir=*)                           ;;
	--localstatedir=*)                        ;;
	--sharedstatedir=*)                       ;;
	--infodir=*)                              ;;
	--disable-dependency-tracking)            ;;
	--enable-dependency-tracking)             ;;
	# End of ignored options.
	--enable-vorbis)          _vorbis=yes     ;;
	--disable-vorbis)         _vorbis=no      ;;
	--enable-tremor)          _tremor=yes     ;;
	--disable-tremor)         _tremor=no      ;;
	--enable-flac)            _flac=yes       ;;
	--disable-flac)           _flac=no        ;;
	--enable-mad)             _mad=yes        ;;
	--disable-mad)            _mad=no         ;;
	--enable-zlib)            _zlib=yes       ;;
	--disable-zlib)           _zlib=no        ;;
	--enable-png)             _png=yes        ;;
	--disable-png)            _png=no         ;;
	--enable-freetype2)       _freetype2=yes  ;;
	--disable-freetype2)      _freetype2=no   ;;
	--enable-wxwidgets)       _wxwidgets=yes  ;;
	--disable-wxwidgets)      _wxwidgets=no   ;;
	--enable-iconv)           _iconv=yes      ;;
	--disable-iconv)          _iconv=no       ;;
	--enable-boost)           _boost=yes      ;;
	--disable-boost)          _boost=no       ;;
	--enable-verbose-build)   _verbose_build=yes ;;
	--with-ogg-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		OGG_CFLAGS="-I$arg/include"
		OGG_LIBS="-L$arg/lib"
		;;
	--with-vorbis-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		VORBIS_CFLAGS="-I$arg/include"
		VORBIS_LIBS="-L$arg/lib"
		;;
	--with-tremor-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		TREMOR_CFLAGS="-I$arg/include"
		TREMOR_LIBS="-L$arg/lib"
		;;
	--with-flac-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		FLAC_CFLAGS="-I$arg/include"
		FLAC_LIBS="-L$arg/lib"
		;;
	--with-mad-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		MAD_CFLAGS="-I$arg/include"
		MAD_LIBS="-L$arg/lib"
		;;
	--with-zlib-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		ZLIB_CFLAGS="-I$arg/include"
		ZLIB_LIBS="-L$arg/lib"
		;;
	--with-png-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		PNG_CFLAGS="-I$arg/include"
		PNG_LIBS="-L$arg/lib"
		;;
	--with-freetype2-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		_freetypepath="$arg:$arg/bin"
		;;
	--with-wx-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		_wxpath="$arg:$arg/bin"
		;;
	--with-boost-prefix=*)
		arg=`echo $ac_option | cut -d '=' -f 2`
		BOOST_CFLAGS="-I$arg/include"
		BOOST_LIBS="-L$arg/lib"
		;;
	--with-staticlib-prefix=*)
		_staticlibpath=`echo $ac_option | cut -d '=' -f 2`
		;;
	--with-xcodetools-path=*)
		_xcodetoolspath=`echo $ac_option | cut -d '=' -f 2`
		;;
	--enable-debug)
		_debug_build=yes
		;;
	--disable-debug)
		_debug_build=no
		;;
	--enable-c++11)
		_use_cxx11=yes
		;;
	--disable-c++11)
		_use_cxx11=no
		;;
	--enable-Werror)
		CXXFLAGS="$CXXFLAGS -Werror"
		;;
	--enable-release)
		_release_build=yes
		;;
	--disable-release)
		_release_build=no
		;;
	--enable-profiling)
		_enable_prof=yes
		;;
	--host=*)
               if test -z "$CONFIGURE_NO_HOST"; then
                       _host=`echo $ac_option | cut -d '=' -f 2`
               else
                       echo "Ignoring --host option!" >&2
               fi
		;;
	--prefix=*)
		_prefix=`echo $ac_option | cut -d '=' -f 2`
		;;
	--bindir=*)
		_bindir=`echo $ac_option | cut -d '=' -f 2`
		;;
	--datadir=*)
		_datadir=`echo $ac_option | cut -d '=' -f 2`
		;;
	--mandir=*)
		_mandir=`echo $ac_option | cut -d '=' -f 2`
		;;
	--libdir=*)
		_libdir=`echo $ac_option | cut -d '=' -f 2`
		;;
	*)
		option_error
		;;
	esac;
done;

guessed_host=`$_srcdir/config.guess`
get_system_exe_extension $guessed_host
NATIVEEXEEXT=$_exeext

case $_host in
android | android-v7a)
	_host_os=android
	_host_cpu=arm
	_host_alias=arm-linux-androideabi
	;;
bada)
	_host_os=bada
	if test "$_debug_build" = yes; then
		_host_cpu=i686
		_host_alias=i686-mingw32
	else
		_host_cpu=arm
		_host_alias=arm-samsung-nucleuseabi
	fi
	;;
caanoo)
	_host_os=gph-linux
	_host_cpu=arm
	_host_alias=arm-none-linux-gnueabi
	;;
dingux)
	_host_os=linux
	_host_cpu=mipsel
	_host_alias=mipsel-linux
	;;
dreamcast)
	_host_os=dreamcast
	_host_cpu=sh
	_host_alias=sh-elf
	CXXFLAGS="$CXXFLAGS -ml -m4-single-only"
	LDFLAGS="$LDFLAGS -ml -m4-single-only"
	;;
ds)
	_host_os=ds
	_host_cpu=arm
	_host_alias=arm-eabi
	;;
gamecube)
	_host_os=gamecube
	_host_cpu=ppc
	_host_alias=powerpc-gekko
	;;
gp2x)
	_host_os=gph-linux
	_host_cpu=arm
	_host_alias=arm-open2x-linux
	;;
gp2xwiz)
	_host_os=gph-linux
	_host_cpu=arm
	_host_alias=arm-open2x-linux
	;;
i586-mingw32msvc)
	_host_os=mingw32msvc
	_host_cpu=i586
	;;
iphone)
	_host_os=iphone
	_host_cpu=arm
	_host_alias=arm-apple-darwin9
	;;
linupy)
	_host_os=linux
	_host_cpu=arm
	;;
maemo)
	_host_os=maemo
	_host_cpu=arm
	_host_alias=arm-linux

	# The prefix is always the same on Maemo so we hardcode the default
	# here. It is still possible to define a custom prefix which is
	# needed when packaging the app with a user-specific app ID.
	test "x$prefix" = xNONE && prefix=/opt/scummvm
	# Maemo apps are installed into app-specific directories. The
	# default directory structure of ScummVM makes no sense here so we
	# hardcode Maemo specific directories here.
	datarootdir='${prefix}/share'
	datadir=/opt/scummvm/share
	docdir='${datarootdir}/doc/scummvm'
	;;
motoezx)
	_host_os=linux
	_host_cpu=arm
	_host_alias=arm-linux-gnu
	;;
motomagx)
	_host_os=linux
	_host_cpu=arm
	_host_alias=arm-linux-gnueabi
	;;
n64)
	_host_os=n64
	_host_cpu=mips
	_host_alias=mips64
	;;
neuros)
	_host_os=linux
	_host_cpu=arm
	;;
openpandora)
	_host_os=linux
	_host_cpu=arm
	_host_alias=arm-angstrom-linux-gnueabi
	;;
ppc-amigaos)
	_host_os=amigaos
	_host_cpu=ppc
	;;
ppc-morphos)
	_host_os=morphos
	_host_cpu=ppc
	;;
ps2)
	_host_os=ps2
	_host_cpu=mips64r5900el
	_host_alias=ee
	;;
ps3)
	_host_os=ps3
	_host_cpu=ppc
	_host_alias=powerpc64-ps3-elf

	# The prefix is always the same on PS3 so we hardcode the default
	# here. It is still possible to define a custom prefix which is
	# needed when packaging the app with a user-specific app ID.
	test "x$prefix" = xNONE && prefix=/dev_hdd0/game/SCUM12000/USRDIR
	# PS3 apps are installed into app-specific directories. The
	# default directory structure of ScummVM makes no sense here so we
	# hardcode PS3 specific directories here.
	datarootdir='${prefix}/data'
	datadir='${datarootdir}'
	docdir='${prefix}/doc'
	;;
psp)
	_host_os=psp
	_host_cpu=mipsallegrexel
	_host_alias=psp
	;;
raspberrypi)
	_host_os=linux
	_host_cpu=arm
	# This tuple is the one used by the official Rpi toolchain.
	# It may change in the future.
	_host_alias=arm-linux-gnueabihf
	;;
samsungtv)
	_host_os=linux
	_host_cpu=arm
	_host_alias=arm-linux-gnueabi
	;;
webos)
	_host_os=webos
	_host_cpu=arm
	_host_alias=arm-none-linux-gnueabi
	# The prefix is always the same on WebOS so we hardcode the default
	# here. It is still possible to define a custom prefix which is
	# needed when packaging the app with a user-specific app ID.
	test "x$prefix" = xNONE && prefix=/media/cryptofs/apps/usr/palm/applications/org.scummvm.scummvm
	# WebOS apps are installed into app-specific directories. The
	# default directory structure of ScummVM makes no sense here so we
	# hardcode WebOS specific directories here.
	datarootdir='${prefix}/data'
	datadir='${datarootdir}'
	docdir='${prefix}/doc'
	;;
wii)
	_host_os=wii
	_host_cpu=ppc
	_host_alias=powerpc-gekko
	;;
wince)
	_host_os=wince
	_host_cpu=arm
	_host_alias=arm-mingw32ce
	;;
*)
	if test -n "$_host"; then
		guessed_host=`$_srcdir/config.sub $_host`
	fi
	_host_cpu=`echo $guessed_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
	_host_vendor=`echo $guessed_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
	_host_os=`echo $guessed_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
	;;
esac

if test -z "$_host_alias"; then
	_host_alias="$_host_cpu-$_host_os"
else
	# if _host_alias was set, default to the standard GNU tools
	_ranlib=$_host_alias-ranlib
	_strip=$_host_alias-strip
	_ar="$_host_alias-ar cru"
	_as="$_host_alias-as"
	_windres=$_host_alias-windres
fi

#
# Determine extra build flags for debug and/or release builds
#

if test "$_debug_build" != no; then
	# debug mode not explicitly disabled -> compile with -g
	CXXFLAGS="$CXXFLAGS -g"
fi

if test "$_release_build" = yes; then
	# Release mode enabled: enable optimizations. This also
	# makes it possible to use -Wuninitialized, so let's do that.
	CXXFLAGS="$CXXFLAGS -O2"
	CXXFLAGS="$CXXFLAGS -Wuninitialized"
fi


#
# Determine extension used for executables
#
get_system_exe_extension $_host_os
HOSTEXEEXT=$_exeext

#
# Determine separator used for $PATH
#
case $_host_os in
os2-emx*)
	SEPARATOR=";"
	;;
*)
	SEPARATOR=":"
	;;
esac

#
# Determine the C++ compiler
#
echo_n "Looking for C++ compiler... "

# Check whether the given command is a working C++ compiler
test_compiler() {
	cat > tmp_cxx_compiler.cpp << EOF
	class Foo { int a; };
	int main(int argc, char **argv) {
		Foo *a = new Foo(); delete a; return 0;
	}
EOF

	echo "testing compiler: $1" >> "$TMPLOG"

	if test -n "$_host"; then
		# In cross-compiling mode, we cannot run the result
		eval "$1 $CXXFLAGS $LDFLAGS -o $TMPO.o -c tmp_cxx_compiler.cpp" 2> /dev/null && cc_check_clean tmp_cxx_compiler.cpp
	else
		eval "$1 $CXXFLAGS $LDFLAGS -o $TMPO$HOSTEXEEXT tmp_cxx_compiler.cpp" 2> /dev/null && eval "$TMPO$HOSTEXEEXT 2> /dev/null" && cc_check_clean tmp_cxx_compiler.cpp
	fi
}

# Prepare a list of candidates for the C++ compiler
if test -n "$CXX" && test_compiler "$CXX"; then
	# Use the compiler specified in CXX
	echo $CXX
else
	if test -n "$_host"; then
		compilers="$_host_alias-g++ $_host_alias-c++ $_host-g++ $_host-c++"
	else
		compilers="g++ c++ CC"
	fi

	# Iterate over all candidates, pick the first working one
	CXX=
	for compiler in $compilers; do
		if test_compiler $compiler; then
			echo "success testing compiler: $compiler" >> "$TMPLOG"
			CXX=$compiler
			echo $CXX
			break
		else
			echo "failure testing compiler: $compiler" >> "$TMPLOG"
		fi
	done
fi

if test -z "$CXX"; then
	echo "none found!"
	exit 1
fi

# By default, use the C++ compiler as linker
LD=$CXX

#
# Determine the compiler version
#
echocheck "compiler version"

have_gcc=no
cc_check_define __GNUC__ && have_gcc=yes

if test "$have_gcc" = yes; then
	add_line_to_config_mk 'HAVE_GCC = 1'
	_cxx_major=`gcc_get_define __GNUC__`
	_cxx_minor=`gcc_get_define __GNUC_MINOR__`
	cxx_version="`( $CXX -dumpversion ) 2>&1`"

	if test -n "`gcc_get_define __clang__`"; then
		add_line_to_config_mk 'HAVE_CLANG = 1'
	fi

	if test "$_cxx_major" -eq 2 && test "$_cxx_minor" -ge 95 || \
	   test "$_cxx_major" -gt 2 ; then
		cxx_version="$cxx_version, ok"
		cxx_verc_fail=no
	else
		cxx_version="$cxx_version, bad"
		cxx_verc_fail=yes
	fi
else
	# TODO: Big scary warning about unsupported compilers
	cxx_version=`( $CXX -version ) 2>&1`
	if test "$?" -eq 0; then
		cxx_version="`echo "${cxx_version}" | sed -ne 's/^.*[^0-9]\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*$/\1/gp'`"
		if test -z "${cxx_version}"; then
			cxx_version="not found"
			cxx_verc_fail=yes
		fi
	else
		cxx_version="not found"
		cxx_verc_fail=yes
	fi

	case $_host_os in
		irix*)
			case $cxx_version in
				7.4.4*)
					# We just assume this is SGI MIPSpro
					_cxx_major=7
					_cxx_minor=4
					cxx_verc_fail=no
					add_line_to_config_mk 'CXX_UPDATE_DEP_FLAG = -MDupdate "$(*D)/$(DEPDIR)/$(*F).d"'
					add_line_to_config_mk '-include Makedepend'
					;;
				*)
					cxx_version="$cxx_version, bad"
					cxx_verc_fail=yes
					;;
			esac
			;;
		solaris*)
			cxx_version=`( $CXX -V ) 2>&1`
			cxx_version="`echo "${cxx_version}" | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\).*/\1/'`"

			case $cxx_version in
				5.1[0-2])
					cxx_verc_fail=no
					;;
				*)
					cxx_version="$cxx_version, bad"
					cxx_verc_fail=yes
					;;
			esac
			;;
		*)
			cxx_version="$cxx_version, bad"
			cxx_verc_fail=yes
			;;
	esac
fi

echo "$cxx_version"

if test "$cxx_verc_fail" = yes ; then
	echo
	echo "The version of your compiler is not supported at this time"
	echo "Please ensure you are using GCC >= 2.95"
	exit 1
else
	echo found non-gcc compiler version ${cxx_version}
fi

#
# Check whether the compiler supports C++11
#
have_cxx11=no
cat > $TMPC << EOF
int main(int argc, char *argv[]) { if (argv == nullptr) return -1; else return 0; }
EOF
cc_check -std=c++11 && have_cxx11=yes
if test "$_use_cxx11" = "yes" ; then
	_use_cxx11=$have_cxx11
fi

#
# Setup compiler specific CXXFLAGS now that we know the compiler version.
# Foremost, this means enabling various warnings.
# In addition, we set CXX_UPDATE_DEP_FLAG for GCC >= 3.0 and for ICC.
#
if test "$have_gcc" = yes ; then
	if test "$_cxx_major" -ge "3" ; then
		# Try to use ANSI mode when C++11 is disabled.
		if test "$_use_cxx11" = "no" ; then
			case $_host_os in
			# newlib-based system include files suppress non-C89 function
			# declarations under __STRICT_ANSI__
			amigaos* | android | dreamcast | ds | gamecube | mingw* | morphos* |n64 | psp | ps2 | wii | wince )
				;;
			*)
				CXXFLAGS="$CXXFLAGS -ansi"
				;;
			esac
		fi
		CXXFLAGS="$CXXFLAGS -W -Wno-unused-parameter"
		add_line_to_config_mk 'HAVE_GCC3 = 1'
		add_line_to_config_mk 'CXX_UPDATE_DEP_FLAG = -MMD -MF "$(*D)/$(DEPDIR)/$(*F).d" -MQ "$@" -MP'
	fi

	if test "$_cxx_major" -eq 4 && test "$_cxx_minor" -ge 3 || \
	   test "$_cxx_major" -gt 4 ; then
		CXXFLAGS="$CXXFLAGS -Wno-empty-body"
	else
		CXXFLAGS="$CXXFLAGS -Wconversion"
	fi
fi

echo_n "Building as C++11... "
if test "$_use_cxx11" = "yes" ; then
	case $_host_os in
	# newlib-based system include files suppress non-C89 function
	# declarations under __STRICT_ANSI__
	amigaos* | android | dreamcast | ds | gamecube | mingw* | morphos* | n64 | psp | ps2 | wii | wince )
		_use_cxx11=no
		;;
	*)
		CXXFLAGS="$CXXFLAGS -std=c++11"
		;;
	esac
fi
echo $_use_cxx11


# By default, we add -pedantic to the CXXFLAGS to catch some potentially
# non-portable constructs, like use of GNU extensions.
# However, some platforms use GNU extensions in system header files, so
# for these we must not use -pedantic.
case $_host_os in
android | gamecube | psp | wii)
	;;
*)
	# ICC does not support pedantic, while GCC and clang do.
	if test "$have_icc" = no ; then
		CXXFLAGS="$CXXFLAGS -pedantic"
	fi
	;;
esac

# Check if std::nullptr_t is available
echo_n "Checking if C++11 std::nullptr_t is available..."
cat > $TMPC << EOF
#include <cstddef>
int main(int argc, char *argv[]) {
	std::nullptr_t i = nullptr;
	return 0;
}
EOF
cc_check
if test "$TMPR" -eq 0; then
		echo yes
else
		echo no
		define_in_config_if_yes yes 'NO_CXX11_NULLPTR_T'
fi

if test -n "$STRINGS"; then
	_strings=$STRINGS
else
	echo_n "Checking for $_host_alias-strings... " >> "$TMPLOG"
	if `which $_host_alias-strings >/dev/null 2>&1`; then
		_strings=$_host_alias-strings
		echo yes >> "$TMPLOG"
	else
		_strings=strings
		echo no >> "$TMPLOG"
	fi
fi

#
# Check for endianness
#
echo_n "Checking endianness... "
cat > tmp_endianness_check.cpp << EOF
unsigned short ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
unsigned short ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
void _ascii() { char* s = (char*) ascii_mm; s = (char*) ascii_ii; }
unsigned short ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
unsigned short ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
void _ebcdic() { char* s = (char*) ebcdic_mm; s = (char*) ebcdic_ii; }
int main() { _ascii (); _ebcdic (); return 0; }
EOF
$CXX $CXXFLAGS -c -o $TMPO.o tmp_endianness_check.cpp
if $_strings $TMPO.o | grep BIGenDianSyS >/dev/null; then
	_endian=big
elif $_strings $TMPO.o | grep LiTTleEnDian >/dev/null; then
	_endian=little
fi
echo $_endian;
cc_check_clean tmp_endianness_check.cpp

case $_endian in
	big)
		add_line_to_config_h '#undef SCUMM_LITTLE_ENDIAN'
		add_line_to_config_h '#define SCUMM_BIG_ENDIAN'
		;;
	little)
		add_line_to_config_h '#define SCUMM_LITTLE_ENDIAN'
		add_line_to_config_h '#undef SCUMM_BIG_ENDIAN'
		;;
	*)
		exit 1
		;;
esac

#
# Determine a data type with the given length
#
find_type_with_size() {
	for datatype in int short char long "long long" unknown; do
		cat > tmp_find_type_with_size.cpp << EOF
typedef $datatype ac__type_sizeof_;
int main() {
	static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) == $1)];
	test_array [0] = 0;
	return 0;
}
EOF
		if $CXX $CXXFLAGS -c -o $TMPO.o tmp_find_type_with_size.cpp 2>/dev/null ; then
			break
		else
			if test "$datatype" = "unknown"; then
				echo "couldn't find data type with $1 bytes"
				exit 1
			fi
			continue
		fi
	done
	cc_check_clean tmp_find_type_with_size.cpp
	echo "$datatype"
}

#
# Determine data type sizes
#
echo_n "Type with 1 byte... "
type_1_byte=`find_type_with_size 1`
TMPR="$?"
echo "$type_1_byte"
test $TMPR -eq 0 || exit 1	# check exit code of subshell

echo_n "Type with 2 bytes... "
type_2_byte=`find_type_with_size 2`
TMPR="$?"
echo "$type_2_byte"
test $TMPR -eq 0 || exit 1	# check exit code of subshell

echo_n "Type with 4 bytes... "
type_4_byte=`find_type_with_size 4`
TMPR="$?"
echo "$type_4_byte"
test $TMPR -eq 0 || exit 1	# check exit code of subshell

echo_n "Type with 8 bytes... "
type_8_byte=`find_type_with_size 8`
TMPR="$?"
echo "$type_8_byte"
test $TMPR -eq 0 || exit 1	# check exit code of subshell

#
# Check whether memory alignment is required
#
# For some CPU types, unaligned memory access is either not supported at
# all (and so leads to a crash), requires a super-slow emulation via an
# exception handler, or just results in incorrect results.
# On the other hand, accessing data in a manner that works regardless of
# alignment can be a lot slower than regular access, so we don't want
# to use it if we don't have to.
#
# So we do the following: For CPU families where we know whether unaligned
# access is safe & fast, we enable / disable unaligned access accordingly.
# Otherwise, we just disable memory alignment.
#
# NOTE: In the past, for non-cross compiled builds, we would also run some code
# which would try to test whether unaligned access worked or not. But this test
# could not reliably determine whether unaligned access really worked in all
# situations (and across different implementations of the target CPU arch), nor
# whether it was fast (as opposed to slowly emulated by fault handlers). Hence,
# we do not use this approach anymore.
#
# NOTE: The only kinds of unaligned access we allow are for 2 byte and 4
# byte loads / stores. No promises are made for bigger sizes, such as 8
# or 16 byte loads, for which architectures may behave differently than
# for the smaller sizes.
echo_n "Alignment required... "
case $_host_cpu in
	i[3-6]86 | x86_64 | ppc*)
		# Unaligned access should work
		_need_memalign=no
		;;
	alpha* | arm* | bfin* | hp* | mips* | sh* | sparc* | ia64 | nv1*)
		# Unaligned access is not supported or extremely slow.
		_need_memalign=yes
		;;
	*)
		# Status of unaligned access is unknown, so assume the worst.
		_need_memalign=yes
		;;
esac
echo "$_need_memalign"

define_in_config_h_if_yes $_need_memalign 'SCUMM_NEED_ALIGNMENT'

#
# Determine build settings
#
echo_n "Checking hosttype... "
echo $_host_os
case $_host_os in
	amigaos*)
		add_line_to_config_mk 'AMIGAOS = 1'
		# Use 'long' for ScummVM's 4 byte typedef, because AmigaOS
		# already typedefs (u)int32 as (unsigned) long and suppress
		# those noisy format warnings caused by the 'long' 4 byte
		type_4_byte='long'
		CXXFLAGS="$CXXFLAGS -Wno-format"
		# Dependencies might also be compiled with stack protection
		LDFLAGS="$LDFLAGS -L/sdk/local/newlib/lib -fstack-protector"
		;;
	beos*)
		DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
		# Needs -lbind -lsocket for the timidity MIDI driver
		LDFLAGS="-L/boot/home/config/lib"
		CFLAGS="-I/boot/home/config/include"
		CXXFLAGS="$CXXFLAGS -fhuge-objects"
		LIBS="$LIBS -lbind -lsocket"
		_seq_midi=no
		;;
	cygwin*)
		echo ERROR: Cygwin building is not supported by ScummVM anymore. Consider using MinGW.
		exit 1
		;;
	darwin*)
		DEFINES="$DEFINES -DMACOSX"
		LIBS="$LIBS -framework AudioUnit -framework AudioToolbox -framework Carbon -framework CoreMIDI"
		add_line_to_config_mk 'MACOSX = 1'

		# Now we may have MacPorts or Fink installed
		# Which put libraries and headers in non-standard places
		# Checking them here

		# MacPorts
		# There is no way to get the prefix, so implementing a hack here
		macport_version=`port version 2>/dev/null`
		if test "$?" -eq 0; then
			macport_version="`echo "${macport_version}" | sed -ne 's/Version: \([0-9]\.[0-9]\.[0-9]\)/\1/gp'`"
			echo_n "You seem to be running MacPorts version ${macport_version}..."

			macport_prefix=`which port`
			# strip off /bin/port from /opt/local/bin/port
			macport_prefix=`dirname ${macport_prefix}`
			macport_prefix=`dirname ${macport_prefix}`

			echo "adding ${macport_prefix} to paths"

			LDFLAGS="-L${macport_prefix}/lib $LDFLAGS"
			CXXFLAGS="-I${macport_prefix}/include $CXXFLAGS"

			if test -z "$_staticlibpath"; then
				_staticlibpath=${macport_prefix}
				echo "Set staticlib-prefix to ${_staticlibpath}"
			fi
		fi

		# Fink
		# There is no way to get the prefix, so implementing a hack here
		fink_version=`fink -V 2>/dev/null`
		if test "$?" -eq 0; then
			fink_version="`echo "${fink_version}" | sed -ne 's/Package manager version: \([0-9.]*\)/\1/gp'`"
			echo_n "You seem to be running Fink version ${fink_version}..."

			fink_prefix=`which fink`
			# strip off /bin/fink from /sw/bin/port
			fink_prefix=`dirname ${fink_prefix}`
			fink_prefix=`dirname ${fink_prefix}`

			echo "adding ${fink_prefix} to paths"

			LDFLAGS="-L${fink_prefix}/lib $LDFLAGS"
			CXXFLAGS="-I${fink_prefix}/include $CXXFLAGS"

			if test -z "$_staticlibpath"; then
				_staticlibpath=${fink_prefix}
				echo "Set staticlib-prefix to ${_staticlibpath}"
			fi
		fi

		# Homebrew
		brew_version=`brew -v 2>/dev/null`
		if test "$?" -eq 0; then
			brew_version="`echo "${brew_version}" | sed -ne 's/Homebrew \([0-9.]*\)/\1/gp'`"
			echo_n "You seem to be running Homebrew version ${brew_version}..."

			brew_prefix=`brew --prefix`

			echo "adding ${brew_prefix} to paths"

			LDFLAGS="-L${brew_prefix}/lib $LDFLAGS"
			CXXFLAGS="-I${brew_prefix}/include $CXXFLAGS"

			if test -z "$_staticlibpath"; then
				_staticlibpath=${brew_prefix}
				echo "Set staticlib-prefix to ${_staticlibpath}"
			fi
		fi

		# If _staticlibpath is not set yet try first /sw (fink) then /usr/local
		# (the macports case is handled above).
		if test -z "$_staticlibpath"; then
			if test -d "/sw"; then
				_staticlibpath=/sw
				echo "Set staticlib-prefix to ${_staticlibpath}"
			elif test -d "/usr/local"; then
				_staticlibpath=/usr/local
				echo "Set staticlib-prefix to ${_staticlibpath}"
			else
				echo "Could not determine prefix for static libraries"
			fi
		fi

		# If _xcodetoolspath is not set yet use xcode-select to get the path
		if test -z "$_xcodetoolspath"; then
			_xcodetoolspath=`xcode-select -print-path`/Tools
			if test -d "$_xcodetoolspath"; then
				echo "Set xcodetools-path to ${_xcodetoolspath}"
			else
				_xcodetoolspath=
				echo "Could not determine path for Xcode Tools"
			fi
		fi
		;;
	freebsd*)
		LDFLAGS="$LDFLAGS -L/usr/local/lib"
		CXXFLAGS="$CXXFLAGS -I/usr/local/include"
		;;
	haiku*)
		DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
		# Needs -lnetwork for the timidity MIDI driver
		LIBS="$LIBS -lnetwork"
		_seq_midi=no
		;;
	irix*)
		DEFINES="$DEFINES -DIRIX"
		DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
		LIBS="$LIBS -lmd -lfastm -lm"
		_ranlib=:
		;;
	linux* | uclinux*)
		# When not cross-compiling, enable large file support, but don't
		# care if getconf doesn't exist or doesn't recognize LFS_CFLAGS.
		if test -z "$_host"; then
			CXXFLAGS="$CXXFLAGS $(getconf LFS_CFLAGS 2>/dev/null)"
		fi
		;;
	mingw*)
		DEFINES="$DEFINES -DWIN32"
		# append_var DEFINES "-D__USE_MINGW_ANSI_STDIO=0"  # Modern MinGW does not need it
		LDFLAGS="$LDFLAGS -static-libgcc -static-libstdc++"
		LIBS="$LIBS -lmingw32 -lwinmm"
		OBJS="$OBJS scummvmtoolswinres.o"
		add_line_to_config_mk 'WIN32 = 1'
		;;
	mint*)
		DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
		;;
	morphos*)
		LDFLAGS="$LDFLAGS -L/usr/local/lib -noixemul"
		CXXFLAGS="$CXXFLAGS -D__MORPHOS_SHAREDLIBS"
		# We have to use 'long' for our 4 byte typedef because MorphOS already typedefs (u)int32
		# as (unsigned) long, and consequently we'd get a compiler error otherwise.
		type_4_byte='long'
		add_line_to_config_mk 'MORPHOS = 1'
		;;
	riscos)
		DEFINES="$DEFINES -DRISCOS"
		add_line_to_config_mk 'RISCOS = 1'
		LDFLAGS="$LDFLAGS -L$GCCSDK_INSTALL_ENV/lib"
		CXXFLAGS="$CXXFLAGS -I$GCCSDK_INSTALL_ENV/include"
		_pkgconfig=$GCCSDK_INSTALL_ENV/ro-pkg-config
		_wxconfig=$GCCSDK_INSTALL_ENV/bin/wx-config
		_freetypepath=$GCCSDK_INSTALL_ENV/bin
		LDFLAGS="$LDFLAGS -static"
		;;
	solaris*)
		DEFINES="$DEFINES -DSOLARIS"
		DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
		# Needs -lbind -lsocket for the timidity MIDI driver
		LIBS="$LIBS -lnsl -lsocket"
		;;
esac

if test -n "$_host"; then
	# Cross-compiling mode - add your target here if needed
	echo "Cross-compiling to $_host"
	case "$_host" in
		arm-linux|arm*-linux-gnueabi|arm-*-linux)
			;;
		arm-*riscos)
			# toolchain binaries prefixed by host
			_ranlib=$_host-ranlib
			_strip=$_host-strip
			_ar="$_host-ar cru"
			_as="$_host-as"
			;;
		*darwin*)
			_ranlib=$_host-ranlib
			_strip=$_host-strip
			;;
		linupy)
			DEFINES="$DEFINES -DLINUPY"
			;;
		m68k-atari-mint)
			DEFINES="$DEFINES -DSYSTEM_NOT_SUPPORTING_D_TYPE"
			_ranlib=m68k-atari-mint-ranlib
			_ar="m68k-atari-mint-ar cru"
			;;
		*mingw32*)
			_windres=$_host-windres
			_ar="$_host-ar cru"
			_ranlib=$_host-ranlib
			;;
		mips-sgi*)
			LDFLAGS="$LDFLAGS -static-libgcc"
			LIBS="$LIBS -laudio"
			;;
		ppc-amigaos|ppc-morphos)
			# Only static builds link successfully on buildbot
			LDFLAGS=`echo $LDFLAGS | sed 's/-use-dynld//'`
			LDFLAGS="$LDFLAGS -static"

			# toolchain binaries prefixed by host
			_ranlib=$_host-ranlib
			_strip=$_host-strip
			_ar="$_host-ar cru"
			_as="$_host-as"
			_windres=$_host-windres
			;;
		raspberrypi)
			# This is needed because the official cross compiler doesn't have multiarch enabled
			# but Raspbian does.
			# Be careful as it's the linker (LDFLAGS) which must know about sysroot.
			# These are needed to build against Raspbian's libSDL.
			LDFLAGS="$LDFLAGS --sysroot=$RPI_ROOT"
			LDFLAGS="$LDFLAGS -B$RPI_ROOT/usr/lib/arm-linux-gnueabihf"
			LDFLAGS="$LDFLAGS -Xlinker --rpath-link=$RPI_ROOT/usr/lib/arm-linux-gnueabihf/pulseaudio"
			LDFLAGS="$LDFLAGS -Xlinker --rpath-link=$RPI_ROOT/usr/lib/arm-linux-gnueabihf"
			LDFLAGS="$LDFLAGS -Xlinker --rpath-link=$RPI_ROOT/lib/arm-linux-gnueabihf"
			LDFLAGS="$LDFLAGS -Xlinker --rpath-link=$RPI_ROOT/opt/vc/lib"
			LDFLAGS="$LDFLAGS -L$RPI_ROOT/opt/vc/lib"
			CXXFLAGS="$CXXFLAGS -isystem $RPI_ROOT/usr/include/arm-linux-gnueabihf"
			CXXFLAGS="$CXXFLAGS -I$RPI_ROOT/usr/include"
			# This is so optional OpenGL ES includes are found.
			CXXFLAGS="$CXXFLAGS -I$RPI_ROOT/opt/vc/include"
			;;
		*)
			echo "WARNING: Unknown target, continuing with auto-detected values"
			;;
	esac
fi

#
# Determine whether host is POSIX compliant, or at least POSIX
# compatible enough to support our POSIX code (including dlsym(),
# mkdir() and some other APIs).
#
# TODO: Instead of basing this on the host name, we should really base
# this on the presence of features (such as the dlsym and mkdir APIs).
#
echo_n "Checking if host is POSIX compliant... "
case $_host_os in
	amigaos* | cygwin* | dreamcast | ds | gamecube | mingw* | morphos* | n64 | ps2 | psp | wii | wince)
		_posix=no
		;;
	android | beos* | bsd* | darwin* | freebsd* | gph-linux | haiku* | hpux* | iphone | irix* | linux* | mint* | netbsd* | openbsd* | riscos | solaris* | sunos* | uclinux* | webos)
		_posix=yes
		;;
	os2-emx*)
		_posix=yes	# FIXME: Really???
		;;
	*)
		# given this is a shell script, we might assume some type of posix.
		# However, the host system might be a totally different one, so
		# we can assume nothing about it.
		# Indeed, as mentioned further above, we really should test for the
		# presences of relevant APIs on the host anyway...
		_posix=no
		;;
esac
echo $_posix

if test "$_posix" = yes ; then
	DEFINES="$DEFINES -DPOSIX"
	add_line_to_config_mk 'POSIX = 1'
fi

#
# Check whether to enable a verbose build
#
echo_n "Checking whether to have a verbose build... "
echo "$_verbose_build"
add_to_config_mk_if_yes "$_verbose_build" 'VERBOSE_BUILD = 1'

#
# Check for math lib
#
cat > $TMPC << EOF
int main(void) { return 0; }
EOF
cc_check -lm && LDFLAGS="$LDFLAGS -lm"

#
# Check for pkg-config
#
echocheck "pkg-config"
_pkg_config=no
command -v $_pkgconfig >/dev/null 2>&1 && _pkg_config=yes
echo "$_pkg_config"

if test "$_pkg_config" = yes && test -n "$_host" && test -z "$PKG_CONFIG_LIBDIR"; then
	echo "WARNING: When cross-compiling PKG_CONFIG_LIBDIR must be set to the location of the .pc files for the target"
fi

#
# Check for Ogg Vorbis
#
echocheck "Ogg Vorbis"
if test "$_vorbis" = auto ; then
	_vorbis=no
	cat > $TMPC << EOF
#include <vorbis/codec.h>
int main(void) { vorbis_packet_blocksize(0,0); return 0; }
EOF
	cc_check $OGG_CFLAGS $OGG_LIBS $VORBIS_CFLAGS $VORBIS_LIBS \
		-lvorbisfile -lvorbis -logg && _vorbis=yes
fi
if test "$_vorbis" = yes ; then
	LIBS="$LIBS $OGG_LIBS $VORBIS_LIBS -lvorbisfile -lvorbis -lvorbisenc -logg"
	INCLUDES="$INCLUDES $OGG_CFLAGS $VORBIS_CFLAGS"
fi
define_in_config_if_yes "$_vorbis" 'USE_VORBIS'
echo "$_vorbis"

#
# Check for Tremor
#
echocheck "Tremor"
if test "$_tremor" = auto ; then
	_tremor=no
	cat > $TMPC << EOF
#include <tremor/ivorbiscodec.h>
int main(void) { vorbis_info_init(0); return 0; }
EOF
	cc_check $TREMOR_CFLAGS $TREMOR_LIBS -lvorbisidec && \
	_tremor=yes
fi
if test "$_tremor" = yes && test "$_vorbis" = no; then
	add_line_to_config_h '#define USE_TREMOR'
	add_line_to_config_h '#define USE_VORBIS'
	LIBS="$LIBS $TREMOR_LIBS -lvorbisenc"
	INCLUDES="$INCLUDES $TREMOR_CFLAGS"
else
	if test "$_vorbis" = yes; then
		_tremor="no (Ogg Vorbis/Tremor support is mutually exclusive)"
	fi
	add_line_to_config_h '#undef USE_TREMOR'
fi
add_to_config_mk_if_yes "$_tremor" 'USE_TREMOR = 1'
echo "$_tremor"

#
# Check for FLAC
#
echocheck "FLAC >= 1.1.3"
if test "$_flac" = auto ; then
	_flac=no
	cat > $TMPC << EOF
#include <FLAC/format.h>
#include <FLAC/stream_encoder.h>
FLAC__StreamEncoderInitStatus x;
int main(void) { return FLAC__STREAM_SYNC_LEN >> 30; /* guaranteed to be 0 */ }
EOF
	if test "$_vorbis" = yes ; then
		cc_check $FLAC_CFLAGS $FLAC_LIBS $OGG_CFLAGS $OGG_LIBS \
			-lFLAC -logg && _flac=yes
	else
		cc_check $FLAC_CFLAGS $FLAC_LIBS \
			-lFLAC && _flac=yes
	fi
fi
if test "$_flac" = yes ; then
	if test "$_vorbis" = yes ; then
		LIBS="$LIBS $FLAC_LIBS $OGG_LIBS -lFLAC -logg"
	else
		LIBS="$LIBS $FLAC_LIBS -lFLAC"
	fi
	INCLUDES="$INCLUDES $FLAC_CFLAGS"
fi
define_in_config_if_yes "$_flac" 'USE_FLAC'
echo "$_flac"

#
# Check for MAD (MP3 library)
#
echocheck "MAD"
if test "$_mad" = auto ; then
	_mad=no
	cat > $TMPC << EOF
#include <mad.h>
int main(void) { return 0; }
EOF
	cc_check $MAD_CFLAGS $MAD_LIBS -lmad && _mad=yes
fi
if test "$_mad" = yes ; then
	LIBS="$LIBS $MAD_LIBS -lmad"
	INCLUDES="$INCLUDES $MAD_CFLAGS"
fi
define_in_config_if_yes "$_mad" 'USE_MAD'
echo "$_mad"

#
# Check for PNG
#
echocheck "PNG >= 1.2.8"
if test "$_pkg_config" = "yes" && $_pkgconfig --exists libpng; then
	PNG_LIBS="$PNG_LIBS `$_pkgconfig --libs libpng`"
	PNG_CFLAGS="$PNG_CFLAGS `$_pkgconfig --cflags libpng`"
else
	PNG_LIBS="$PNG_LIBS -lpng -lz"
fi
if test "$_png" = auto ; then
	_png=no
	cat > $TMPC << EOF
#include <png.h>
int main(void) {
#if PNG_LIBPNG_VER >= 10208
#else
  syntax error
#endif
  return 0;
}
EOF
	cc_check $PNG_CFLAGS $PNG_LIBS && _png=yes
fi
if test "$_png" = yes ; then
	LIBS="$LIBS $PNG_LIBS"
	INCLUDES="$INCLUDES $PNG_CFLAGS"
fi
define_in_config_if_yes "$_png" 'USE_PNG'
echo "$_png"

#
# Check for ZLib
#
echocheck "zlib"
if test "$_zlib" = auto ; then
	_zlib=no
	cat > $TMPC << EOF
#include <string.h>
#include <zlib.h>
int main(void) { return strcmp(ZLIB_VERSION, zlibVersion()); }
EOF
	cc_check $ZLIB_CFLAGS $ZLIB_LIBS -lz && _zlib=yes
fi
if test "$_zlib" = yes ; then
	LIBS="$LIBS $ZLIB_LIBS -lz"
	INCLUDES="$INCLUDES $ZLIB_CFLAGS"
fi
define_in_config_if_yes "$_zlib" 'USE_ZLIB'
echo "$_zlib"

#
# Check for FreeType2 to be present
#
find_freetype() {
        # Wrapper function which tries to find freetype
        # either by calling freetype-config or by using
        # pkg-config.
        # As of freetype-2.9.1 the freetype-config file
        # no longer gets installed by default.
	if test "$_pkg_config" = "yes" && $_pkgconfig --exists freetype2; then
		FREETYPE2_LIBS=`$_pkgconfig --libs freetype2`
		FREETYPE2_CFLAGS=`$_pkgconfig --cflags freetype2`
		FREETYPE2_STATIC_LIBS=`$_pkgconfig --static --libs freetype2`
		_freetype_found="true"
	else
		# Look for the freetype-config script
		find_freetypeconfig
		if test -n "$_freetypeconfig"; then
			# Since 2.3.12, freetype-config prepends $SYSROOT to everything.
			# This means we can't pass it a --prefix that includes $SYSROOT.
			freetypeprefix="$_freetypepath"
			if test -n "$SYSROOT" -a "$SYSROOT" != "/"; then
				teststring=VeryImplausibleSysrootX1Y2Z3
				if ( env SYSROOT=/$teststring "$_freetypeconfig" --cflags | grep $teststring 2> /dev/null > /dev/null ); then
					echo "Adapting FreeType prefix to SYSROOT" >> "$TMPLOG"
					freetypeprefix="${freetypeprefix##$SYSROOT}"
				fi
			fi
			FREETYPE2_LIBS=`$_freetypeconfig --prefix="$freetypeprefix" --libs`
			FREETYPE2_CFLAGS=`$_freetypeconfig --prefix="$freetypeprefix" --cflags`
			FREETYPE2_STATIC_LIBS=`$_freetypeconfig --prefix="$freetypeprefix" --static --libs 2>/dev/null`
			_freetype_found="true"
		fi
	fi
}

if test "$_freetype2" != "no"; then
	find_freetype
	if test $_freetype_found != true; then
		_freetype2=no
	else
		if test "$_freetype2" = "auto"; then
			_freetype2=no

			cat > $TMPC << EOF
#include <ft2build.h>
#include FT_FREETYPE_H

int main(int argc, char *argv[]) {
	FT_Library library;
	FT_Error error = FT_Init_FreeType(&library);
	FT_Done_FreeType(library);
}
EOF

			cc_check_no_clean $FREETYPE2_CFLAGS $FREETYPE2_LIBS && _freetype2=yes
			# Modern freetype-config scripts accept --static to get all
			# required flags for static linking. We abuse this to detect
			# FreeType2 builds which are static themselves.
			if test "$_freetype2" != "yes"; then
				FREETYPE2_LIBS="$FREETYPE2_STATIC_LIBS"
				cc_check_no_clean $FREETYPE2_CFLAGS $FREETYPE2_LIBS && _freetype2=yes
			fi
			cc_check_clean
		fi

		if test "$_freetype2" = "yes"; then
			LIBS="$LIBS $FREETYPE2_LIBS"
			CXXFLAGS="$CXXFLAGS $FREETYPE2_CFLAGS"
		fi
	fi

fi

echocheck "FreeType2"
echo "$_freetype2"

define_in_config_if_yes "$_freetype2" "USE_FREETYPE2"

#
# Check for Boost
#
echocheck "Boost => 1.32.0"
if test "$_boost" = auto ; then
	_boost=no
	cat > $TMPC << EOF
#include <iostream>
#include <boost/version.hpp>
int main(void) { if (BOOST_VERSION < 103200) return 1; return 0; }
EOF
	cc_check $BOOST_CFLAGS $BOOST_LIBS && _boost=yes
fi
echo "$_boost"

if test "$_boost" = yes ; then
	_boost=no
	echo_n "Checking whether Boost.ProgramOptions has been compiled... "
	cat > $TMPC << EOF
#include <boost/program_options.hpp>
int main(void) { boost::program_options::options_description generic("Generic options"); return 0; }
EOF
	cc_check $BOOST_CFLAGS $BOOST_LIBS -lboost_program_options && _boost=yes
	add_to_config_mk_if_yes "$_boost" 'BOOST_SUFFIX = '

	# If not working without suffix, try -mt suffix
	if test "$_boost" = no ; then
		cc_check $BOOST_CFLAGS $BOOST_LIBS -lboost_program_options-mt && _boost=yes
		add_to_config_mk_if_yes "$_boost" 'BOOST_SUFFIX = -mt'
	fi
	add_to_config_mk_if_yes "$_boost" 'USE_BOOST = 1'
	echo "$_boost"
fi

#
# Check for iconv
#
echo_n "Checking whether iconv.h is present... "
if test "$_iconv" = auto ; then
	_iconv=no
	cat > $TMPC << EOF
#include <iconv.h>
int main(int, char **) {
	return 0;
}
EOF
	cc_check && _iconv=yes
fi

create_iconv_test() {
	cat > $TMPC << EOF
#include <iconv.h>
int main(int, char **) {
	iconv_t iconv = iconv_open("UTF-32", "SJIS");
	iconv_close(iconv);
	return 0;
}
EOF
}
echo "$_iconv"

if test "$_iconv" = yes ; then
	echo_n "Checking whether iconv needs linking against libiconv... "

	needs_iconvlib='auto'
	create_iconv_test
	cc_check -liconv && needs_iconvlib='yes'
	# We do check linking without -liconv here too, just in case
	# it would fail otherwise too
	create_iconv_test
	cc_check && needs_iconvlib='no'

	if test "$needs_iconvlib" = auto ; then
		_iconv=no
		echo "does not link at all"
	else
		if test "$needs_iconvlib" = yes ; then
			_iconvlibs='-liconv'
		else
			_iconvlibs=''
		fi
		echo "$needs_iconvlib"

		echo_n "Checking signature of iconv... "
		uses_const=no

		cat > $TMPC << EOF
#include <iconv.h>
int main(int argc, char **argv) {
	iconv_t iconvP;
	const char **inbuf = 0;
	iconv(iconvP, inbuf, 0, 0, 0);
	return 0;
}
EOF
		cc_check $_iconvlibs && uses_const=yes

		if test "$uses_const" = yes ; then
			echo "iconv_t, const char **, size_t *, char **, size_t *"
			_iconvcflags='-DICONV_USES_CONST'
		else
			echo "iconv_t, char **, size_t *, char **, size_t *"
			_iconvcflags='-UICONV_USES_CONST'
		fi
	fi
fi

echocheck "iconv"
define_in_config_if_yes "$_iconv" 'USE_ICONV'
echo "$_iconv"

#
# Check for wxWidgets
#
if test "$_wxwidgets" = auto ; then
	_wxwidgets=no
	find_wxconfig
	if test -n "$_wxconfig"; then
		_wxwidgets=yes
	fi
fi

if test "$_wxwidgets" = yes ; then
	_wxincludes="`$_wxconfig --prefix="$_wxpath" --cflags`"
	_wxlibs="`$_wxconfig --prefix="$_wxpath" --libs`"
	_wxstaticlibs="`$_wxconfig --prefix="$_wxpath" --static --libs 2> /dev/null`"
	_wxstaticlibs=`echo $_wxstaticlibs | sed 's|-lpng||' | sed 's|-lz||'`
	# _wxstaticlibs may contain non-static libraries that we also have in _wxstaticlibs.
	# remove those to avoid dependency on non-static libraries

	if test "$have_gcc" = yes ; then
		if test "$_cxx_major" -ge "8" ; then
			# These warnings appear a lot in wx headers
			_wxincludes="$_wxincludes -Wno-deprecated-copy -Wno-cast-function-type -Wno-cast-qual"
		fi
	fi
	# Use the compiler specified by wx-config when not cross-compiling. This is needed on some systems to get a working executable.
	if test -z "$_host"; then
		CXX="`$_wxconfig --cxx`"
		LD=$CXX
	fi

echo_n "Checking for wxwidgets gui dev component... "
	has_wx_gui_dev=no

	cat > $TMPC << EOF
#include <wx/wx.h>

class Foo : public wxFrame {
public:
	Foo(const wxString& title) : wxFrame(NULL, wxID_ANY, title) {}
};

class FooApp : public wxApp {
public:
	virtual bool OnInit();
};

IMPLEMENT_APP(FooApp)

bool FooApp::OnInit() {
    Foo *foo = new Foo(wxT("Foo"));
    foo->Show(true);
    return true;
}
EOF
	cc_check $_wxincludes $_wxlibs && has_wx_gui_dev=yes

	if test "$has_wx_gui_dev" = no ; then
		_wxincludes=""
		_wxlibs=""
		_wxstaticlibs=""
		_wxwidgets=no
		echo "not found"
	else
		echo "found"
	fi

fi
add_to_config_mk_if_yes "$_wxwidgets" 'USE_WXWIDGETS = 1'


#
# Figure out installation directories
#
test -z "$_bindir" && _bindir="$_prefix/bin"
test -z "$_datadir" && _datadir="$_prefix/share"
test -z "$_mandir" && _mandir="$_prefix/share/man"
test -z "$_libdir" && _libdir="$_prefix/lib"

#
# Set variables for profiling.
# We need to do it here to prevent mess-ups with the tests e.g. on the PSP
#
if test "$_enable_prof" = yes ; then
	CXXFLAGS="$CXXFLAGS -pg"
	LDFLAGS="$LDFLAGS -pg"
fi

_def_media_path='#define APP_MEDIA_PATH "'$_datadir'"'

echo
echo "Creating config.h"
cat > config.h << EOF
/* This file is automatically generated by configure */
/* DO NOT EDIT MANUALLY */

#ifndef CONFIG_H
#define CONFIG_H

$_config_h_data

/* paths */
$_def_media_path

/* Data types */
typedef unsigned $type_1_byte byte;
typedef unsigned int uint;
typedef unsigned $type_1_byte uint8;
typedef unsigned $type_2_byte uint16;
typedef unsigned $type_4_byte uint32;
typedef unsigned $type_8_byte uint64;
typedef signed $type_1_byte int8;
typedef signed $type_2_byte int16;
typedef signed $type_4_byte int32;
typedef signed $type_8_byte int64;

#if defined(__APPLE__) && !defined(__ppc__)
#ifndef _UINT64
#define _UINT64
#endif
#endif

#endif /* CONFIG_H */
EOF

echo "Creating config.mk"
cat > config.mk << EOF
# -------- Generated by configure -----------

CXX := $CXX
CXXFLAGS := $CXXFLAGS
LD := $LD
LIBS += $LIBS
RANLIB := $_ranlib
STRIP := $_strip
AR := $_ar
AS := $_as
ASFLAGS := $ASFLAGS
WINDRES := $_windres
WINDRESFLAGS := $WINDRESFLAGS
WIN32PATH=$_win32path
AMIGAOSPATH=$_amigaospath
MORPHOSPATH=$_morphospath
STATICLIBPATH=$_staticlibpath
XCODETOOLSPATH=$_xcodetoolspath

EXEEXT := $HOSTEXEEXT

PREFIX := $_prefix
BINDIR := $_bindir
DATADIR := $_datadir
MANDIR := $_mandir
LIBDIR := $_libdir

$_config_mk_data

INCLUDES += $INCLUDES
OBJS += $OBJS
DEFINES += $DEFINES
LDFLAGS += $LDFLAGS

WXINCLUDES := $_wxincludes
WXLIBS := $_wxlibs
WXSTATICLIBS := $_wxstaticlibs

FREETYPE2_CFLAGS := $FREETYPE2_CFLAGS
FREETYPE2_LIBS := $FREETYPE2_LIBS

ICONVLIBS := $_iconvlibs
ICONVCFLAGS := $_iconvcflags

SAVED_CONFIGFLAGS       := $SAVED_CONFIGFLAGS
SAVED_LDFLAGS           := $SAVED_LDFLAGS
SAVED_PKG_CONFIG_LIBDIR := $SAVED_PKG_CONFIG_LIBDIR
SAVED_CXX               := $SAVED_CXX
SAVED_CXXFLAGS          := $SAVED_CXXFLAGS
SAVED_CPPFLAGS          := $SAVED_CPPFLAGS
SAVED_ASFLAGS           := $SAVED_ASFLAGS
SAVED_WINDRESFLAGS      := $SAVED_WINDRESFLAGS
EOF

#
# Create a custom Makefile when building outside the source tree
# TODO: Add a better check than just looking for 'Makefile'
#
if test ! -f Makefile.common ; then
echo "Creating Makefile"

cat > Makefile << EOF
# -------- Generated by configure -----------
srcdir = $_srcdir
vpath %.h \$(srcdir)
vpath %.cpp \$(srcdir)
vpath %.c \$(srcdir)
vpath %.m \$(srcdir)
vpath %.mm \$(srcdir)
vpath %.asm \$(srcdir)
vpath %.s \$(srcdir)
vpath %.S \$(srcdir)
include \$(srcdir)/Makefile
EOF

fi
