# XXX: SCons spews bizarre errors if this isn't done before the main configure
# context is created.
gtkenv = Environment()
env = Environment()

endian_test_C = """
#include <endian.h>

int main(int argc, char** argv)
{
	if(__BYTE_ORDER == __BIG_ENDIAN)
		return 0;
	else
		return 1;
}
"""

def EndianTestPosix(context):
	context.Message("Checking system endianness...")
	if context.TryLink(endian_test_C, ".c"):
		if context.TryRun(endian_test_C, ".c")[0]:
			context.Result(2)
			return 2
		else:
			context.Result(1)
			return 1
	context.Result(0)
	return 0

Have_GTK = False

# XXX: are gtkenv['PLATFORM'] and env['PLATFORM'] guaranteed to be the same? I'd assume so...
if gtkenv['PLATFORM'] == 'posix':
	gtkenv.ParseConfig('pkg-config --cflags --libs gtk+-2.0')
	gtkconf = Configure(gtkenv, custom_tests = {'EndianTestPosix' : EndianTestPosix } )
	if gtkconf.CheckLib('', 'gtk_main_iteration_do'):
		Have_GTK = True
	endian = gtkconf.EndianTestPosix()
	if endian == 2:
		gtkenv.Append(CPPDEFINES=["ENDIAN_BIG"])
		env.Append(CPPDEFINES=["ENDIAN_BIG"])
	elif endian == 1:
		gtkenv.Append(CPPDEFINES=["ENDIAN_LITTLE"])
		env.Append(CPPDEFINES=["ENDIAN_LITTLE"])
	else:
		print "Endian test failed to compile/link! Bailing!"
		Exit(1)

gtkconf.Finish()
if Have_GTK:
	gtkenv.Append(CPPPATH=["."])
	gtkenv.SharedLibrary('GtkModule', [ 'arch/LoadingWindow/LoadingWindow_GtkModule.cpp' ])
	gtkenv.Command('GtkModule.so', 'libGtkModule.so', 'cp $SOURCE $TARGET')

# FIXME: Compilation is broken without -DCRASH_HANDLER
# TODO: Add command-line switches to turn debug on/off among other things
env.Append(CPPDEFINES=["DEBUG", "CRASH_HANDLER"])
# XXX We should check for these.
env.Append(LIBS=["lua", "lualib", "png", "gif", "rt"])

arch_test_C = """
#include <stdio.h>

int main(int argc, char** argv)
{
	#if defined(__i386__)
	printf("x86");
	#elif defined(__PPC__)
	printf("ppc");
	#elif defined(__amd64__)
	printf("x86_64");
	#else
	return 1;
	#endif
	return 0;
}
"""

def ArchTest(context):
	context.Message("Determining CPU arch...")
	ct = context.TryRun(arch_test_C, '.c')
	if ct[0] == 0:
		context.Result(0)
		return 0
	if ct[1] == "x86":
		context.Result(1)
		return 1
	elif ct[1] == "ppc":
		context.Result(2)
		return 2;
	elif ct[1] == "x86_64":
		context.Result(3)
		return 3;

backtrace_symbols_C = """
#include <execinfo.h>
int main()
{
	void *BacktracePointer=main;
	return backtrace_symbols (&BacktracePointer, 1) == 0? 1:0;
}
"""

def BacktraceSymbolsTest(context):
	context.Message("Checking for working backtrace_symbols()")
	res = context.TryRun(backtrace_symbols_C, '.c')[0]
	context.Result(res)
	return res

cxa_demangle_C = """
#include <cxxabi.h>
#include <stdlib.h>
#include <typeinfo>

int main()
{
	struct foo { } fum;
	int status;
	char *realname = abi::__cxa_demangle(typeid(fum).name(), 0, 0, &status);
	free( realname );
	return 0;
}
"""

def CxaDemangleTest(context):
	context.Message("Checking for working cxa_demangle")
	res = context.TryRun(cxa_demangle_C, '.c')[0]
	context.Result(res)
	return res

