// Input.cs
// Worthless Bums 2012.


function globalInputLocked ()
{//echo("globalInputLocked()");
	if ($timescale == 0)
	{//echo("Paused");
		return true;
	}
	if ($mainMenuPushed)
	{//echo("Main Menu");
		return true;
	}
	if ($monsterTurnOngoing)
	{//echo("Paused");
		return true;
	}
	if ($currentCharacterActionFlag)
	{//echo("Character Action Flag");
		return true;		// New getScriptTimer() function not working?
	}
	if ($squadInfoGuiPushed)
	{//echo("Squad Info");
		return true;
	}
	if ($promotionGuiPushed)
	{//echo("Promotion");
		return true;
	}
	if ($deathScreenPushed)
	{//echo("Death Screen");
		return true;
	}
	if ($survivorScreenPushed)
	{//echo("Survivor Screen");
		return true;
	}
	if ($guiInProgress)
	{//echo("Gui in Progress");
		return true;
	}
	if ($consoleActivated)
	{//echo("console is activated!");
		return true;
	}
	return false;
}
function enableGuiInProgress ()
{
	$guiInProgress = true;
}
function disableGuiInProgress ()
{
	$guiInProgress = false;
}
//function up (%val)
function down (%val)
{//echo("up()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	if ($AutoFacing	||
		$playerSquad[$activeCharacter].facing == $northDirection)
	{
		moveCharacter($activeCharacter, $northDirection);
	}
	else
	{
		faceDirection($northDirection);//setSquadMemberFacing($northDirection, $playerSquad[$activeCharacter]);
	}
}