alsa_test_C = """
#include <alsa/asoundlib.h>
/* ensure backward compatibility */
#if !defined(SND_LIB_MAJOR) && defined(SOUNDLIB_VERSION_MAJOR)
#define SND_LIB_MAJOR SOUNDLIB_VERSION_MAJOR
#endif
#if !defined(SND_LIB_MINOR) && defined(SOUNDLIB_VERSION_MINOR)
#define SND_LIB_MINOR SOUNDLIB_VERSION_MINOR
#endif
#if !defined(SND_LIB_SUBMINOR) && defined(SOUNDLIB_VERSION_SUBMINOR)
#define SND_LIB_SUBMINOR SOUNDLIB_VERSION_SUBMINOR
#endif

#  if(SND_LIB_MAJOR > 0)
#  else
#    if(SND_LIB_MAJOR < 0)
#       error not present
#    endif
#   if(SND_LIB_MINOR > 9)
#   else
#     if(SND_LIB_MINOR < 9)
#          error not present
#      endif
#      if(SND_LIB_SUBMINOR < 0)
#        error not present
#      endif
#    endif
#  endif
"""

def AlsaVersionTest(context):
	context.Message("Checking for ALSA >= 0.9.0...")
	res = context.TryCompile(alsa_test_C, '.c')
	context.Result(res)
	return res

oss_getversion_test_C = """
#include <sys/soundcard.h>
int main() {
	return OSS_GETVERSION & 0xFF;
}
"""

def OSSGetVersionTest(context):
	context.Message("Checking for OSS_GETVERSION...")
	res = context.TryCompile(oss_getversion_test_C, '.c')
	context.Result(res)
	return res

cstdlib_llabs_test_CPP = """
#include <stdlib.h>
#include <cstdlib>

using namespace std;

int foo() { return llabs(1); }
"""

def CstdlibLlabsTest(context):
	context.Message("Checking if cstdlib breaks llabs...")
	res = not context.TryCompile(cstdlib_llabs_test_CPP, '.cpp')
	context.Result(res)
	return res

conf = Configure(env, custom_tests = {
	'EndianTestPosix' : EndianTestPosix,
	'ArchTest' : ArchTest,
	'BacktraceSymbolsTest' : BacktraceSymbolsTest,
	'CxaDemangleTest' : CxaDemangleTest,
	'AlsaVersionTest' : AlsaVersionTest,
	'OSSGetVersionTest' : OSSGetVersionTest,
	'CstdlibLlabsTest' : CstdlibLlabsTest })

Lights = [
	"arch/Lights/LightsDriver.cpp",
	"arch/Lights/LightsDriver_SystemMessage.cpp",
]

cpuTypeI = conf.ArchTest()
if cpuTypeI == 1:
	env.Append(CPPDEFINES=["CPU_X86"])
	if env['PLATFORM'] == 'posix':
		# NOPORT: Again, assuming Linux
		env.Append(CPPDEFINES=["BACKTRACE_METHOD_X86_LINUX", "LUA_USE_LINUX"])
		Lights += [ "arch/Lights/LightsDriver_LinuxWeedTech.cpp", "arch/Lights/LightsDriver_LinuxParallel.cpp" ]
elif cpuTypeI == 2:
	env.Append(CPPDEFINES=["CPU_PPC"])
	# XXX: Backtrace components for this arch?
elif cpuTypeI == 3:
	env.Append(CPPDEFINES=["CPU_X86_64"])
	# XXX: Backtrace components for this arch? Can I use x86 components?
else:
	print "Couldn't determine CPU type! Bailing!"
	Exit(1)

Screens = [
	"Screen.cpp",
	"ScreenAttract.cpp",
	"ScreenBookkeeping.cpp",
	"ScreenCenterImage.cpp",
	"ScreenCredits.cpp",
	"ScreenDebugOverlay.cpp",
	"ScreenDemonstration.cpp",
	"ScreenEdit.cpp",
	"ScreenEditMenu.cpp",
	"ScreenEnding.cpp",
	"ScreenEvaluation.cpp",
	"ScreenExit.cpp",
	"ScreenNetEvaluation.cpp",
	"ScreenNetSelectMusic.cpp",
	"ScreenNetSelectBase.cpp",
	"ScreenNetRoom.cpp",
	"ScreenEz2SelectMusic.cpp",
	"ScreenEz2SelectPlayer.cpp",
	"ScreenGameplay.cpp",
	"ScreenGameplayLesson.cpp",
	"ScreenGameplayNormal.cpp",
	"ScreenHowToPlay.cpp",
	"ScreenInstructions.cpp",
	"ScreenJukebox.cpp",
	"ScreenMapControllers.cpp",
	"ScreenMessage.cpp",
	"ScreenMiniMenu.cpp",
	"ScreenMusicScroll.cpp",
	"ScreenNameEntry.cpp",
	"ScreenNameEntryTraditional.cpp",
	"ScreenOptions.cpp",
	"ScreenOptionsEditCourse.cpp",
	"ScreenOptionsEditCourseEntry.cpp",
	"ScreenOptionsEditPlaylist.cpp",
	"ScreenOptionsEditProfile.cpp",
	"ScreenOptionsEditWorkout.cpp",
	"ScreenOptionsManageCourses.cpp",
	"ScreenOptionsManageEditSteps.cpp",
	"ScreenOptionsManageProfiles.cpp",
	"ScreenOptionsManageWorkouts.cpp",
	"ScreenOptionsMaster.cpp",
	"ScreenOptionsMasterPrefs.cpp",
	"ScreenOptionsMemoryCard.cpp",
	"ScreenOptionsReviewWorkout.cpp",
	"ScreenPackages.cpp",
	"ScreenPlayerOptions.cpp",
	"ScreenNetworkOptions.cpp",
	"ScreenPrompt.cpp",
	"ScreenRanking.cpp",
	"ScreenReloadSongs.cpp",
	"ScreenSandbox.cpp",
	"ScreenSaveSync.cpp",
	"ScreenServiceAction.cpp",
	"ScreenStatsOverlay.cpp",
	"ScreenSelect.cpp",
	"ScreenSelectCharacter.cpp",
	"ScreenSelectDifficulty.cpp",
	"ScreenSelectGroup.cpp",
	"ScreenSelectMaster.cpp",
	"ScreenSelectMode.cpp",
	"ScreenSelectMusic.cpp",
	"ScreenSelectStyle.cpp",
	"ScreenSyncOverlay.cpp",
	"ScreenSystemLayer.cpp",
	"ScreenSetTime.cpp",
	"ScreenSongOptions.cpp",
	"ScreenSplash.cpp",
	"ScreenStage.cpp",
	"ScreenTestFonts.cpp",
	"ScreenTestInput.cpp",
	"ScreenTestLights.cpp",
	"ScreenTestSound.cpp",
	"ScreenTextEntry.cpp",
	"ScreenTitleMenu.cpp",
	"ScreenUnlockStatus.cpp",
	"ScreenWithMenuElements.cpp",
]