//function down (%val)
function up (%val)
{//echo("down()");
	if (globalInputLocked())
	{//echo("global input locked!");
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	if ($AutoFacing	||
		$playerSquad[$activeCharacter].facing == $southDirection)
	{
		moveCharacter($activeCharacter, $southDirection);
	}
	else
	{
		faceDirection($southDirection);//setSquadMemberFacing($southDirection, $playerSquad[$activeCharacter]);
	}
}
function left (%val)
{//echo("left()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	if ($AutoFacing	||
		$playerSquad[$activeCharacter].facing == $westDirection)
	{
		moveCharacter($activeCharacter, $westDirection);
	}
	else
	{
		faceDirection($westDirection);//setSquadMemberFacing($westDirection, $playerSquad[$activeCharacter]);
	}
}
function right (%val)
{//echo("right()");
	if (globalInputLocked())
	{//echo("Right BLOCKED!");
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	if ($AutoFacing	||
		$playerSquad[$activeCharacter].facing == $eastDirection)
	{
		moveCharacter($activeCharacter, $eastDirection);
	}
	else
	{
		faceDirection($eastDirection);//setSquadMemberFacing($eastDirection, $playerSquad[$activeCharacter]);
	}
}
function faceDirection (%direction)
{//echo("faceDirection()");
	if ($playerSquad[$activeCharacter].facing == %direction)
	{
		return;
	}
	if ($playerSquad[$activeCharacter].currentActionPoints >= getActionPointCost(10))
	{
		if (!$GravityWellOn	&&
			$FacingCostsAP)
		{//echo("DEDUCT FACING AP!");
			setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - getActionPointCost(10));
		}
	}
	else if ($FacingCostsAP)
	{updateEventText($whiteColor @ "Not enough AP to change facing" @ $defaultColor @ "!");
		return;
	}
	if (%direction == $playerSquad[$activeCharacter].facing)
	{
		return;
	}
	if ($generateTutorialLevel	&&
		%direction == $northDirection)	// South, but T2D v3.0 flipped the y-axis xD
	{
		if ($tutorialSection == 7)
		{
			tutorialMessage8();
		}
	}
	setSquadMemberFacing(%direction, $playerSquad[$activeCharacter]);
	clearTargetIndicators(false);
	initializeReadout();
	scheduleMonsterTurn();
	clearFireControl();
	$fogOfWar.showFogOfWar();
	triggerContextSensitiveUI(false);
	releaseCharacterActionLock();
}
//function faceUp (%val)
function faceDown (%val)
{//echo("faceUp()");
	if (%val	&&
		!$currentCharacterActionFlag)
	{
		faceDirection($northDirection);
	}
}
//function faceDown (%val)
function faceUp (%val)
{//echo("faceDown()");
	if (%val	&&
		!$currentCharacterActionFlag)
	{
		faceDirection($southDirection);
	}
}
function faceLeft (%val)
{//echo("faceLeft()");
	if (%val	&&
		!$currentCharacterActionFlag)
	{
		faceDirection($westDirection);
	}
}
function faceRight (%val)
{//echo("faceRight()");
	if (%val	&&
		!$currentCharacterActionFlag)
	{
		faceDirection($eastDirection);
	}
}
function downscale (%val)
{//echo("downscale()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	//sceneWindow2D.setCameraZoom(sceneWindow2D.getCameraZoom() - 0.01);
	//echo("sceneWindow2D.getCameraZoom() =" SPC sceneWindow2D.getCameraZoom());
	//return;
	switch ($scaleLevel)
	{
		case 2:
			setZoom1x();
			$scaleLevel = 1;
		case 3:
			setZoom2x();
			$scaleLevel = 2;
	}
}
function upscale (%val)
{//echo("upscale()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	//sceneWindow2D.setCameraZoom(sceneWindow2D.getCameraZoom() + 0.01);
	//echo("sceneWindow2D.getCameraZoom() =" SPC sceneWindow2D.getCameraZoom());
	//return;
	switch ($scaleLevel)
	{
		case 1:
			setZoom2x();
			$scaleLevel = 2;
		case 2:
			setZoom3x();
			$scaleLevel = 3;
	}
}
function talentSlot1 (%val)
{//echo("talentSlot1()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	switch ($playerSquad[$activeCharacter].characterClass)
	{
		case 0:	leaderTalent1();
		case 1:	scoutTalent1();
		case 2:	grenadierTalent1();
		case 3:	supportTalent1();
		case 4:	engineerTalent1();
	}
}
function talentSlot2 (%val)
{//echo("talentSlot2()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	switch ($playerSquad[$activeCharacter].characterClass)
	{
		case 0:	leaderTalent2();
		case 1:	scoutTalent2();
		case 2:	grenadierTalent2();
		case 3:	supportTalent2();
		case 4:	engineerTalent2();
	}
}
function talentSlot3 (%val)
{//echo("talentSlot3()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	switch ($playerSquad[$activeCharacter].characterClass)
	{
		case 0:	leaderTalent3();
		case 1:	scoutTalent3();
		case 2:	grenadierTalent3();
		case 3:	supportTalent3();
		case 4:	engineerTalent3();
	}
}
function talentSlot4 (%val)
{//echo("talentSlot4()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	switch ($playerSquad[$activeCharacter].characterClass)
	{
		case 0:	leaderTalent4();
		case 1:	scoutTalent4();
		case 2:	grenadierTalent4();
		case 3:	supportTalent4();
		case 4:	engineerTalent4();
	}
}
function reload (%val)
{//echo("reload()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	if (isLargeUnit($playerSquad[$activeCharacter]))
	{
		//updateEventText($whiteColor @ "HULK SUIT DOES NOT RELOAD.");
		//setIndividualDialoguePopup($playerSquad[$activeCharacter], "HULK SUIT DOES NOT RELOAD.", "dialogue");
		enableGuiInProgress();
		cancelButton.setText("No");
		cancelButton.position = "64 89";
		quitButton.setText("Yes");
		quitButton.position = "160 164";
		messageBoxOKCancel("Discard Hulk Suit?",
						   "Discard Hulk Suit?",
						   "removeUnitHulkSuit($activeCharacter);disableGuiInProgress();",	// Yes.
						   "disableGuiInProgress();");										// No.
		return;
	}
	clearFireControl();
	if (($playerSquad[$activeCharacter].weapon).currentAmmo >= ($playerSquad[$activeCharacter].weapon).capacity)
	{//echo("1");
		updateEventText($whiteColor @ "No need to reload!");
		return;
	}
	%actionPointCost = $playerSquad[$activeCharacter].currentActionPoints;
	
	// Check for Scout talent "Autoloader".
	%talents = $playerSquad[$activeCharacter].talents;
	if ($playerSquad[$activeCharacter].characterClass == 1	&&
		getWord(%talents, 5) == 1)
	{//echo("2");
		%actionPointCost = $autoloaderLoadCost;
	}
	
	if ($playerSquad[$activeCharacter].currentActionPoints <= 0)
	{//echo("3");
		updateEventText($whiteColor @ "Not enough action points to reload!");
		return;
	}
	else if ($playerSquad[$activeCharacter].ammo <= 0)
	{//echo("4");
		$playerSquad[$activeCharacter].ammo = 0;
		updateEventText($whiteColor @ "No ammo to reload!");
		setIndividualDialoguePopup($playerSquad[$activeCharacter], "No ammo left to reload!", "dialogue");
	}
	else
	{
		setCurrentActionPoints($activeCharacter, $playerSquad[$activeCharacter].currentActionPoints - %actionPointCost);
		reloadWeapon();
		updateEventText($squadColor @ $playerSquad[$activeCharacter].name SPC $friendlyActionColor @ "reloads" @ $defaultColor @ ".");
		setWeaponReloadDialogue($playerSquad[$activeCharacter]);
		initializeReadout();
		scheduleMonsterTurn();
	}
}
function testStairs ()
{//echo("testStairs()");
	resetSquadGuardModes();
	if ($generateTutorialLevel)
	{
		$generateTutorialLevel = false;
		Canvas.popDialog(tutorial);
		descendStairsCamera();
		popLoadingDungeon();
		schedule(1, 0, "pushLoadingDungeon");
		//sceneWindow2D.schedule(2500, 0, "endLevel");
		updateSaveStateDataDisplay();
		Canvas.showCursor();
		stopBGMOgg();
		playMainMenuMusic();
		$gameInProgress = false;
		tutorialOverMan();
		schedule(3500, 0, "popLoadingDungeon");
		schedule(3500, 0, "pushMainMenu");
		// TODO: Tutorial end message?
		return;
	}
	
	clearSquadMemberLabels();
	// Purge unused memory!
	purgeResources();
	
	// Trigger new level object spawning!
	$NewLevelObjectSpawning = true;
	// Clear Disruptor location!
	$ElevatorDisruptorXIndex = -1;
	$ElevatorDisruptorYIndex = -1;
	
	$GlobalStats.totalLevelsPassed++;
	clearFireControl();
	fadeOut(0);
	$descendingElevator = true;
	$squadMemberDiedThisLevel = false;
	
	// START Mission Objective Stuff-------------------------------------------------------------
	updateMissionObjectives();
	$grenadesUsed = 0;
	$enemiesKnockedIntoSpace = 0;
	$enemiesKilledInMelee = 0;
	// END Mission Objective Stuff----------------------------------------------------------------
	
	// Win game condition!
	if ($gameIsDemo)
	{
		// Limit demo to the first two decks!
		if ($commandDeckLevel 		>= 5	&&
			$engineeringDeckLevel 	>= 5)
		{//echo("PLAYER WON THE GAME!");
			// Initialize New Game Plus settings.
			$NewGamePlus++;		// Should we allow this to go on forever?
			$NewGameStart = 1;
			resetNewGamePlusDeckLevels();
			saveCurrentGame();
			// Game won state - get the ball rolling!
			gameWonMan();
			return;
		}
	}
	else
	{
		if ($commandDeckLevel 		>= 5	&&
			$engineeringDeckLevel 	>= 5	&&
			$medicalDeckLevel 		>= 5	&&
			$armoryDeckLevel 		>= 5	&&
			$bridgeDeckLevel		>= 5)
		{//echo("Entering Alien Ship!");
			// NOTE: THIS SHOULD BE FOR ENTERING THE ALIEN SHIP!
			//		 Leave blank for now!
		}
		if ($commandDeckLevel 		>= 5	&&
			$engineeringDeckLevel 	>= 5	&&
			$medicalDeckLevel 		>= 5	&&
			$armoryDeckLevel 		>= 5	&&
			$bridgeDeckLevel		>= 5	&&
			$alienDeckLevel			>= 5)
		{//echo("PLAYER WON THE GAME!");
			triggerWinGameAchievements();
			// Initialize New Game Plus settings.
			$NewGamePlus++;		// Should we allow this to go on forever?
			$NewGameStart = 1;
			resetNewGamePlusDeckLevels();
			saveCurrentGame();
			// Game won state - get the ball rolling!
			gameWonMan();
			return;
		}
	}
	$timescale = 1;
	if ($inventoryTabOut)
	{
		pushInInventoryTab();
	}
	$onOverworldMap = 0;
	incrementAndSyncDungeonLevels();		// This will automatically bump from level 5 of a deck to level 1 of the next deck!
	squadRefundActionPoints();
	$generateNewLevel = true;
	$squadFoundStairs = false;
	Canvas.hideCursor();
	descendStairsCamera();
	popLoadingDungeon();
	schedule(1, 0, "pushLoadingDungeon");
	initializeEndLevelScreenGui();
	Canvas.schedule($endLevelScreenDelay, "pushDialog", endLevelScreenGui);
	Canvas.schedule($endLevelScreenDelay, "showCursor");
}
function continueTestStairs ()
{//echo("continueTestStairs()");
	saveCurrentGame();
	schedule(1250, 0, "cameraReset");
	schedule(1500, 0, "loadOnlySave");
	schedule(2000, 0, "showDungeonLevelMessage");
	schedule(2010, 0, "popLoadingDungeon");
	schedule(2060, 0, "initializeSurvivorScreen");
}
// NOTE: No longer used!
function testStairsFromOverworld ()
{//echo("testStairsFromOverworld()");
	$timescale = 1;
	if ($inventoryTabOut)
	{
		pushInInventoryTab();
	}
	$onOverworldMap = 0;
	Canvas.hideCursor();
	schedule(1/*1000*/, 0, "pushLoadingDungeon");
	schedule(1250, 0, "cameraReset");
	$nextDungeonLevelEvent = schedule(1500, 0, "nextDungeonLevel");
	waitDungeonLevelEvent();
}
function waitDungeonLevelEvent ()
{//echo("waitDungeonLevelEvent()");
	if (isEventPending($nextDungeonLevelEvent))
	{
		schedule(50, 0, "waitDungeonLevelEvent");
	}
	else
	{
		popOverworld();
		popLoadingDungeon();
		Canvas.showCursor();
		updatePortraits();
		handleActiveCharacterIndicator();
		startMinimap();
	}
}
function enterLevel (%val)
{//echo("enterLevel()");
	enforceSquadPersistence();
	if (!$leaderPersist		&&
		!$scoutPersist		&&
		!$grenadierPersist	&&
		!$supportPersist)
	{
		return;
	}
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{//echo("entering new level!");
		if (squadIsCloseToStairs())
		{
			if ($monsterList.getCount() > 0)
			{
				%fail = false;
				for (%i = 0; %i < $monsterList.getCount(); %i++)
				{
					if (($monsterList.getObject(%i)).name $= "Hulk"		||
						($monsterList.getObject(%i)).name $= "Revenant"	||
						($monsterList.getObject(%i)).name $= "Brainien"	||
						($monsterList.getObject(%i)).name $= "Gunship"	||
						($monsterList.getObject(%i)).name $= "Matrix"	||
						($monsterList.getObject(%i)).name $= "Patriarch")
					{
						%fail = true;
					}
				}
				if (!%fail	&&
					!isElevatorDisrupted())
				{
					powerElevatorOn();
				}
			}
			else
			{
				powerElevatorOn();
			}
			if ($elevatorPowered)
			{
				updateEventText($whiteColor @ "You descend the stairs...");
				testStairs();
			}
			else
			{
				updateEventText($whiteColor @ "The elevator is not powered!");
			}
		}
		else
		{
			updateEventText($whiteColor @ "Can't descend! Squad not in elevator zone!");
			setIndividualDialoguePopup($playerSquad[$activeCharacter], "Squad not in elevator zone!", "dialogue");
			return;
		}
		
		if (isElevatorDisrupted())
		{
			setIndividualDialoguePopup($playerSquad[$activeCharacter], "Something is disrupting the elevator...", "dialogue");
		}
	}
}
function firePrimary (%val)
{//echo("firePrimary()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{//echo("TESTING PRIMARY WEAPON FIRE HOOK!");teststairs();return;		// For testing purposes only!
		initiateFireControls();
	}
}
function endTurn (%val)
{//echo("endTurn()");echo(globalInputLocked());
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{
		if ($generateTutorialLevel)
		{
			if ($tutorialSection == 9)
			{
				tutorialMessage10();
			}
		}
		$InputManualEndTurn = true;
		clearFireControl();
		playerEndTurn();
	}
}
function toggleTutorial (%val)
{//echo("toggleTutorial()");
//return;	// Disabled for now!
	if (globalInputLocked())
	{
		return;
	}
	if (%val != 0)
	{
		toggleTutorialOverlay();
	}
}
function takeOffAsteroidBase ()
{
	$currentSystem = "Asteroid Base";
	takeOffButton();
}
function interact (%val)
{//echo("interact()" SPC %val);
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{
		clearFireControl();
		environmentInteract($playerSquad[$activeCharacter].facing);
	}
}
function grab (%val)
{//echo("grab()" SPC %val);
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{
		clearFireControl();
		grabItem();
	}
}
function cycleCharacter (%val)
{//echo("cycleCharacter()");
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		switchToNextSquadMember();
	}
}
function reverseCycleCharacter (%val)
{//echo("reverseCycleCharacter()");
	if (globalInputLocked())
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	if (%val != 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		switchToPreviousSquadMember();
	}
}
function toggleSolo (%val)
{//echo("toggleSolo()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		//clearFireControl();
		toggleScrollingEventLog();
	}
}
function selectLeader (%val)
{//echo("selectLeader() = " @ %val);
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		selectSquadMember(0);
	}
}
function selectScout (%val)
{//echo("selectScout() = " @ %val);
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		selectSquadMember(1);
	}
}
function selectGrenadier (%val)
{//echo("selectGrenadier() = " @ %val);
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		selectSquadMember(2);
	}
}
function selectSupport (%val)
{//echo("selectSupport() = " @ %val);
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		cancelAutoSwitchEvents();
		clearFireControl();
		clearTargetIndicators(false);
		selectSquadMember(3);
	}
}
function togglePause (%val)
{//echo("togglePause() = " @ %val);
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		clearTargetIndicators(false);
		togglePauseGame();
	}
}
function pushSquadInfoGui ()
{//echo("pushSquadInfoGui()");
	if ($mainMenuPushed)
	{
		return;
	}
	if ($monsterTurnOngoing)
	{
		return;
	}
	if ($fireControlsLocked)
	{
		clearTargetIndicators(false);
		unlockFireControls();
	}
	$squadInfoGuiPushed = true;
	updateSquadInfoGui();
	%xSize = getWord($Game::Resolution, 0);
	%ySize = getWord($Game::Resolution, 1);
	%endPosX = (%xSize - getWord(squadInfoGuiFrame.extent, 0)) / 2;
	%endPosY = (%ySize - getWord(squadInfoGuiFrame.extent, 1)) / 2;
	squadInfoGuiFrame.position = -800 SPC %endPosY;	// Start here.
	// Tween movement.
	%delay = 8.0;
	%totalSlices = 100;
	for (%i = 1; %i <= %totalSlices; %i++)
	{//echo("%i =" SPC %i);
		%slice = mRound((%xSize + 800) / %totalSlices);
		%position = (%slice * %i - 800) SPC %endPosY;
		schedule(%i * %delay, 0, "setSquadInfoGuiFramePosition", %position);
		if ((%slice * %i - 800) >= %endPosX)
		{
			schedule(%i * %delay, 0, "uiTweenCameraShake");
			%i = %totalSlices + 1;
		}
	}
	canvas.pushDialog(squadInfoGui);
}
function setSquadInfoGuiFramePosition (%position)
{//echo("setSquadInfoGuiFramePosition()");
	squadInfoGuiFrame.position = %position;
}
function popSquadInfoGui ()
{//echo("popSquadInfoGui()");
	$squadInfoGuiPushed = false;
	%xSize = getWord($Game::Resolution, 0);
	%ySize = getWord($Game::Resolution, 1);
	%endPosX = -800;
	%endPosY = (%ySize - getWord(squadInfoGuiFrame.extent, 1)) / 2;
	squadInfoGuiFrame.position = -800 SPC %endPosY;	// Start here.
	// Tween movement.
	%delay = 8.0;
	%totalSlices = 100;
	for (%i = 1; %i <= %totalSlices; %i++)
	{//echo("%i =" SPC %i);
		%slice = mRound((%xSize + 800) / %totalSlices);
		%position = (-1 * %slice * %i) SPC %endPosY;
		schedule(%i * %delay, 0, "setSquadInfoGuiFramePosition", %position);
		if (-1 * %slice * %i <= %endPosX)
		{
			%i = %totalSlices + 1;
		}
	}
	Canvas.schedule(400, "popDialog", squadInfoGui);
}
function squadInfo (%val)
{//echo("squadInfo()");
//return;	// Disabled for now!
	if ($timescale == 0	&&
		!$squadInfoScreenPushed)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		
		return;
	}
	else if ($promotionGuiPushed)
	{
		
		return;
	}
	if (%val == 0)
	{
		if ($fireControlsLocked)
		{
			clearTargetIndicators(false);
			unlockFireControls();
		}
		pushSquadInfoGui();
	}
}
function promotions (%val)
{//echo("promotions()");
	if ($mainMenuPushed)
	{
		return;
	}
	if ($monsterTurnOngoing)
	{
		return;
	}
	else if ($squadInfoGuiPushed)
	{
		return;
	}
	if (%val == 0)
	{
		if ($fireControlsLocked)
		{
			clearTargetIndicators(false);
			unlockFireControls();
		}
		if ($promotionConfirmationGuiPushed)
		{
			popPromotionConfirmationGui();
		}
		else if ($promotionGuiPushed)
		{
			popPromotionGui();
		}
		else
		{
			pushPromotionGui();
		}
	}
}
function grenade (%val)
{//echo("grenade()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	toggleSightToUnit($playerSquad[$activeCharacter]);
	return;
}
function guardMode (%val)
{//echo("guardMode()");
	if (globalInputLocked())
	{
		return;
	}
	if (%val == 0)
	{
		return;
	}
	clearFireControl();
	turnOnGuardMode($activeCharacter);
}
function squadInfoToggle (%val)
{//echo("squadInfoToggle() = " @ %val);
return;
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val == 0)
	{
		updateSquadInfoGui();
		if ($squadInfoScreenPushed)
		{
			$timescale = 1;
			canvas.Popdialog(squadInfoGui);
		}
		else
		{
			$timescale = 0;		// Remember to unpause when we pop the gui!
			canvas.Pushdialog(squadInfoGui);
		}
	}
}
function nextItem (%val)
{//echo("nextItem()");echo("%val =" SPC %val);
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val == 0)
	{
		selectNextItem();
	}
}
function prevItem (%val)
{//echo("prevItem()");echo("%val =" SPC %val);
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val == 0)
	{
		selectPreviousItem();
	}
}
function useItem (%val)
{//echo("useItem()");
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val == 0)
	{
		useSelectedItem();
	}
}
function activateConsole (%val)
{//echo("activateConsole()");echo("%val =" SPC %val);
	if (%val == 0)
	{//echo("toggling console!");
		if ($consoleActivated)
		{
			ToggleConsole(true);
			ToggleConsole(true);
			ToggleConsole(true);
		}
		else
		{
			ToggleConsole(true);
		}
	}
}
function setJoystickTriggerFlag (%flag)
{//echo("setJoystickTriggerFlag()");
	$JoystickTriggerIsActing = %flag;
}
function joystickTriggerLeft (%val)
{
	joystickTriggers(%val);
}
function joystickTriggerRight (%val)
{
	joystickTriggers(%val);
}
function joystickTriggers (%val)
{//echo("joystickTriggers()");echo("%val =" SPC %val);
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if ($JoystickTriggerIsActing)
	{
		return;
	}
	if (%val > 0)
	{
		setJoystickTriggerFlag(true);
		prevItem(0);
		schedule($JoystickTriggerDelay, 0, "setJoystickTriggerFlag", false);
	}
	else
	{
		setJoystickTriggerFlag(true);
		nextItem(0);
		schedule($JoystickTriggerDelay, 0, "setJoystickTriggerFlag", false);
	}
}
function dropItem (%val)
{//echo("dropItem()");
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val == 0)
	{
		dropSelectedItem();
	}
}
function mainMenu (%val)
{//echo("mainMenu()");
	if (%val)
	{//echo("RUNNING");
		if ($fireControlInitiated)
		{
			clearTargetIndicators(false);
			$fireControlInitiated = false;
			return;
		}
		if ($monsterTurnOngoing)
		{
			return true;
		}
		if ($currentCharacterActionFlag)
		{
			return true;
		}
		if ($deathScreenPushed)
		{
			return true;
		}
		if ($weaponSwapPushed)
		{
			return;
		}
		if ($survivorScreenPushed)
		{
			return;
		}
		if ($fireControlsLocked)
		{
			clearTargetIndicators(false);
			unlockFireControls();
		}
		if ($merchantGuiPushed)
		{
			popMerchantGui();
			return;
		}
		if ($promotionConfirmationGuiPushed)
		{
			popPromotionConfirmationGui();
			return;
		}
		else if ($promotionGuiPushed)
		{
			popPromotionGui();
			return;
		}
		if ($squadInfoScreenPushed)
		{
			squadInfo(0);
		}
		else if ($squadInfoGuiPushed)
		{
			popSquadInfoGui(0);
		}
		else
		{
			if ($mainMenuPushed	&&
				!$gameInProgress)//sceneWindow2D.getSceneGraph() $= "")
			{
				return;
			}
			updateSaveStateDataDisplay();
			updateMainMenuSaveStateDeckLevelText();
			goToMainMenu();
		}
	}
}
function goToMainMenu ()
{//echo("goToMainMenu()");
//echo("$timescale =" SPC $timescale);
//echo("$mainMenuPushed =" SPC $mainMenuPushed);
	//if ($timescale == 0)
	if ($mainMenuPushed)
	{
		//$timescale = 1;
		// Test zoom levels.
		setZoom1x();
		setZoom2x();
		setZoom3x();
		// Set correct zoom level.
		switch ($scaleLevel)
		{
			case 1:	setZoom1x();
			case 2:	setZoom2x();
			case 3:	setZoom3x();
		}
		popMainMenu();
	}
	else
	{
		//$timescale = 0;			// Locks most keyboard input and music continues to play.
		pushMainMenu();
	}
}
function missionLog (%val)
{//echo("missionLog()");
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		
		return;
	}
	if (%val == 1)
	{
		activateMissionLog();
	}
}
function targetClosestHostileControl (%val)
{//echo("targetClosestHostileControl()");
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		
		return;
	}
	if (%val != 0)
	{
	}
}
function targetShipControl (%val)
{//echo("targetShipControl()");
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val != 0)
	{
		targetingShip();
	}
}
function targetPlanetControl (%val)
{//echo("targetPlanetControl()");
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
	if (%val != 0)
	{
		targetingPlanet();
	}
}
function hailTarget (%val)
{//echo("hailTarget()");
	if ($timescale == 0)
	{
		return;
	}
	if ($mainMenuPushed)
	{
		
		return;
	}
	if (%val != 0)
	{
		hailPlayerTarget();
	}
}
function zoomInControl (%val)
{//echo("zoomInControl()");
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
}
function zoomOutControl (%val)
{//echo("zoomOutControl()");
	if (globalInputLocked())
	{
		return;
	}
	if ($mainMenuPushed)
	{
		return;
	}
}