DataStructures = [
	"AdjustSync.cpp",
	"Attack.cpp",
	"AutoKeysounds.cpp",
	"BackgroundUtil.cpp",
	"BannerCache.cpp",
	"CatalogXml.cpp",
	"Character.cpp",
	"CodeDetector.cpp",
	"Command.cpp",
	"CommonMetrics.cpp",
	"Course.cpp",
	"CourseLoaderCRS.cpp",
	"CourseUtil.cpp",
	"CourseWriterCRS.cpp",
	"DateTime.cpp",
	"Difficulty.cpp",
	"EnumHelper.cpp",
	"Font.cpp",
	"FontCharAliases.cpp",
	"FontCharmaps.cpp",
	"Game.cpp",
	"GameCommand.cpp",
	"GameConstantsAndTypes.cpp",
	"GameInput.cpp",
	"GameplayAssist.cpp",
	"GamePreferences.cpp",
	"Grade.cpp", 
	"HighScore.cpp",
	"Inventory.cpp",
	"LocalizedString.cpp",
	"LuaReference.cpp",
	"LuaExpressionTransform.cpp",
	"LyricsLoader.cpp",
	"ModsGroup.cpp",
	"NoteData.cpp",
	"NoteDataUtil.cpp",
	"NoteDataWithScoring.cpp",
	"NoteTypes.cpp",
	"NotesLoader.cpp",
	"NotesLoaderBMS.cpp",
	"NotesLoaderDWI.cpp",
	"NotesLoaderKSF.cpp",
	"NotesLoaderSM.cpp",
	"NotesWriterDWI.cpp",
	"NotesWriterSM.cpp",
	"OptionRowHandler.cpp",
	"PlayerAI.cpp",
	"PlayerNumber.cpp",
	"PlayerOptions.cpp",
	"PlayerStageStats.cpp",
	"PlayerState.cpp",
	"Preference.cpp",
	"Profile.cpp",
	"RandomSample.cpp",
	"RadarValues.cpp",
	"RoomInfoDisplay.cpp",
	"RoomWheel.cpp",
	"SampleHistory.cpp",
	"ScreenDimensions.cpp",
	"ScoreKeeper.cpp",
	"ScoreKeeperGuitar.cpp",
	"ScoreKeeperNormal.cpp",
	"ScoreKeeperRave.cpp",
	"Song.cpp",
	"SongCacheIndex.cpp",
	"SongOptions.cpp",
	"SongUtil.cpp",
	"SoundEffectControl.cpp",
	"StageStats.cpp",
	"Steps.cpp",
	"StepsUtil.cpp",
	"Style.cpp",
	"StyleUtil.cpp",
	"TimingData.cpp",
	"Trail.cpp",
	"TrailUtil.cpp",
	"TitleSubstitution.cpp",
	"Tween.cpp",
	"Workout.cpp",
]

FileTypes = [
	"IniFile.cpp",
	"MsdFile.cpp",
	"XmlFile.cpp",
	"XmlFileUtil.cpp",
]

StepMania = [
	"StepMania.cpp",
	"GameLoop.cpp",
	"global.cpp",
	"SpecialFiles.cpp",
	"arch/RageDriver.cpp",
]

Sound = [
	"arch/Sound/RageSoundDriver.cpp",
	"arch/Sound/RageSoundDriver_Null.cpp",
	"arch/Sound/RageSoundDriver_Generic_Software.cpp",
]

MemoryCard = [
	"arch/MemoryCard/MemoryCardDriver.cpp",
]

Dialog = [
	"arch/Dialog/Dialog.cpp",
	"arch/Dialog/DialogDriver.cpp",
]

RageSoundFileReaders = [
	"RageSoundReader_WAV.cpp",
]

ArchHooks = [
	'arch/ArchHooks/ArchHooks.cpp',
	'arch/ArchHooks/ArchHooksUtil.cpp',
]

MovieTexture = [
	"arch/MovieTexture/MovieTexture.cpp",
	"arch/MovieTexture/MovieTexture_Null.cpp",
]

InputHandler = [
	"arch/InputHandler/InputHandler.cpp",
	"arch/InputHandler/InputHandler_MonkeyKeyboard.cpp",
]

LoadingWindow = [
	"arch/LoadingWindow/LoadingWindow.cpp",
]

LowLevelWindow = [
	"arch/LowLevelWindow/LowLevelWindow.cpp",
]
Threads = []
ArchUtils = []

# # # Detection stuff here, it's easiest

if conf.CstdlibLlabsTest():
	env.Append(CPPDEFINES=["NEED_CSTDLIB_WORKAROUND"])

if not conf.CheckLib('png', 'png_create_read_struct'):
	print "*** libpng is required to build StepMania; please make sure that"
	print "*** it is installed to continue the build process."
	Exit(1)

# DANGER: There's something funky with the header check. Fails on this system where
#			autoconf's doesn't. Haven't tested it on others.
if conf.CheckLib('jpeg', 'jpeg_read_scanlines'):# and conf.CheckHeader('jpeglib.h')
	FileTypes += [ "RageSurface_Save_JPEG.cpp", "RageSurface_Load_JPEG.cpp" ]
else:
	# XXX: Bail but allow forcing
	print "*** WARNING: libjpeg not found. You will not be able to read JPEG files."
	env.Append(CPPDEFINES=["NO_JPEG_SUPPORT"])

if conf.CheckLib('vorbisfile', 'ov_info'):
	RageSoundFileReaders += [ "RageSoundReader_Vorbisfile.cpp" ]