// Updates the key bind variables.
function updateKeybinds ()
{//echo("updateKeybinds()");//echo("$keybindCount =" SPC $keybindCount);
	// Loop through all keybindings.
	for (%i = 0; %i < $keybindCount; %i++)
	//for (%i = 0; %i < $staticKeybindCount; %i++)
	{
		// Grab the command and name of the bind being changed, and the map that owns it.
		%cmd = $keybindCommand[%i];
		%name = $keybindName[%i];
		%map = $keybindMap[%i];
		%action = %map.getBinding(%cmd);
	/*echo(%i);
	echo("%cmd =" SPC %cmd);
	echo("%name =" SPC %name);
	echo("%map =" SPC %map);
	echo("%action =" SPC %action);*/
		switch$ (%cmd)
		{
			case "up":
				$UpBind = %action;
			case "down":
				$DownBind = %action;
			case "left":
				$LeftBind = %action;
			case "right":
				$RightBind = %action;
				
			case "faceUp":
				$FaceUpBind = %action;
			case "faceDown":
				$FaceDownBind = %action;
			case "faceLeft":
				$FaceLeftBind = %action;
			case "faceRight":
				$FaceRightBind = %action;
				
			case "enterLevel":
				$EnterLevelBind = %action;
			case "firePrimary":
				$PrimaryBind = %action;
				
			case "cycleCharacter":
				$CycleCharacterBind = %action;
			case "reverseCycleCharacter":
				$ReverseCycleCharacterBind = %action;
			case "selectLeader":
				$SelectLeaderBind = %action;
			case "selectScout":
				$SelectScoutBind = %action;
			case "selectGrenadier":
				$SelectGrenadierBind = %action;
			case "selectSupport":
				$SelectSupportBind = %action;
				
			case "interact":
				$InteractBind = %action;
			case "grab":
				$GrabBind = %action;
			case "downscale":
				$DownscaleBind = %action;
			case "upscale":
				$UpscaleBind = %action;
			case "promotions":
				$PromotionsBind = %action;
			case "grenade":
				$WeaponAttachmentBind = %action;
			case "GuardMode":
				$GuardModeBind = %action;
				
			case "mainMenu":
				$MainMenuBind = %action;
			case "endTurn":
				$EndturnBind = %action;
				
			case "toggleSolo":
				$ToggleSoloBind = %action;
				
			case "toggleTutorial":
				$ToggleTutorialBind = %action;
				
			case "talentSlot1":
				$TalentSlot1Bind = %action;
			case "talentSlot2":
				$TalentSlot2Bind = %action;
			case "talentSlot3":
				$TalentSlot3Bind = %action;
			case "talentSlot4":
				$TalentSlot4Bind = %action;
				
			case "reload":
				$ReloadBind = %action;
				
			case "squadInfo":
				$SquadInfoBind = %action;
				
			case "nextItem":
				$NextItemBind = %action;
			case "joystickTriggerRight":
			echo("joystickTriggerRight action =" SPC %action);
				$NextItemBind = %action;
				
			case "prevItem":
				$PrevItemBind = %action;
			case "joystickTriggerLeft":
			echo("joystickTriggerLeft action =" SPC %action);
				$PrevItemBind = %action;
				
			case "useItem":
				$UseItemBind = %action;
			case "dropItem":
				$DropItemBind = %action;
		}
	}
}

// Saves default keybindings to a preference file.
function saveDefaultKeybindingsToFile ()
{//echo("saveDefaultKeybindingsToFile()");
	// Open the file for writing.
	%filepath = expandFilename($UserDirectory @ "/Worthless Bums/Steam Marines/keybindings.cs");
	//echo("%filepath =" SPC %filepath);
	// Create the file object.
	%saveFile = new fileobject();
	//%ret = %saveFile.OpenForWrite(%filepath);
	%ret = %saveFile.OpenForWrite(getUserDataDirectory() @ "/Worthless Bums/Steam Marines/keybindings.cs");
	//echo("%ret =" SPC %ret);
	
	// Set global binds back to defaults.
	$UpBind = "keyboard up";
	$DownBind = "keyboard down";
	$LeftBind = "keyboard left";
	$RightBind = "keyboard right";
	
	$FaceUpBind = "shift up";
	$FaceDownBind = "shift down";
	$FaceLeftBind = "shift left";
	$FaceRightBind = "shift right";
	
	$EnterLevelBind = "keyboard l";
	$PrimaryBind = "keyboard z";
	$SecondaryBind = "keyboard x";
	
	$CycleCharacterBind = "keyboard tab";
	$ReverseCycleCharacterBind = "keyboard lcontrol";
	$SelectLeaderBind = "keyboard f1";
	$SelectScoutBind = "keyboard f2";
	$SelectGrenadierBind = "keyboard f3";
	$SelectSupportBind = "keyboard f4";
	
	$ToggleSoloBind = "keyboard s";
	$ToggleTutorialBind = "keyboard t";
	
	$InteractBind = "keyboard e";
	$GrabBind = "keyboard g";
	$DownscaleBind = "keyboard minus";
	$UpscaleBind = "keyboard =";
	$PromotionsBind = "keyboard p";
	$WeaponAttachmentBind = "keyboard c";
	$GuardModeBind = "keyboard q";
	
	$MainMenuBind = "keyboard escape";
	$EndTurnBind = "keyboard enter";
	$TargetPlanetBind = "keyboard q";
	$ZoomInBind = "keyboard numpadadd";
	$ZoomOutBind = "keyboard numpadminus";
	
	$TalentSlot1Bind = "keyboard 1";
	$TalentSlot2Bind = "keyboard 2";
	$TalentSlot3Bind = "keyboard 3";
	$TalentSlot4Bind = "keyboard 4";
	
	$ReloadBind = "keyboard r";
	
	$SquadInfoBind = "keyboard i";
	
	$NextItemBind = "keyboard ]";
	$PrevItemBind = "keyboard [";
	$UseItemBind = 	"keyboard backslash";
	$DropItemBind = "keyboard backspace";
	
	// Variables we track in the keybinds file.
	// Write the data we need to save.
	%saveFile.WriteLine("$UpBind " @ $UpBind);
	%saveFile.WriteLine("$DownBind " @ $DownBind);
	%saveFile.WriteLine("$LeftBind " @ $LeftBind);
	%saveFile.WriteLine("$RightBind " @ $RightBind);
	
	%saveFile.WriteLine("$FaceUpBind " @ $FaceUpBind);
	%saveFile.WriteLine("$FaceDownBind " @ $FaceDownBind);
	%saveFile.WriteLine("$FaceLeftBind " @ $FaceLeftBind);
	%saveFile.WriteLine("$FaceRightBind " @ $FaceRightBind);
	
	%saveFile.WriteLine("$EnterLevelBind " @ $EnterLevelBind);
	%saveFile.WriteLine("$PrimaryBind " @ $PrimaryBind);
	//%saveFile.WriteLine("$SecondaryBind " @ $SecondaryBind);
	
	%saveFile.WriteLine("$CycleCharacterBind " @ $CycleCharacterBind);
	%saveFile.WriteLine("$ReverseCycleCharacterBind " @ $ReverseCycleCharacterBind);
	%saveFile.WriteLine("$SelectLeaderBind " @ $SelectLeaderBind);
	%saveFile.WriteLine("$SelectScoutBind " @ $SelectScoutBind);
	%saveFile.WriteLine("$SelectGrenadierBind " @ $SelectGrenadierBind);
	%saveFile.WriteLine("$SelectSupportBind " @ $SelectSupportBind);
	
	%saveFile.WriteLine("$InteractBind " @ $InteractBind);
	%saveFile.WriteLine("$GrabBind " @ $GrabBind);
	%saveFile.WriteLine("$DownscaleBind " @ $DownscaleBind);
	%saveFile.WriteLine("$UpscaleBind " @ $UpscaleBind);
	%saveFile.WriteLine("$PromotionsBind " @ $PromotionsBind);
	%saveFile.WriteLine("$WeaponAttachmentBind " @ $WeaponAttachmentBind);
	%saveFile.WriteLine("$GuardModeBind " @ $GuardModeBind);
	
	%saveFile.WriteLine("$MainMenuBind " @ $MainMenuBind);
	
	%saveFile.WriteLine("$EndTurnBind " @ $EndTurnBind);
	
	%saveFile.WriteLine("$ToggleSoloBind " @ $ToggleSoloBind);
	
	%saveFile.WriteLine("$ToggleTutorialBind " @ $ToggleTutorialBind);
	
	%saveFile.WriteLine("$TalentSlot1Bind " @ $TalentSlot1Bind);
	%saveFile.WriteLine("$TalentSlot2Bind " @ $TalentSlot2Bind);
	%saveFile.WriteLine("$TalentSlot3Bind " @ $TalentSlot3Bind);
	%saveFile.WriteLine("$TalentSlot4Bind " @ $TalentSlot4Bind);
	
	%saveFile.WriteLine("$ReloadBind " @ $ReloadBind);
	
	%saveFile.WriteLine("$SquadInfoBind " @ $SquadInfoBind);
	
	%saveFile.WriteLine("$NextItemBind " @ $NextItemBind);
	%saveFile.WriteLine("$PrevItemBind " @ $PrevItemBind);
	%saveFile.WriteLine("$UseItemBind " @ $UseItemBind);
	%saveFile.WriteLine("$DropItemBind " @ $DropItemBind);
	
	// Close the save file.
	%saveFile.close();
}
// Saves keybindings to a preference file.
function saveKeybindingsToFile ()
{//echo("saveKeybindingsToFile()");echo("$NextItemBind =" SPC $NextItemBind);echo("$UseItemBind =" SPC $UseItemBind);
	// Before saving force all the global bindings to be updated.
	updateKeybinds();
	
	// Strip all tabs and replace with spaces!
	$UpBind = strreplace($UpBind, "	", " ");
	$DownBind = strreplace($DownBind, "	", " ");
	$LeftBind = strreplace($LeftBind, "	", " ");
	$RightBind = strreplace($RightBind, "	", " ");
	
	$FaceUpBind = strreplace($FaceUpBind, "	", " ");
	$FaceDownBind = strreplace($FaceDownBind, "	", " ");
	$FaceLeftBind = strreplace($FaceLeftBind, "	", " ");
	$FaceRightBind = strreplace($FaceRightBind, "	", " ");
	
	$EnterLevelBind = strreplace($EnterLevelBind, "	", " ");
	$PrimaryBind = strreplace($PrimaryBind, "	", " ");
	
	$CycleCharacterBind = strreplace($CycleCharacterBind, "	", " ");
	$ReverseCycleCharacterBind = strreplace($ReverseCycleCharacterBind, "	", " ");
	$SelectLeaderBind = strreplace($SelectLeaderBind, "	", " ");
	$SelectScoutBind = strreplace($SelectScoutBind, "	", " ");
	$SelectGrenadierBind = strreplace($SelectGrenadierBind, "	", " ");
	$SelectSupportBind = strreplace($SelectSupportBind, "	", " ");
	
	$InteractBind = strreplace($InteractBind, "	", " ");
	$GrabBind = strreplace($GrabBind, "	", " ");
	$DownscaleBind = strreplace($DownscaleBind, "	", " ");
	$UpscaleBind = strreplace($UpscaleBind, "	", " ");
	$PromotionsBind = strreplace($PromotionsBind, "	", " ");
	$WeaponAttachmentBind = strreplace($WeaponAttachmentBind, "	", " ");
	$GuardModeBind = strreplace($GuardModeBind, "	", " ");
	
	$MainMenuBind = strreplace($MainMenuBind, "	", " ");
	$EndTurnBind = strreplace($EndTurnBind, "	", " ");
	$ToggleSoloBind = strreplace($ToggleSoloBind, "	", " ");
	$ToggleTutorialBind = strreplace($ToggleTutorialBind, "	", " ");
	
	$TalentSlot1Bind = strreplace($TalentSlot1Bind, "	", " ");
	$TalentSlot2Bind = strreplace($TalentSlot2Bind, "	", " ");
	$TalentSlot3Bind = strreplace($TalentSlot3Bind, "	", " ");
	$TalentSlot4Bind = strreplace($TalentSlot4Bind, "	", " ");
	
	$ReloadBind = strreplace($ReloadBind, "	", " ");
	$SquadInfoBind = strreplace($SquadInfoBind, "	", " ");
	
	$NextItemBind = strreplace($NextItemBind, "	", " ");
	$PrevItemBind = strreplace($PrevItemBind, "	", " ");
	$UseItemBind = strreplace($UseItemBind, "	", " ");
	$DropItemBind = strreplace($DropItemBind, "	", " ");
	
	// Create the file object.
	%saveFile = new fileobject();
	
	// Open the file for writing.
	%ret = %saveFile.OpenForWrite(getUserDataDirectory() @ "/Worthless Bums/Steam Marines/keybindings.cs");
	//echo("%ret =" SPC %ret);
	
	// Variables we track in the keybinds file.
	// Write the data we need to save.
	%saveFile.WriteLine("$UpBind " @ $UpBind);
	%saveFile.WriteLine("$DownBind " @ $DownBind);
	%saveFile.WriteLine("$LeftBind " @ $LeftBind);
	%saveFile.WriteLine("$RightBind " @ $RightBind);
	
	%saveFile.WriteLine("$FaceUpBind " @ $FaceUpBind);
	%saveFile.WriteLine("$FaceDownBind " @ $FaceDownBind);
	%saveFile.WriteLine("$FaceLeftBind " @ $FaceLeftBind);
	%saveFile.WriteLine("$FaceRightBind " @ $FaceRightBind);
	
	%saveFile.WriteLine("$EnterLevelBind " @ $EnterLevelBind);
	%saveFile.WriteLine("$PrimaryBind " @ $PrimaryBind);
	//%saveFile.WriteLine("$SecondaryBind " @ $SecondaryBind);
	
	%saveFile.WriteLine("$CycleCharacterBind " @ $CycleCharacterBind);
	%saveFile.WriteLine("$ReverseCycleCharacterBind " @ $ReverseCycleCharacterBind);
	%saveFile.WriteLine("$SelectLeaderBind " @ $SelectLeaderBind);
	%saveFile.WriteLine("$SelectScoutBind " @ $SelectScoutBind);
	%saveFile.WriteLine("$SelectGrenadierBind " @ $SelectGrenadierBind);
	%saveFile.WriteLine("$SelectSupportBind " @ $SelectSupportBind);
	
	%saveFile.WriteLine("$InteractBind " @ $InteractBind);
	%saveFile.WriteLine("$GrabBind " @ $GrabBind);
	%saveFile.WriteLine("$DownscaleBind " @ $DownscaleBind);
	%saveFile.WriteLine("$UpscaleBind " @ $UpscaleBind);
	%saveFile.WriteLine("$PromotionsBind " @ $PromotionsBind);
	%saveFile.WriteLine("$WeaponAttachmentBind " @ $WeaponAttachmentBind);
	%saveFile.WriteLine("$GuardModeBind " @ $GuardModeBind);
	
	%saveFile.WriteLine("$MainMenuBind " @ $MainMenuBind);
	%saveFile.WriteLine("$EndTurnBind " @ $EndTurnBind);
	%saveFile.WriteLine("$ToggleSoloBind " @ $ToggleSoloBind);
	%saveFile.WriteLine("$ToggleTutorialBind " @ $ToggleTutorialBind);
	
	//%saveFile.WriteLine("$ZoomInBind " @ $ZoomInBind);
	//%saveFile.WriteLine("$ZoomOutBind " @ $ZoomOutBind);
	
	%saveFile.WriteLine("$TalentSlot1Bind " @ $TalentSlot1Bind);
	%saveFile.WriteLine("$TalentSlot2Bind " @ $TalentSlot2Bind);
	%saveFile.WriteLine("$TalentSlot3Bind " @ $TalentSlot3Bind);
	%saveFile.WriteLine("$TalentSlot4Bind " @ $TalentSlot4Bind);
	
	%saveFile.WriteLine("$ReloadBind " @ $ReloadBind);
	
	%saveFile.WriteLine("$SquadInfoBind " @ $SquadInfoBind);
	
	%saveFile.WriteLine("$NextItemBind " @ $NextItemBind);
	%saveFile.WriteLine("$PrevItemBind " @ $PrevItemBind);
	%saveFile.WriteLine("$UseItemBind "  @ $UseItemBind);
	%saveFile.WriteLine("$DropItemBind " @ $DropItemBind);
	
	// Close the save file.
	%saveFile.close();
}