else:
	env.Append(CPPDEFINES=["NO_VORBIS_SUPPORT"])

if conf.CheckLib('mad', 'mad_stream_buffer'):
	RageSoundFileReaders += [ "RageSoundReader_MP3.cpp" ]
else:
	env.Append(CPPDEFINES=["NO_MP3_SUPPORT"])

if not conf.CheckLib('GL', 'glGetError'):
	print "Can't find suitable OpenGL library."
	Exit(1)

if not conf.CheckLib('GLU', 'gluErrorString'):
	print "Can't find suitable GLU library."
	Exit(1)

if env['PLATFORM'] == 'posix':
	if not conf.CheckLib('pthread', 'pthread_join'):
		print "Pthread not present! Your system is insane! Bailing!"
		Exit(1)
	# NOPORT: This assumes Linux. I don't know how to check for say, FreeBSD or even OS X vs. Linux.
	env.Append(CPPDEFINES=["UNIX", "LINUX", ("BACKTRACE_METHOD_TEXT", "\"\\\"FIXME\\\"\""),
				("BACKTRACE_LOOKUP_METHOD_TEXT", "\"\\\"FIXME\\\"\"")])
				#XXX ^ Why is the builder supposed to define BACKTRACE_*_TEXT?
	ArchUtils += [ 
		"archutils/Unix/LinuxThreadHelpers.cpp",
		"archutils/Unix/RunningUnderValgrind.cpp",
		"archutils/Unix/EmergencyShutdown.cpp",
		"archutils/Unix/GetSysInfo.cpp",
		"archutils/Unix/AssertionHandler.cpp",
		"archutils/Unix/SignalHandler.cpp",
		"archutils/Unix/CrashHandler.cpp",
		"archutils/Unix/CrashHandlerChild.cpp",
		"archutils/Unix/CrashHandlerInternal.cpp",
		"archutils/Unix/Backtrace.cpp",
		"archutils/Unix/BacktraceNames.cpp",
	]
	if not conf.CheckLib('rt', 'clock_gettime'):
		print "librt is missing?"
		Exit(1)
	ArchHooks += [ "arch/ArchHooks/ArchHooks_Unix.cpp" ]
	Threads += [ "arch/Threads/Threads_Pthreads.cpp" ]
	MemoryCard += [ "arch/MemoryCard/MemoryCardDriverThreaded_Linux.cpp" ]
	InputHandler += [ "arch/InputHandler/InputHandler_Linux_Joystick.cpp" ]
	# Backtrace stuff
	if conf.CheckLib('dl', 'dladdr'):
		env.Append(CPPDEFINES=['BACKTRACE_LOOKUP_METHOD_DLADDR'], LINKFLAGS="-rdynamic")
	elif conf.BacktraceSymbolsTest():
		env.Append(CPPDEFINES=["BACKTRACE_LOOKUP_METHOD_BACKTRACE_SYMBOLS"], LINKFLAGS='-rdynamic')
	else:
		print "*** Couldn't find suitable symbol lookup method."
		print "*** Generated crash logs will be worthless."
	if conf.CheckHeader('libiberty.h') and conf.CheckLib('iberty', 'cplus_demangle'):
		env.Append(CPPDEFINES=['HAVE_LIBIBERTY'])
	else:
		print "*** Backtrace support has been detected, but libiberty is not installed."
		print "*** Libiberty will make crash reports for developers much easier to read,"
		print "*** and is strongly recommended."
	# ALSA is Linux-exclusive
	if conf.AlsaVersionTest() and conf.CheckLib('asound', 'snd_ctl_open'):
		env.Append(CPPDEFINES=["HAVE_ALSA"])
		Sound += [	"arch/Sound/ALSA9Dynamic.cpp",
					"arch/Sound/ALSA9Helpers.cpp",
					"arch/Sound/RageSoundDriver_ALSA9_Software.cpp" ]
	# OSS is available on POSIX OSes besides Linux
	if conf.CheckHeader('sys/soundcard.h'):
		env.Append(CPPDEFINES=["HAVE_OSS"])
		Sound += [ 'arch/Sound/RageSoundDriver_OSS.cpp' ]
		if conf.OSSGetVersionTest():
			env.Append(CPPDEFINES=["HAVE_OSS_GETVERSION"])