// Helper function that returns true iff the second of the specified string is a keybind modifier!
function hasKeyModifier (%srcString)
{//echo("hasKeyModifier()");
	%wordCheck = getWord(%srcString, 1);
	if (%wordCheck $= "shift"	||
		%wordCheck $= "ctrl"	||
		%wordCheck $= "alt")
	{
		return true;
	}
	return false;
}

// Binds a custom key.
function bindCustomKey (%keybind, %line)
{//echo("bindCustomKey()");
	%keybind = restWords(%line);
	%keybind = strreplace(%keybind, "	", " ");
	// If key modifiers are in the bind, strip devices from the bind!
	if (hasKeyModifier(%keybind))
	{
		// Strip "keyboard" from bind!
		%keybind = strreplace(%keybind, "keyboard ", "");
		// Strip "joystick0" and "joystick1" from bind!
		%keybind = strreplace(%keybind, "joystick0 ", "");
		%keybind = strreplace(%keybind, "joystick1 ", "");
	}
	//echo(%keybind);
	
	// Return keybind.
	return %keybind;
}

// Loads keybindings from a preference file.
function loadKeybindingsFromFile ()
{//echo("loadKeybindingsFromFile()");
	// Load the saved preferences (keybindings).
	// The save file object.
	%saveFile = new fileobject();
	// Check the file open status.
	%ret = %saveFile.OpenForRead(getUserDataDirectory() @ "/Worthless Bums/Steam Marines/keybindings.cs");
	//echo("%ret =" SPC %ret);
	
	// Can't open the file.
	if (%ret == -1)
	{//echo("can't open - failed!");
		// This is super bad.
		return false;
	}
	
	// Variables we track in the save file.
	for (%line = %saveFile.ReadLine(); !(%line $= ""); %line = %saveFile.ReadLine())
	{
		// Get a line.
		%word = GetWord(%line, 0);
		//echo("%word =" SPC %word);
		
		// Load each parameter by line keyword.
		switch$ (%word)
		{
			case "$UpBind":
				$UpBind = bindCustomKey($UpBind, %line);
			case "$DownBind":
				$DownBind = bindCustomKey($DownBind, %line);
			case "$LeftBind":
				$LeftBind = bindCustomKey($LeftBind, %line);
			case "$RightBind":
				$RightBind = bindCustomKey($RightBind, %line);
				
			case "$FaceUpBind":
				$FaceUpBind = bindCustomKey($FaceUpBind, %line);
			case "$FaceDownBind":
				$FaceDownBind = bindCustomKey($FaceDownBind, %line);
			case "$FaceLeftBind":
				$FaceLeftBind = bindCustomKey($FaceLeftBind, %line);
			case "$FaceRightBind":
				$FaceRightBind = bindCustomKey($FaceRightBind, %line);
				
			case "$EnterLevelBind":
				$EnterLevelBind = bindCustomKey($EnterLevelBind, %line);
			case "$PrimaryBind":
				$PrimaryBind = bindCustomKey($PrimaryBind, %line);
			
			case "$CycleCharacterBind":
				$CycleCharacterBind = bindCustomKey($CycleCharacterBind, %line);
			case "$ReverseCycleCharacterBind":
				$ReverseCycleCharacterBind = bindCustomKey($ReverseCycleCharacterBind, %line);
			case "$SelectLeaderBind":
				$SelectLeaderBind = bindCustomKey($SelectLeaderBind, %line);
			case "$SelectScoutBind":
				$SelectScoutBind = bindCustomKey($SelectScoutBind, %line);
			case "$SelectGrenadierBind":
				$SelectGrenadierBind = bindCustomKey($SelectGrenadierBind, %line);
			case "$SelectSupportBind":
				$SelectSupportBind = bindCustomKey($SelectSupportBind, %line);
				
			case "$InteractBind":
				$InteractBind = bindCustomKey($InteractBind, %line);
			case "$GrabBind":
				$GrabBind = bindCustomKey($GrabBind, %line);
			case "$DownscaleBind":
				$DownscaleBind = bindCustomKey($DownscaleBind, %line);
			case "$UpscaleBind":
				$UpscaleBind = bindCustomKey($UpscaleBind, %line);
			case "$PromotionsBind":
				$PromotionsBind = bindCustomKey($PromotionsBind, %line);
			case "$WeaponAttachmentBind":
				$WeaponAttachmentBind = bindCustomKey($WeaponAttachmentBind, %line);
			case "$GuardModeBind":
				$GuardModeBind = bindCustomKey($GuardModeBind, %line);
				
			case "$MainMenuBind":
				$MainMenuBind = bindCustomKey($MainMenuBind, %line);
			case "$EndTurnBind":
				$EndTurnBind = bindCustomKey($EndTurnBind, %line);
				
			case "$ToggleSoloBind":
				$ToggleSoloBind = bindCustomKey($ToggleSoloBind, %line);
				
			case "$ToggleTutorialBind":
				$ToggleTutorialBind = bindCustomKey($ToggleTutorialBind, %line);
			
			case "$TalentSlot1Bind":
				$TalentSlot1Bind = bindCustomKey($TalentSlot1Bind, %line);
			case "$TalentSlot2Bind":
				$TalentSlot2Bind = bindCustomKey($TalentSlot2Bind, %line);
			case "$TalentSlot3Bind":
				$TalentSlot3Bind = bindCustomKey($TalentSlot3Bind, %line);
			case "$TalentSlot4Bind":
				$TalentSlot4Bind = bindCustomKey($TalentSlot4Bind, %line);
				
			case "$ReloadBind":
				$ReloadBind = bindCustomKey($ReloadBind, %line);
				
			case "$SquadInfoBind":
				$SquadInfoBind = bindCustomKey($SquadInfoBind, %line);
				
			case "$NextItemBind":
				$NextItemBind = bindCustomKey($NextItemBind, %line);
			case "$PrevItemBind":
				$PrevItemBind = bindCustomKey($PrevItemBind, %line);
			case "$UseItemBind":
				$UseItemBind = bindCustomKey($UseItemBind, %line);
			case "$DropItemBind":
				$DropItemBind = bindCustomKey($DropItemBind, %line);
		}
	}
	%saveFile.close();
	return true;
}
function getDeviceFromKeybind (%keybind)
{//echo("getDeviceFromKeybind()");
	%word = getWord(%keybind, 0);
	switch$ (%word)
	{
		case "keyboard": 	return -1;
		case "joystick0":	return 0;
		case "joystick1":	return 1;
	}
	return -1;		// Default to keyboard.
}
function setupInputs ()
{//echo("setupInputs()");
	%prefFile = new fileobject();
	%ret = %prefFile.OpenForRead(getUserDataDirectory() @ "/Worthless Bums/Steam Marines/keybindings.cs");
	if (!%ret)
	{//echo("can't open file, setupInputs() loading defaults!");
		%prefFile.close();
		saveDefaultKeybindingsToFile();
		setupInputs();
		return;
	}

	$enableDirectInput = "1";
	activateDirectInput();
	
	// If the load fails, set default bindings.
	%loadKeybindState = loadKeybindingsFromFile();
	if (!%loadKeybindState)
	{//echo("??!");
		$UpBind = "keyboard up";
		$DownBind = "keyboard down";
		$LeftBind = "keyboard left";
		$RightBind = "keyboard right";
		
		$FaceUpBind = "shift up";
		$FaceDownBind = "shift down";
		$FaceLeftBind = "shift left";
		$FaceRightBind = "shift right";
		
		$EnterLevelBind = "keyboard l";
		$PrimaryBind = "keyboard z";
		$SecondaryBind = "keyboard x";
		
		$CycleCharacterBind = "keyboard tab";
		$ReverseCycleCharacterBind = "keyboard lcontrol";
		$SelectLeaderBind = "keyboard f1";
		$SelectScoutBind = "keyboard f2";
		$SelectGrenadierBind = "keyboard f3";
		$SelectSupportBind = "keyboard f4";
		
		$InteractBind = "keyboard e";
		$GrabBind = "keyboard g";
		
		$DownscaleBind = "keyboard minus";
		$UpscaleBind = "keyboard =";
		
		$PromotionsBind = "keyboard p";
		$MainMenuBind = "keyboard escape";
		$WeaponAttachmentBind = "keyboard c";
		$GuardModeBind = "keyboard q";
		
		$EndTurnBind = "keyboard enter";
		$ToggleSoloBind = "keyboard s";
		$ToggleTutorialBind = "keyboard t";
		
		$TalentSlot1Bind = "keyboard 1";
		$TalentSlot2Bind = "keyboard 2";
		$TalentSlot3Bind = "keyboard 3";
		$TalentSlot4Bind = "keyboard 4";
		
		$ReloadBind = "keyboard r";
		
		$SquadInfoBind = "keyboard i";
		
		$NextItemBind = "keyboard ]";
		$PrevItemBind = "keyboard [";
		$UseItemBind  = "keyboard backslash";
		$DropItemBind = "keyboard backspace";
	}
	
	// Delete moveMap if necessary.
	if (isObject(moveMap))
	{
		moveMap.delete();
	}
	
	new ActionMap(moveMap);
	
	// Setup the keybinding package which sniffs our bindings to display them to the options dialog.
	activatePackage(KeybindPackage);
	
	// These are the "bindings" which will call the specified script functions (they're up above this) when an input event is recieved from one of the input devices.
	moveMap.bind(keyboard, $UpBind, "up", "Move Up");										// Works!
	moveMap.bind(keyboard, $DownBind, "down", "Move Down");									// Works!
	moveMap.bind(keyboard, $LeftBind, "left", "Move Left");									// Works!
	moveMap.bind(keyboard, $RightBind, "right", "Move Right");								// Works!
	
	moveMap.bind(keyboard, $FaceUpBind, "faceUp", "Face Up");								// Works!
	moveMap.bind(keyboard, $FaceDownBind, "faceDown", "Face Down");							// Works!
	moveMap.bind(keyboard, $FaceLeftBind, "faceLeft", "Face Left");							// Works!
	moveMap.bind(keyboard, $FaceRightBind, "faceRight", "Face Right");						// Works!
	
	moveMap.bind(keyboard, $EnterLevelBind, "enterLevel", "Use Elevator");					// Works!
	moveMap.bind(keyboard, $PrimaryBind, "firePrimary", "Fire");							// Works!
	
	moveMap.bind(keyboard, $CycleCharacterBind, "cycleCharacter", "Cycle Squad");			// Works!
	moveMap.bind(keyboard, $ReverseCycleCharacterBind, "reverseCycleCharacter", "Reverse Cycle Squad");	// Works!
	moveMap.bind(keyboard, $SelectLeaderBind, "selectLeader", "Select Leader");				// Works!
	moveMap.bind(keyboard, $SelectScoutBind, "selectScout", "Select Scout");				// Works!
	moveMap.bind(keyboard, $SelectGrenadierBind , "selectGrenadier", "Select Grenadier");	// Works!
	moveMap.bind(keyboard, $SelectSupportBind, "selectSupport", "Select Support");			// Works!
	
	moveMap.bind(keyboard, $InteractBind, "interact", "Interact");							// Works!
	moveMap.bind(keyboard, $GrabBind, "grab", "Grab");										// Works!
	moveMap.bind(keyboard, $DownscaleBind, "downscale", "Zoom Out");						// Works!
	moveMap.bind(keyboard, $UpscaleBind, "upscale", "Zoom In");								// Works!
	moveMap.bind(keyboard, $PromotionsBind, "promotions", "Promotion Screen");				// Works!
	moveMap.bind(keyboard, $WeaponAttachmentBind, "grenade", "Weapon Attachment");			// Works!
	moveMap.bind(keyboard, $GuardModeBind, "guardMode", "Guard Mode");						// Works!
	
	moveMap.bind(keyboard, $MainMenuBind, "mainMenu", "Main Menu/Pause");					// Works!
	moveMap.bind(keyboard, $EndTurnBind, "endTurn", "End Turn");							// Works!
	moveMap.bind(keyboard, $ToggleSoloBind, "toggleSolo", "Event Log");						// Works!
	moveMap.bind(keyboard, $ToggleTutorialBind, "toggleTutorial", "Tutorial");				// Works!
	
	moveMap.bind(keyboard, $TalentSlot1Bind, "talentSlot1", "Talent Slot 1");				// Works!
	moveMap.bind(keyboard, $TalentSlot2Bind, "talentSlot2", "Talent Slot 2");				// Works!
	moveMap.bind(keyboard, $TalentSlot3Bind, "talentSlot3", "Talent Slot 3");				// Works!
	moveMap.bind(keyboard, $TalentSlot4Bind, "talentSlot4", "Talent Slot 4");				// Works!
	
	moveMap.bind(keyboard, $ReloadBind, "reload", "Reload / Discard Suit");					// Works!
	
	moveMap.bind(keyboard, $SquadInfoBind, "squadInfo", "Squad Info");						// Works!
	
	
	// HACK
	if (strstr($NextItemBind, "joystick") >= 0)
	{
		moveMap.bind(keyboard, $NextItemBind, "joystickTriggers", "Next Item");				// Works!
	}
	else
	{
		moveMap.bind(keyboard, $NextItemBind, "nextItem", "Next Item");						// Works!
	}
	if (strstr($PrevItemBind, "joystick") >= 0)
	{
		moveMap.bind(keyboard, $PrevItemBind, "joystickTriggers", "Next Item");				// Works!
	}
	else
	{
		moveMap.bind(keyboard, $PrevItemBind, "prevItem", "Next Item");						// Works!
	}
	// END OF HACK
	
	
	moveMap.bind(keyboard, $UseItemBind,  "useItem", "Use Item");							// Works!
	moveMap.bind(keyboard, $DropItemBind, "dropItem", "Drop Item");							// Works!
	
	deactivatePackage(KeybindPackage);
	%prefFile.close();
	moveMap.push();
}