if Have_GTK:
	env.Append(CPPDEFINES=["HAVE_GTK"])
	LoadingWindow += [ "arch/LoadingWindow/LoadingWindow_Gtk.cpp" ]

# REMEMBER, only ONE LowLevelWindow!
if conf.CheckLib('X11', 'XMapWindow') and conf.CheckLib('Xrandr', 'XRRSizes'):
	env.Append(CPPDEFINES=["HAVE_X11"])
	ArchUtils += [ "archutils/Unix/X11Helper.cpp" ]
	LowLevelWindow += [ "arch/LowLevelWindow/LowLevelWindow_X11.cpp" ]
	InputHandler += [ "arch/InputHandler/InputHandler_X11.cpp" ]
	if conf.CheckLib('Xtst', 'XTestQueryExtension'):
		env.Append(CPPDEFINES=["HAVE_LIBXTST"])

Arch = LoadingWindow + Sound + ArchHooks + InputHandler + MovieTexture +\
		Lights + MemoryCard + LowLevelWindow + ArchUtils + Dialog +\
		Threads

ActorsInGameplayAndMenus = [
	"BGAnimation.cpp",
	"BGAnimationLayer.cpp",
	"Banner.cpp",
	"DifficultyIcon.cpp",
	"MeterDisplay.cpp",
	"StreamDisplay.cpp",
	"Transition.cpp",
]

ActorsInMenus = [
	"ActiveAttackList.cpp",
	"BPMDisplay.cpp",
	"ComboGraph.cpp",
	"CourseContentsList.cpp",
	"CourseEntryDisplay.cpp",
	"DifficultyList.cpp",
	"DifficultyMeter.cpp",
	"DifficultyRating.cpp",
	"DualScrollBar.cpp",
	"EditMenu.cpp",
	"FadingBanner.cpp",
	"GradeDisplay.cpp",
	"GraphDisplay.cpp",
	"GrooveRadar.cpp",
	"GroupList.cpp",
	"HelpDisplay.cpp",
	"MemoryCardDisplay.cpp",
	"MenuTimer.cpp",
	"ModeSwitcher.cpp",
	"MusicBannerWheel.cpp",
	"MusicList.cpp",
	"MusicSortDisplay.cpp",
	"MusicWheel.cpp",
	"MusicWheelItem.cpp",
	"OptionIcon.cpp",
	"OptionIconRow.cpp",
	"OptionRow.cpp",
	"OptionsCursor.cpp",
	"PaneDisplay.cpp",
	"ScrollBar.cpp",
	"ScrollingList.cpp",
	"SnapDisplay.cpp",
	"TextBanner.cpp",
	"WheelBase.cpp",
	"WheelItemBase.cpp",
	"WheelNotifyIcon.cpp",
	"WorkoutGraph.cpp",
]

ActorsInGameplay = [
	"ArrowEffects.cpp",
	"AttackDisplay.cpp",
	"Background.cpp",
	"BeginnerHelper.cpp",
	"CombinedLifeMeterTug.cpp",
	"Combo.cpp",
	"DancingCharacters.cpp",
	"Foreground.cpp",
	"GhostArrowRow.cpp",
	"HoldJudgment.cpp",
	"Judgment.cpp",
	"LifeMeter.cpp",
	"LifeMeterBar.cpp",
	"LifeMeterBattery.cpp",
	"LifeMeterTime.cpp",
	"LyricDisplay.cpp",
	"NoteDisplay.cpp",
	"NoteField.cpp",
	"PercentageDisplay.cpp",
	"Player.cpp",
	"ReceptorArrow.cpp",
	"ReceptorArrowRow.cpp",
	"ScoreDisplay.cpp",
	"ScoreDisplayBattle.cpp",
	"ScoreDisplayCalories.cpp",
	"ScoreDisplayLifeTime.cpp",
	"ScoreDisplayNormal.cpp",
	"ScoreDisplayOni.cpp",
	"ScoreDisplayPercentage.cpp",
	"ScoreDisplayRave.cpp",
]

PCRE = [
	"pcre/chartables.c",
	"pcre/get.c",
	"pcre/maketables.c",
	"pcre/pcre.c",
	"pcre/study.c",
]

Lua = [ "lua-5.1/src/lapi.c",
	"lua-5.1/src/lauxlib.c",
	"lua-5.1/src/lbaselib.c",
	"lua-5.1/src/lcode.c",
	"lua-5.1/src/ldblib.c",
	"lua-5.1/src/ldebug.c",
	"lua-5.1/src/ldo.c",
	"lua-5.1/src/ldump.c",
	"lua-5.1/src/lfunc.c",
	"lua-5.1/src/lgc.c",
	"lua-5.1/src/linit.c",
	"lua-5.1/src/liolib.c",
	"lua-5.1/src/llex.c",
	"lua-5.1/src/lmathlib.c",
	"lua-5.1/src/lmem.c",
	"lua-5.1/src/loadlib.c",
	"lua-5.1/src/lobject.c",
	"lua-5.1/src/lopcodes.c",
	"lua-5.1/src/loslib.c",
	"lua-5.1/src/lparser.c",
	"lua-5.1/src/lstate.c",
	"lua-5.1/src/lstring.c",
	"lua-5.1/src/lstrlib.c",
	"lua-5.1/src/ltable.c",
	"lua-5.1/src/ltablib.c",
	"lua-5.1/src/ltm.c",
	"lua-5.1/src/lundump.c",
	"lua-5.1/src/lvm.c",
	"lua-5.1/src/lzio.c",
]

RageFile = [
	"RageFileBasic.cpp",
	"RageFile.cpp",
	"RageFileDriver.cpp",
	"RageFileManager.cpp",
	"RageFileDriverDirect.cpp",
	"RageFileDriverDirectHelpers.cpp",
	"RageFileDriverMemory.cpp",
	"RageFileDriverZip.cpp",
	"RageFileDriverDeflate.cpp",
	"RageFileDriverSlice.cpp",
	"RageFileDriverTimeout.cpp",
]

Rage = PCRE + RageFile + RageSoundFileReaders + [
	"RageBitmapTexture.cpp",
	"RageDisplay.cpp",
	"RageDisplay_OGL.cpp", # XXX: Should we require GL on Windows?
	"RageDisplay_OGL_Helpers.cpp",
	"RageDisplay_Null.cpp",
	"RageException.cpp",
	"RageInput.cpp",
	"RageInputDevice.cpp",
	"RageLog.cpp",
	"RageMath.cpp",
	"RageModelGeometry.cpp",
	"RageSound.cpp",
	"RageSoundManager.cpp",
	"RageSoundUtil.cpp",
	"RageSoundMixBuffer.cpp",
	"RageSoundPosMap.cpp",
	"RageSoundReader.cpp",
	"RageSoundReader_Chain.cpp",
	"RageSoundReader_Extend.cpp",
	"RageSoundReader_FileReader.cpp",
	"RageSoundReader_Pan.cpp",
	"RageSoundReader_PitchChange.cpp",
	"RageSoundReader_PostBuffering.cpp",
	"RageSoundReader_Preload.cpp",
	"RageSoundReader_Resample_Good.cpp",
	"RageSoundReader_SpeedChange.cpp",
	"RageSoundReader_ThreadedBuffer.cpp",
	"RageSurface.cpp",
	"RageSurfaceUtils.cpp",
	"RageSurfaceUtils_Dither.cpp",
	"RageSurfaceUtils_Palettize.cpp",
	"RageSurfaceUtils_Zoom.cpp",
	"RageSurface_Load.cpp",
	"RageSurface_Load_PNG.cpp", # XXX: Do we have libraries for all these image formats in the tree or something?
	"RageSurface_Load_GIF.cpp",
	"RageSurface_Load_BMP.cpp",
	"RageSurface_Load_XPM.cpp",
	"RageTexture.cpp",
	"RageTexturePreloader.cpp",
	"RageTextureRenderTarget.cpp",
	"RageSurface_Save_BMP.cpp",
	"RageSurface_Save_PNG.cpp",
	"RageTextureID.cpp",
	"RageTextureManager.cpp",
	"RageThreads.cpp",
	"RageTimer.cpp",
	"RageTypes.cpp",
	"RageUtil.cpp",
	"RageUtil_CharConversions.cpp",
	"RageUtil_BackgroundLoader.cpp",
	"RageUtil_FileDB.cpp",
	"RageUtil_WorkerThread.cpp",
]