// Sets up default Xbox 360 controller hardbinds!
function setupXbox360DefaultHardbinds ()
{//echo("setupXbox360DefaultHardbinds()");
	%prefFile = new fileobject();
	%ret = %prefFile.OpenForRead(getUserDataDirectory() @ "/Worthless Bums/Steam Marines/keybindings.cs");
	if (!%ret)
	{//echo("can't open file, setupInputs() loading defaults!");
		%prefFile.close();
		saveDefaultKeybindingsToFile();
		setupInputs();
		return;
	}

	$enableDirectInput = "1";
	activateDirectInput();
	
	// If the load fails, set default bindings.
	%loadKeybindState = loadKeybindingsFromFile();
	if (!%loadKeybindState)
	{//echo("??!");
		$UpBind = "keyboard up";
		$DownBind = "keyboard down";
		$LeftBind = "keyboard left";
		$RightBind = "keyboard right";
		
		$FaceUpBind = "shift up";
		$FaceDownBind = "shift down";
		$FaceLeftBind = "shift left";
		$FaceRightBind = "shift right";
		
		$EnterLevelBind = "keyboard l";
		$PrimaryBind = "keyboard z";
		$SecondaryBind = "keyboard x";
		
		$CycleCharacterBind = "keyboard tab";
		$ReverseCycleCharacterBind = "keyboard lcontrol";
		$SelectLeaderBind = "keyboard f1";
		$SelectScoutBind = "keyboard f2";
		$SelectGrenadierBind = "keyboard f3";
		$SelectSupportBind = "keyboard f4";
		
		$InteractBind = "keyboard e";
		$GrabBind = "keyboard g";
		
		$DownscaleBind = "keyboard minus";
		$UpscaleBind = "keyboard =";
		
		$PromotionsBind = "keyboard p";
		$MainMenuBind = "keyboard escape";
		$WeaponAttachmentBind = "keyboard c";
		$GuardModeBind = "keyboard q";
		
		$EndTurnBind = "keyboard enter";
		$ToggleSoloBind = "keyboard s";
		$ToggleTutorialBind = "keyboard t";
		
		$TalentSlot1Bind = "keyboard 1";
		$TalentSlot2Bind = "keyboard 2";
		$TalentSlot3Bind = "keyboard 3";
		$TalentSlot4Bind = "keyboard 4";
		
		$ReloadBind = "keyboard r";
		
		$SquadInfoBind = "keyboard i";
		
		$NextItemBind = "keyboard ]";
		$PrevItemBind = "keyboard [";
		$UseItemBind  = "keyboard backslash";
		$DropItemBind = "keyboard backspace";
	}
	
	// Delete moveMap if necessary.
	if (isObject(moveMap))
	{
		moveMap.delete();
	}
	
	new ActionMap(moveMap);
	
	// Setup the keybinding package which sniffs our bindings to display them to the options dialog.
	activatePackage(KeybindPackage);
	
	// Reset keybind count!
	//$keybindCount = 0;
	
	// MAC: Xbox 360 controller hardbinds!
	if ($platform $= "macos")
	{
		moveMap.bind(joystick0, "joystick0 button5", "up", "Move Up");							// Works!
		moveMap.bind(joystick0, "joystick0 button6", "down", "Move Down");						// Works!
		moveMap.bind(joystick0, "joystick0 button7", "left", "Move Left");						// Works!
		moveMap.bind(joystick0, "joystick0 button8", "right", "Move Right");					// Works!
		
		moveMap.bind(joystick0, "joystick0 button14", "enterLevel", "Use Elevator");			// Works!
		moveMap.bind(joystick0, "joystick0 button12", "firePrimary", "Fire");					// Works!
		
		moveMap.bind(joystick0, "joystick0 button13", "cycleCharacter", "Cycle Squad");		// Works!
		
		moveMap.bind(joystick0, "joystick0 button16", "interact", "Interact");					// Works!
		moveMap.bind(joystick0, "joystick0 button18", "grab", "Grab");							// Works!
		moveMap.bind(joystick0, "joystick0 button17", "grenade", "Weapon Attachment");			// Works!
		moveMap.bind(joystick0, "joystick0 button19", "guardMode", "Guard Mode");				// Works!
		
		moveMap.bind(joystick0, "joystick0 button10", "mainMenu", "Main Menu/Pause");			// Works!
		moveMap.bind(joystick0, "joystick0 button9", "endTurn", "End Turn");					// Works!
		
		moveMap.bind(joystick0, "joystick0 button11", "reload", "Reload / Discard Suit");		// Works!
	}
	// WINDOWS: Xbox 360 controller hardbinds!
	else
	{//echo("BINDING XBOX WINDOWS BUTTONS.");
		moveMap.bind(joystick0, "joystick0 upov", "up", "Move Up");							// Works!
		moveMap.bind(joystick0, "joystick0 dpov", "down", "Move Down");						// Works!
		moveMap.bind(joystick0, "joystick0 lpov", "left", "Move Left");						// Works!
		moveMap.bind(joystick0, "joystick0 rpov", "right", "Move Right");						// Works!
		
		moveMap.bind(joystick0, "joystick0 button5", "enterLevel", "Use Elevator");			// Works!
		moveMap.bind(joystick0, "joystick0 button9", "firePrimary", "Fire");					// Works!
		
		moveMap.bind(joystick0, "joystick0 button4", "cycleCharacter", "Cycle Squad");			// Works!
		
		moveMap.bind(joystick0, "joystick0 button0", "interact", "Interact");					// Works!
		moveMap.bind(joystick0, "joystick0 button2", "grab", "Grab");							// Works!
		moveMap.bind(joystick0, "joystick0 button1", "grenade", "Weapon Attachment");			// Works!
		moveMap.bind(joystick0, "joystick0 button3", "guardMode", "Guard Mode");				// Works!
		
		//moveMap.bind(joystick0, "joystick0 button6", "mainMenu", "Main Menu/Pause");			// Works!
		moveMap.bind(joystick0, "keyboard escape", "mainMenu", "Main Menu/Pause");				// Works!
		moveMap.bind(joystick0, "joystick0 button7", "endTurn", "End Turn");					// Works!
		
		moveMap.bind(joystick0, "joystick0 button8", "reload", "Reload / Discard Suit");		// Works!
		
		$PrevItemBind = "joystick0 zaxis";
		$NextItemBind = "joystick0 rzaxis";
		moveMap.bind(joystick0, $PrevItemBind, "joystickTriggerLeft", "Previous Item");
		moveMap.bind(joystick0, $NextItemBind, "joystickTriggerRight", "Next Item");
		moveMap.bind(joystick0, "joystick0 button6", "useItem", "Use Item");
	}
	
	deactivatePackage(KeybindPackage);
	%prefFile.close();
	moveMap.push();
	saveKeybindingsToFile();
}
function setupDefaultInputs ()
{//echo("setupDefaultInputs()");
	// Setup default keybinds.
	$UpBind = "keyboard up";
	$DownBind = "keyboard down";
	$LeftBind = "keyboard left";
	$RightBind = "keyboard right";
	
	$FaceUpBind = "shift up";
	$FaceDownBind = "shift down";
	$FaceLeftBind = "shift left";
	$FaceRightBind = "shift right";
	
	$EnterLevelBind = "keyboard l";
	$PrimaryBind = "keyboard z";
	$CycleCharacterBind = "keyboard tab";
	$ReverseCycleCharacterBind = "keyboard lcontrol";
	
	$InteractBind = "keyboard e";
	$GrabBind = "keyboard g";
	$DownscaleBind = "keyboard minus";
	$UpscaleBind = "keyboard =";
	$PromotionsBind = "keyboard p";
	$WeaponAttachmentBind = "keyboard c";
	$GuardModeBind = "keyboard q";
	
	$MainMenuBind = "keyboard escape";
	$EndTurnBind = "keyboard enter";
	$ToggleSoloBind = "keyboard s";
	$ToggleTutorialBind = "keyboard t";
	
	$TalentSlot1Bind = "keyboard 1";
	$TalentSlot2Bind = "keyboard 2";
	$TalentSlot3Bind = "keyboard 3";
	$TalentSlot4Bind = "keyboard 4";
	
	$ReloadBind = "keyboard r";
	
	$SquadInfoBind = "keyboard i";
	
	$NextItemBind = "keyboard ]";
	$PrevItemBind = "keyboard [";
	$UseItemBind  = "keyboard backslash";
	$DropItemBind = "keyboard backspace";
	
	saveKeybindingsToFile();
	$enableDirectInput = "1";
	activateDirectInput();
	
	if (isObject(moveMap))
	{
		moveMap.delete();
	}
	new ActionMap(moveMap);
	
	activatePackage(KeybindPackage);
	
	// These are the "bindings" which will call the specified script functions (they're up above this) when an input event is recieved from one of the input devices.
	moveMap.bind(keyboard, $UpBind, "up");												// Works!
	moveMap.bind(keyboard, $DownBind, "down");											// Works!
	moveMap.bind(keyboard, $LeftBind, "left");											// Works!
	moveMap.bind(keyboard, $RightBind, "right");										// Works!
	
	moveMap.bind(keyboard, $FaceUpBind, "faceUp");										// Works!
	moveMap.bind(keyboard, $FaceDownBind, "faceDown");									// Works!
	moveMap.bind(keyboard, $FaceLeftBind, "faceLeft");									// Works!
	moveMap.bind(keyboard, $FaceRightBind, "faceRight");								// Works!
	
	moveMap.bind(keyboard, $EnterLevelBind, "enterLevel");								// Works!
	moveMap.bind(keyboard, $PrimaryBind, "firePrimary");								// Works!
	moveMap.bind(keyboard, $CycleCharacterBind, "cycleCharacter");						// Works!
	moveMap.bind(keyboard, $ReverseCycleCharacterBind, "reverseCycleCharacter");		// Works!
	
	moveMap.bind(keyboard, $InteractBind, "interact");									// Works!
	moveMap.bind(keyboard, $GrabBind, "grab");											// Works!
	moveMap.bind(keyboard, $SquadInfoBind, "squadInfo");								// Works!
	moveMap.bind(keyboard, $PromotionsBind, "promotions");								// Works!
	moveMap.bind(keyboard, $WeaponAttachmentBind, "grenade", "Weapon Attachment");		// Works!
	moveMap.bind(keyboard, $GuardModeBind, "guardMode", "Guard Mode");					// Works!
	
	moveMap.bind(keyboard, $MainMenuBind , "mainMenu");									// Works!
	moveMap.bind(keyboard, $EndTurnBind , "targetClosestHostileControl");				// Works!
	moveMap.bind(keyboard, $ToggleSoloBind , "toggleSolo");								// Works!
	moveMap.bind(keyboard, $ToggleTutorialBind , "faceTarget");							// Works!
	
	moveMap.bind(keyboard, $TalentSlot1Bind, "talentSlot1", "Talent Slot 1");			// Works!
	moveMap.bind(keyboard, $TalentSlot2Bind, "talentSlot2", "Talent Slot 1");			// Works!
	moveMap.bind(keyboard, $TalentSlot3Bind, "talentSlot3", "Talent Slot 1");			// Works!
	moveMap.bind(keyboard, $TalentSlot4Bind, "talentSlot4", "Talent Slot 1");			// Works!
	
	moveMap.bind(keyboard, $ReloadBind, "reload", "Reload / Discard Suit");				// Works!
	
	moveMap.bind(keyboard, $SquadInfoBind, "squadInfo", "Squad Info");					// Works!
	
	deactivatePackage(KeybindPackage);
}
function loadKeybindings ()
{//echo("loadKeybindings()");
	$keybindCount = 0;
	if (isFunction("setupKeybinds"))
	{
		setupKeybinds();
	}
}