Actors = [
	"Actor.cpp",
	"ActorFrame.cpp",
	"ActorFrameTexture.cpp",
	"ActorScroller.cpp",
	"ActorProxy.cpp",
	"ActorUtil.cpp",
	"ActorSound.cpp",
	"AutoActor.cpp",
	"BitmapText.cpp",
	"Model.cpp",
	"DynamicActorScroller.cpp",
	"ModelManager.cpp",
	"ModelTypes.cpp",
	"Quad.cpp",
	"RollingNumbers.cpp",
	"Sprite.cpp",
]

GlobalSingletons = [
	"AnnouncerManager.cpp",
	"Bookkeeper.cpp",
	"CharacterManager.cpp",
	"CryptManager.cpp",
	"ExportStrings.cpp",
	"FontManager.cpp",
	"GameSoundManager.cpp",
	"GameManager.cpp",
	"GameState.cpp",
	"InputFilter.cpp",
	"InputMapper.cpp",
	"InputQueue.cpp",
	"LuaBinding.cpp",
	"LuaManager.cpp",
	"LightsManager.cpp",
	"MemoryCardManager.cpp",
	"MessageManager.cpp",
	"NetworkSyncManager.cpp",
	"NoteSkinManager.cpp",
	"PrefsManager.cpp",
	"ProfileManager.cpp",
	"ScreenManager.cpp",
	"SongManager.cpp",
	"StatsManager.cpp",
	"ThemeManager.cpp",
	"UnlockManager.cpp",
	"WorkoutManager.cpp",
]

# XXX: This wouldn't be included if WITHOUT_NETWORKING, but I don't have that setting implemented (yet)
Screens += [ "ScreenSMOnlineLogin.cpp" ]
GlobalSingletons += [ "ezsockets.cpp" ]

crypto = [
	"crypto/CryptBn.cpp",
	"crypto/CryptMD5.cpp",
	"crypto/CryptNoise.cpp",
	"crypto/CryptPrime.cpp",
	"crypto/CryptRSA.cpp",
	"crypto/CryptRand.cpp",
	"crypto/CryptSH512.cpp",
	"crypto/CryptSHA.cpp",
]

cryptopp = [
	"crypto51/algebra.cpp",
	"crypto51/algparam.cpp",
	"crypto51/asn.cpp",
	"crypto51/cryptlib.cpp",
	"crypto51/files.cpp",
	"crypto51/filters.cpp",
	"crypto51/integer.cpp",
	"crypto51/iterhash.cpp",
	"crypto51/misc.cpp",
	"crypto51/mqueue.cpp",
	"crypto51/nbtheory.cpp",
	"crypto51/osrng.cpp",
	"crypto51/pkcspad.cpp",
	"crypto51/pubkey.cpp",
	"crypto51/queue.cpp",
	"crypto51/rsa.cpp",
	"crypto51/sha.cpp",
	"CryptHelpers.cpp",
]

env = conf.Finish()

# This must be after configuration stuff apparently
SConscript(['libtommath/SConscript'])
SConscript(['libtomcrypt/SConscript'])

env.Append(LIBS=["tomcrypt", "tommath"],
	LIBPATH=["libtommath", "libtomcrypt"],
	CPPFLAGS=' -g2', CPPPATH=['.']) # NOPORT debug symbols?
# env.Append(CFLAGS=env['CPPFLAGS'], CPATH=env['CPPPATH'] # For lua
env.Program('stepmania',
	Screens + DataStructures + FileTypes + StepMania + Arch +\
	ActorsInGameplayAndMenus + ActorsInMenus + ActorsInGameplay + Rage +\
	Actors + GlobalSingletons + crypto + cryptopp + Lua )

